Coder Social home page Coder Social logo

uiwjs / react-textarea-code-editor Goto Github PK

View Code? Open in Web Editor NEW
453.0 4.0 24.0 36.61 MB

A simple code editor with syntax highlighting.

Home Page: https://uiwjs.github.io/react-textarea-code-editor/

License: MIT License

Shell 0.18% TypeScript 80.20% HTML 8.54% Less 11.08%
react react18 typescript react-component editor textarea textarea-editor textarea-component code-editor nextjs

react-textarea-code-editor's People

Contributors

badestrand avatar bombillazo avatar charles-smith avatar jaywcjlove avatar kallielev avatar renovate-bot avatar renovate[bot] avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

react-textarea-code-editor's Issues

JSON Highlighting of Value the same as the Name when a string

Hi

When highlighting JSON the name value pair is highlighting the same colour when the value is a string.
Is it possible to define the value if it a string so that it can be given another colour.

{
"state": "initial"
}

in this case both "state" and "initial" are the same colour. And for larger JSON objects it makes most of the object the same colour.

This way the colour scheme is more customisable through .w-tc-editor-var and I can match it to other outputs such as JSONPretty

[Feature Request] Copy to Clipboard or Customizable Button Bar

Proposal

Hi, first of all, this is a great react component. I have used it for some of my projects and it works as intended. Great stuff!

I'd like to propose a change. Specifically on adding a few floating menu navigation inside the code editor. This will allow the developers to insert some contextual functionality into the component.

Disabling line wrap for long lines

Is there any way to disable line wrapping within the editor and have horizontal scrolling instead? This would be important for editing YAML containing long strings.

NextJS React Component does not respect div height

As I understand it, it is best to set the div containing the code editor to control the overall height of the editor and then to set the style within the editor. However, with NextJS I cannot get it to respect the div's height and it will not limit its own height.

Please see this sandbox: https://codesandbox.io/s/react-textarea-code-editor-example-nextjs-forked-x8evko?file=/pages/index.js

index.js in the sandbox demonstrates that setting the height to "100px" in the containing div is not respected by the editor.
index2.js is my attempt at setting it within the editor, which does limit the height, but then pasting into the editor causes weird behaviour. The cursor does not line up to the pasted content.

Custom Syntax Highlighting

Is there a way to customise which specific words in the textarea are colored/highlighted based on a custom regex function or similar? I saw the issue regarding the prism plugins but am unclear on how to implement a custom function with these that is not language related.

For example being able to detect words that start with # and color them blue.

Thanks

Bug: Code Editor + Jest not working

Hey! Thanks for this library.

The Code Editor does not work when using Jest. One reason is Jest not supporting import statements natively but what I am not understanding is that it should be using cjs - but it is not.

I created a down-to-earth, super-easy repository (it literally does nothing but importing your library and console.log). Just do npm i and run yarn jest to trigger jest.

https://github.com/activenode-bugs/uiw-react-textarea-code-editor-jest

You will see the error message of Cannot use import statement outside a module.

I googled this for hours and tried multiple things but maybe I'm overlooking something. It will always end up in trying to load unified from the rehype library with an import statement instead of going for a non-module approach.

What works (which is not a satisfying solution):

I've looked into your package folder which contains esm, cjs AND a dist folder. If you use jest with moduleNameMapper and then map @uiw/react-textarea-code-editor to @uiw/react-textarea-code-editor/dist/editor.js it will work / run.

moduleNameMapper: {
    // if you use the following, it will work
    // '@uiw/react-textarea-code-editor':
    //   '<rootDir>/node_modules/@uiw/react-textarea-code-editor/dist/editor.js',
  },

But the question is WHY? My first thought then is: Shouldn't your repo point main: "dist/editor.js" if this works seamlessly?

Which triggers my follow up question why there even is esm, cjs AND dist (can you clarify the differentiation?) and why does dist/editor.js work but cjs does not?

I feel like there is something weird going on which you can probably clarify as I am not as deep into this as you are :) Thank you so much in advance!

Max number of lines so it doesn't overflow my div?

Hi,

I've got a problem with formatting, I even tried editing the source, but I could achieve setting maximum height or at least setting the maximum possible number of lines.

I'd love to use scrollbar if the code get's too big.

Here's the example:

image

image

Snímek obrazovky 2022-06-23 v 11 37 25

Dependency Dashboard

This issue lists Renovate updates and detected dependencies. Read the Dependency Dashboard docs to learn more.

Other Branches

