{"version":3,"file":"previewText.mjs","names":[],"sources":["../../../../src/components/SummarizedMessagePreview/previewText.ts"],"sourcesContent":["import type { LocalMessage } from 'stream-chat';\nimport type { List, ListItem, Nodes, TableRow } from 'mdast';\nimport { toString as mdastToString } from 'mdast-util-to-string';\nimport remarkGfm from 'remark-gfm';\nimport remarkParse from 'remark-parse';\nimport type { PluggableList } from 'unified';\nimport { unified } from 'unified';\n\nimport type { ChatContextValue } from '../../context/ChatContext';\nimport { getTranslatedMessageText } from '../../context/MessageTranslationViewContext';\nimport type { TranslationContextValue } from '../../context/TranslationContext';\nimport {\n  htmlToTextPlugin,\n  imageToLink,\n  plusPlusToEmphasis,\n} from '../Message/renderText/remarkPlugins';\nimport type { ChannelPreviewMessageType } from './hooks/useLatestMessagePreview';\n\n/** Remark plugins of the latest-message preview, shared by its markdown and plain-text forms. */\nexport const previewRemarkPlugins: PluggableList = [\n  htmlToTextPlugin,\n  [remarkGfm, { singleTilde: false }],\n  plusPlusToEmphasis,\n  imageToLink,\n];\n\n// The processor is built lazily so importing this file does not build it: building fails when a\n// test file mocks the plugin modules.\nconst createPlainTextProcessor = () =>\n  unified().use(remarkParse).use(previewRemarkPlugins);\nlet plainTextProcessor: ReturnType<typeof createPlainTextProcessor> | undefined;\n\n/**\n * How plain text is read:\n * - `display`: the visible one-line preview. Lists keep their markers (`-`, `1.`, `[x]`) and tables\n *   their `|` cell separators, so the reader can tell what the message contains.\n * - `announcement`: text read by screen readers. Only the words are kept, plus the numbers of\n *   ordered list items.\n */\nexport type PlainTextFormat = 'announcement' | 'display';\n\n/**\n * Nodes whose children are blocks (paragraphs, list items, rows), read as words apart. Lists, and\n * tables in the `display` format, are read by their own branches of {@link toPlainText} first.\n */\nconst blockContainerTypes = new Set<Nodes['type']>([\n  'blockquote',\n  'footnoteDefinition',\n  'listItem',\n  'root',\n  'table',\n  'tableRow',\n]);\n\nconst joinAsWords = (parts: string[]) => parts.filter(Boolean).join(' ');\n\n/** Whether the list item is a task (`- [x]` or `- [ ]`). */\nconst isTaskItem = (item: ListItem) => typeof item.checked === 'boolean';\n\n/** The number of an ordered list item (\"3.\"), counted from the list's `start`. */\nconst getOrderedItemNumber = (list: List, index: number) =>\n  `${(list.start ?? 1) + index}.`;\n\n/**\n * The marker read before a list item. Ordered items keep their number (\"3. done\") in both formats,\n * as the message list shows them. The `display` format also shows the bullet of an unordered item\n * and the checkbox of a task item.\n */\nconst getListItemMarker = (\n  list: List,\n  item: ListItem,\n  index: number,\n  format: PlainTextFormat,\n): string => {\n  const number = list.ordered ? getOrderedItemNumber(list, index) : undefined;\n  if (format === 'announcement') return number ?? '';\n  const checkbox = isTaskItem(item) ? (item.checked ? '[x]' : '[ ]') : '';\n  return joinAsWords([number ?? '-', checkbox]);\n};\n\n/**\n * A table row in the `display` format, its cells between `|` separators: `| API | done |`. The\n * result is plain text, not markdown, so cell text is shown as is, a `|` inside a cell included.\n */\nconst tableRowToDisplayText = (row: TableRow) =>\n  `| ${row.children.map((cell) => toPlainText(cell, 'display')).join(' | ')} |`;\n\n/**\n * Reads a markdown node as text in the given format. Block containers join their children as\n * words; inline content is concatenated.\n */\nconst toPlainText = (node: Nodes, format: PlainTextFormat): string => {\n  if (node.type === 'list') {\n    return joinAsWords(\n      node.children.map((item, index) =>\n        joinAsWords([\n          getListItemMarker(node, item, index, format),\n          toPlainText(item, format),\n        ]),\n      ),\n    );\n  }\n  if (node.type === 'table' && format === 'display') {\n    return joinAsWords(node.children.map(tableRowToDisplayText));\n  }\n  if (blockContainerTypes.has(node.type) && 'children' in node) {\n    return joinAsWords(node.children.map((child) => toPlainText(child as Nodes, format)));\n  }\n  // A hard line break separates words; `mdastToString` reads it as nothing.\n  if (node.type === 'break') return ' ';\n  if ('children' in node) {\n    return node.children.map((child) => toPlainText(child as Nodes, format)).join('');\n  }\n  return mdastToString(node);\n};\n\nconst collapseWhitespace = (text: string) => text.replace(/\\s+/g, ' ').trim();\n\n/**\n * Strips markdown syntax from message text with the preview's remark plugins, in the given\n * {@link PlainTextFormat}. Blocks such as paragraphs and list items are joined with a space, and\n * line breaks read as spaces. When processing throws or yields nothing, returns the raw text on\n * one line.\n */\nexport const markdownToPlainText = (text: string, format: PlainTextFormat): string => {\n  try {\n    const processor = (plainTextProcessor ??= createPlainTextProcessor());\n    const plainText = toPlainText(\n      processor.runSync(processor.parse(text)) as Nodes,\n      format,\n    );\n    return collapseWhitespace(plainText) || collapseWhitespace(text) || text;\n  } catch {\n    return collapseWhitespace(text) || text;\n  }\n};\n\n/**\n * {@link markdownToPlainText} in the `announcement` format, for text read by screen readers:\n * `**done**` reads as `done`, `[docs](https://…)` as `docs`, and list bullets, task checkboxes and\n * table separators are dropped.\n */\nexport const stripMarkdownToText = (text: string): string =>\n  markdownToPlainText(text, 'announcement');\n\n/** Preview types whose text is never the message text: system strings and the GIPHY title. */\nconst typesWithoutMessageText = new Set<ChannelPreviewMessageType>([\n  'deleted',\n  'empty',\n  'error',\n  'giphy',\n  'poll',\n]);\n\n/** Whether a preview of this type can show the message text (or a caption) at all. */\nconst previewTypeMayShowMessageText = (type: ChannelPreviewMessageType) =>\n  !typesWithoutMessageText.has(type);\n\nexport type GetPlainPreviewTextParams = {\n  /** `display` for the visible preview, `announcement` for text read by screen readers. */\n  format: PlainTextFormat;\n  /** AI-generated text is returned verbatim, as the row labels read it. */\n  isMessageAIGenerated?: ChatContextValue['isMessageAIGenerated'];\n  /** Message the preview was built from. */\n  latestMessage: LocalMessage | undefined;\n  /** Preview text from `useLatestMessagePreview`. */\n  text: string;\n  /** Preview type from `useLatestMessagePreview`. */\n  type: ChannelPreviewMessageType;\n  userLanguage: TranslationContextValue['userLanguage'];\n};\n\n/**\n * The `useLatestMessagePreview` text as plain text in the given format. When the preview starts\n * with the message text, that part loses its markdown syntax and the rest (an attachment's\n * duration) stays. Labels, attachment titles, system strings and AI-generated text are returned as\n * they are.\n */\nexport const getPlainPreviewText = ({\n  format,\n  isMessageAIGenerated,\n  latestMessage,\n  text,\n  type,\n  userLanguage,\n}: GetPlainPreviewTextParams): string => {\n  if (\n    !latestMessage ||\n    !previewTypeMayShowMessageText(type) ||\n    isMessageAIGenerated?.(latestMessage)\n  )\n    return text;\n  const messageText =\n    getTranslatedMessageText({ language: userLanguage, message: latestMessage }) ||\n    latestMessage.text;\n  // The preview shows the message text (or a caption), optionally followed by a duration, when it\n  // starts with it; otherwise it shows an attachment's title or a generic label.\n  if (!messageText || !text.startsWith(messageText)) return text;\n  return markdownToPlainText(messageText, format) + text.slice(messageText.length);\n};\n"],"mappings":";;;;;;;;;;AAmBA,IAAa,uBAAsC;CACjD;CACA,CAAC,WAAW,EAAE,aAAa,MAAM,CAAC;CAClC;CACA;AACF;AAIA,IAAM,iCACJ,QAAQ,CAAC,CAAC,IAAI,WAAW,CAAC,CAAC,IAAI,oBAAoB;AACrD,IAAI;;;;;AAeJ,IAAM,sCAAsB,IAAI,IAAmB;CACjD;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;AAED,IAAM,eAAe,UAAoB,MAAM,OAAO,OAAO,CAAC,CAAC,KAAK,GAAG;;AAGvE,IAAM,cAAc,SAAmB,OAAO,KAAK,YAAY;;AAG/D,IAAM,wBAAwB,MAAY,UACxC,IAAI,KAAK,SAAS,KAAK,MAAM;;;;;;AAO/B,IAAM,qBACJ,MACA,MACA,OACA,WACW;CACX,MAAM,SAAS,KAAK,UAAU,qBAAqB,MAAM,KAAK,IAAI,KAAA;CAClE,IAAI,WAAW,gBAAgB,OAAO,UAAU;CAChD,MAAM,WAAW,WAAW,IAAI,IAAK,KAAK,UAAU,QAAQ,QAAS;CACrE,OAAO,YAAY,CAAC,UAAU,KAAK,QAAQ,CAAC;AAC9C;;;;;AAMA,IAAM,yBAAyB,QAC7B,KAAK,IAAI,SAAS,KAAK,SAAS,YAAY,MAAM,SAAS,CAAC,CAAC,CAAC,KAAK,KAAK,EAAE;;;;;AAM5E,IAAM,eAAe,MAAa,WAAoC;CACpE,IAAI,KAAK,SAAS,QAChB,OAAO,YACL,KAAK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