File size: 948 Bytes
23d418f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// Splitting an excerpt into plain and highlighted pieces from the server's spans.

export type Piece = { text: string; mark: boolean }

/** text cut at the spans ([start, end) character offsets, in order, as the server sends
 * them): pieces alternate plain / marked; spans out of range or overlapping an earlier
 * one are clipped, never thrown on (a highlight must not break the page). */
export function pieces(text: string, spans: [number, number][]): Piece[] {
  const out: Piece[] = []
  let at = 0
  for (const [rawStart, rawEnd] of spans) {
    const start = Math.max(at, Math.min(rawStart, text.length))
    const end = Math.max(start, rawEnd) // slice() clamps an end past the text
    if (start > at) out.push({ text: text.slice(at, start), mark: false })
    if (end > start) out.push({ text: text.slice(start, end), mark: true })
    at = end
  }
  if (at < text.length) out.push({ text: text.slice(at), mark: false })
  return out
}