import { LightningElement, api } from "lwc"; import cx from "classnames"; import { CoveoHighlights } from "typings/custom"; const toChunks = (value: string, highlights: CoveoHighlights) => { if (!highlights || highlights.length < 1) { return [ { value, id: 0 } ]; } let endIndex = 0; // @ts-ignore Dark Magic (TM) return highlights.reduce((acc, { length, offset }, i) => { const plainValue = value.slice(endIndex, offset); const plainChunk = { value: plainValue, id: endIndex }; endIndex = offset + length; const boldValue = value.slice(offset, endIndex); const boldChunk = { value: boldValue, class: "bold", id: offset }; let chunks = plainValue.length > 0 ? [...acc, plainChunk, boldChunk] : [...acc, boldChunk]; const remaining = value.slice(endIndex); if (remaining.length > 0 && highlights.length - 1 === i) { chunks = [ ...chunks, { value: remaining, id: value.length } ]; } return chunks; }, []); }; export default class SidebarSearchResult extends LightningElement { @api description!: string; @api descriptionHighlights!: CoveoHighlights; @api href!: string; @api selected!: boolean; @api header!: string; @api titleHighlights!: CoveoHighlights; @api select!: Function; private get titleChunks() { return toChunks(this.header, this.titleHighlights); } private get descriptionChunks() { return toChunks(this.description, this.descriptionHighlights); } private get className(): string { return cx("sidebar-item", this.selected && "sidebar-item-selected"); } private onClick(e: PointerEvent) { e.preventDefault(); this.select(); window.location.href = this.href; } }