Extending Quill to support soft line breaks

Viewed 1473

I'm attempting to extend Quill with a custom Blot to allow newlines inside of <p> tags. Per the advice given by the library author, I eventually landed on code that looks like this:

import * as Quill from 'quill';

const Delta = Quill.import('delta');
const Embed = Quill.import('blots/embed');

export class SoftLineBreakBlot extends Embed {
    static blotName = 'softbreak';
    static tagName = 'br';  
    static className = 'softbreak';
}

export function shiftEnterHandler(this: any, range) {    
    const currentLeaf = this.quill.getLeaf(range.index)[0];
    const nextLeaf = this.quill.getLeaf(range.index + 1)[0];    
    this.quill.insertEmbed(range.index, "softbreak", true, Quill.sources.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, "softbreak", true, Quill.sources.USER);
    }
    // Now that we've inserted a line break, move the cursor forward
    this.quill.setSelection(range.index + 1, Quill.sources.SILENT);    
}

export function brMatcher(node, delta) {
    let newDelta = new Delta();
    newDelta.insert({softbreak: true});
    return newDelta;
}

I'm using the ngx-quill wrapper around Quill, in an Angular 10 project. My Quill module is defined like so:

QuillModule.forRoot({
      format: 'json',
      modules: {
        keyboard: {
          bindings: {
            "shift enter": {
              key: 13,
              shiftKey: true,
              handler: shiftEnterHandler
            }
          }
        },
        clipboard: {
          matchers: [            
             [ "BR", brMatcher ]
          ],          
        }
      },
    }),

However, whenever I press Shift+Enter, my cursor moves forward, but the insertEmbed() call appears to have no effect. What am I doing wrong?

1 Answers

It looks like you just forgot to call Quill.register(SoftLineBreakBlot)

So:

...
export class SoftLineBreakBlot extends Embed {
    static blotName = 'softbreak';
    static tagName = 'br';  
    static className = 'softbreak';
}
...

Becomes:

...
export class SoftLineBreakBlot extends Embed {
    static blotName = 'softbreak';
    static tagName = 'br';  
    static className = 'softbreak';
}
Quill.register(SoftLineBreakBlot);
...
Related