These updates are pending. To force PRs open, click the checkbox below.

  • chore(deps): update actions/checkout action to v4
  • chore(deps): update actions/setup-node action to v4
  • chore(deps): update peaceiris/actions-gh-pages action to v4

Open

These updates have all been created already. Click a checkbox below to force a retry/rebase of any.

Detected dependencies

github-actions
.github/workflows/ci.yml
  • actions/checkout v3
  • actions/setup-node v3
  • peaceiris/actions-gh-pages v3
  • ncipollo/release-action v1
.github/workflows/pull_request.yml
  • actions/checkout v3
  • actions/setup-node v3
npm
core/package.json
  • @babel/runtime ^7.18.6
  • rehype ~13.0.0
  • rehype-prism-plus 2.0.0
  • @babel/runtime >=7.10.0
  • react >=16.9.0
  • react-dom >=16.9.0
package.json
  • @types/react-test-renderer ^18.0.0
  • @kkt/scope-plugin-options ^7.5.2
  • @kkt/less-modules ^7.5.2
  • @kkt/ncc ^1.0.14
  • compile-less-cli ^1.9.0
  • husky ^8.0.3
  • kkt ^7.5.2
  • lint-staged ^14.0.0
  • lerna ^7.1.3
  • prettier ^3.0.0
  • react-test-renderer ^18.2.0
  • tsbb ^4.2.1
  • node >=16.0.0
  • typescript ^5.1.3
www/package.json
  • @uiw/react-loader ^4.21.14
  • @uiw/react-markdown-preview-example ^2.0.0
  • code-example ^3.3.6
  • react ^18.2.0
  • react-dom ^18.2.0
  • styled-components ^6.0.5
  • @babel/plugin-proposal-private-property-in-object ^7.21.11
  • @kkt/raw-modules ^7.5.1
  • @kkt/scope-plugin-options ^7.5.1
  • @types/react ^18.0.31
  • @types/react-dom ^18.0.11
  • kkt ^7.5.1
  • markdown-react-code-preview-loader ^2.1.2
  • source-map-explorer ^2.5.3

  • Check this box to trigger a request for Renovate to run again on this repository

Dark mode

Is there a way to use custom styles for the text area?

[Question] Raw data is not aligned with parsed data

Hi everyone,

I am facing with the issue when trying to load the data from the api. There are some special characters which can be displayed normal on

 and <textarea>. But when I try to put these data to the code editor, it is parsed to the content below.
Screen Shot 2022-05-30 at 6 14 06 PM

The raw data that I used the pre and textarea to show
Screen Shot 2022-05-30 at 6 14 15 PM
Screen Shot 2022-05-30 at 6 14 24 PM

Could you guys try to have a look on this issue?

Thanks,

Is `font-family: inherit;` in `.w-tc-editor` required?

Thank you for your hard work.

I am using this library with Tailwind. However, after adding the font-mono class, it is not working in the library. The reason for this is that the class .w-tc-editor is set to font-family: inherit;, which overrides the font-mono setting. This could happen to any custom class.

Although I can use inline styles or !important to fix this issue, I believe that using a class to provide the style is better practice. Furthermore, even without any font settings, the element would still inherit the style.

Auto styles are incorrect when printing

When printing, the colors of the code are incorrect when styles are using auto.

My system:
MacOS Ventura 13.1 set to Dark theme
Chrome 108.0.5359.124 (Official Build) (arm64)

To reproduce:

  1. Go to the official CodeSandbox example: https://mcebp.csb.app/
  2. Print the page

Screenshot 2023-01-02 at 5 09 16 PM

I am the maintainer of react-to-print, and this issue was discovered by one of our users: MatthewHerbst/react-to-print#540. I looked at the styles and didn't see anything obviously wrong, but I am not an expert in that area. If I can be of any assistance solving this, please let me know.

stop code wrap

Is there any way to stop code wrap and make it horizontal scroll
image

Support of shortcuts for React v16

