HTMLSerializer - Grouped images

Hey @thejuniperstudio,

This is a really interesting question! We had a conversation about it internally to discuss the best way to do it. The solution we came up with is a bit complex. Basically, when you render a rich text field, you pass a function invocation that accepts your Rich Text array as an argument and returns your HTML Serializer. :point_left: Let's call this the "intermediary" function. In a plain JavaScript implementation, that would look like this:

PrismicDom.RichText.asHtml(
  text,
  linkResolver,
  htmlSerializerIntermediary(text)
)

As a result, the intermediary will have inside it the rich text field that you are processing and also your HTML Serializer function (which is meant to process each element of the rich text array, one at a time). So, the intermediary will allow the HTML Serializer to compare the current element in the Rich Text array against the rest of the array and customize the output conditionally, like this:

const htmlSerializerIntermediary = (richText) => {
  const htmlSerializer = (type, element, content, children) => {
  const index = richText.findIndex((el) => JSON.stringify(el) === JSON.stringify(element))
    if (richText[index - 1]?.type === type) {
      return `<p class="sibling">${element.text}</p>`
    }
    switch (type) {
      case Elements.paragraph:
        return `<p>${element.text}</p>`
      default:
        return `<span>${element.text}</span>`
    }
  }
  return htmlSerializer
}

Sorry, I probably didn't explain that very well! I'm still wrapping my head around it :laughing:

I've attached a file that brings it all together. (Again, this is with our basic JavaScript packages — you will need to tweak it for React.) Please take a look and let me know if it makes any sense:

complex-serializer.js (1.0 KB)

Sam