OverviewFilesCommitsIssuesDocsReleasesPeers

holepunchto-deps / @holepunchto / keet-editor-parser / src / display / to-display-partial.js

48 lines · javascript ref:
const { DISPLAY_TYPES } = require('../constants.js')

module.exports = { displayPartial }

function displayPartial({ text, display = [] }, opts = {}) {
  const total = text.length
  let { start = 0, end = total } = opts

  // normalize bounds
  start = Math.max(0, Math.min(start | 0, total))
  end = Math.max(start, Math.min(end | 0, total))

  let adjustedEnd = end
  const outDisplay = []

  for (const d of display) {
    const displayStart = d.start | 0
    const displayEnd = displayStart + (d.length | 0)

    // intersection with [start, end)
    const intersectionStart = Math.max(displayStart, start)
    const intersectionEnd = Math.min(displayEnd, end)

    // outside -> discard
    if (intersectionEnd <= intersectionStart) continue

    // custom emoji must not be cut; if cut, drop it
    if (d.type === DISPLAY_TYPES.EMOJI) {
      const isCut =
        intersectionStart > displayStart || intersectionEnd < displayEnd
      if (isCut) {
        adjustedEnd = Math.min(adjustedEnd, displayStart)
        continue
      }
    }
    // cut or fully inside -> keep adjusted
    outDisplay.push({
      ...d,
      start: intersectionStart - start,
      length: intersectionEnd - intersectionStart
    })
  }

  const outText = text.slice(start, adjustedEnd)

  return { text: outText, display: outDisplay }
}