jpuri / draftjs-utils Goto Github PK
View Code? Open in Web Editor NEWAn collection of useful utility functions for DraftJS.
License: MIT License
An collection of useful utility functions for DraftJS.
License: MIT License
Hi there,
I've been trying to add an uppercase functionality to @jpuri 's editor but I can't find a way to add "textTransform" to customInlineStylesMap. Is there a way to add new inline styles to it?
Thank you!
E.g. if is set 'FONTSIZE' for one part of text, and same style but with different value for another, and we select the whole text, then getSelectionCustomInlineStyle
returns FONTSIZE: undefined
. Seams it should return an array of styles, like: ["fontsize-30", "fontsize-22"]
.
This can be reproduced in https://github.com/jpuri/react-draft-wysiwyg
I'm posting it here, because react-draft-wysiwyg
is utilizing this function, which should do its job better. :)
Hello,
I can't manage to use getSelectionCustomInlineStyle, the only doc says that we have to pass it an array of styles but what does it means ??
I tried ['MY_CUSTOM_STYLE_NAME']
and it returns an undefined on this.
Do I have to pass whole css structure as an array ?
Thank you for your time :)
Exception in inline.js line 240 of commit: 98d5c66
export function extractInlineStyle(editorState) {
if(editorState) {
const styleList = editorState.getCurrentContent().getBlockMap().map(block => block.get('characterList')).toList().flatten();
styleList.forEach(style => {
if (style && style.indexOf('color-') === 0) {
addToCustomStyleMap('color', 'color', style.substr(6));
} else if (style && style.indexOf('bgcolor-') === 0) {
addToCustomStyleMap('bgcolor', 'backgroundColor', style.substr(8));
} else if (style && style.indexOf('fontsize-') === 0) {
addToCustomStyleMap('fontSize', 'fontSize', style.substr(9));
} else if (style && style.indexOf('fontfamily-') === 0) {
addToCustomStyleMap('fontFamily', 'fontFamily', style.substr(11));
}
});
}
}
does
editorState.getCurrentContent().getBlockMap().map(block => block.get('characterList')).toList().flatten();
return Array<string>
?
I am a newbie.
This is best demonstrated with a GIF:
https://jsfiddle.net/thibaudcolas/Lo2zL37h/
Here I'm pressing return
once and then undoing it with ctrl + Z, but it takes two undo operations to get back to the pre-newline state.
The problem is that after insertNewUnstyledBlock
produces the split-block
change, removeSelectedBlocksStyle
makes a change-block-type
. This should be a single operation.
It might be enough to use Modifier.setBlockType(content, selection, 'unstyled')
directly in insertNewUnstyledBlock
. I'm happy to try and make a PR doing this.
Hey,
I would like to know if it is possible to use the toggleCustomInlineStyle method on an entity (RawDraftEntity) ?
For example, I have an html code with custom tags
<var data-name="$test">
I use htmlToDraft method for convert this code with a customChunkRenderer
private static customChunkRenderer(nodeName: string, node: HTMLElement): RawDraftEntity | undefined {
let draftEntity: RawDraftEntity | undefined;
if (nodeName === 'var') {
const data = {
name: node.dataset.name
};
draftEntity = {
type: VariableType,
mutability: 'IMMUTABLE',
data: data
};
}
return draftEntity;
}
When I want to change the text size of my item, with the toggleCustomInlineStyle method, I get the following error message
TypeError: record is undefined
removeStyle
.../node_modules/draft-js/lib/CharacterMetadata.js:56
53 | };
54 |
55 | CharacterMetadata.removeStyle = function removeStyle(record, style) {
> 56 | var withoutStyle = record.set('style', record.getStyle().remove(style));
| ^ 57 | return CharacterMetadata.create(withoutStyle);
58 | };
59 |
Then I want to retrieve the HTML code with the style applied to my item, with draftToHtml and my method customEntityTransform
private static customEntityTransform(...args): any {
const entity = args[0] as RawDraftEntity;
let value: string | undefined;
if (entity.type === VariableType) {
value = '<var data-name="' + entity.data.name + '">';
}
return value;
}
Thank you very much
I have the following code
_handleReturn(event) {
// Find out if user did a hard or soft newline
var editorState = handleNewLine(this.state.editorState, event);
if (editorState) {
this._onChange(editorState);
return true;
}
return false;
}
It does log a soft newline when using shift enter, but it still generates a new unstyled block instead of a /n
Any examples how i should handle this? I'm using DrafJS 0.10.1
trying to npm install or yarn install on https://github.com/zuiidea/antd-admin
gives me:
on npm:
npm ERR! addLocal Could not install xxx/node_modules/draftjs-utils
on yarn:
yarn install v0.27.5
info No lockfile found.
[1/4] Resolving packages...
error "xxx/draftjs-utils" doesn't exist.
I think this is related to recent new release from your packages
Hey I'm having trouble figuring out how toggleCustomInlineStyle
works.
I was successfully able to change the inline font-size by doing something like:
const newEditorState = toggleCustomInlineStyle(figure.editorState, 'fontSize', e.target.value);
this.setState({editorState: newEditorState})
but then when I wanted to do the same thing with font-weight, letter-spacing, etc... it doesn't work.
Is this function not supported? If so, how can I achieve it?
When importing this library I get the error that the window
is not defined as it is rendered on the server side.
In the js folder of this project the window is not used but when checking out the lib/draftjs-utils.js
I see that there is a reference to the window. It would be nice if you could alter it so it doesn't crash on SSR ๐ข
Sometimes you need to include line feeds in you selected text, so I it would be nice to do this:
const text = getSelectionText(editorState, "\n");
console.log(text);
And the result would be
> Dear Foo\nHow are you ?
I have to ship my app to IE users.
https://caniuse.com/#search=startsWith
I know that I can use a polyfill but, it's not obvious, and requires digging where startsWith was used.
Here is a link to a polyfill for those who need a quick fix
https://github.com/zloirock/core-js/blob/master/packages/core-js/modules/es.string.starts-with.js
// import 'core-js/stable/string/starts-with';
if your using es6 + webpack
I notice that the text-align attributes (really, anything in the "data" object of a block, but i dont think you are using it here for anything other than text-align) are not carried over to new blocks when hitting the enter key to create a new line. If i'm currently right aligned with my text, I would expect that alignment to continue when hitting the enter key for a new line (this is how bold, underline, lists, etc behave).
I found this issue on draftjs facebookarchive/draft-js#723 that suggests some workarounds that can be done for persisting things in the "data" object when splitting a block. Maybe something similar can be done here in the insertNewUnstyledBlock function https://github.com/jpuri/draftjs-utils/blob/master/js/block.js#L169 (though the name of the function might not make sense anymore if it were to persist styling from the current block)
Hello!!! I am curious if typescript typings is available. Please, let me know.
based on my test, it is possible that entity across multiple blocks. You can reproduce this by inputing multiple blocks in the editor, select multiple blocks, create and apply an entity to the selected blocks. it will work.(multiple entity decorators will be created for each block)
As shown in the figure, when I use the insertNewUnstyledBlock() in a block with content, I hope to jump out of this block and create a new unstyle block. The fact is that he did create a new block, but in the original block he seems to be executed. Like split-block, And I need to wrap it twice. can you guide me how to deal with this problem?
Hello @jpuri, thank you for such a great tool.
It looks like background color toggle doesn't work properly. You can specify background color, but can't toggle it back by clicking on the same color (the way it works with text color).
It might be caused by this line: https://github.com/jpuri/draftjs-utils/blob/master/js/inline.js#L211
const styleKey = styleType === 'bgcolor' ? 'backgroundColor' : styleType;
if (!currentStyle.has(`${styleKey}-${style}`)) {
currentStyle
contains bgcolor-rgb(...)
, but not the backgroundColor-rgb(...)
, might be a typo?
Reproducible on https://jpuri.github.io/react-draft-wysiwyg/#/
https://youtu.be/WJDcKKTH89E
With npm v7, I am unable to install this library alongside immutable
without using the --legacy-peer-deps
flag:
Package JSON:
{
...
"draftjs-utils": "0.10.2",
"immutable": "4.0.0-rc.12",
...
}
โ npm -v
7.0.8
โ node -v
v15.1.0
โ npm install
npm ERR! code ERESOLVE
npm ERR! ERESOLVE unable to resolve dependency tree
npm ERR!
npm ERR! While resolving: xxx
npm ERR! Found: [email protected]
npm ERR! node_modules/immutable
npm ERR! immutable@"4.0.0-rc.12" from the root project
npm ERR!
npm ERR! Could not resolve dependency:
npm ERR! peer immutable@"3.x.x || 4.x.x" from [email protected]
npm ERR! node_modules/draftjs-utils
npm ERR! draftjs-utils@"0.10.2" from the root project
npm ERR!
npm ERR! Fix the upstream dependency conflict, or retry
npm ERR! this command with --force, or --legacy-peer-deps
npm ERR! to accept an incorrect (and potentially broken) dependency resolution.
npm ERR!
npm ERR! See /Users/joncursi/.npm/eresolve-report.txt for a full report.
npm ERR! A complete log of this run can be found in:
npm ERR! /Users/joncursi/.npm/_logs/2020-11-10T11_15_54_545Z-debug.log
This will help a lot when I update the package version
Thanks a lot!
Here is a demo reproducing the issue, as well as a GIF:
https://jsfiddle.net/thibaudcolas/Lo2zL37h/
I could track this down to removeSelectedBlocksStyle
:
Lines 94 to 101 in 112bbe4
The error is because tryToRemoveBlockStyle
returns null
within code-block
(https://github.com/facebook/draft-js/blob/548fd5d1b1c31b7b4c79cd70b101fae69d522b3f/src/model/modifier/RichTextEditorUtil.js#L389-L396).
I think removeSelectedBlockStyle
should at least handle this gracefully, something like:
export function removeSelectedBlocksStyle(editorState: EditorState): EditorState {
const newContentState = RichUtils.tryToRemoveBlockStyle(editorState);
if (newContentState) {
return EditorState.push(editorState, newContentState, 'change-block-type');
}
return editorState;
}
For the purpose of handleNewLine
, the above wouldn't do anything on return though, which still isn't the right behaviour. Here is what I did in my code (not fully tested yet):
/**
* Rely on DraftUtils for soft newlines, and hard newlines that do not fall
* in the special "defer breaking out of the block" case.
*/
handleNewLine(editorState, event) {
if (isSoftNewlineEvent(event)) {
return DraftUtils.handleNewLine(editorState, event);
}
const content = editorState.getCurrentContent();
const selection = editorState.getSelection();
const key = selection.getStartKey();
const offset = selection.getStartOffset();
const block = content.getBlockForKey(key);
const isDeferredBreakoutBlock = ['code-block'].includes(
block.getType(),
);
if (isDeferredBreakoutBlock) {
const isEmpty =
selection.isCollapsed() &&
offset === 0 &&
block.getLength() === 0;
if (isEmpty) {
return EditorState.push(
editorState,
Modifier.setBlockType(content, selection, 'unstyled'),
'change-block-type',
);
}
return false;
}
return DraftUtils.handleNewLine(editorState, event);
},
I'm happy to submit a PR if this looks like a suitable solution.
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.