Ais-Highlight breaking on Nuxt Client-Only (No-ssr)

Hello team,

I’m creating a multi index search inside a client-only component with Nuxt and I’ve noticed that the ais-highlight component breaks pretty badly in this scenario.

Reproduction sandbox

Steps for reproduction

  1. Type something in the search box (the text will be highlighted in yellow).
  2. Hit backspace you remove a character from the search.
  3. The rendering breaks and instead of showing the yellow highlight it renders the tag.

Is there anything wrong with the code or a way to avoid this behavior?

Vue-Instantsearch bug issue

Hi @joao, thanks for bringing this up. Our team will follow-up on the GH issue you created here: https://github.com/algolia/vue-instantsearch/issues/773. (Just re-linking in case anyone else is experiencing this and looking for answers.)

From that GH issue, here is a shared workaround (remaking highlight on your side, without relying on InstantSearch’ highlighting):

vue
<template>
  <div class="ais-Highlight" v-html="innerHtml"></div>
</template>

<script>
function getPropertyByPath(object, path) {
  const parts = path.split('.');

  return parts.reduce((current, key) => current && current[key], object);
}

const htmlEscapes = {
  '&': '&amp;',
  '<': '&lt;',
  '>': '&gt;',
  '"': '&quot;',
  "'": '&#39;',
};

const regexUnescapedHtml = /[&<>"']/g;

// make sure escape can be done only once, by doing it per hihglight component
function escapeHtml(html) {
  return html.replace(regexUnescapedHtml, character => htmlEscapes[character])
}

export default {
  props: {
    hit: {
      type: Object,
      required: true,
    },
    attribute: {
      type: String,
      required: true,
    },
  },
  computed: {
    innerHtml() {
      const highlight = getPropertyByPath(this.hit._highlightResult, this.attribute)
      return escapeHtml(highlight.value)
        .replace(/__highlight__/g, '<mark>')
        .replace(/__\/highlight__/g, '</mark>')
    }
  }
}
</script>

(and in the main code:

          <ais-configure
              highlightPreTag="__highlight__"
              highlightPostTag="__/highlight__"
            />
            <ais-hits :escapeHTML="false">

Thanks Maria! I’ve implemented the suggested solution (also in the sandbox) and it works fine in the meanwhile.

2 Likes