rob-race / react-trix Goto Github PK
View Code? Open in Web Editor NEWReact wrapper around Trix editor from Basecamp + some lightweight features
License: ISC License
React wrapper around Trix editor from Basecamp + some lightweight features
License: ISC License
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
customize toolbar for customize showing menu
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;
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.
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!
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
}
}
}
Should the CSS be included or do I need to get that from elsewhere?
We are using this library in a project that needs/uses React & React Dom 16.2 - any chance you can ensure react-trix supports React 16.2..? That would be awesome thanks..
If I type '@' the dropdown appears, and if I remove the '@', the dropdown is still there.
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?
I see nothing but a div :'(
Is it made for trolling purposes or am i having problem with loading trolling.dll into my brain address-space?
https://github.com/souporserious/react-trix/blob/master/src/Trix.jsx
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
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
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
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);
};
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
npm start
and the warning shows up. I've tried copying and pasting the src folder into the node_modules/react-trix folder.
This version isn't compatible with the current version scheme of React, which jumped from 0.14.x
to 15.x.y
.
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!
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!
Hi Team,
I am really impressed with the Trix editor notes functionality . We recently integrated the Trix editor into our React project. The Trix editor is working well; we can add attachments and save content without issues. However, we need help displaying the content in a readable format. Currently, it only shows the text within the editor.
Can you please tell us how to display the Trix content on a normal page?
Used the below React wrapper for Trix :-
https://github.com/rob-race/react-trix
Thanks,
Rahul
The suggested usage of Trix is incorrect.
editor.insertText("editor is ready");
This should be change to editor.insertString("editor is ready");
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!
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
How do we just grab the plain text of the content?
Thanks!
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)
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?
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:
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>
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.
autoFocus doesn't work
<TrixEditor
autoFocus={true}
onChange={(html, text) => setEdit(html)}
onEditorReady={(e) =>console.log("editor ready ", e)}
placeholder="Type your comment here..."
/>
Trix is now at 1.2.0
Could you upgrade please?
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.