Giter Site home page Giter Site logo

mui-rte's Introduction

mui-rte

The Material-UI Rich Text Editor and Viewer

mui-rte is a complete text editor and viewer for the MUI library (formerly Material-UI) based on draft-js and written in Typescript. It is ready to use out of the box yet supports user defined blocks, styles, autocomplete strategies, async/sync custom atomic blocks, callbacks, and decorators as well as toolbar and theme customization to enhance the editor to all needs.

Installation

npm install mui-rte --save

Install the peer dependencies: @mui/material, @mui/icons-material, @mui/styles, react and react-dom. Also you will need to install the peer dependencies for MUI: @emotion/react and @emotion/styled.

Demo

Edit mui-rte basic

Usage

import { createTheme, ThemeProvider } from '@mui/material/styles'
import MUIRichTextEditor from 'mui-rte'

const myTheme = createTheme({
    // Set up your custom MUI theme here
})

ReactDOM.render(
    <ThemeProvider theme={myTheme}>
        <MUIRichTextEditor label="Start typing..." />
    </ThemeProvider>, 
    document.getElementById("root")
)

You can load default content as the following example. The value should be a stringified RawDraftContentState object:

import MUIRichTextEditor from 'mui-rte'

const data = getContentStateAsStringFromSomewhere()

ReactDOM.render(
    <ThemeProvider theme={myTheme}>
        <MUIRichTextEditor 
            defaultValue={data}
            label="Start typing..." 
        />
    </ThemeProvider>, 
    document.getElementById("root")
)

Material-UI v4 compatibility

mui-rte version 2.x is compatible with MUI (v5) only. You can still use version 1.x for Material-UI v4. Current code using mui-rte version 1.x should be compatible with version 2.x, the only breaking change is that it requires to be wrapped on a ThemeProvider as shown in the examples.

Examples

Check the examples directory for more.

Custom Controls

You can define your custom inline styles, blocks, atomic blocks and callback actions to the editor. Just select an icon from @mui/icons-material or create your own FunctionComponent and define your rules.

Adding a custom inline style

This sample adds a control to change the background color and font color of the typed or selected text:

import MUIRichTextEditor from 'mui-rte'
import InvertColorsIcon from '@mui/icons-material/InvertColors'

<MUIRichTextEditor 
    controls={["my-style"]}
    customControls={[
        {
            name: "my-style",
            icon: <InvertColorsIcon />,
            type: "inline",
            inlineStyle: {
                backgroundColor: "black",
                color: "white"
            }
        }
    ]}
/>

Adding a custom block

This sample adds a block to the editor based on a React Element:

import MUIRichTextEditor from 'mui-rte'
import TableChartIcon from '@mui/icons-material/TableChart'

const MyBlock = (props) => {
    return (
        <div style={{
            padding: 10,
            backgroundColor: "#ebebeb"
        }}>
            My Block content is:
            {props.children}
        </div>
    )
}

<MUIRichTextEditor 
    controls={["my-block"]}
    customControls={[
        {
            name: "my-block",
            icon: <TableChartIcon />,
            type: "block",
            blockWrapper: <MyBlock />
        }
    ]}
/>

Adding a custom atomic block (Async)

It is possible to insert custom blocks based on asynchronous behavior using the insertAtomicBlockAsync API. The above example shows an example on how to upload an image and use the MUIRichTextEditor default image control for further edition. You can use this behavior to upload a file when dropping it inside the editor and render it as an image entity after upload.

Check this other sample that shows how to add a @mui/material Card with asynchronous downloaded content.

Adding a custom atomic block (Sync)

Check this sample that shows how to create a control to add a @mui/material Card component to the editor.

Adding a custom callback control

This sample adds a control that will trigger a custom callback function to clear the editor state:

import MUIRichTextEditor from 'mui-rte'
import DoneIcon from '@mui/icons-material/Done'
import { EditorState } from 'draft-js'

<MUIRichTextEditor 
    controls={["my-callback"]}
    customControls={[
        {
            name: "my-callback",
            icon: <DoneIcon />,
            type: "callback",
            onClick: (editorState, name, anchor) => {
                console.log(`Clicked ${name} control`)
                return EditorState.createEmpty()
            }
        }
    ]}
/>

Autocomplete strategies

You can define autocomplete strategies to present suggested content lists based on the text input. Just set your trigger character, add some search keys and the content to insert and the editor will do everything for you. You can navigate through suggestions using the keyboard arrows and finally press 'Enter' to insert your content into the editor.