In onKeyDown handler by default there is a check for event.code property (https://github.com/uiwjs/react-textarea-code-editor/blob/main/src/shortcuts.ts#L7), but this property was added to event only in React v17 (https://blog.saeloun.com/2021/04/23/react-keyboard-event-code.html). Before that we can get it via event.nativeEvent.code accessor. In peerDependencies you have "react": ">=16.9.0" (https://github.com/uiwjs/react-textarea-code-editor/blob/main/package.json#L66), so maybe it is better to extend check in shortcuts method? Something like that:

const code = event.code || event.nativeEvent.code;

CTRL + Z | Undo

Hello guys!

I've a big problem with "undo"...
When I typing any values but I press "Enter", I need to do "UNDO", only the line is currently working, and if I press several times then I will return to the initial state, but with the values I typed before. how can i fix this?

Playground: https://uiwjs.github.io/react-textarea-code-editor/

Cursor not lining up with text and syntax highlighting, indent, etc not working

test

If you look at the gif you can see that the cursor is actually above where the input appears. When you type it's really difficult to know where your input is going to appear and it seems erratic. Also the auto-indent doesn't seem to work and there's no syntax highlighting.

Here's my code:

import React, { useState } from 'react';
import dynamic from 'next/dynamic';

const ReactJson = dynamic(
  () => {
    return import('react-json-view');
  },
  { ssr: false },
);

const CodeEditor = dynamic(
  // @ts-ignore
  () => import("@uiw/react-textarea-code-editor").then((mod) => mod.default),
  { ssr: false }
);

function ConfigJsonViewerComponent(props: any) {
  const config: any = props.config;
  const [editableConfig, setEditableConfig] = useState(JSON.stringify(config, null,'\r'))

  function onEdit(editObj: any): boolean {
    setEditableConfig(editObj);
    return true;
  }

  // @ts-ignore
  return (
    <div>
        <div>
          <h3>
            Configuration <i>{edited ? '(edited)' : ''}</i>
          </h3>
          <CodeEditor
            // @ts-ignore
            value={editableConfig}
            language="json"
            placeholder={editableConfig}
            onChange={(e: any) => onEdit(e.target.value)}
            style={{
              fontSize: 12,
              backgroundColor: "#f5f5f5",
              fontFamily:
                "ui-monospace,SFMono-Regular,SF Mono,Consolas,Liberation Mono,Menlo,monospace"
            }}
          />
        </div>
      )}
    </div>
  );
}

export default ConfigJsonViewerComponent;

This is a next.js app so my next.js config looks like this:

const removeImports = require("next-remove-imports")();
module.exports = removeImports({
  experimental: { esmExternals: true },
  distDir: 'build',
  webpack: config => {
    return {
      ...config,
      node: { __dirname: true },
    };
  }
});

[Feature Request] allow to change theme colors

Hi, extending the theme can be an interesting feature, currently I change the background using chakra-ui color mode to achieve something like this:

image
image

But when I wrote code on the box..

image

Is it possible to customize the syntax highlight colors?

Can't use this library with Next.js using a `next.config.mjs` file

I'm trying to use this with a next.config.mjs file and am probably using this incorrectly. The issue I'm running into is that there is no place for me to pass my existing NextConfig as an argument into removeImports, since the signature looks like:

declare type PluginOptions = {
    test?: RegExp;
    matchImports?: string;
};
declare const _default: (pluginOptions?: PluginOptions) => (nextConfig?: NextConfig) => NextConfig;

I've tried instead to merge the output from removeImports with my initialized config, but that didn't seem to have any effect:

// @ts-check

import removeImports from 'next-remove-imports'

/**
 * Run `build` or `dev` with `SKIP_ENV_VALIDATION` to skip env validation.
 * This is especially useful for Docker builds.
 */
!process.env.SKIP_ENV_VALIDATION && (await import("./src/env.mjs"));


/** @type {import("next").NextConfig} */
const config = {
  reactStrictMode: true,

  /**
   * If you have the "experimental: { appDir: true }" setting enabled, then you
   * must comment the below `i18n` config out.
   *
   * @see https://github.com/vercel/next.js/issues/41980
   */
  i18n: {
    locales: ["en"],
    defaultLocale: "en",
  },
	...removeImports(),
};
export default config;

This must be the case of me doing something incorrectly, but it's blocking my ability to use this package.

The code editor doesn't format numbers well

Single numbers won't format well as it increases their size and it changes the color to red (I assume the color changing is part of the code editor so that's not a problem). I tried it with multiple languages and it doesn't work good for all of them. However, having the numbers next to a string, the problem doesn't occur.
bug number

The latest version is not available in NPM

Hi! I noticed that the latest version of this package, which I'm looking forward to install, hasn't been published to NPM yet.

npm install @uiw/[email protected] 
npm ERR! code ETARGET
npm ERR! notarget No matching version found for @uiw/[email protected].
npm ERR! notarget In most cases you or one of your dependencies are requesting
npm ERR! notarget a package version that doesn't exist.

