Code Monkey home page Code Monkey logo

react-trix's Introduction

React Trix 0.10.2

React wrapper around Trix editor from Basecamp. With additional features that I needed when I was CTO at Roadmap when sending emails and collaborating with comments.

Getting started

Install via npm

npm install react-trix --save

Trix will be included as dependency. You should already have React installed.

Usage

Make sure you have the latest Trix JavaScript and optionally their CSS on pages where you are using react-trix.

Classic script tag

<script src="https://rawgit.com/basecamp/trix/master/dist/trix.js"></script>

Or via npm

npm i trix
import "trix/dist/trix";

If you're using npm version with SSR make sure to import trix on page level.

import * as React from "react";
import { TrixEditor } from "react-trix";

export class Test extends React.Component {
  handleEditorReady(editor) {
    // this is a reference back to the editor if you want to
    // do editing programatically
    editor.insertString("editor is ready");
  }
  handleChange(html, text) {
    // html is the new html content
    // text is the new text content
  }
  render() {
    return (
      <TrixEditor onChange={this.handleChange} onEditorReady={this.handleEditorReady} />
    );
  }
}

Properties

Those are the optional properties you can use on the <TrixEditor />.

New in v0.7.0

The default name for the file upload is file. You may use the fileParamName to change its name, for instance blob to work with Ruby on Rails.

let mergeTags = [{
  trigger: "@",
  tags: [
    {name: "Dominic St-Pierre", tag: "@dominic"},
    {name: "John Doe", tag: "@john"}
  ]
}, {
  trigger: "{",
  tags: [
    {name: "First name", tag: "{{ .FirstName }}"},
    {name: "Last name", tag: "{{ .LastName }}"}
  ]
}]
<TrixEditor
  className="custom-css-class"
  autoFocus={true}
  placeholder="editor's placeholder"
  value="initial content <strong>for the editor</strong>"
  uploadURL="https://domain.com/imgupload/receiving/post"
  uploadData={{"key1": "value", "key2": "value"}}
  fileParamName="blob"
  mergeTags={mergeTags}
  onChange={on_change_handler}
  onEditorReady={on_editor_ready_handler}
/>

Merge tags

You give a trigger character, for example "@" and when the user type this character a small popup suggestions will be displayed where user can click and the tag will be added.

You may customize the suggestion box via the CSS class react-trix-suggestions like this:

.react-trix-suggestions {
  /* for the container */
}

.react-trix-suggestions a {
  /* for each suggestion */
}

Running the tests

Still having some issues testing Trix with enzyme/jsdom.

Contributions

Contributions are welcome and appreciated.

react-trix's People

Contributors

alexcameron7 avatar bradrees avatar cguess avatar dependabot[bot] avatar drd avatar dstpierre avatar huntermeyer avatar jusmat avatar pixyj avatar plantfansam avatar rob-race avatar souporserious avatar tobiasberg 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

react-trix's Issues

Shouldn't check for 204 status code for upload

Currently, the file upload part of this (awesome!) library checks for a "204 No Content" status code, and then goes on to read its responseText.