Simple strategy example

This is an example to show emoji suggestions when the user start typing a text like ':face', ':joy', or ':grin':

import MUIRichTextEditor from 'mui-rte'

const emojis = [
    {
        keys: ["face", "grin"],
        value: "๐Ÿ˜€",
        content: "๐Ÿ˜€",
    },
    {
        keys: ["face", "joy"],
        value: "๐Ÿ˜‚",
        content: "๐Ÿ˜‚",
    },
    {
        keys: ["face", "sweat"],
        value: "๐Ÿ˜…",
        content: "๐Ÿ˜…",
    }
]

<MUIRichTextEditor 
    autocomplete={{
        strategies: [
            {
                items: emojis,
                triggerChar: ":"
            }
        ]
    }}
/>

Check this sample that shows how to add multiple autocomplete strategies to a single editor.

Atomic strategy example

Check this sample that shows how to combine atomic custom controls with the autocomplete strategy feature.

Custom Decorators

You can define custom decorators to apply styles and/or functionality based on a provided regular expression.

Adding custom functionality with a decorator

To add some functionality when a user inputs a #hashtag use the following example. In this case, everytime the user inputs a word starting with a # character it will be automatically converted into a styled link:

import MUIRichTextEditor from 'mui-rte'

const MyHashTagDecorator = (props) => {
    const hashtagUrl = "http://myurl/" + props.decoratedText
    return (
        <a 
            href={hashtagUrl}
            style={{
                color: "green"
            }}
        >
            {props.children}
        </a>
    )
}

<MUIRichTextEditor 
    label="Type something here..."
    decorators={[
        {
            component: MyHashTagDecorator,
            regex: /\#[\w]+/g
        }
    ]}
/>

Inline toolbar

The editor includes an inline toolbar option which renders a pop-up inside the editor area when the user makes a selection. The inline toolbar supports user defined controls. Notice that only inline type controls will be rendered. The controls displayed on the main toolbar can be different from the ones in the inline toolbar. You can also hide the main toolbar and just enable the inline toolbar.

import MUIRichTextEditor from 'mui-rte'

<MUIRichTextEditor 
    label="Type something here..."
    inlineToolbar={true}
/>

Styling the editor

You can style the editor using the Material-UI theming feature. First create a theme with createMuiTheme and override classes such as root, container, editor, and editorContainer. Check the examples directory for more.

import { createMuiTheme, MuiThemeProvider } from '@mui/material/styles'
import MUIRichTextEditor from 'mui-rte'

const defaultTheme = createMuiTheme()

Object.assign(defaultTheme, {
    overrides: {
        MUIRichTextEditor: {
            root: {
                marginTop: 20,
                width: "80%"
            },
            editor: {
                borderBottom: "1px solid gray" 
            }
        }
    }
})

<MuiThemeProvider theme={defaultTheme}>
    <MUIRichTextEditor 
        label="Type something here..."
    />
</MuiThemeProvider>

API

<MUIRichTextEditor /> (TMUIRichTextEditorProps)

Property Type description
id string optional Base Id name for the component HTML elements.
ref TMUIRichTextEditorRef optional Sets a reference instance of the editor component.
label string optional String to show when there is no content.
readOnly boolean optional Read only mode. The toolbar is disabled by default.
value string deprecated Use defaultValue instead.
defaultValue string optional Default content to load. Should be a stringified Draft.Model.Encoding.RawDraftContentState object.
inheritFontSize boolean optional Inherit font size from parent. Useful for read only mode.
error boolean optional Renders the editor with an error style.
controls string[] optional List of controls to display in the main toolbar. If not provided, all controls will be rendered. Current available values are: "title", "bold", "italic", "underline", "strikethrough", "highlight", "undo", "redo", "link", "media", "numberList", "bulletList", "quote", "code", "clear", "save".
customControls TCustomControl[] optional Defines an array of user custom inline styles, blocks and callbacks. See more information in 'Custom Controls' below.
decorators TDecorator[] optional Defines an array of user custom decorators. See more information in 'Custom Decorators'.
toolbar boolean optional Defines if the main toolbar should be rendered.
toolbarButtonSize small | medium optional Sets the size on the default IconButton component for the main toolbar.
inlineToolbar boolean optional Defines if the inline toolbar should be rendered.
inlineToolbarControls string[] optional List of controls to display in the inline toolbar. Available values are: "bold", "italic", "underline", "strikethrough", "highlight", "link", "clear", and user defined inline controls. If not provided and inlineToolbar is true the following inline styles will be displayed: bold, italic, underline and clear.
keyCommands TKeyCommand[] optional Defines an array of TKeyCommand objects for adding key bindings to the editor.
draftEditorProps TDraftEditorProps optional Defines an object containing specific draft-js Editor properties.
maxLength number optional Sets the maximum characters count that can be input into the editor.
autocomplete TAutocomplete optional Sets autocomplete strategies to present suggestion lists as the user types into the editor.
onSave (data:string) => void optional Function triggered when the save button is pressed. The data is a stringified Draft.Model.Encoding.RawDraftContentState object.
onChange (state: EditorState) => void optional Function triggered on any change in the editor (key input, delete, etc.). The state is a Draft.Model.ImmutableData.EditorState object.
onFocus () => void optional Function triggered when when the editor acquires focus.
onBlur () => void optional Function triggered when when the editor loses focus.

