guardian / scribe

DEPRECATED: A rich text editor framework for the web platform
http://guardian.github.io/scribe/
Apache License 2.0
3.51k stars 245 forks source link

<img> split out of <figure> on Scribe.insertHTML() #423

Closed laurencedorman closed 9 years ago

laurencedorman commented 9 years ago

Hello, I'm trying to implement a way to insert images into a contenteditable="true" div using Scribe.

I place the cursor at what I assume to be the end of a line:

<p>Some text here</p>[CURSOR]
<p>Some more text here</p>
<p>Even more text here</p>

Call the function with the figure markup:

Scribe.insertHTML('
    <figure>
        <img src="http://..." />
        <figcaption>Caption</figcaption>
    </figcaption>
');

Result I would expect:

<p>Some text here</p>
<figure>
    <img src="http://..." />
    <figcaption>Caption</figcaption>
</figcaption>
<p>Some more text here</p>
<p>Even more text here</p>

Result I obtain:

<p>Some text here <img src="http://..." /></p>
<figure>
    <figcaption>Caption</figcaption>
</figcaption>
<p>Some more text here</p>
<p>Even more text here</p>

I'm not entirely familiar with everything Scribe does at the moment; is this some automatic formatter that's pulling apart the markup?

hmgibson23 commented 9 years ago

Hard to tell without stepping through but best guess would be that you're trying to put a block level element - in this case a <figure> - inside a <p> which is not allowed.

laurencedorman commented 9 years ago

Hadn't thought of that - so basically I need to make sure the cursor is actually at the end of a <p> and not inside it? Does Scribe have any helper functions for that sort of thing?

hmgibson23 commented 9 years ago

You should be able to check the position of the scribe markers and that will show you where the selection begins and ends.

laurencedorman commented 9 years ago

In the end I got around it in the following way:

  1. Create a selection with new scribe.api.Selection();
  2. Place a scribe marker with selection.placeMarkers();
  3. Get the HTML of the Scribe instance with scribe.getHTML();
  4. Find the marker index in the HTML string.
  5. Find the next <p> or </p>, whichever is closer.
  6. Split the string at this point (where the line ends) and insert the figure HTML.
  7. Join the string back together and remove the scribe marker em.
  8. Reinject the resulting markup with scribe.setHTML();

I'm guessing it's not really what would be recommended, but I can't think of a better way for now. The execCommand does too much stuff on its own; which leads me to think that I think my problem is with the native API, not Scribe.

laurencedorman commented 9 years ago

Ok, took the time to learn a bit more about how Scribe works and made a much better solution inspired by the Coursera table plugin. Will try and find the time to open source the plugin. Thanks for your help.

jackmoore commented 9 years ago

@ld0rman I hope you find the time, I would be interesting in seeing your plugin.