Regardless of whether it is actually possible to send a 204 and also send content (which doesn't seem to be the case on my webserver - but that might be a config thing), I don't think this is correct. Can this perhaps be made configurable, perhaps with a more sensible default like 201?

Cheers!

Trix loses CSS upon refresh/reload

I'm running into some weird behavior where if I refresh or reload a page with this Trix React component, the CSS disappears. I've attached screenshots of the behavior in my app. I'm using styled-components and I've attached my code for the component. I've added trix.css to my public folder.

with css

without css

import React from 'react';
import styled from 'styled-components';
import { TrixEditor } from 'react-trix';

export const Wrapper = styled.div`
  width: 690px;
  background: #fff6df;
  border-radius: 6px;
`;

export const TextBox = (props) => {
  return (
    <>
      <Wrapper style={props.style}>
        <TrixEditor
          onChange={props.onChange}
          value={props.value}
          onEditorReady={props.onEditorReady}
        />
      </Wrapper>
    </>
  );
};

Any guidance would be great. Thanks!

autoFocus doesn't work

autoFocus doesn't work

 <TrixEditor
 autoFocus={true}
 onChange={(html, text) => setEdit(html)}
 onEditorReady={(e) =>console.log("editor ready ", e)}
 placeholder="Type your comment here..."
 />

NextJS SSR Problem

Hi, I'm using nextjs along with this react-trix,
I found some exception,
When the page load (for the first time), its returning an error
Warning: Did not expect server HTML to contain a <trix-toolbar> in <div>.
editor not found

However when I try to load other page first , then change my route to the page that have trix editor, there's no problem, the problem is only when I load the page that have trix editor for the first time

image

npm install not working

It seems there's a problem with react-addons-test-utils in this package.

I am unable to npm install to be able to build

$ npm install
npm WARN deprecated [email protected]: This package is unmaintained. Use @sinonjs/formatio instead
npm WARN deprecated [email protected]: no longer maintained
npm ERR! code ETARGET
npm ERR! notarget No matching version found for react-addons-test-utils@^16.4.0
npm ERR! notarget In most cases you or one of your dependencies are requesting
npm ERR! notarget a package version that doesn't exist.
npm ERR! notarget
npm ERR! notarget It was specified as a dependency of 'react-trix'
npm ERR! notarget

npm ERR! A complete log of this run can be found in:
npm ERR!     /home/billd/.npm/_logs/2018-10-16T20_44_22_575Z-debug.log

Is it compatible with React 16.4?

React 16.4

import React, { Component } from "react";
import { TrixEditor } from "react-trix";
import "trix/dist/trix-core";
import "trix/dist/trix";
import "trix/dist/trix.css";

export default class WysiwygEditor extends Component {
  handleEditorReady(editor) {
    // this is a reference back to the editor if you want to
    // do editing programatically
    editor.insertText("editor is ready");
  }
  handleChange(html, text) {
    // html is the new html content
    // text is the new text content
  }
  render() {
    return (
      <TrixEditor
        onChange={this.handleChange}
        onEditorReady={this.handleReady}
      />
    );
  }
}
ReferenceError: navigator is not defined
    at Object.<anonymous> (/Volumes/Data/www/code-pilots/vacancy-frontend/node_modules/trix/dist/trix-core.js:6:244)
    at Object.<anonymous> (/Volumes/Data/www/code-pilots/vacancy-frontend/node_modules/trix/dist/trix-core.js:6:343)
    at Object.<anonymous> (/Volumes/Data/www/code-pilots/vacancy-frontend/node_modules/trix/dist/trix-core.js:6:356)
    at Object.<anonymous> (/Volumes/Data/www/code-pilots/vacancy-frontend/node_modules/trix/dist/trix-core.js:11:21015)
    at Module._compile (internal/modules/cjs/loader.js:678:30)
    at Module._compile (/Volumes/Data/www/code-pilots/vacancy-frontend/node_modules/source-map-support/source-map-support.js:492:25)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:689:10)
    at Module.load (internal/modules/cjs/loader.js:589:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:528:12)
    at Function.Module._load (internal/modules/cjs/loader.js:520:3)

It's not easy to initial value from API

Normal way is not working. The editor is only show the start value is 000.

class MyTrixEditor extends Component {
  state = { content: '000' }

  componentDidMount () {
    loadFromAPI().then(r => { this.setState({ content: r.data }) })
  }

render () {
    return (
      <Editor
        mergeTags={null}
        value={this.state.content}
        onChange={this.handleChange}
        onEditorReady={this.handleEditorReady}
      />
    )
  }
}

I have to do something like this:

class MyTrixEditor extends Component {
  editor = null
  handleEditorReady = editor => {
    this.editor = editor
  }

  componentDidUpdate (prevProps, prevState, snapshot) {
    const { content } = this.state
    if (content && content !== prevState.content && this.editor) {
      this.editor.loadHTML('') // do this to avoid weird position of cursor
      this.editor.insertHTML(content)
      this.editor = null    // must add this to avoid repeat insert new value
    }
  }
}

Allow basic keyboard controls of merge tags

Hi there!

One small improvement to the merge tags would be to allow the user to press UP and DOWN to navigate the options, and ENTER to select. Otherwise, the user is required to move their hands from the keyboard while typing.

I wanted to offer the idea for you to implement since its your project, but I'll happily open a PR for it! I'll be needing the functionality shortly so I'll share the love!

In case you want to finish this, I updated/commented a few things

It works really well, thanks a lot.

import React, { PropTypes } from 'react';

// with ExtractTextPlugin (cannot do that in a npm non-root package)
// but you can put it in the doc
import 'trix/dist/trix.css';