TCustomControl

Property Type description
id string optional The HTML id attribute for the control
name string required The name of the custom control. For rendering the control this name should be added to the MUIRichTextEditor controls property.
icon JSX.Element optional The @mui/icons-material icon for the control. For "atomic" control type, the icon is not required. Check this for available icons.
component React.FunctionComponent<TToolbarComponentProps> optional The custom function component for the control. The icon has priority over the component, so if the icon is set the component will be ignored. For "atomic" control type, the component is not required.
type string required Either "inline", "block", "atomic" or "callback"
inlineStyle string optional The React.CSSProperties object for styling the text when using a custom inline style.
blockWrapper React.ReactElement optional The custom React component used for rendering a custom block.
atomicComponent React.FunctionComponent optional The custom React FunctionComponent used for rendering a custom atomic block.
onClick (editorState: EditorState, name: string, anchor: HTMLElement | null) => EditorState | void optional The callback function triggered when the custom control is clicked. The received arguments include the current EditorState object, the name of the clicked control and the HTMLElement from which the click was raised. If a new EditorState object is returned it will be replace the current one in the editor (useful to explicitly modify the EditorState).

TToolbarComponentProps

Property Type description
id string The id for the component.
onMouseDown (e: React.MouseEvent) => void The mousedown handler.
active boolean Defines if the block or inline type is active for the current editor selection.
disabled boolean Sets if the toolbar is disabled.

TDecorator

Property Type description
component React.FunctionComponent required The React component to use for rendering the decorator.
regex RegExp required The regular expression to match a decorator.

TKeyCommand

Property Type description
key number required The code of the key to bind.
name string required The name of the command.
callback (state: EditorState) => EditorState required The callback function to execute when the key binding is matched. It should return the EditorState to set.

TDraftEditorProps

Property Type description
spellCheck boolean optional Use browser spelling check.
stripPastedStyles boolean optional Remove styles when pasting text into the editor.
handleDroppedFiles (selectionState: SelectionState, files: Blob[]) => DraftHandleValue optional Handle files that have been dropped into the editor. The DraftHandleValue is either handled or not-handled.

TAutocomplete

Property Type description
strategies TAutocompleteStrategy[] required Array of autocomplete strategies.
suggestLimit number optional Defines the amount of suggestions to present to the user. Default is 5.

TAutocompleteStrategy

Property Type description
triggerChar string required A single character that triggers the autocomplete strategy.
items TAutocompleteItem[] required List of autocomplete suggestion items.
insertSpaceAfter boolean optional If false it won't add an space after inserting the content into the editor. Default is true.
atomicBlockName string optional Use an atomic custom control type to add the content to the editor.

TAutocompleteItem

Property Type description
keys string[] required The list of keys that the user needs to type to reveal this item suggestion.
value any required The value to insert into the editor when the item is selected.
content string | JSX.Element required The content presented in the autocomplete suggestion list for this item. Note that this content is render under a ListItem component.

TMUIRichTextEditorRef

Property Type description
focus () => void Triggers the focus event on the editor.
save () => void Triggers the save method on the editor.
insertAtomicBlock (name: string, data: any) deprecated Use insertAtomicBlockSync instead.
insertAtomicBlockSync (name: string, data: any) Inserts an atomic block named as name (if exists) with the provided data into the editor.
insertAtomicBlockAsync (name: string, promise: Promise<TAsyncAtomicBlockResponse>, placeholder?: string) => void Inserts an atomic block named as name (if exists) asynchronously with the provided data into the editor. The placeholder text will be shown on the editor until the promise is resolved.