Is there no defined type of language available?

I'm just using it after declaring it myself.
Is there any better way? 😢

export type Languages =
  | 'abap'
  | 'aes'
  | 'apex'
  | 'azcli'
  | 'bat'
  | 'bicep'
  | 'brainfuck'
  | 'c'
  | 'cameligo'
  | 'clike'
  | 'clojure'
  | 'coffeescript'
  | 'cpp'
  | 'csharp'
  | 'csp'
  | 'css'
  | 'dart'
  | 'dockerfile'
  | 'ecl'
  | 'elixir'
  | 'erlang'
  | 'flow9'
  | 'freemarker2'
  | 'fsharp'
  | 'go'
  | 'graphql'
  | 'handlebars'
  | 'hcl'
  | 'html'
  | 'ini'
  | 'java'
  | 'javascript'
  | 'js'
  | 'json'
  | 'jsx'
  | 'julia'
  | 'kotlin'
  | 'less'
  | 'lex'
  | 'lexon'
  | 'liquid'
  | 'livescript'
  | 'lua'
  | 'm3'
  | 'markdown'
  | 'mips'
  | 'msdax'
  | 'mysql'
  | 'nginx'
  | 'objective-c'
  | 'pascal'
  | 'pascaligo'
  | 'perl'
  | 'pgsql'
  | 'php'
  | 'pla'
  | 'plaintext'
  | 'postiats'
  | 'powerquery'
  | 'powershell'
  | 'proto'
  | 'pug'
  | 'python'
  | 'qsharp'
  | 'r'
  | 'razor'
  | 'redis'
  | 'redshift'
  | 'restructuredtext'
  | 'ruby'
  | 'rust'
  | 'sb'
  | 'scala'
  | 'scheme'
  | 'scss'
  | 'shell'
  | 'sol'
  | 'sparql'
  | 'sql'
  | 'st'
  | 'stylus'
  | 'swift'
  | 'systemverilog'
  | 'tcl'
  | 'toml'
  | 'ts'
  | 'tsx'
  | 'twig'
  | 'typescript'
  | 'vb'
  | 'vbscript'
  | 'verilog'
  | 'vue'
  | 'xml'
  | 'yaml';

export interface CodeEditorProps extends TextareaCodeEditorProps {
  value: string;
  language: Languages;
}

Very Slow in Safari

Hi, this editor looks great. Unfortunately, it seems to run really slowly in Safari. Either that or updates are not being painted immediately.

Thanks,
Nicholas

Unable to access ref on CodeEditor using NextJS dynamic

Can you please provide an example of how to attach a ref to the CodeEditor component when using NextJS dynamic to load the editor. I get the error:

Warning: Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()?

I've tried setting up a forwardRef, but can't seem to get the ref assigned.

Thanks :)

How to use with Remixjs?

i'm getting this error below when loading the root of my web app. code editor is on a separate route.

and i'm getting this same error after following the advice here: https://remix.run/docs/en/v1/pages/gotchas#importing-esm-packages

that is, adding this package to my remix.config.js isn't helping. any suggestions would be greatly appreciated! ty for an awesome component

