editor-js / paragraph

Paragraph Tool for Editor.js 2.0
MIT License
44 stars 125 forks source link

Add a new field for the `data` object in paragraph named: `dir` #43

Closed alirezakay closed 3 years ago

alirezakay commented 3 years ago

Hi, I have a request for a new feature.

I'm using on a project and I need to handle multilingual texts, both rtl and ltr ones. I dynamically change the direction style of a paragraph and that's not big of a deal. But I'm currently coping with how to save the direction to the data object so that I can save the whole data including the direction of each paragraph.

It's good if we could have sth like this: {dir: "ltr | rtl"}

...
      {
         "type": "paragraph",
         "data": {
            "text": "This is an rtl text",
            "dir": "rtl"
         }
      },
      {
         "type": "paragraph",
         "data": {
            "text": "Just an ltr text"
         }
      },
...
or2008 commented 3 years ago

@alirezakay +1 how do you dynamically change the direction style of a paragraph?

alirezakay commented 3 years ago

@alirezakay +1 how do you dynamically change the direction style of a paragraph?

In the onChange event handler of the Editor:

  const onChange = (api) => {
    const currIdx = api.blocks.getCurrentBlockIndex();
    const currBlock = api.blocks.getBlockByIndex(currIdx);
    if (currBlock) {
      const { innerText } = currBlock.holder;
      currBlock.holder.style.direction = getDir(innerText);
    }
  }

The getDir(innerText) function, gets a text and return the direction (i.e. "ltr" or "rtl"). you should detect the direction using regex and knowing the range of the alphabets of rtl languages like Arabic, Persian and ...

const weakChars = '\u0600-\u06FF\u0000-\u0040\u005B-\u0060\u007B-\u00BF\u00D7\u00F7\u02B9-\u02FF\u2000-\u2BFF\u2010-\u2029\u202C\u202F-\u2BFF';
const rtlChars = '\u0591-\u07FF\u200F\u202B\u202E\uFB1D-\uFDFD\uFE70-\uFEFC';

const rtlRegex = new RegExp('^([' + weakChars + '])*[' + rtlChars + ']', 'u');

const getDir = (text) => {
  const isRTL = rtlRegex.test(text);
  let dir = 'ltr';
  if (isRTL) {
    dir = "rtl";
  }
  return dir;
}

P.S. The range of rtl languages and the regex form are adopted from a fine answer from StackOverflow and unfortunately, I don't have the URL to mention here!

orbachar commented 3 years ago

@alirezakay Amazing! I didn't know you can get current block index from Editorjs, that what I was missing

thanks for sharing this clean code.

P.S here is the stackoverflow URL https://stackoverflow.com/questions/12006095/javascript-how-to-check-if-character-is-rtl