// They do clever stuff on window.Trix, you can't use export/import loaders as suggested here:
// https://github.com/basecamp/trix/issues/80
// Instead we do the dumbest thing possible with webpack, use the script loader.
// Acceptable since the file is already minified and has no reusable dependencies.
// npm i script-loader -S
import 'script!trix/dist/trix.js';

// There are 2 flows possible for updates:

// 1. regular user flow: User types stuff -> this.editor.value + trix-change -> this.props.onChange
// 2. forced flow (reset...): this.props.value -> this.editor.value (trix-change not triggered)
class TrixEditor extends React.Component {

  // 1. For the first flow we forward trix-change events to this.props.onChange
  componentDidMount() {
    this.editor = document.getElementById(`editor-${this._id}`);
    this.editor.addEventListener('trix-change', this.props.onChange);
    this.editor.addEventListener('trix-initialize', this.props.onChange);
  }

  // 2. Value is not read after initialization (See https://github.com/spiffytech/trix/commit/0e19f2cadb5cd0092fe6b16c25919f0c4ae387de)
  // so for the second flow, we need to check that we are not at the end of the feedback loop
  // of the firt flow and update Trix' value
  componentWillReceiveProps(nextProps) {
    if (nextProps.value !== this.editor.value) {
      this.editor.value = nextProps.value;
    }
  }

  // We don't need to update on this.props.value changes since Trix won't read it anyway.
  shouldComponentUpdate() {
    return false;
  }

  componentWillUnmount() {
    this.editor.removeEventListener('trix-change', this.props.onChange);
    this.editor.removeEventListener('trix-initialize', this.props.onChange);
  }

  _id = this._generateId()

  // I don't get it, I guess you took it from someone who did ;)
  _generateId() {
    let timestamp = Date.now();
    let uniqueNumber = 0;

    (() => {
      // If created at same millisecond as previous
      if (timestamp <= uniqueNumber) {
        timestamp = ++uniqueNumber;
      } else {
        uniqueNumber = timestamp;
      }
    })();

    return 'T' + timestamp;
  }

  render() {
    // http://stackoverflow.com/questions/25553910/one-liner-to-take-some-properties-from-object-in-es6
    const forwardedProps = ({ toolbar }) => ({ toolbar });
    return (
      <div>
        <trix-editor id={`editor-${this._id}`} input={`input-${this._id}`}/>
        <input type="hidden" id={`input-${this._id}`} value={this.props.value} {...forwardedProps(this.props)}/>
      </div>
    );
  }
}

TrixEditor.propTypes = {
  onChange: PropTypes.func.isRequired,
  value: PropTypes.string,
  toolbar: PropTypes.object
};


export default TrixEditor;

Documentation is not up to date

The suggested usage of Trix is incorrect.
editor.insertText("editor is ready");

This should be change to editor.insertString("editor is ready");

"editor not found" when using inside modal

Hi,

so i used this editor quite a while inside a modal of my ui libary.
when updating create-react-app to the latest react-scripts version (also included a webpack major update), i get an error
editor not found from inside this component.

This is not an issue outside a modal. It doesn't matter if i render the modal initially or not.

I'm using the latest versions of react-scripts, antd, trix and react-trix

I've created codesandbox to illustrate the problem:
https://codesandbox.io/s/elastic-diffie-sovxvb?file=/src/App.js

onChange, onEditorReady events not firing on Firefox with version 0.2.0

After upgrading to 0.2.0, I get the following error from the component that uses Trix:

Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object. Check the render method of `TextAreaInput`.

I can't tell what has changed in react-trix or trix itself that might trigger this error; the usage seems to correspond to the examples pretty closely:

https://github.com/WikiEducationFoundation/WikiEduDashboard/blob/30611248d982c1d9281c901b7b2b353314b930bd/app/assets/javascripts/components/common/text_area_input.jsx#L50

Is CSS missing?

Should the CSS be included or do I need to get that from elsewhere?

Upgrade Trix to 1.0.0

Hi @dstpierre thank you for the great package!

Was wondering if it would be possible to upgrade the package to use trix 1.0.0, since they releases a few cool new features like image galleries etc.

A quick fix is to manually import the latest JS and CSS, and then the latest features work.

<link href="https://rawgit.com/basecamp/trix/master/dist/trix.css" rel="stylesheet">
<script src="https://rawgit.com/basecamp/trix/master/dist/trix.js"></script>

But integration into the package would be awesome.