Error [ERR_REQUIRE_ESM]: require() of ES Module /Users/stuartrobinson/repos/mailpotato/frontend/mk-remix-supabase-public-demo/node_modules/rehype/index.js from /Users/stuartrobinson/repos/mailpotato/frontend/mk-remix-supabase-public-demo/api/index.js not supported.
Instead change the require of /Users/stuartrobinson/repos/mailpotato/frontend/mk-remix-supabase-public-demo/node_modules/rehype/index.js in /Users/stuartrobinson/repos/mailpotato/frontend/mk-remix-supabase-public-demo/api/index.js to a dynamic import() which is available in all CommonJS modules.
    at node_modules/@uiw/react-textarea-code-editor/cjs/utils.js (/Users/stuartrobinson/repos/mailpotato/frontend/mk-remix-supabase-public-demo/api/index.js:819:118)
    at /Users/stuartrobinson/repos/mailpotato/frontend/mk-remix-supabase-public-demo/api/index.js:7:50
    at node_modules/@uiw/react-textarea-code-editor/cjs/index.js (/Users/stuartrobinson/repos/mailpotato/frontend/mk-remix-supabase-public-demo/api/index.js:1058:362)
    at /Users/stuartrobinson/repos/mailpotato/frontend/mk-remix-supabase-public-demo/api/index.js:7:50
    at Object.<anonymous> (/Users/stuartrobinson/repos/mailpotato/frontend/mk-remix-supabase-public-demo/api/index.js:17853:49)
    at /Users/stuartrobinson/repos/mailpotato/frontend/mk-remix-supabase-public-demo/node_modules/@remix-run/serve/dist/index.js:43:17
    at Layer.handle [as handle_request] (/Users/stuartrobinson/repos/mailpotato/frontend/mk-remix-supabase-public-demo/node_modules/express/lib/router/layer.js:95:5)
    at next (/Users/stuartrobinson/repos/mailpotato/frontend/mk-remix-supabase-public-demo/node_modules/express/lib/router/route.js:144:13)
    at next (/Users/stuartrobinson/repos/mailpotato/frontend/mk-remix-supabase-public-demo/node_modules/express/lib/router/route.js:140:7)
    at next (/Users/stuartrobinson/repos/mailpotato/frontend/mk-remix-supabase-public-demo/node_modules/express/lib/router/route.js:140:7)
    at next (/Users/stuartrobinson/repos/mailpotato/frontend/mk-remix-supabase-public-demo/node_modules/express/lib/router/route.js:140:7)
    at next (/Users/stuartrobinson/repos/mailpotato/frontend/mk-remix-supabase-public-demo/node_modules/express/lib/router/route.js:140:7)
    at next (/Users/stuartrobinson/repos/mailpotato/frontend/mk-remix-supabase-public-demo/node_modules/express/lib/router/route.js:140:7)
    at next (/Users/stuartrobinson/repos/mailpotato/frontend/mk-remix-supabase-public-demo/node_modules/express/lib/router/route.js:140:7)
    at Route.dispatch (/Users/stuartrobinson/repos/mailpotato/frontend/mk-remix-supabase-public-demo/node_modules/express/lib/router/route.js:114:3)
    at Layer.handle [as handle_request] (/Users/stuartrobinson/repos/mailpotato/frontend/mk-remix-supabase-public-demo/node_modules/express/lib/router/layer.js:95:5)
    at /Users/stuartrobinson/repos/mailpotato/frontend/mk-remix-supabase-public-demo/node_modules/express/lib/router/index.js:284:15
    at param (/Users/stuartrobinson/repos/mailpotato/frontend/mk-remix-supabase-public-demo/node_modules/express/lib/router/index.js:365:14)
    at param (/Users/stuartrobinson/repos/mailpotato/frontend/mk-remix-supabase-public-demo/node_modules/express/lib/router/index.js:376:14)
    at Function.process_params (/Users/stuartrobinson/repos/mailpotato/frontend/mk-remix-supabase-public-demo/node_modules/express/lib/router/index.js:421:3)
    at next (/Users/stuartrobinson/repos/mailpotato/frontend/mk-remix-supabase-public-demo/node_modules/express/lib/router/index.js:280:10)
    at logger (/Users/stuartrobinson/repos/mailpotato/frontend/mk-remix-supabase-public-demo/node_modules/morgan/index.js:144:5)
    at Layer.handle [as handle_request] (/Users/stuartrobinson/repos/mailpotato/frontend/mk-remix-supabase-public-demo/node_modules/express/lib/router/layer.js:95:5)
    at trim_prefix (/Users/stuartrobinson/repos/mailpotato/frontend/mk-remix-supabase-public-demo/node_modules/express/lib/router/index.js:328:13)
    at /Users/stuartrobinson/repos/mailpotato/frontend/mk-remix-supabase-public-demo/node_modules/express/lib/router/index.js:286:9
    at Function.process_params (/Users/stuartrobinson/repos/mailpotato/frontend/mk-remix-supabase-public-demo/node_modules/express/lib/router/index.js:346:12)
    at next (/Users/stuartrobinson/repos/mailpotato/frontend/mk-remix-supabase-public-demo/node_modules/express/lib/router/index.js:280:10)
    at SendStream.error (/Users/stuartrobinson/repos/mailpotato/frontend/mk-remix-supabase-public-demo/node_modules/serve-static/index.js:121:7)
    at SendStream.emit (node:events:513:28)
    at SendStream.error (/Users/stuartrobinson/repos/mailpotato/frontend/mk-remix-supabase-public-demo/node_modules/send/index.js:270:17)
    at SendStream.onStatError (/Users/stuartrobinson/repos/mailpotato/frontend/mk-remix-supabase-public-demo/node_modules/send/index.js:417:12)
    at next (/Users/stuartrobinson/repos/mailpotato/frontend/mk-remix-supabase-public-demo/node_modules/send/index.js:759:28)
    at /Users/stuartrobinson/repos/mailpotato/frontend/mk-remix-supabase-public-demo/node_modules/send/index.js:767:23
    at FSReqCallback.oncomplete (node:fs:190:21)

