Editing an entity's decorated text - draftjs

We have a Figure decorator which allows us to insert a link which you can hover over to get a preview of an image. We insert this image along with some metadata (caption, etc.) using a modal form. This all works great. However we also want the ability to click the link and pop up the modal to edit it.
Entity.replaceData() works great for updating the metadata, the only problem that remains is the decorated text which comes from the modal too. It appears the Entity knows little to nothing about the content it's decorating.
How can we find and replace the text? Is there a way around this?
(I've tried setting the content in Draft to an arbitrary single character and making the decorator show the content/title (which would be fine), however when trying to delete the figure, Draft seems to jump over the content and delete something before it. I guess it's due to different text lengths. I thought setting it as 'IMMUTABLE' would solve this but that didn't help.)
EDIT:
Here's my decorator:
function LinkedImageDecorator(props: Props) {
Entity.mergeData(props.entityKey, { caption: "hello world" });
const entity = Entity.get(props.entityKey);
const data = entity.getData();
return <LinkedImage data={data} text={props.children} offsetKey={props.offsetKey} />
}
function findLinkedImageEntities(contentBlock: ContentBlock, callback: EntityRangeCallback) {
contentBlock.findEntityRanges((character) => {
const entityKey = character.getEntity();
return (
entityKey != null &&
Entity.get(entityKey).getType() === ENTITY_TYPE.IMAGE
);
}, callback);
}
export default {
strategy: findLinkedImageEntities,
component: LinkedImageDecorator,
editable: false,
};
As you can see, I'm testing out Entity.mergeData which will eventually be the callback of my LinkedImage component (which would open a modal onClick.) So the metadata is easy to update, I just need to be able to update the decorated text which is passed in as props.children.

So I finally solved this with the help of Jiang YD and tobiasandersen. Here goes...
First I inject my decorator with a reference to my editor (which keeps track of EditorState):
const decorators = new CompositeDecorator([{
strategy: findLinkedImageEntities,
component: LinkedImageDecorator,
props: { editor: this }
}];
this.editorState = EditorState.set(this.editorState, { decorator });
From there I can do this in my LinkedImageDecorator:
const { decoratedText, children, offsetKey, entityKey, editor } = this.props;
// This looks messy but seems to work fine
const { startOffset, blockKey } = children['0'].props;
const selectionState = SelectionState.createEmpty(blockKey).merge({
anchorOffset: startOffset,
focusOffset: startOffset + decoratedText.length,
});
const editorState = editor.getEditorState();
let newState = Modifier.replaceText(
editorState.getCurrentContent(),
selectionState,
"my new text",
null,
entityKey,
);
editor.editorState = EditorState.push(editorState, newState, 'insert-fragment');
Not sure if this is the cleanest way of doing this but it seems to work well!

just put the global component instance reference in the decorator props.
const compositeDecorator = new CompositeDecorator([
{
strategy: handleStrategy,
component: HandleSpan,
props: {parent:refToYourComponentWhichContainsTheEditorState}
}
props.parent.state.editorState.getCurrentContent()

Related

In DraftJs How to re adjust the cursor after setting the state via decorator and strategy?

Problem: Loses focus when selected the hash tag.
Example: type #on and select any tag the editor is losing the focus.
In above codepen: how can I add/retain cursor after the hash tag?
Following this article
https://bigbite.net/2017/12/13/building-editor-draft-js-react/
Code from this article.
https://codepen.io/bigbite/pen/gXNOvz
I've to add that in my own use case.
UC: While editing the content in editor when user presses the key combination then show a dropdown, which will contain the custom react component name, and user will be able to select the custom component and it will add that component via decorator and strategy.
It has been achieved but the editor loses its focus at the same time.
I can achieve the focus via ref this.editor.focus() but shows the cursor at the start of the editor.
const addEntityAndComponent = (editorState, content) => {
const contentState = editorState.getCurrentContent();
const selection = editorState.getSelection();
const contentStateWithEntity = contentState.createEntity(content, 'IMMUTABLE', { content });
const entityKey = contentStateWithEntity.getLastCreatedEntityKey();
const newContentState = Modifier.insertText(contentStateWithEntity, selection, content, null, entityKey);
const newEditorState = EditorState.push(editorState, newContentState);
return EditorState.forceSelection(newEditorState, newContentState.getSelectionAfter());
};
I'm using the lib to achieve the functionality.
https://github.com/jpuri/react-draft-wysiwyg/
Here is my code.
https://github.com/iozeey/react-draft-wysiwyg-custom-component
Hope it will be helpful.
Followed this doc.
https://draftjs.org/docs/advanced-topics-managing-focus
Tried solution from here but did not work.
https://draftjs.org/docs/api-reference-editor-state#movefocustoend
I was using this package.
https://github.com/jpuri/react-draft-wysiwyg/blob/master/src/Editor/index.js#L348
My solution was to reset the cursor position after focusing the editor.
focus() {
const se = this.state.editorState.getSelection();
this.editor.focus();
this.setState({
editorState: EditorState.forceSelection(this.state.editorState, se),
});
}

Is there a onScroll event for ag-grid

I am looking for a scroll event on ag-grid, I want to know when the scroll reaches the end and load the next set of rows, I know if you set the infinite scroll mode then ag-grid calles the getRows method, but in my application I do not get the next set of rows right away, I make a call to the server and server sends a separate message to the client with the new set of rows
After getting in deep, I found the perfect solution to this problem.
Please note here I am used AngularJS, But very easy to understand.
onBodyScroll:function(params) {
var bottom_px = $scope.gridOptions.api.getVerticalPixelRange().bottom;
var grid_height = $scope.gridOptions.api.getDisplayedRowCount() * $scope.gridOptions.api.getSizesForCurrentTheme().rowHeight;
if(bottom_px == grid_height)
{
alert('Bottom')
}
},
There's a grid event called 'onBodyScroll' which you can attach an event handler to it.
This event is somewhat secret as it was not there on their GridOptions type before version 18, even though it does work.
see this comment: https://github.com/ag-grid/ag-grid-enterprise/issues/89#issuecomment-264477535
They do have this event in document tho: https://www.ag-grid.com/javascript-grid-events/#miscellaneous
BodyScrollEvent
bodyScroll - The body was scrolled horizontally or vertically.
onBodyScroll = (event: BodyScrollEvent) => void;
interface BodyScrollEvent {
// Event identifier
type: string;
api: GridApi;
columnApi: ColumnApi;
direction: ScrollDirection;
left: number;
top: number;
}
You should be able to do that thing (loading the data from the server) as per below example.
First of all, define your dataSource.
const dataSource: IServerSideDatasource = {
getRows: (params: IServerSideGetRowsParams) => this._getRows(params, [])
};
this.gridApi.setServerSideDatasource(dataSource);
Declare _getRows method like this.
private _getRows(params: IServerSideGetRowsParams, data: any[]) {
this.gridApi.showLoadingOverlay();
service.getData(params) // the payload your service understands
.subscribe((result: any[]) => {
params.successCallback(result, -1);
params.failCallback = () => console.log('some error occured while loading new chunk of data');
this.gridApi.hideOverlay();
},
error => this._serverErrorHandler(error)
);
}
This is pretty much self-explanatory. Let's me know if anything is unclear to you.
BTW, I've used typescript for the example, javascript example would be kind of the same for ag-grid-react

Angular 2, dynamic forms; updateValue() do not update checkbox form control

I'm building a angular 2 (2.0.0-rc.4) application with the new form API (2.0.2) and i've got a problem when i'm trying to update checkbox form controls with updateValue().
This is what i've done:
I've built a dynamic form with the new form API (based on the section in the cookbook: https://angular.io/docs/ts/latest/cookbook/dynamic-form.html). I've extended the form class to also handle checkboxes:
export class FormControlCheckbox extends FormBase <string> {
controlType: string;
options: { key: string, value: string, checked: boolean } [] = [];
checked: boolean = false;
constructor(options: {} = {}) {
super( options );
this.controlType = "checkbox";
this.options = options['options'] || [];
this.checked = this.options[0].checked;
}
}
This is what it looks like when it's created:
new FormControlCheckbox({
type: "checkbox",
label: 'A label',
name: "a-name",
value: "",
description: "a description",
options: [
{
label: 'A label',
name: "a-name",
checked: false
}
],
})
When the application are loaded the form controls are created and grouped together, everything works fine and the form get submitted as intended. I only had to do a workaround to make the checkbox update on change and the markup are as followed:
<input [formControlName]="control.key" [(ngModel)]="control.checked" [id]="control.key" [type]="control.controlType" [attr.checked]="control.checked ? true : null" [value] = "control.checked" (change)="control.checked = $event.target.checked">
I've also tried this markup (it also works fine):
<input [formControlName]="control.key" [(ngModel)]="control.checked" [id]="control.key" [type]="control.controlType" [attr.checked]="control.checked ? true : null" [value] = "control.checked" (change)="control.checked = check.checked" #check>
This is where my problem occurs
I'm adding a feature that updates the control values when the form just have been loaded (the user should be able to revisit the page and update previous values). The code below update all the control values.
for (var key in new_values) {
//the form control keys are the same as the key in the list of new_values
this.form.controls[key].updateValue(new_values[key]); //works for text, select and option
this.form.controls[key].updateValueAndValidity(); //not sure if needed?
this.form.controls[key].markAsDirty();
}
Text, option and select inputs gets updated but the checkboxes are unchanged. No errors or warnings. I've searched a lot for similar problems but have not found a similar problem or a solution.
Am I missing something obvious? Or have somebody had the same problem and want to share their solution?
Thanks!
Solved the problem by changing the values before creating the control-groups (before this it's possible to change the values (ex. x.value). It solved my problem but do not solve the fact that dynamically changes to checkbox form controls are not reflected in the DOM element.

Create an instance of a React class from a string

I have a string which contains a name of the Class (this is coming from a json file). This string tells my Template Class which layout / template to use for the data (also in json). The issue is my layout is not displaying.
Home.jsx:
//a template or layout.
var Home = React.createClass({
render () {
return (
<div>Home layout</div>
)
}
});
Template.jsx:
var Template = React.createClass({
render: function() {
var Tag = this.props.template; //this is the name of the class eg. 'Home'
return (
<Tag />
);
}
});
I don't get any errors but I also don't see the layout / Home Class. I've checked the props.template and this logs the correct info. Also, I can see the home element in the DOM. However it looks like this:
<div id='template-holder>
<home></home>
</div>
If I change following line to:
var Tag = Home;
//this works but it's not dynamic!
Any ideas, how I can fix this? I'm sure it's either simple fix or I'm doing something stupid. Help would be appreciated. Apologies if this has already been asked (I couldn't find it).
Thanks,
Ewan
This will not work:
var Home = React.createClass({ ... });
var Component = "Home";
React.render(<Component />, ...);
However, this will:
var Home = React.createClass({ ... });
var Component = Home;
React.render(<Component />, ...);
So you simply need to find a way to map between the string "Home" and the component class Home. A simple object will work as a basic registry, and you can build from there if you need more features.
var components = {
"Home": Home,
"Other": OtherComponent
};
var Component = components[this.props.template];
No need to manually map your classes to a dictionary, or "registry", as in Michelle's answer. A wildcard import statement is already a dictionary!
import * as widgets from 'widgets';
const Type = widgets[this.props.template];
...
<Type />
You can make it work with multiple modules by merging all the dictionaries into one:
import * as widgets from 'widgets';
import * as widgets2 from 'widgets2';
const registry = Object.assign({}, widgets, widgets2);
const widget = registry[this.props.template];
I would totally do this to get dynamic dispatch of react components. In fact I think I am in a bunch of projects.
I had the same problem, and found out the solution by myself. I don't know if is the "best pratice" but it works and I'm using it currently in my solution.
You can simply make use of the "evil" eval function to dynamically create an instance of a react component. Something like:
function createComponent(componentName, props, children){
var component = React.createElement(eval(componentName), props, children);
return component;
}
Then, just call it where you want:
var homeComponent = createComponent('Home', [props], [...children]);
If it fits your needs, maybe you can consider something like this.
Hope it helps.
I wanted to know how to create React classes dynamically from a JSON spec loaded from a database and so I did some experimenting and figured it out. My basic idea was that I wanted to define a React app through a GUI instead of typing in code in a text editor.
This is compatible with React 16.3.2. Note React.createClass has been moved into its own module.
Here's condensed version of the essential parts:
import React from 'react'
import ReactDOMServer from 'react-dom/server'
import createReactClass from 'create-react-class'
const spec = {
// getDefaultProps
// getInitialState
// propTypes: { ... }
render () {
return React.createElement('div', null, 'Some text to render')
}
}
const component = createReactClass(spec)
const factory = React.createFactory(component)
const instance = factory({ /* props */ })
const str = ReactDOMServer.renderToStaticMarkup(instance)
console.log(str)
You can see a more complete example here:
https://github.com/brennancheung/02-dynamic-react/blob/master/src/commands/tests/createClass.test.js
Here is the way it will work from a string content without embedding your components as statically linked code into your package, as others have suggested.
import React from 'react';
import { Button } from 'semantic-ui-react';
import createReactClass from 'create-react-class';
export default class Demo extends React.Component {
render() {
const s = "return { render() { return rce('div', null, rce(components['Button'], {content: this.props.propA}), rce(components['Button'], {content: 'hardcoded content'})); } }"
const createComponentSpec = new Function("rce", "components", s);
const componentSpec = createComponentSpec(React.createElement, { "Button": Button });
const component = React.createElement(createReactClass(componentSpec), { propA: "content from property" }, null);
return (
<div>
{component}
</div>
)
}
}
The React class specification is in string s. Note the following:
rce stands for React.createElement and given as a first param when callingcreateComponentSpec.
components is a dictionary of extra component types and given as a second param when callingcreateComponentSpec. This is done so that you can provide components with clashing names.
For example string Button can be resolved to standard HTML button, or button from Semantic UI.
You can easily generate content for s by using https://babeljs.io as described in https://reactjs.org/docs/react-without-jsx.html. Essentially, the string can't contain JSX stuff, and has to be plain JavaScript. That's what BabelJS is doing by translating JSX into JavaScript.
All you need to do is replace React.createElement with rce, and resolve external components via components dictionary (if you don't use external components, that you can skip the dictionary stuff).
Here is equivalent what in the code above. The same <div> with two Semantic UI Buttons in it.
JSX render() code:
function render() {
return (
<div>
<Button content={this.props.propA}/>
<Button content='hardcoded content'/>
</div>
);
}
BabelJS translates it into:
function render() {
return React.createElement("div", null, React.createElement(Button, {
content: this.props.propA
}), React.createElement(Button, {
content: "hardcoded content"
}));
}
And you do replacement as outlined above:
render() { return rce('div', null, rce(components['Button'], {content: this.props.propA}), rce(components['Button'], {content: 'hardcoded content'})); }
Calling createComponentSpec function will create a spec for React class.
Which then converted into actual React class with createReactClass.
And then brought to life with React.createElement.
All you need to do is return it from main component render func.
When you use JSX you can either render HTML tags (strings) or React components (classes).
When you do var Tag = Home, it works because the JSX compiler transforms it to:
var Template = React.createElement(Tag, {});
with the variable Tag in the same scope and being a React class.
var Tag = Home = React.createClass({
render () {
return (
<div>Home layout</div>
)
}
});
When you do
var Tag = this.props.template; // example: Tag = "aClassName"
you are doing
var Template = React.createElement("aClassName", null);
But "aClassName" is not a valid HTML tag.
Look here

How do I submit a form using a store under ExtJs?

Is there a way to have a form submit create an object in a store under ExtJs 4?
It seems strange to me that the grid is built completely around the store mechanism and I see no obvious way to plug a form into a store. But I am most likely just missing something.
You can add a model instance to a store upon form submit using this code:
onSaveClick: function()
{
var iForm = this.getFormPanel().getForm(),
iValues = iForm.getValues(),
iStore = this.getTasksStore();
iStore.add( iValues );
},
This is within an MVC controller, so this is the controller.
For model editing, you can 'bind' a form to a model instance using loadRecord:
iFormPanel.loadRecord( this.selection );
You can then update the model instance using updateRecord():
iFormPanel.getForm().updateRecord();
Just for fun (and as it might help some), it is similar to the following code:
onSaveClick: function()
{
var iForm = this.getFormPanel().getForm(),
iRecord = iForm.getRecord(),
iValues = iForm.getValues();
iRecord.set ( iValues );
},
If your store is has autoSync: true. An Update (or Create) call will be made via the configured proxy. If there's no autoSync, you'll have to sync your store manually.
You can subclass Ext.form.action.Action to provide load/save actions for a Form to be performed on a Store. The only gotcha is that somehow there's no "official" way to select any non-standard Action in Ext.form.Basic, so I'd suggest an unofficial override:
Ext.define('Ext.form.Advanced', {
override: 'Ext.form.Basic',
submit: function(options) {
var me = this,
action;
options = options || {};
action = options.submitAction || me.submitAction;
if ( action ) {
return me.doAction(action, options);
}
else {
return me.callParent(arguments);
}
},
load: function(options) {
var me = this,
action;
options = options || {};
action = options.loadAction || me.loadAction;
if ( action ) {
return me.doAction(action, options);
}
else {
return me.callParent(arguments);
}
}
});
And, having created the Actions you need, you could then use them in a Form Panel:
Ext.define('My.form.Panel', {
extend: 'Ext.form.Panel',
requires: [ 'Ext.form.Advanced' ],
loadAction: 'My.load.Action',
submitAction: 'My.submit.Action',
...
});
There are other ways and shortcuts though.