I tried forking your repo and rebuilding myself, but I'm fairly new to react packages and am unsure how exactly to do this. Would love to contribute if you have any help or direction on how to get started.

Thanks!

Bug: more than one trixeditor

Because of the way id's are generated this editor can only be used once per form. Otherwise there are duplicate id's and the events are fired for each control.

I suggest using a UUID instead of the current time to create the ID

Firebase Upload URL issue

I am trying to use this with Firebase but am having issues getting the uploadURL to work.
The images are not getting uploaded to Firebase

my form :

<form class="comment-form" onSubmit={this.handleSubmit} onFocus={this.handleFocus}>
<div className="form-group comment-reply-content">
                        
<TrixEditor
      autoFocus={true}
      placeholder="editor's placeholder"
      value="initial content <strong>for the editor</strong>"
      uploadURL="https://firebasestorage.googleapis.com/v0/b/boomapp-8d7cc.appspot.com/o/"
      uploadData={{"key1": "value", "key2": "value"}}
      mergeTags={mergeTags}
      onChange={this.handleChange}
       onEditorReady={this.handleEditorReady}
/>
</div>
<div className="form-group">
          <input type="submit" className="btn btn-primary"  />
</div>
</form>

Is there a reason why `mergeTags` is required?

I am trying to test this out for a use case, I don't think I would need mergeTags props as a functionality. If you could advise on how to get around it or the reason why it's a required prop.

Custom Key Name for "file"

currently the XHR request send the file as a blob in the key value pair "file": blob, however this is not compatiable with Ruby on Rails. This should be customisable. Rails expects a "blob" parameter

Styles is missing

After installing I can't find trix.css for styles import.

image

Where I can take styles for editor?

Needed additional props

Hi there. I saw this issue #28. It is also needed to have possibility to pass locales (trix uses locales like this) and hide buttons via props.

Additional field values are not parsing from form data

I am trying to send additional form data through the uploadData props. From the code it seems to be that these object should go to each form fields, correct?

uploadData={{ "fileName": "test_file", "projectId": "PRID123", "userEmail": "[email protected]", }}

Then I am using busboy to parse the multipart-data with NodeJS as follows:

    //This code will process each non-file field in the form.
    busboy.on('field', (fieldname, val) => {
      //TODO(developer): Process submitted field values here
      console.log(`Processed field ${fieldname}: ${val}.`);
      fields[fieldname]= val;
    });

However, only the first field name returns in the code
> Processed field Content-Type: application/pdf.

which is ok, but not the others I have just passed. I was expecting to happen those from the following source code:

  private uploadAttachment(attachment: any) {
    var file, form, xhr;
    file = attachment.file;
    form = new FormData();
    // add any custom data that were passed
    if (this.props.uploadData) {
      for (var k in this.props.uploadData) {
        form[k] = this.props.uploadData[k];
      }
    }
    form.append("Content-Type", file.type);
    form.append("file", file);
    xhr = new XMLHttpRequest();
    xhr.open("POST", this.props.uploadURL, true);
    xhr.upload.onprogress = (event) => {
      var progress = event.loaded / event.total * 100;
      return attachment.setUploadProgress(progress);
    };

Failed to parse source map

image

The TrixEditor component shows up as desired, but I get this source map parse failed warning. To reproduce, create a new react app, then

npm i react-trix
npm i trix

include component:
image

npm start

and the warning shows up. I've tried copying and pasting the src folder into the node_modules/react-trix folder.

Plain text

How do we just grab the plain text of the content?

Thanks!

The component is not initiallizing

I am retrieving text from an API and then setting the state with the results.

I have set the "value" of the component to the same property on the state as the results.

However, the component is either not receiving or rejecting the text.

When I start typing, and using the onChange event to update the property my text appears .

Any ideas?

'editor not found' in chrome extension iframe

I'm trying to integrate this package into a chrome extension to no avail. I keep getting editor not found in the console. Building with React v16.12 a Webpack v4.41.6

I believe it's because I'm injecting the react app as an iframe into each web page (using react-frame-component), so the document element is different.

I tried passing the iframe's document through props on TrixEditor and and editing the componentDidUpdate in react-trix.js, and it seemed to work. Maybe the package could have an optional prop document to pass in a custom document object?

But still can't get it to fully work, as now I can't get the editor to initialize or fire the onEditorReady. I believe it's an issue with trix core (context: #759), but I've hit a wall.

Any suggestions on where to keep digging or what it might be?

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.