Placeholder behavior not as expected

I just upgraded to version 2.0.3 and the behavior of the placeholder seems to have changed in version 2.0.2 (I believe due to #114).

Behavior prior to 2.0.2
When the placeholder attribute was set, the <code> element was empty until a value is set. The placeholder text is a different, darker color than the actual text color, as it should be.
image

Behavior after 2.0.2
When the placeholder is set and no value is specified, the placeholder is also listed in the <code> tag, so it overlays the actual placeholder. This means that the color is not as dark as it used to be and for some reason, the edges of the font seem rougher (not noticeable in screenshot).
image

Is there a way I can not add the value of the placeholder to the <code> tag, so that the behavior stays the same like versions before 2.0.3?

[Fix] Shift+Tab on single line removes starting tab

Hi! 👋

Firstly, thanks for your work on this project! 🙂

Today I used patch-package to patch @uiw/[email protected] for the project I'm working on.

Shift+Tab works when selecting multiple lines but not when the cursor is in a single line.

Here is the diff that solved my problem:

diff --git a/node_modules/@uiw/react-textarea-code-editor/cjs/shortcuts.js b/node_modules/@uiw/react-textarea-code-editor/cjs/shortcuts.js
index f019f90..0ea03b3 100644
--- a/node_modules/@uiw/react-textarea-code-editor/cjs/shortcuts.js
+++ b/node_modules/@uiw/react-textarea-code-editor/cjs/shortcuts.js
@@ -17,7 +17,11 @@ function shortcuts(e) {
   if (code === 'tab') {
     (0, _utils.stopPropagation)(e);
     if (api.start === api.end) {
-      api.insertText('  ').position(api.start + 2, api.end + 2);
+      if (e.shiftKey) {
+        api.lineStarRemove('  ');
+      } else {
+        api.insertText('  ').position(api.start + 2, api.end + 2);
+      }
     } else if (api.getSelectedValue().indexOf('\n') > -1 && e.shiftKey) {
       api.lineStarRemove('  ');
     } else if (api.getSelectedValue().indexOf('\n') > -1) {
diff --git a/node_modules/@uiw/react-textarea-code-editor/dist/editor.js b/node_modules/@uiw/react-textarea-code-editor/dist/editor.js
index c805142..94b166e 100644
--- a/node_modules/@uiw/react-textarea-code-editor/dist/editor.js
+++ b/node_modules/@uiw/react-textarea-code-editor/dist/editor.js
@@ -42953,7 +42953,7 @@ function shortcuts(e){var api=new SelectionText(e.target);/**
    * Support of shortcuts for React v16
    * https://github.com/uiwjs/react-textarea-code-editor/issues/128
    * https://blog.saeloun.com/2021/04/23/react-keyboard-event-code.html
-   */var code=(e.code||e.nativeEvent.code).toLocaleLowerCase();if(code==='tab'){stopPropagation(e);if(api.start===api.end){api.insertText('  ').position(api.start+2,api.end+2);}else if(api.getSelectedValue().indexOf('\n')>-1&&e.shiftKey){api.lineStarRemove('  ');}else if(api.getSelectedValue().indexOf('\n')>-1){api.lineStarInstert('  ');}else{api.insertText('  ').position(api.start+2,api.end);}api.notifyChange();}else if(code==='enter'){stopPropagation(e);var indent="\n".concat(api.getIndentText());api.insertText(indent).position(api.start+indent.length,api.start+indent.length);api.notifyChange();}else if(code&&/^(quote|backquote|bracketleft|digit9|comma)$/.test(code)&&api.getSelectedValue()){stopPropagation(e);var val=api.getSelectedValue();var txt='';switch(code){case'quote':txt="'".concat(val,"'");if(e.shiftKey){txt="\"".concat(val,"\"");}break;case'backquote':txt="`".concat(val,"`");break;case'bracketleft':txt="[".concat(val,"]");if(e.shiftKey){txt="{".concat(val,"}");}break;case'digit9':txt="(".concat(val,")");break;case'comma':txt="<".concat(val,">");break;}api.insertText(txt);api.notifyChange();}}
+   */var code=(e.code||e.nativeEvent.code).toLocaleLowerCase();if(code==='tab'){stopPropagation(e);if(api.start===api.end){if(e.shiftKey){api.lineStarRemove('  ');}else{api.insertText('  ').position(api.start + 2, api.end + 2);};}else if(api.getSelectedValue().indexOf('\n')>-1&&e.shiftKey){api.lineStarRemove('  ');}else if(api.getSelectedValue().indexOf('\n')>-1){api.lineStarInstert('  ');}else{api.insertText('  ').position(api.start+2,api.end);}api.notifyChange();}else if(code==='enter'){stopPropagation(e);var indent="\n".concat(api.getIndentText());api.insertText(indent).position(api.start+indent.length,api.start+indent.length);api.notifyChange();}else if(code&&/^(quote|backquote|bracketleft|digit9|comma)$/.test(code)&&api.getSelectedValue()){stopPropagation(e);var val=api.getSelectedValue();var txt='';switch(code){case'quote':txt="'".concat(val,"'");if(e.shiftKey){txt="\"".concat(val,"\"");}break;case'backquote':txt="`".concat(val,"`");break;case'bracketleft':txt="[".concat(val,"]");if(e.shiftKey){txt="{".concat(val,"}");}break;case'digit9':txt="(".concat(val,")");break;case'comma':txt="<".concat(val,">");break;}api.insertText(txt);api.notifyChange();}}
 ;// CONCATENATED MODULE: ./src/styles.ts
 var container={position:'relative',textAlign:'left',boxSizing:'border-box',padding:0,overflow:'hidden'};var styles_textarea={position:'absolute',top:0,left:0,height:'100%',width:'100%',resize:'none',color:'inherit',opacity:0.8,overflow:'hidden',MozOsxFontSmoothing:'grayscale',WebkitFontSmoothing:'antialiased',WebkitTextFillColor:'transparent'};var editor={margin:0,border:0,background:'none',boxSizing:'inherit',display:'inherit',fontFamily:'inherit',fontSize:'inherit',fontStyle:'inherit',fontVariantLigatures:'inherit',fontWeight:'inherit',letterSpacing:'inherit',lineHeight:'inherit',tabSize:'inherit',textIndent:'inherit',textRendering:'inherit',textTransform:'inherit',whiteSpace:'pre-wrap',wordBreak:'keep-all',overflowWrap:'break-word',outline:0};
 ;// CONCATENATED MODULE: ./src/style/index.less
diff --git a/node_modules/@uiw/react-textarea-code-editor/esm/shortcuts.js b/node_modules/@uiw/react-textarea-code-editor/esm/shortcuts.js
index 25bc764..7a4390d 100644
--- a/node_modules/@uiw/react-textarea-code-editor/esm/shortcuts.js
+++ b/node_modules/@uiw/react-textarea-code-editor/esm/shortcuts.js
@@ -11,7 +11,11 @@ export default function shortcuts(e) {
   if (code === 'tab') {
     stopPropagation(e);
     if (api.start === api.end) {
-      api.insertText('  ').position(api.start + 2, api.end + 2);
+      if (e.shiftKey) {
+        api.lineStarRemove('  ');
+      } else {
+        api.insertText('  ').position(api.start + 2, api.end + 2);
+      }
     } else if (api.getSelectedValue().indexOf('\n') > -1 && e.shiftKey) {
       api.lineStarRemove('  ');
     } else if (api.getSelectedValue().indexOf('\n') > -1) {
diff --git a/node_modules/@uiw/react-textarea-code-editor/src/shortcuts.ts b/node_modules/@uiw/react-textarea-code-editor/src/shortcuts.ts
index 8e0a2c8..5a91851 100644
--- a/node_modules/@uiw/react-textarea-code-editor/src/shortcuts.ts
+++ b/node_modules/@uiw/react-textarea-code-editor/src/shortcuts.ts
@@ -13,7 +13,11 @@ export default function shortcuts(e: React.KeyboardEvent<HTMLTextAreaElement>) {
   if (code === 'tab') {
     stopPropagation(e);
     if (api.start === api.end) {
-      api.insertText('  ').position(api.start + 2, api.end + 2);
+      if (e.shiftKey) {
+        api.lineStarRemove('  ');
+      } else {
+        api.insertText('  ').position(api.start + 2, api.end + 2);
+      }
     } else if (api.getSelectedValue().indexOf('\n') > -1 && e.shiftKey) {
       api.lineStarRemove('  ');
     } else if (api.getSelectedValue().indexOf('\n') > -1) {

This issue body was partially generated by patch-package.

Static build outputs `[object Object],[object Object],[object Object]` if value prop is set initially

Thanks for the awesome and simple to use package. I like it, since it's very simple and it suits my needs perfectly. However, I stumbled upon an issue that I can't seem to get rid of.

If I give CodeEditor an initial value (see code sample below), then when building the project into static files it will display [object Object],[object Object],[object Object] in the editor.

I first thought it had something to do with the state. I initially had a useState and passed the value of that state to the value prop of the editor. But after some inspection, I found that even if the value prop is set to a simple string, it will still render [object Object],[object Object],[object Object] inside the editor.

This only occurs when I build the project into static files. During the development with the live server, this bug does not occur.

Package Version: 1.4.16
Vite version: 2.8.0

Component CodeEditor.tsx:

import { ChangeEvent } from "react";
import { useMantineTheme } from "@mantine/core";

import CodeEditor from '@uiw/react-textarea-code-editor';
import "@uiw/react-textarea-code-editor/dist.css";

type Props = {
    query: string | null,
    setQuery: (value: string) => void,
};
const Editor = ({ query, setQuery }: Props) => {
    const theme = useMantineTheme();

    return (
        <CodeEditor
            value={`SELECT *`}
            language="sql"
            placeholder="Enter a SQL query."
            onChange={(evn: ChangeEvent<HTMLTextAreaElement>) => setQuery(evn.target.value)}
            padding={theme.spacing.md}
            style={{
                height: '100%',
                fontSize: theme.fontSizes.lg,
                backgroundColor: theme.colorScheme === 'dark' ? theme.colors.dark[5] : "white",
                border: theme.colorScheme === 'dark' ? 'none' : `1px solid ${theme.colors.gray[4]}`,
                borderRadius: theme.radius.sm,
                resize: 'none',
                overflowY: 'auto',
                fontFamily:
                    "ui-monospace,SFMono-Regular,SF Mono,Consolas,Liberation Mono,Menlo,monospace"
            }}
        />
    );
};

export default Editor

Rendered HTML:

<pre aria-hidden="true" class=" language-sql" tabindex="0">
  <code class=" language-sql">
    [object Object],[object Object],[object Object]
  </code>
  <br>
</pre>

Output:
image

[Feature Request] CSV support

CSV support would be great to have, for each column a different color from a color palette
Let me know if this is hard to do, or if you'd like a PR, thanks!

Possibly shown user errors in inserted code

think will be great to add the possibility send errors props with the format

type Errors = {
   startAt: number; // start position in string
   endAt: number; // end position in string
   message: string; // message by hover
}[]

startAt, endAt will use to add a red underline for the respective code
the message will show by hovering over the error line, but it is harder to implement

ref to textarea throwing exception.

When trying to get ref to underlying textarea, it is returning some exception.

version: 1.4.15

sample code.

export function SimpleHTMLEditor() {

    const editorRef = React.useRef(false);

    const onBold = () => {
        // editorRef.current is pointing to some exception.
    };

    return (
        <>
            <button onClick={onBold} >bold text</button>
            <CodeEditor
                ref={editorRef}
                value={code}
                language="html"
                placeholder="Please enter HTML code."
            />
        </>
    );
}

Disable prop

Add prop to allow disabling the code editor (not-editable)

Next.js Support?

When I try to use this package in a React/Nextjs project, I get the following errors:

Module not found: ESM packages (rehype) need to be imported. Use 'import' to reference the package instead. https://nextjs.org/docs/messages/import-esm-externals
and

wait  - compiling...
error - ../../node_modules/@uiw/react-textarea-code-editor/esm/style/index.css
Global CSS cannot be imported from within node_modules.
Read more: https://nextjs.org/docs/messages/css-npm
Location: ../../node_modules/@uiw/react-textarea-code-editor/esm/index.js

The link in the error message suggests the following:

Reach out to the maintainer and ask for them to publish a compiled version of their dependency.
Compiled dependencies do not have references to CSS files, or any other files that require bundler-specific integrations.

So I wanted to hear the thoughts of the maintainers of this package. Thanks!

bundle size

I integrated this nice editor in my project and my bundle size (produced with Vite 4) increased of ~900KB.
Is this expected?

Text overflow not working

Whenever I add “overflow:”auto”” to the style in this with a fixed height, the text seems to overlap itself and get messed up as if it’s coming back down from the top as seen in the picture. Is there a way to properly have an overflow scroll here?
image

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.