All files index.ts

0% Statements 0/219
0% Branches 0/1
0% Functions 0/1
0% Lines 0/219

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220                                                                                                                                                                                                                                                                                                                                                                                                                                                       
import { Observable, Subject } from "rxjs"
import { Reader, Report } from "@prose-reader/core"
import { filter, takeUntil, tap } from "rxjs/operators"

type Highlight = {
  anchorCfi: string
  focusCfi: string
  id: string
  text?: string
  spineItemIndex?: number | undefined
  anchorNode?: Node
  anchorOffset?: number
  focusNode?: Node
  focusOffset?: number
  element?: HTMLElement
}

type SubjectType = { type: `onHighlightClick`; data: Highlight } | { type: `onUpdate`; data: Highlight[] }

const SHOULD_NOT_LAYOUT = false
const HIGHLIGHT_ID_PREFIX = `prose-reader-enhancer-highlights`

/**
 * @todo
 * Optimize refresh of elements
 */
export const highlightsEnhancer =
  <InheritOptions, InheritOutput extends Reader>(next: (options: InheritOptions) => InheritOutput) =>
  (
    options: InheritOptions,
  ): InheritOutput & {
    highlights: {
      add: (highlight: Highlight) => void
      has: (highlight: Highlight) => boolean
      remove: (id: string) => void
      isHighlightClicked: (event: MouseEvent | TouchEvent | PointerEvent) => boolean
      $: Observable<SubjectType>
    }
  } => {
    const reader = next(options)
    const highlights$ = new Subject<SubjectType>()
    let highlights: Highlight[] = []

    const getRangeForHighlight = (
      overlayElement: HTMLElement,
      anchor: { node: Node; offset?: number },
      focus: { node: Node; offset?: number },
    ) => {
      const range = overlayElement.ownerDocument.createRange()
      try {
        range.setStart(anchor.node, anchor.offset || 0)
        range.setEnd(focus.node, focus.offset || 0)
      } catch (e) {
        Report.error(e)
      }

      return range
    }

    const drawHighlight = (overlayElement: HTMLElement, highlight: Highlight) => {
      const { node: anchorNode, offset: anchorOffset } = reader.resolveCfi(highlight.anchorCfi) || {}
      const { node: focusNode, offset: focusOffset } = reader.resolveCfi(highlight.focusCfi) || {}

      if (anchorNode && focusNode) {
        // remove old previous highlight
        highlight.element?.remove()

        const range = getRangeForHighlight(
          overlayElement,
          { node: anchorNode, offset: anchorOffset },
          { node: focusNode, offset: focusOffset },
        )

        highlight.text = range.toString()

        const rectElements = Array.from(range.getClientRects()).map((domRect) => {
          const rectElt = overlayElement.ownerDocument.createElement(`div`)
          rectElt.style.cssText = `
            position: absolute;
            width: ${domRect.width}px;
            height: ${domRect.height}px;
            top: ${domRect.top}px;
            left: ${domRect.left}px;
            background-color: green;
            opacity: 50%;
          `
          rectElt.setAttribute(`data-${HIGHLIGHT_ID_PREFIX}`, ``)

          return rectElt
        })

        const containerElement = overlayElement.ownerDocument.createElement(`div`)
        containerElement.style.cssText = `
          pointer-events: auto;
        `

        highlight.element = containerElement

        rectElements.forEach((el) => containerElement.appendChild(el))
        overlayElement.appendChild(containerElement)

        containerElement.addEventListener(`click`, () => {
          highlights$.next({ type: `onHighlightClick`, data: highlight })
        })
      }
    }

    const drawHighlightsForItem = (overlayElement: HTMLElement, itemIndex: number) => {
      highlights.forEach((highlight) => {
        if (highlight.spineItemIndex === itemIndex) {
          drawHighlight(overlayElement, highlight)
        }
      })
    }

    const enrichHighlight = (highlight: Highlight) => {
      const cfiMetaInfo = reader.getCfiMetaInformation(highlight.anchorCfi)

      return {
        ...highlight,
        spineItemIndex: cfiMetaInfo?.spineItemIndex,
      }
    }

    const _add = (highlight: Highlight) => {
      const newHighlight = enrichHighlight(highlight)

      highlights.push(newHighlight)

      if (newHighlight.spineItemIndex !== undefined) {
        reader.manipulateSpineItems(({ index, overlayElement }) => {
          if (index !== newHighlight.spineItemIndex) return SHOULD_NOT_LAYOUT

          drawHighlight(overlayElement, newHighlight)

          return SHOULD_NOT_LAYOUT
        })
      }

      return highlight
    }

    const add = (highlight: Highlight | Highlight[]) => {
      ;(!Array.isArray(highlight) ? [highlight] : highlight).forEach(_add)

      highlights$.next({ type: `onUpdate`, data: highlights })
    }

    const remove = (id: string) => {
      highlights = highlights.filter((highlight) => {
        if (highlight.id === id) {
          highlight.element?.remove()
        }

        return highlight.id !== id
      })

      highlights$.next({ type: `onUpdate`, data: highlights })
    }

    const has = (highlight: Highlight) => !!highlights.find(({ id }) => id === highlight.id)

    const isHighlightClicked = (event: MouseEvent | TouchEvent | PointerEvent) => {
      if (event.target instanceof HTMLElement) {
        return event.target.hasAttribute(`data-${HIGHLIGHT_ID_PREFIX}`)
      }

      return false
    }

    /**
     * If the user has registered highlights before the reader was ready we want to
     * init them and draw them
     */
    reader.$.loadStatus$
      .pipe(
        filter((state) => state === "ready"),
        tap(() => {
          highlights = highlights.map((highlight) => {
            if (!highlight.spineItemIndex) return enrichHighlight(highlight)

            return highlight
          })

          highlights$.next({ type: `onUpdate`, data: highlights })

          reader.manipulateSpineItems(({ overlayElement, index }) => {
            drawHighlightsForItem(overlayElement, index)

            return SHOULD_NOT_LAYOUT
          })
        }),
        takeUntil(reader.$.destroy$),
      )
      .subscribe()

    const refreshHighlightsOnLayout$ = reader.$.layout$.pipe(
      tap(() => {
        reader.manipulateSpineItems(({ overlayElement, index }) => {
          drawHighlightsForItem(overlayElement, index)

          return SHOULD_NOT_LAYOUT
        })
      }),
    )

    refreshHighlightsOnLayout$.pipe(takeUntil(reader.$.destroy$)).subscribe()

    return {
      ...reader,
      highlights: {
        add,
        remove,
        has,
        isHighlightClicked,
        $: highlights$.asObservable(),
      },
    }
  }