Coder Social home page Coder Social logo

draftjs-utils's People

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  avatar  avatar

draftjs-utils's Issues

Adding textTransform to customInlineStylesMap

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!

getSelectionCustomInlineStyle does not return values for multiple styles

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. :)

How to use getSelectionCustomInlineStyle ?

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 :)

Uncaught TypeError: e.indexOf is not a function

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.

handleNewLine does not produce the right undo stack when breaking out of a block

This is best demonstrated with a GIF:

https://jsfiddle.net/thibaudcolas/Lo2zL37h/

draftjs-utils-newline-undo-stack

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.

Error record is undefined when use toggleCustomInlineStyle on an entity (RawDraftEntity)

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

How do you use the handleNewLine utility

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

draftjs-utils doesn't exist

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

How to add custom inline styles for font-weight, letter-spacing, etc...

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?

Importing library on server side causes crash

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 ๐Ÿ˜ข

text-align not persisted on new lines

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)

Typescript typings?

Hello!!! I am curious if typescript typings is available. Please, let me know.

getEntityRange should return range for multiple blocks?

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)

How to use insertNewUnstyledBlock()?

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?

ๆœชๅ‘ฝๅ

Background color toggle

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

NPM v7 Install Issue

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

handleNewLine throws error when pressing enter at the end of a code block

Here is a demo reproducing the issue, as well as a GIF:

https://jsfiddle.net/thibaudcolas/Lo2zL37h/

draftjs-utils-code-block-error

I could track this down to removeSelectedBlocksStyle:

draftjs-utils/js/block.js

Lines 94 to 101 in 112bbe4

/**
* Function will change block style to unstyled for selected blocks.
* RichUtils.tryToRemoveBlockStyle does not workd for blocks of length greater than 1.
*/
export function removeSelectedBlocksStyle(editorState: EditorState): EditorState {
const newContentState = RichUtils.tryToRemoveBlockStyle(editorState);
return EditorState.push(editorState, newContentState, 'change-block-type');
}

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);
},

draftjs-utils-code-block-solution

I'm happy to submit a PR if this looks like a suitable solution.

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.