TAsyncAtomicBlockResponse

Property Type description
data any required The data assigned to the entity added into the editor.

Changelog

Check the release notes for the changelog.

Development

For development use:

$ npm run build
$ npm run serve

Future plans

  • Add test coverage
  • Refactor code
  • Add new features

Suggestions and issues

Please feel free to leave your comment on the Issues tab.

License

Licensed under MIT License.

mui-rte's People

Contributors

dependabot[bot] avatar kanekv avatar manashathparia avatar niuware avatar steurt 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  avatar  avatar  avatar

mui-rte's Issues

make editor area fit 100% height

I want to force editor to fit 100% of the available height. When I add more lines it pushes height over that limit. How is it possible to force it to stay within the limit?

Display: flex causes overflow

I want to inline the label and the rte. So I tried using a flexbox however that causes the rte to overflow rather than new line.

image

Allow toolbar disable

Hi, currently the API says you can pass toolbar={false}, but it will only hide the toolbar if readOnly is true and toolbar is false, we should be able to edit without the toolbar.

Links are relative instead of absolute

Thank you for putting this put there it is really helpful.

I am not sure if this is happening only for me but links are relative.
In the example below, the link will open to: www.localhost:3000/www.github.com
I suspect it can be fixed by pre-pending the href with '//' in the Link component:

