How to reproduce medium.com editor's "embed media" button with Mobiledoc-kit?

282 Views Asked by At

We are building an editor and decided to use Mobiledoc-kit to overcome contentEditable limitations.

And as we really, really enjoy medium.com editor's simplicity we are trying to reproduce its "insert media" functionality, which is "to allow media insertion only on the empty lines" what roughly translates to the empty section in default the mobiledoc-kit scenario. That way behavior consists of two events:

  • show button/allow insertion when there is no other content in the current line
  • hide/disallow insertion in opposite case.

In order to achieve that I'm trying to:

  • observe "enter" key press to show button
  • observe section length to hide/show button

I still didn't figure out how to detect "enter" key press and method that I'm using to detect section length postEditor.editor.range.tail.section.length returns previous section length inside both didUpdatePost and willRender callbacks.

This was my first day with mobiledoc-kit and any feedback on whether I choose correct path or not and suggestions how to proceed further on are really, really appreciated.

1

There are 1 best solutions below

1
On BEST ANSWER

The cursorDidChange hook (docs here) is likely what you will want to use.

You can observe cursor movement and react when the cursor is in an empty markup section, e.g.:

editor.cursorDidChange(() => {
  // if the range isn't collapsed (i.e., the user has selected some text),
  // just return
  if (!editor.range.isCollapsed) { return; }

  // head is a mobiledoc-kit position object.
  // range consists of two positions: head and tail.
  // For a collapsed range, head === tail
  let head = editor.range.head;

  // section can be a markup section (contains user-editable text
  // or a card section. All sections have an `isBlank` method
  let section = head.section;
  if (section.isBlank) {
    // the cursor is in a blank section; show the media insertion UI
  }
});