{"version":3,"file":"mentionsMarkdownPlugin.mjs","names":[],"sources":["../../../../../../src/components/Message/renderText/rehypePlugins/mentionsMarkdownPlugin.ts"],"sourcesContent":["import { escapeRegExp } from '../regex';\nimport type { ReplaceFunction } from 'hast-util-find-and-replace';\nimport { findAndReplace } from 'hast-util-find-and-replace';\nimport { u } from 'unist-builder';\nimport { visit } from 'unist-util-visit';\n\nimport type { Element } from 'hast';\nimport type { LocalMessage, UserGroupResponse, UserResponse } from 'stream-chat';\n\nexport type RenderTextMentionEntity =\n  | (UserResponse & {\n      mentionType: 'user';\n    })\n  | {\n      id: 'channel';\n      mentionType: 'channel';\n      name?: 'channel';\n    }\n  | {\n      id: 'here';\n      mentionType: 'here';\n      name?: 'here';\n    }\n  | {\n      id: string;\n      mentionType: 'role';\n      name?: string;\n    }\n  | {\n      id: string;\n      mentionType: 'user_group';\n      name?: string;\n    };\n\nexport type RenderTextMentionMetadata = Pick<\n  Partial<LocalMessage>,\n  | 'mentioned_channel'\n  | 'mentioned_groups'\n  | 'mentioned_here'\n  | 'mentioned_roles'\n  | 'mentioned_users'\n>;\n\ntype MentionReplacement = {\n  entity: RenderTextMentionEntity;\n  mentionDisplayText: string;\n};\n\ntype MentionLookup = {\n  mentionDisplayTextSet: Set<string>;\n  mentionReplacementMap: Map<string, MentionReplacement>;\n  mentionReplacements: MentionReplacement[];\n  mentionsRegex: RegExp | null;\n};\n\ntype MentionPluginAndDisplayTextSet = {\n  mentionDisplayTextSet: Set<string>;\n  plugin: () => (tree: HastTree) => void;\n};\n\ntype HastTree = Parameters<typeof findAndReplace>[0];\ntype MentionTraversalParent = {\n  children: unknown[];\n};\ntype TextNode = {\n  type: 'text';\n  value: string;\n};\n\n// A mention match ends at the end of the string, before whitespace, or before trailing\n// punctuation, which stays outside the mention node.\nconst MENTION_TRAILING_BOUNDARY = String.raw`(?=$|\\s|[!,.?;:'\")\\]}])`;\n\n/**\n * Returns the display texts, without the leading `@`, that match the entity in message text.\n * Roles and user groups match by name or ID, other entities by name falling back to ID.\n *\n * @param entity - Mention entity to resolve.\n * @returns Display texts the mention renderer wraps.\n */\nexport const getMentionDisplayTexts = (entity: RenderTextMentionEntity) => {\n  if (entity.mentionType === 'user') {\n    return [entity.name || entity.id].filter(Boolean);\n  }\n\n  if (entity.mentionType === 'channel' || entity.mentionType === 'here') {\n    return [entity.name || entity.id];\n  }\n\n  return Array.from(new Set([entity.name, entity.id].filter(Boolean)));\n};\n\nexport const getRenderTextMentionEntities = (\n  metadata?: RenderTextMentionMetadata,\n): RenderTextMentionEntity[] => {\n  if (!metadata) return [];\n\n  const mentions: RenderTextMentionEntity[] = (metadata.mentioned_users ?? []).map(\n    (user) => ({\n      ...user,\n      mentionType: 'user',\n    }),\n  );\n\n  if (metadata.mentioned_channel) {\n    mentions.push({\n      id: 'channel',\n      mentionType: 'channel',\n      name: 'channel',\n    });\n  }\n\n  if (metadata.mentioned_here) {\n    mentions.push({\n      id: 'here',\n      mentionType: 'here',\n      name: 'here',\n    });\n  }\n\n  if (metadata.mentioned_roles?.length) {\n    mentions.push(\n      ...metadata.mentioned_roles.map((role) => ({\n        id: role,\n        mentionType: 'role' as const,\n        name: role,\n      })),\n    );\n  }\n\n  if (metadata.mentioned_groups?.length) {\n    mentions.push(\n      ...metadata.mentioned_groups.map((group: UserGroupResponse) => ({\n        id: group.id,\n        mentionType: 'user_group' as const,\n        name: group.name,\n      })),\n    );\n  }\n\n  return mentions;\n};\n\n/**\n * Whether the message mentions anyone: a user, `@channel`, `@here`, a role or a user group. It is\n * true exactly when `getRenderTextMentionEntities` returns at least one entity, without building\n * them.\n *\n * @param metadata - The message's mention fields.\n */\nexport const messageHasMentions = (metadata?: RenderTextMentionMetadata) =>\n  Boolean(\n    metadata?.mentioned_users?.length ||\n    metadata?.mentioned_channel ||\n    metadata?.mentioned_here ||\n    metadata?.mentioned_roles?.length ||\n    metadata?.mentioned_groups?.length,\n  );\n\nconst createMentionLookup = (\n  mentionEntities: RenderTextMentionEntity[],\n): MentionLookup => {\n  const mentionReplacementMap = mentionEntities.reduce((replacementMap, entity) => {\n    getMentionDisplayTexts(entity).forEach((mentionDisplayText) => {\n      const prefixedMentionDisplayText = `@${mentionDisplayText}`;\n\n      if (!replacementMap.has(prefixedMentionDisplayText)) {\n        replacementMap.set(prefixedMentionDisplayText, {\n          entity,\n          mentionDisplayText: prefixedMentionDisplayText,\n        });\n      }\n    });\n\n    return replacementMap;\n  }, new Map<string, MentionReplacement>());\n  const mentionReplacements = Array.from(mentionReplacementMap.values()).sort(\n    (a, b) => b.mentionDisplayText.length - a.mentionDisplayText.length,\n  );\n\n  return {\n    mentionDisplayTextSet: new Set(mentionReplacementMap.keys()),\n    mentionReplacementMap,\n    mentionReplacements,\n    mentionsRegex: mentionReplacements.length\n      ? new RegExp(\n          `(?:${mentionReplacements\n            .map(({ mentionDisplayText }) => escapeRegExp(mentionDisplayText))\n            .join('|')})${MENTION_TRAILING_BOUNDARY}`,\n          'g',\n        )\n      : null,\n  };\n};\n\nexport const mentionsMarkdownPluginFromLookup =\n  ({\n    mentionDisplayTextSet,\n    mentionReplacementMap,\n    mentionReplacements,\n    mentionsRegex,\n  }: MentionLookup) =>\n  () => {\n    const replace: ReplaceFunction = (mentionDisplayText) => {\n      const replacement = mentionReplacementMap.get(mentionDisplayText);\n\n      if (!replacement) return mentionDisplayText;\n\n      return u(\n        'element',\n        {\n          mentionedEntity: replacement.entity,\n          properties: {},\n          tagName: 'mention',\n        },\n        [u('text', mentionDisplayText)],\n      );\n    };\n\n    const transform = (tree: HastTree) => {\n      if (!mentionReplacements.length || !mentionsRegex) return;\n\n      // Remark GFM turns e-mail-like text into links, so a mention such as \"@your.name@as.email\"\n      // arrives as a text ending in \"@\" followed by a mailto link. For a known mention, drop that\n      // \"@\" and replace the link with a text node holding the mention text before `replace` runs.\n      if (mentionDisplayTextSet.size) {\n        visit(\n          tree,\n          (node: unknown, index, parent: MentionTraversalParent | undefined) => {\n            if (typeof index === 'undefined') return;\n            if (!parent) return;\n\n            const nextChild = parent.children.at(index + 1) as Element;\n            const nextChildHref = nextChild?.properties?.href as string | undefined;\n            const textNode = node as TextNode;\n\n            if (\n              textNode.type === 'text' &&\n              // The text node has to end with the `@` that starts the mention.\n              textNode.value.endsWith('@') &&\n              nextChildHref?.startsWith('mailto:')\n            ) {\n              const newTextValue = textNode.value.replace(/@$/, '');\n              const rawDisplayName = nextChildHref.replace('mailto:', '');\n              const mentionDisplayText = `@${rawDisplayName}`;\n              if (!mentionDisplayTextSet.has(mentionDisplayText)) return;\n              parent.children[index] = u('text', newTextValue);\n              parent.children[index + 1] = u('text', mentionDisplayText);\n            }\n          },\n        );\n      }\n\n      findAndReplace(tree, [mentionsRegex, replace]);\n    };\n\n    return transform;\n  };\n\nexport const createMentionPluginAndDisplayTextSet = (\n  mentionEntities: RenderTextMentionEntity[],\n): MentionPluginAndDisplayTextSet => {\n  const mentionLookup = createMentionLookup(mentionEntities);\n\n  return {\n    mentionDisplayTextSet: mentionLookup.mentionDisplayTextSet,\n    plugin: mentionsMarkdownPluginFromLookup(mentionLookup),\n  };\n};\n\nexport function mentionsMarkdownPlugin(\n  mentionEntities: RenderTextMentionEntity[],\n): () => (tree: HastTree) => void {\n  return createMentionPluginAndDisplayTextSet(mentionEntities).plugin;\n}\n"],"mappings":";;;;;AAuEA,IAAM,4BAA4B,OAAO,GAAG;;;;;;;;AAS5C,IAAa,0BAA0B,WAAoC;CACzE,IAAI,OAAO,gBAAgB,QACzB,OAAO,CAAC,OAAO,QAAQ,OAAO,EAAE,CAAC,CAAC,OAAO,OAAO;CAGlD,IAAI,OAAO,gBAAgB,aAAa,OAAO,gBAAgB,QAC7D,OAAO,CAAC,OAAO,QAAQ,OAAO,EAAE;CAGlC,OAAO,MAAM,KAAK,IAAI,IAAI,CAAC,OAAO,MAAM,OAAO,EAAE,CAAC,CAAC,OAAO,OAAO,CAAC,CAAC;AACrE;AAEA,IAAa,gCACX,aAC8B;CAC9B,IAAI,CAAC,UAAU,OAAO,CAAC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