Giter Club home page Giter Club logo

react-trix-rte's Introduction

React Trix RTE

NPM GitHub Workflow Status npm

React Trix rich text editor is react wrapper built for the Trix editor created by Basecamp. We have built this library because we were rewriting the same component in multiple project.

This wrapper uses React hooks and adds readable event listeners on the Trix editor. The library also adds two toolbar components which has the ability to customize the toolbar actions as per our need.

Demo

Please see the some live example on ReactTrixRTE-Storybook

ReactTrixRTE

Installation

To install the React Trix RTE, run the following command in the console.

npm install react-trix-rte
OR
yarn add react-trix-rte

Usage

import Trix from "trix";
import React, { useState } from "react";
import { ReactTrixRTEInput } from "react-trix-rte";

export default function TrixEditor(props) {
  const [value, setValue] = useState("");

  function handleChange(event, newValue) {
    setValue(newValue); // OR custom on change listener.
  }

  return (
    <ReactTrixRTEInput
      defaultValue="<div>React Trix Rich Text Editor</div>"
      onChange={handleChange}
    />
  )
}

Upgrading to 1.0.7 or higher

React Trix RTE version 1.0.7 removes the dependency import for Trix because using Trix outside directly causes problems. Read issue: 17 and 19.

Import import Trix from "trix"; to the component using React Trix RTE.

ReactTrixInput API

ReactTrixInput is the Trix editor input which by default comes with the toolbar. The ReactTrixInput comes with following properties that could be accepted.

Name Type Description
id string The HTML id attribute for the input field
name string The HTML name attribute for the input field
toolbarId string If a custom toolbar is used for the Trix Input, pass the toolbarId of the custom toolbar to the input.
isRailsDirectUpload boolean React Trix editor support direct uploading of the files to the service if you are using Rails as a backend server. This defaults to false
railsDirectUploadUrl string Custom URL for Rails direct upload (data-direct-upload-url)
railsBlobUrl string Custom URL for Rails blob template (data-blob-url-template)
placeholder string Adds a placeholder to the React Trix Input
defaultValue string The default value of the React Trix Input
autofocus boolean Autofocus in the trix input. This is defaults to false
className string Apply a custom css class to the editor
trixInputRef function Adds a custom ref to the React Trix Input to programmatically edit text. Read the documentation for manual things you can perform on Trix editor here
onBeforeInitialize function Fires when the <trix-editor> element is attached to the DOM just before Trix installs its editor object.
onInitialize function Fires when the <trix-editor> element is attached to the DOM and its editor object is ready for use.
onChange function Fires whenever the editor’s contents have changed.
onSelectionChange function Fires any time the selected range changes in the editor.
onBlur function Fire when the editor loses focus.
onFocus function Fire when the editor gains focus.
onFileAccepted function Fires when a file is dropped or inserted into the editor. You can access the DOM File object through the file property on the event. Call preventDefault on the event to prevent attaching the file to the document.
onAttachmentAdd function Fires after an attachment is added to the document. You can access the Trix attachment object through the attachment property on the event. If the attachment object has a file property, you should store this file remotely and set the attachment’s URL attribute. See the attachment example for detailed information.
onAttachmentRemove function Fires when an attachment is removed from the document. You can access the Trix attachment object through the attachment property on the event. You may wish to use this event to clean up remotely stored files.

ReactTrixRTEToolbar API

ReactTrixRTEToolbar is the custom Trix editor toolbar component. This component helps in customizing the toolbar options, classes and attributes in better way.

Name Type Description
toolbarId string The ReactTrixInput initialize the default toolbar if the toolbarId is missing or not matching. Make sure the toolbarId matches.
disableGroupingAction boolean Defaults to false. If the disableGroupingAction is enabled the toolbar actions are not grouped for a type. Example: text tools won't be grouped
toolbarActions array Allows customizing the list of toolbar actions. The available actions are ["bold", "italic", "strike", "link", "heading1", "quote", "code", "bullet", "number", "outdent", "indent", "attachFiles", "undo", "redo"].
customToolbarActions object Override the toolbar actions properties or add custom toolbar actions. You can refer to default toolbar actions options

Custom Toolbar Usage