const Link: React.FC<ILinkProps> = (props: ILinkProps) => {
    const { url } = props.contentState.getEntity(props.entityKey).getData()
    return (
        <a
            href={`//${url}`}

image

image

Unable to set value when using nextjs

Hi,

I am trying to use mui-rte in a next js project. Whenever i try to assign a value to the value prop i am getting the following error:

Unexpected token a in JSON at position 0
SyntaxError: Unexpected token a in JSON at position 0
at JSON.parse ()
at useEditorState (/Users/user/dev/test/mui-rte-test/node_modules/mui-rte/dist/index.js:1:14383)
at /Users/user/dev/test/mui-rte-test/node_modules/mui-rte/dist/index.js:1:14629
at useReducer (/Users/user/dev/test/mui-rte-test/node_modules/react-dom/cjs/react-dom-server.node.development.js:1361:57)
at Object.useState (/Users/user/dev/test/mui-rte-test/node_modules/react-dom/cjs/react-dom-server.node.development.js:1299:10)
at Object.useState (/Users/user/dev/test/mui-rte-test/node_modules/react/cjs/react.development.js:1637:21)
at Object.MUIRichTextEditor [as render] (/Users/user/dev/test/mui-rte-test/node_modules/mui-rte/dist/index.js:1:14602)
at ReactDOMServerRenderer.render (/Users/user/dev/test/mui-rte-test/node_modules/react-dom/cjs/react-dom-server.node.development.js:3795:44)
at ReactDOMServerRenderer.read (/Users/user/dev/test/mui-rte-test/node_modules/react-dom/cjs/react-dom-server.node.development.js:3565:29)
at renderToString (/Users/user/dev/test/mui-rte-test/node_modules/react-dom/cjs/react-dom-server.node.development.js:4296:27)
at render (/Users/user/dev/test/mui-rte-test/node_modules/next/dist/next-server/server/render.js:81:16)
at Object.renderPage (/Users/user/dev/test/mui-rte-test/node_modules/next/dist/next-server/server/render.js:346:16)
at Function.getInitialProps (/Users/user/dev/test/mui-rte-test/.next/server/static/development/pages/_document.js:485:19)
at Object.loadGetInitialProps (/Users/user/dev/test/mui-rte-test/node_modules/next/dist/next-server/lib/utils.js:59:29)
at Object.renderToHTML (/Users/user/dev/test/mui-rte-test/node_modules/next/dist/next-server/server/render.js:350:36)
at async DevServer.renderToHTML (/Users/user/dev/test/mui-rte-test/node_modules/next/dist/next-server/server/next-server.js:703:24)

Any idea what is going on?

Appreciate this project!!!

M

onChange not working

i am trying to pass the text inside mui-rte to the state using onChange where I have passed handleChange function which takes a prop and changes that value to the state. However, it is giving this error TypeError: Cannot read property 'value' ofundefined``

Here is my code:

 const [Ques, setQues] = useState({
    answer: '',
    question: ''
  });

  const handleChange = prop => event => {
    setQues({ ...Ques, [prop]: event.target.value });
    console.log(event.target.value);
  };
<MUIRichTextEditor
            label="Start Typing ..."
            controls={[
              'title',
              'bold',
              'italic',
              'underline',
              'strikethrough',
              'highlight',
              'undo',
              'redo',
              'save'
            ]}
            value={Ques.answer}
            onChange={handleChange('answer')}
            className="p-1"
          />

```Any suggestion would be highly appreciated.

two instances on one page

Hi guys thanks for this lib. I want to report a bug. Chrome shows these warnings when I have two rtes on page

Screen Shot 2020-02-26 at 5 49 38 PM

Compilation Error in Typescript React Project

Hi,

I installed the module in my react typescript project and I am getting typescript error within the mui-rte source code.

image

Below is my tsconfig.

{ "compilerOptions": { "target": "es5", "lib": [ "dom", "dom.iterable", "esnext" ], "allowJs": true, "skipLibCheck": true, "esModuleInterop": true, "allowSyntheticDefaultImports": true, "strict": true, "forceConsistentCasingInFileNames": true, "module": "esnext", "moduleResolution": "node", "resolveJsonModule": true, "isolatedModules": true, "noEmit": true, "jsx": "react", "noImplicitAny": false }, "include": [ "src" ] }

Updating of content doesn't rerender

Hey, that component is quite nice.
There is just one thing, I don't get:
I download some data and want to show it in your component. The format is ok. But when render my view the first time, I have no data, so the default value is empty. When I am getting the data and update my state, my view is rerender (as it should) but your component is still empty. Do you know how I could fix it?

Support server render

I use readOnly prop to display contents but it does not show up in server render.
Did I miss something? Please help. SEO is very important to us.

Compilation Error: Not all code paths return a value

Compilation error when noImplicitReturns is set.

node_modules/mui-rte/src/MUIRichTextEditor.tsx:411:21 - error TS7030: Not all code paths return a value.

411     blockRenderer = (contentBlock: ContentBlock) => {
                        ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

'link' control not working as expected (mui-rte: v 1.11.0)

Hello, at first thank you for this MUI/Draft.js library.

At first I stumbled on a bug ..

I wonder how to use (or create) the link embedded control ? You provide it but I cannot figure how to use it. The button link doesn't do anything.

... then I find out (maybe why).

You provide a basic example on Codesandbox which is on mui-rte 1.11.0. I think that the bug is related to this last version. cf. : https://codesandbox.io/s/mui-rte-basic-ypfdo?fontsize=14

We figure out that v. 1.9.3 works fine. The bug must lies somewhere in the toolbar (cf. release note 1.10), I think that maybe the popover position isn't correctly initialized.

Have a nice day.

Compilation Error in Typescript React Project

Hi,
when I try compile project with "noUnusedParameters": true,, I get error in
ERROR in ..\node_modules\mui-rte\src\MUIRichTextEditor.tsx(178,62)
TS6133: 'contentState' is declared but its value is never read.

How to use Editor.forceSelection() in this library, can you please share an example?

I have been trying to update the value of my MUIRTE using the following code.

 const change = (state) => {
    const currentSelection = state.getSelection()
    const content_state = state.getCurrentContent()
    const newEditorState = EditorState.forceSelection(content_state, currentSelection)
    const final = JSON.stringify(convertToRaw(newEditorState))
    setEditorState(final)
  }

But I am unable to do so and I am getting this error in the console

Uncaught TypeError: editorState.getImmutable is not a function

I am using the forceSelection because it helps in removing the cursor reset error in the MUIRichTextEditor component. As answered in this post: https://stackoverflow.com/questions/43868815/how-to-stop-draftjs-cursor-jumping-to-beginning-of-text

Please help!

Control text during typing

While typing, you cannot control text until you click the Save button. It would be better to have an onChange function.

Button ID is undefined

Hi. Awesome package, this is working really nicely in my project.

I have come across a minor thing, in which I see some console warnings where id is coming out as undefined for each button.

[DOM] Found 9 elements with non-unique id #undefined: (More info: https://goo.gl/9p2vKq)
<button class=โ€‹"MuiButtonBase-root MuiIconButton-root" tabindex=โ€‹"0" type=โ€‹"button" id=โ€‹"undefined" aria-label=โ€‹"Bold">โ€‹โ€ฆโ€‹</button>โ€‹
<button class=โ€‹"MuiButtonBase-root MuiIconButton-root" tabindex=โ€‹"0" type=โ€‹"button" id=โ€‹"undefined" aria-label=โ€‹"Italic">โ€‹โ€ฆโ€‹</button>
...

Extend props with `id`

It would be useful to have an id property to pass to draft-js editor. In this way it can be used in combination with htmlFor for better accessibility and for testing.

I want to add another button in the editor (NOT in the controls), how to provide state to that particular independent button.

I understand that one way of doing so is to add a custom control and use the onClick on that control to get the state of the editor, is there another way to get the state of the editor, why can' t I get the state of the editor?? Please help out. Also please let me know how to make this editor a controlled input, I can give the value from the change and the onChange is hooked up to the state, whenever I try this, the editor starts typing in reverse and I am unable to fix that.

Update version of draftJS to 0.11.1

Editor is giving warning to update DraftJS on react as 'componentWillUpdate' has been renamed in the react version 17.x and is not recommended for use.

bundle size issue

I notice when you import MUI components, you are doing import { XXX } from '@material-ui/core'. This will result in the whole MUI package to be built into the bundle.

This should be updated to import XXX from '@material-ui/core/XXX'.

Problem with cursor

Hi, i try use this library but i have problem with cursor. I have render method where i render MUIRichTextEditor. I have state, which control what i have into textEditor. I try add onChange callback but when i try update my state every time when i write something in textEditor, cursor move to first position.

Do you have any idea how can i fix it? I don't want to use save callBack.

Code here

  export default class TextEditor extends React.Component {
     state = {
          editorState: '',
     }

     setEditorState(editorState) {
        this.setState({
             editorState: draftToHtml(convertToRaw(editorState.getCurrentContent())));
        })
      }

      getEditorValue() {
          const contentHTML = convertFromHTML(this.state.editorState);
          const state = ContentState.createFromBlockArray(contentHTML.contentBlocks, contentHTML.entityMap);

           return JSON.stringify(convertToRaw(state))
        }

       render() {
             return (
                  <MUIRichTextEditor 
                      controls={['title', 'bold', 'numberList', 'bulletList', 'undo', 'redo']}
                      label="Test"
                      onChange={::this.setEditorState}
                      value={this.getEditorValue()}
                  />
             )
       }

Problem with selecting inline styles when no text is selected

When trying to select an inline style (i.e. bold and italic) without any text selected, button is not marked. I'm unable to figure out what's causing this. This does not appear to be a problem in Draft.js demo on their official site. Are you able to help or point me in the right direction?

Small toolbar buttons

Is there a way to set the toolbar button as small using the Material UI size attribute?

Content is removed when creating URL in chrome.

When aliasing an URL in chrome the alias is removed when you press space or enter. When starting to type again the first character of the word will have the href tag on it, but not the whole word.
It looks like this
image
Only the Y becomes clickable after we try to write the name again after it has been removed.

This behavior does not exists in Firefox, edge dev or edge.
I'm not sure if this is a mui-rte issue or a draftjs issue though.

@material-ui/core dependency version

I'm currently using version 3.9.2 of @material-ui/core which the package.json of the latest version of this library suggests should be compatible. However I get the error:

Module not found: Can't resolve '@material-ui/core/ButtonGroup' in '/mnt/c/git/hivemind.on-demand.web/node_modules/mui-rte/dist'

What version of this library would be compatible with 3.x of @material-ui/core?

buttons in the toolbar are forced to be IconButton

Is it possible to override IconButton in the toolbar? May be CustomControl should propagate all of the props to IconButton so we can replace component in there (I would like to be able to insert something completely custom in there).

How do I focus the editor?

two cases:

  1. how do I focus the editor when it is mounted?
  2. how do I focus the editor when I click on certain area?

Thanks!

onChange restarting the cursor from the beginning

Hi @niuware, I have been using mui-rte in a Material UI dialog box. When I start to write the cursor is at the beginning, but when I write few words, then, the cursor again moves to the beginning. Therefore, I have to constantly move the cursor to write a sentence. I think onChange method is creating a problem, however, I cannot figure out what is causing the problem? Your help is highly appreciated.

Code:

const [post, setPost] = useState({
  content: '',
  answer_errors: {},
  open: false,
  errors: null
});

const handleChange = prop => event => {
  setPost({
    ...post,
    [prop]: JSON.stringify(convertToRaw(event.getCurrentContent()))
  });
};

<MUIRichTextEditor
  label="Write your aswer..."
  controls={[
    'bold',
    'italic',
    'underline',
    'highlight',
    'link',
    'media',
    'numberList',
    'bulletList',
    'quote'
  ]}
  inlineToolbar={true}
  onChange={handleChange('content')}
  value={post.content}
/>;

Image Upload Support (browse and clipboard)

Nice work.

Do you have plans to add clipboard paste support for images that will auto-upload to a configured URL? As a bonus if there were a configuration for direct integration with an S3 bucket without needing to host or use a Lambda as an intermediary, that would be nice.

EDIT:
Could we add handlePastedFiles to TDraftEditorProps?
That should allow me to pass a function to MUIRichTextEditor in my render that can handle the upload of the pasted image to S3 then insert it into the editor as a normal image reference to a URL.

What do you think?

Here's a sample handler I found:

handlePastedFiles (files) {
        let state = this.state.editorState;
        files.forEach( item => {
            this.uploadFile(item).then(res => {
                const contentStateWithEntity = state.getCurrentContent().createEntity('IMAGE', 'IMMUTABLE', { src: res.data })
                const entityKey = contentStateWithEntity.getLastCreatedEntityKey()
                const editorStateWithEntity = EditorState.set(state, {
                    currentContent: contentStateWithEntity
                });
                const newEditorState = AtomicBlockUtils.insertAtomicBlock(
                    editorStateWithEntity,
                    entityKey,
                    ' '
                );
                const newState = EditorState.forceSelection(
                    newEditorState,
                    newEditorState.getCurrentContent().getSelectionAfter()
                )
                this.setState({editorState: newState})
            })
        })
    }
```

Thanks in advance,
Rob

Unable to reset the editor

I am trying to reset the editor using the following commands:

const editorState = EditorState.createEmpty();
const updateEditorState = EditorState.set(editorState);

I read the document for reset in the examples folder and it does not work.

Also in the demo I tried using the clear icon to remove text with and without selecting the text, it does not work, can someone please look into this or help out, I really need this.

Additional header/title styles

the Title control ultimately maps to a H2 tag if I convert the content to html. How does one add additional header tags. I tried creating a custom block, but there doesn't seem to be a way to specify the style for something like draft-js-export-html to render additional header tags. Everything comes out as a paragraph tag.

eg:

<MUIRichTextEditor
     controls={["header-one"]}
     customControls={[
          {
                name: "header-one",
                type: "block",
                icon: <TitleIcon />,
                style: 'header-one',
                blockWrapper: <h1/>
          }                            
/>

Function to change value

Currently it is impossible to change value of MUIRichTextEditor after it's load. Sometimes I need to change value of MUIRichTextEditor after load. Because I receive some external data, that I need to set as MUIRichTextEditor value. Can you add feature to update value after first load.

make @material-ui/* peer dependency

if material-iu used in my project is older then material-ui used in mui-rte i see warning in console

Screen Shot 2020-04-27 at 8 33 04 AM

this means mui/styles is included twice and this will most likely break server side rendering

How to check if MUIRichTextEditor is empty?

Hi @niuware , thank you for your wonderful rich text editor package. I would like to know how do I check if MUIRichTextEditor is empty or not, because even if it is empty, there is some default object already created there.

Support for Draft JS plugins?

Hi again.

I wanted to add a custom draft-js mention plugin and realized that there is no option for that.

It would be really helpful to be able to pass plugins prop.

Support for custom styles?

Hey there. First of all thanks for this package, it was really straightforward to integrate with our current MUI-based codebase.

I've been going through the source code and noticed that the styles are hardcoded. I think it would be really handy if we could provide custom classes prop with the supported keys(i.e. container, editor, etc.).

Also it would be really helpful if the EditorControls component had its own class.

feature request: support draft decorators

Hi guys
you have support for decorators already but it does not work with draft decorators liek this one
https://github.com/SamyPesse/draft-js-prism
may be you can remove

        props.decorators.forEach(deco => decorators.push({
            strategy: (contentBlock: any, callback: any) => {
                findDecoWithRegex(deco.regex, contentBlock, callback)
            },
            component: deco.component
        }))

wrap current decorators in example folder in simpledecorator
and allow to use draft decorators directly?

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.