OverviewFilesCommitsIssuesDocsReleasesPeers

holepunchto-deps / @holepunchto / keet-editor / src / extensions / helpers / to-text.js

26 lines · javascript ref:
import { NODE_TYPE } from '../../constants.js'

const LENGTH_BY_NODE_TYPE = {
  [NODE_TYPE.FILE_ANY]: 1,
  [NODE_TYPE.FILE_IMAGE]: 1,
  [NODE_TYPE.FILE_VIDEO]: 1
}

export const getNodeTextLength = (node) => {
  if (node.isText) return node.text.length

  const { name } = node.type

  if (name === 'emoji') return node.attrs['data-emoji']?.length || 0

  if (name === 'mention') return ((node.attrs.label?.length || 0) + 1)

  return LENGTH_BY_NODE_TYPE[name] ?? 1
}

export const getDocTextLength = (doc) => {
  let len = -1 // because root element is a paragraph and we should not include it to calculations
  doc.descendants((node) => { len += getNodeTextLength(node) })
  return len
}