import React, { useState } from "react";
import Trix from "trix";
import { ReactTrixRTEInput, ReactTrixRTEToolbar } from "react-trix-rte";

export default function TrixEditor(props) {
  const [value, setValue] = useState("");

  function handleChange(event, newValue) {
    setValue(newValue); // OR custom on change listener.
  }

  return (
    <Fragment>
      <ReactTrixRTEToolbar toolbarId="react-trix-rte-editor" />
      <ReactTrixRTEInput
        toolbarId="react-trix-rte-editor"
        defaultValue="<div>React Trix Rich Text Editor</div>"
        onChange={handleChange}
      />
    </Fragment>
  )
}

Contributing

Read more about contributing to the ReactTrixRTE.

Author

Abhay Nikam

Contributor

CUnknown

License

This project is licensed under the MIT License

react-trix-rte's People

Contributors

abhaynikam avatar ajclaasen avatar alejo4373 avatar axxxx0n avatar cunknown avatar dependabot[bot] avatar mech avatar othercroissant avatar radhenazarkar 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

Watchers

 avatar  avatar  avatar

react-trix-rte's Issues

Warning in console

Hi!

Receiving an error message in the console:

Warning: g: Support for defaultProps will be removed from function components in a future major release. Use JavaScript default parameters instead.
    at g (webpack-internal:///(app-pages-browser)/./node_modules/react-trix-rte/dist/index.js:1:29553)
    at span
    at w (webpack-internal:///(app-pages-browser)/./node_modules/react-trix-rte/dist/index.js:1:31197)
    at div
    at trix-toolbar
    at k (webpack-internal:///(app-pages-browser)/./node_modules/react-trix-rte/dist/index.js:1:31713)
    at div
    at TrixEditor
    at BailoutToCSR (webpack-internal:///(app-pages-browser)/./node_modules/next/dist/shared/lib/lazy-dynamic/dynamic-bailout-to-csr.js:13:11)

Using @react-trix-rte with nextjs 14

Upgrade Trix to v2

Hi,

Is there a way to upgrade the Trix from v1.3.1 to v2.0.8 as it fix quite a bit of Safari bugs.

Regards

Support for Mentions?

Is there documented, or undocumented, support for mentions?

I have a list of users, but am wondering what's the preferred way to attach them to the react-trix-rte component in order to allow mentions.

Storybook is out of date

I'd like to update storybook to take advantage of the updated API around adding parameters and decorators to stories.

Error: Invalid hook call. when using <ReactTrixRTEInput/> component

I am trying to implement this RTE and I keep getting Error: Invalid hook call.

I installed 'trix' with yarn add trix and I installed react-trix-rte the same way.

This is the code that is producing the error:

import React, { useState, useContext } from 'react'
import { Typography, Container, Paper, TextField } from '@material-ui/core'
import { makeStyles } from '@material-ui/core/styles'
import { AppContext } from '../../AppContext'
import Trix from 'trix'
import { ReactTrixRTEInput } from 'react-trix-rte'

const useStyles = makeStyles(theme => ({
    root: {
        flexGrow: 1,
        padding: 20,        
    },
    paper: {
        display: "flex",
        flexDirection: "column",
        alignItems: "center",
        backgroundColor: "white",
        padding: 20
    },
    inputBox: {
        marginTop: 20,
        width: "80%"
    },
    input: {
        width: "100%",
        marginBottom: 20
    }
})) 

export default function NewAnnouncementScreen() {

    const classes = useStyles()
    const app = useContext(AppContext)

    const [title, setTitle] = useState("")
    const [value, setValue] = useState("")
  
    function handleChange(event, newValue) {
        setValue(newValue); // OR custom on change listener.
    }

    return (        
        <div className={classes.root}>
            <Container>
                <Paper className={classes.paper}>
                    <Typography variant="h3">Create new Announcement</Typography>

                    <div className={classes.inputBox}>
                        <TextField
                            label="Announcement Title"
                            value={title}
                            onChange={e => setTitle(e.target.value)}
                            variant="outlined"
                            className={classes.input}
                        />
                        
                        <ReactTrixRTEInput
                            defaultValue="<div>Enter your announcement here</div>"
                            onChange={handleChange}
                        />
                    </div>                    
                </Paper>                
            </Container>            
        </div>                
    )
}

Am I missing an obvious mistake here or is it something else?

These are the versions that got installed:

    "react-trix-rte": "^1.0.9",
    "trix": "^1.3.1",

Add highlight text tool in the toolbar

The highlight tool in the toolbar should be able to help with applying some predefined colors to the rich text and highlight the content.

  • Should be part of text tool.
  • Add documentation.
  • Add predefined colors similar to Basecamp.
  • Add storybook.
  • Add changelog

Inspiration: Basecamp.

Uncaught NotSupportedError: Failed to execute 'registerElement' on 'Document': Registration failed for type 'trix-toolbar'. A type with that name is already registered.

I have a Rails project that's being gradually ported over to React. I need to render a Trix editor in both the old Rails UI and the new React UI. React-trix-rte throws Uncaught NotSupportedError: Failed to execute 'registerElement' on 'Document': Registration failed for type 'trix-toolbar'. A type with that name is already registered. when require('trix') is present in application.js.

I can get around this by adding the check window.customElements.get("trix-editor")|| before r.registerElement("trix-editor") and window.customElements.get("trix-toolbar")|| before r.registerElement("trix-toolbar") in the minified JS but I can't seem to find where to add this check in the non-minified source of either this project or trix itself.

Thoughts on how to get around this issue? Thank you for your time!

Copy & paste

Hey,
is there a handler like add attachment for when an image is copied and pasted here..
Please help ASAP..
great work on the library BTW

Encounter editor being unmounted, but something still setting the state

Not sure if this is related with the way I try to lazy load the editor to solve windows problem. In my Next.js, I load the editor like so:

const TrixEditor = dynamic(() => import("form-controls/TrixEditor"), {
  ssr: false,
  loading: () => <p>Loading editor...</p>,
});

However, after I navigate to elsewhere and start typing, I have this warning:

Warning: Can't perform a React state update on an unmounted component.
This is a no-op, but it indicates a memory leak in your application.
To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function.

at u (webpack-internal:///./node_modules/react-trix-rte/dist/index.js:1:23242)
at div
at TrixEditor (webpack-internal:///./form-controls/TrixEditor.js:92:24)
at LoadableImpl (webpack-internal:///./node_modules/next/dist/shared/lib/loadable.js:103:38)
....

Using window causes server side rendering to fail

Hi!

I tried to use react-trix-rte in SSR context. Of couse this means no window or document object exist, but the editor tries to access that.

This is the error I am getting:

ReactOnRails::PrerenderError in Posts#index

ERROR in SERVER PRERENDERING
Encountered error: "ReferenceError: window is not defined"
when prerendering Posts with props: {"initialPosts":{"data":[{"id":"a3b49222-9d4d-482f-92fd-d5953b066330","type":"post","attributes":{"id":"a3b49222-9d4d-482f-92fd-d5953b066330","aliasName":null,"content":"","voteCount":1,"qliqTitle":"valami","qliqUri":"hello","qliqUserUri":null,"slug":"hello","title":"hello","username":"eee","createdAt":"2020-11-29T22:02:58.611Z","updatedAt":"2020-11-29T22:02:59.567Z","linkId":null,"mediaId":null,"pollingId":null,"postItemId":"a3b49222-9d4d-482f-92fd-d5953b066330","qliqId":"47d7391a-3ee7-49cf-9dc
... TRUNCATED ...
":"7ada051c-ec5a-4bec-b6f0-fbf26c86b005","aliasName":null,"content":null,"voteCount":1,"qliqTitle":"Heiiihooo","qliqUri":"heihoo","qliqUserUri":null,"slug":"valami","title":"valami","username":"eee","createdAt":"2020-09-20T21:24:33.472Z","updatedAt":"2020-09-20T21:24:33.472Z","linkId":null,"mediaId":null,"pollingId":null,"postItemId":"7ada051c-ec5a-4bec-b6f0-fbf26c86b005","qliqId":"ef0373c7-d6ee-47e3-8c43-69e4caec991d","userAliasId":"b6cdbf5e-fa37-49fa-b074-0b90b3033e95","fullUri":"/heihoo"}}]}}

code:

        (function() {
          var railsContext = {"railsEnv":"development","inMailer":false,"i18nLocale":"en","i18nDefaultLocale":"en","rorVersion":"12.0.0","rorPro":false,"href":"http://localhost:3000/","location":"/","scheme":"http","host":"localhost","port":3000,"pathname":"/","search":null,"httpAcceptLanguage":"hu,en-US;q=0.9,en;q=0.8,ru;q=0.7,fr;q=0.6","serverSide":true};
              ReactOnRails.clearHydratedStores();

          var props = {"initialPosts":{"data":[{"id":"a3b49222-9d4d
... TRUNCATED ...
,"mediaId":null,"pollingId":null,"postItemId":"7ada051c-ec5a-4bec-b6f0-fbf26c86b005","qliqId":"ef0373c7-d6ee-47e3-8c43-69e4caec991d","userAliasId":"b6cdbf5e-fa37-49fa-b074-0b90b3033e95","fullUri":"/heihoo"}}]}};
          return ReactOnRails.serverRenderReactComponent({
            name: 'Posts',
            domNodeId: 'Posts-react-component-653bc907-72f5-43f5-84a2-b73ca4f2f561',
            props: props,
            trace: true,
            railsContext: railsContext
          });
        })()

n ((execjs):36004:7)
a ((execjs):36006:37)
t.exports ((execjs):36152:139)
Object.(execjs) (<anonymous>:35957:9)
r ((execjs):35858:19)
Module.(execjs) (<anonymous>:36242:5)
r ((execjs):35858:19)
(execjs):35894:18
(execjs):35895:4
(execjs):35843:128

Related gems used:

gem 'jquery-rails'
gem 'webpacker', '~> 5'
gem 'mini_racer', platforms: :ruby
gem "react_on_rails", "= 12.0.0

Code used:

import * as React from 'react';
import { ReactTrixRTEInput, ReactTrixRTEToolbar } from "react-trix-rte";
import { PostItem } from "./PostItem";

export interface PostEditorProps {
  post: PostItem;
}

export const PostEditor = ({ post }: PostEditorProps) => {
  function handleChange(event, newValue) {
    //... todo ...
  }

  return (
    <>
      <ReactTrixRTEToolbar toolbarId="react-trix-rte-editor" />
      <ReactTrixRTEInput
        toolbarId="react-trix-rte-editor"
        defaultValue="<div>Please, be nice!</div>"
        value={ post.content }
        isRailsDirectUpload={ true }
        onChange={handleChange}
      />
    </>);
};

Disable toolbar button turning off the text style

Hi, I have a custom toolbar button which able to change the font color. After I changed the font color (e.g red), and I would like to change the font color from red to blue, when I clicked on the toolbar button, it will turn off the font color.

So, is there any way to disable the toolbar button which performing turning on and off of the text style?

getUniqInputId is not always unique

Hello, and thank you for your great work on this project!

I think I have found a little bug in the utils.js file. If the getUniqInputId() is called twice within the same millisecond, it will return the same result. In that case, the getUniqInputID() will not return unique IDs.

export const getUniqInputId = (prefix = 'react-trix-rte-input-') => {
const uniqueDateTimestamp = new Date().getTime();
return `${prefix}${uniqueDateTimestamp}`
}

These ID collisions can cause some issues when rendering many <ReactTrixRTEInput> elements at the same time.

I am not very familiar with the performance constraints of this package and whether it would be worth the effort, but I think using the uuid package to generate these IDs would ensure they are unique.

Another suggestion I can think of is adding a Math.random() addition to salt the current implementation with a random number.

Please let me know what you think of these suggestions, I would love to write a PR and help out!

Thank you again for all your work, it's been great to work with!

Multiple instances trigger same onChange event

Hello,

I'm trying to use 2 instances of ReactTrixRTEInput on the same page, by giving them different IDs, but they trigger the same onChange event, so the content get mixed up when they end up in the state.

Here's a reproduction of the issue:
https://codesandbox.io/s/react-trix-rte-hsxql

My workaround at the moment is to manually check which input triggered the onChange event, but that's not very elegant:

onChange={(e) =>
    e.target.getAttribute("input") === "react-trix-1" && setFirstValue(e.target.value)
}

Have you seen this issue before?

Thank you for your help,
Nicolas

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.