prismicio/javascript-kit — pull request #57 by pauldijou (2014-07-10 02:23:03+00:00)
Title: Fix spans rendering

Hi guys,

Sorry to tell you this, but [this function](https://github.com/prismicio/javascript-kit/blob/ccf56d2427606772a66acb0143854c3f6b5cb2e5/src/fragments.js#L717-L758) is total crap. It's not that it has a small bug in it, it is just fundamentally wrong. I can't help myself wondering if someone has ever tested it...

Ok, now that I said it, let me explain why: the method will iterate over all the spans of the current fragment and for each one, it will move the cursor forward. Yeah, you read it well: for each span, move the cursor forward. Meaning that if you put two different styles on the same portion of text, it will move to the starting point, apply the first style, and then continue forward to apply the second style to the following text. Wait... what?

```html

Hey, I am awesome!

Hey, I am awesome!
```

Tooooooo bad dude... For that reason, I fully re-implemented it with a new approach based on saving positions of all opening / closing tags, in correct order (meaning reverse order for closing tags), and then iterating over that to generate the final HTML.

(I also love how [spans are just pushed on tags](https://github.com/prismicio/javascript-kit/blob/ccf56d2427606772a66acb0143854c3f6b5cb2e5/src/fragments.js#L737), just creating a pure copy of the spans... talk about useless)

On the same topic, there is a strange behaviour when the span is an hyperlink, which, by the way, broke a current test, but well... Most of the time, the `span.data` will be a valid fragment, but sometimes, from the `micro` repository, for an unknow reason, it will be only the value of the fragment.

```javascript
// It should always be like:
span.data = {
type: 'Link.document',
value: {document: Document, isBroken: false}
};

// But sometime, it is:
span.data = {
document: Document,
isBroken: false
};
```

I wrote a dirty patch for that, with a big `FIXME`. Would be good to investigate why the API is returning such a value.

At least but no last, I decided to expose the `insertSpans` in the API of the `Prismic.Fragments` object because it is super useful to have it when you want to override the `asHtml` function but still call the original `insertSpan` from the Kit.

That's all folks, enjoy.