3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Quill で「Shit + Enterで改行」する方法

Posted at

エディタライブラリのQuillで「Shit + Enterで改行」する方法。
https://github.com/quilljs/quill

なお、Quill標準の動作で、改行はpタグの段落となります。

解決方法

いくつか対応するコードが見つかりますが、こちらの実装が最もスマートな方法だと思います。
https://codepen.io/mackermedia/pen/gmNwZP

var Delta = Quill.import('delta');
let Break = Quill.import('blots/break');
let Embed = Quill.import('blots/embed');

function lineBreakMatcher() {
  var newDelta = new Delta();
  newDelta.insert({'break': ''});
  return newDelta;
}

class SmartBreak extends Break {
  length () {
    return 1
  }
  value () {
    return '\n'
  }
  
  insertInto(parent, ref) {
    Embed.prototype.insertInto.call(this, parent, ref)
  }
}

SmartBreak.blotName = 'break';
SmartBreak.tagName = 'BR'

Quill.register(SmartBreak)

var options = {
  theme: 'bubble',
  modules: {
    clipboard: {
      matchers: [
        ['BR', lineBreakMatcher] 
      ]
    },
    keyboard: {
      bindings: {
        linebreak: {
          key: 13,
          shiftKey: true,
          handler: function (range) {
            let currentLeaf = this.quill.getLeaf(range.index)[0]
            let nextLeaf = this.quill.getLeaf(range.index + 1)[0]

            this.quill.insertEmbed(range.index, 'break', true, 'user');

            // Insert a second break if:
            // At the end of the editor, OR next leaf has a different parent (<p>)
            if (nextLeaf === null || (currentLeaf.parent !== nextLeaf.parent)) {
              this.quill.insertEmbed(range.index, 'break', true, 'user');
            }

            // Now that we've inserted a line break, move the cursor forward
            this.quill.setSelection(range.index + 1, Quill.sources.SILENT);
          }
        }
      }
    }
  }
};

var quill = new Quill('.editor', options);  

var length = quill.getLength()
var text = quill.getText(length - 2, 2)

// Remove extraneous new lines
if (text === '\n\n') {
  quill.deleteText(quill.getLength() - 2, 2)
}

議論

どうも、Smart Break (Shift+Enter改行)のニーズはあるものの、本家では標準機能化することに乗り気では無い様子です。
QuillはHTMLエディタではなく、リッチテキストエディタだから、というのが理由のようですね。
https://github.com/quilljs/quill/issues/252
https://github.com/quilljs/quill/issues/1187

段落と改行の差を意識しなくて良いような、エディタの設計にする方が正しいかもしれません。

3
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?