OverviewFilesCommitsIssuesDocsReleasesPeers

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

58 lines · javascript ref:
module.exports = { displayToSegment }

function displayToSegment({ text, display }) {
  if (!display) return []

  const segments = []
  let currentIndex = 0

  const sorted = display
    .filter((d) => d.start <= text.length - 1)
    .sort((a, b) => a.start - b.start)

  for (const display of sorted) {
    const { start, length, type, content, memberId } = display
    const end = start + length

    if (start > currentIndex) {
      segments.push({
        start: currentIndex,
        end: start,
        styles: []
      })
    }

    const segment = segments.find((s) => s.start === start && s.end === end)

    if (segment) {
      segment.styles.push({
        type,
        content: memberId || content || null
      })
    } else {
      segments.push({
        start,
        end,
        styles: [
          {
            type,
            content: memberId || content || null
          }
        ]
      })
    }

    currentIndex = end
  }

  if (currentIndex < text.length) {
    segments.push({
      start: currentIndex,
      end: text.length,
      styles: []
    })
  }

  return segments
}