editor-js / underline

Inline tool for underlining text fragments
18 stars 22 forks source link

Simpler implementation #19

Closed emad-elsaid closed 1 year ago

emad-elsaid commented 2 years ago

I noticed the bold tool that comes with the core editor uses execCommand and plugins are using another method. there is a problem with the approach that prevent user from applying the tool to a sentence then tries to remove one word of this sentence.

The issue is that it tried to get the tags around the text which will remove the whole tag and replace the sentence with just the text that was highlighted/selected.

Anyway I ended up reimplementing this tool using execCommand

class Underline {
  static get isInline() { return true; }
  static get title() { return "Underline"; }
  static get sanitize() { return { U: {} }; }

  constructor({api}) {
    this.api = api;
    this.commandName = "underline";
    this.button = null;
  }

  render() {
    this.button = document.createElement('button');
    this.button.type = 'button';
    this.button.textContent = 'U';
    this.button.classList.add(this.api.styles.inlineToolButton);
    this.button.style.textDecoration = "underline";
    return this.button;
  }

  surround(range) { document.execCommand(this.commandName); }

  checkState(selection) {
    const isActive = document.queryCommandState(this.commandName);
    this.button.classList.toggle(this.api.styles.inlineToolButtonActive, isActive);
    return isActive;
  }
}

I used the same approach to implement strikethrough too

class StrikeTool {
  static get isInline() { return true; }
  static get title() { return "Strike"; }
  static get sanitize() { return { strike: {} }; }

  constructor({api}) {
    this.api = api;
    this.commandName = "strikeThrough";
    this.button = null;
  }

  render() {
    this.button = document.createElement('button');
    this.button.type = 'button';
    this.button.textContent = 'S';
    this.button.classList.add(this.api.styles.inlineToolButton);
    this.button.style.textDecoration = "line-through";
    this.button.style.fontWeight = "bold";
    return this.button;
  }

  surround(range) { document.execCommand(this.commandName); }

  checkState(selection) {
    const isActive = document.queryCommandState(this.commandName);
    this.button.classList.toggle(this.api.styles.inlineToolButtonActive, isActive);
    return isActive;
  }
}
nickolasjadams commented 2 years ago

Does this fix the problem with creating shortcuts for underline as well?

evanjmg commented 2 years ago

This works so well! Thank you @emad-elsaid

mrinmays commented 2 years ago

Does this fix the problem with creating shortcuts for underline as well?

You can fix this by simply adding

static get shortcut() {
  return 'CMD+U'; // <-- key binding of your preference
}

to the above-mentioned class.