@umodeapporg/ui 0.4.1 → 0.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/components/Form/RichTextEditor.js +1 -0
- package/dist/components/Form/RichTextEditor.js.map +1 -1
- package/dist/components/UI/RichTextContent.js +4 -2
- package/dist/components/UI/RichTextContent.js.map +1 -1
- package/dist/helpers/richText.d.ts +9 -0
- package/dist/helpers/richText.js +37 -11
- package/dist/helpers/richText.js.map +1 -1
- package/package.json +1 -1
- package/src/assets/styles/base.css +23 -1
|
@@ -473,6 +473,7 @@ const RichTextEditor = forwardRef(function RichTextEditor2({
|
|
|
473
473
|
"[&_blockquote]:border-l-2 [&_blockquote]:border-brand-border [&_blockquote]:pl-3 [&_blockquote]:italic [&_blockquote]:text-foreground-subtle",
|
|
474
474
|
"[&_a]:text-brand-emphasis [&_a]:underline",
|
|
475
475
|
"[&_a.rt-file]:text-foreground-muted [&_a.rt-file]:no-underline",
|
|
476
|
+
"[&_a.rt-image-link]:no-underline",
|
|
476
477
|
"[&_user]:whitespace-nowrap [&_user]:rounded [&_user]:bg-brand-soft [&_user]:px-1 [&_user]:font-medium [&_user]:text-brand-emphasis",
|
|
477
478
|
disabled && "cursor-not-allowed opacity-60"
|
|
478
479
|
),
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"RichTextEditor.js","sources":["../../../src/components/Form/RichTextEditor.tsx"],"sourcesContent":["import { forwardRef, useCallback, useEffect, useImperativeHandle, useMemo, useRef, useState } from 'react';\nimport classNames from 'classnames';\nimport { useTranslation } from 'react-i18next';\n\nimport {\n ControlledMenuHandler,\n ControlledMenuItem,\n ControlledMenuList,\n ControlledMenuRoot,\n} from '@/components/UI/ControlledMenu';\nimport {\n ControlledPopoverContent,\n ControlledPopoverHandler,\n ControlledPopoverRoot,\n} from '@/components/UI/ControlledPopover';\nimport ControlledTooltip from '@/components/UI/ControlledTooltip';\nimport {\n activeRichTextColor,\n applyRichTextColor,\n buildFileChipMarkup,\n normalizeRichTextColorNodes,\n RICH_TEXT_COLOR_SWATCH_CLASS,\n RICH_TEXT_COLORS,\n TRichTextColor,\n} from '@/helpers/richText';\nimport { IUseFileAttachmentsResult, TFileUploader, useFileAttachments } from '@/hooks/useFileAttachments';\n\nimport { MaterialSymbol, SymbolCodepoints } from '../UI/MaterialSymbol';\n\nimport AttachmentPreviewList from './attachments/AttachmentPreviewList';\nimport FileDropzone from './attachments/FileDropzone';\nimport ControlledButton from './ControlledButton';\nimport ControlledInput from './ControlledInput';\n\n/** An extra entry in the attach menu, for a source only the host knows about (a camera dialog). */\nexport interface IRichTextAttachAction {\n key: string;\n icon: SymbolCodepoints;\n label: string;\n onClick: () => void;\n}\n\n/**\n * Files travel BESIDE the text: the host owns a list of attachments of its own (a chat message\n * has one) and reads `controller.readyAttachments` when it saves.\n */\nexport interface IRichTextAttachmentsConfig {\n controller: IUseFileAttachmentsResult;\n extraActions?: Array<IRichTextAttachAction>;\n /** The host already renders the staged previews somewhere else. */\n hidePreviews?: boolean;\n /** The host already wraps a wider drop target around this editor. */\n hideDropzone?: boolean;\n}\n\n/**\n * Files travel INSIDE the text: the upload result is written into the body as a chip, so the\n * reference persists anywhere the HTML itself is stored and no host needs a new field.\n */\nexport interface IRichTextInlineUploadConfig {\n uploadFile?: TFileUploader;\n maxFiles?: number;\n maxFileSizeBytes?: number;\n}\n\ninterface IRichTextEditorProps {\n value?: string;\n onChange?: (html: string) => void;\n placeholder?: string;\n disabled?: boolean;\n error?: boolean;\n className?: string;\n minHeight?: number;\n /** Rendered inside the toolbar row, right-aligned: host actions that belong to the field. */\n toolbarSlot?: React.ReactNode;\n /** Rendered in the editor's own bottom bar, after the controls the editor owns. */\n actionsSlot?: React.ReactNode;\n onKeyDown?: (event: React.KeyboardEvent<HTMLDivElement>) => void;\n /** Fires when the editable area loses focus, for hosts that persist on blur. */\n onBlur?: () => void;\n /**\n * Fires with the full HTML when the editor changes the content on its own, which today means\n * an inline upload landing after the field already lost focus. A host that persists on blur\n * would otherwise never hear about the file it just attached.\n */\n onCommit?: (html: string) => void;\n /** 'bare' drops the border and focus ring: the host owns the chrome around the field. */\n variant?: 'default' | 'bare';\n /** Hosts with their own action bar (the chat composer) toggle the formatting row on demand. */\n showToolbar?: boolean;\n /** Renders the formatting toggle in the bottom bar and lets the editor own the row's state. */\n formattingToggle?: boolean;\n attachments?: IRichTextAttachmentsConfig;\n inlineUpload?: IRichTextInlineUploadConfig;\n}\n\nexport interface IRichTextEditorHandle {\n focus: () => void;\n /** Viewport rect of the caret, for anchoring a popover to what is being typed. */\n getCaretRect: () => DOMRect | null;\n /**\n * Text typed after the trigger and before the caret, or null when the caret is not inside a\n * trigger word. Drives both \"is the mention menu relevant\" and \"what is being searched\".\n * Spaces are allowed inside the query (people have compound names); the host decides when a\n * spaced query stopped matching anyone and closes the menu.\n */\n getMentionQuery: (trigger: string) => string | null;\n /**\n * Deletes the trigger AND the query the user typed after it, then writes the markup in their\n * place, so picking someone from a mention menu replaces everything typed since the `@`\n * instead of stacking the mention after it.\n */\n replaceTriggerWith: (trigger: string, query: string, html: string) => void;\n}\n\ninterface IToolbarGroup {\n buttons: Array<IToolbarButton>;\n}\n\ninterface IToolbarButton {\n command: string;\n arg?: string;\n icon: SymbolCodepoints;\n tooltipKey: string;\n isBlock?: boolean;\n}\n\nconst TOOLBAR_GROUPS: Array<IToolbarGroup> = [\n {\n buttons: [\n { command: 'bold', icon: 'format_bold', tooltipKey: 'createTask.rich.bold' },\n { command: 'italic', icon: 'format_italic', tooltipKey: 'createTask.rich.italic' },\n { command: 'strikeThrough', icon: 'strikethrough_s', tooltipKey: 'createTask.rich.strikethrough' },\n ],\n },\n {\n buttons: [\n {\n command: 'insertUnorderedList',\n icon: 'format_list_bulleted',\n tooltipKey: 'createTask.rich.bulletList',\n isBlock: true,\n },\n {\n command: 'insertOrderedList',\n icon: 'format_list_numbered',\n tooltipKey: 'createTask.rich.numberedList',\n isBlock: true,\n },\n {\n command: 'formatBlock',\n arg: 'BLOCKQUOTE',\n icon: 'format_quote',\n tooltipKey: 'createTask.rich.quote',\n isBlock: true,\n },\n ],\n },\n {\n buttons: [\n { command: 'indent', icon: 'format_indent_increase', tooltipKey: 'createTask.rich.indent' },\n { command: 'outdent', icon: 'format_indent_decrease', tooltipKey: 'createTask.rich.outdent' },\n ],\n },\n];\n\nconst MENTION_QUERY_MAX_LENGTH = 40;\nconst IMAGE_INPUT_ACCEPT = 'image/*';\nconst DROPZONE_OVERLAY_CLASS = 'rounded-xl';\n\nconst TOOLBAR_BUTTON_CLASS = 'flex size-7 items-center justify-center rounded-lg transition-colors';\nconst TOOLBAR_BUTTON_IDLE_CLASS = 'text-foreground-subtle hover:bg-muted-hover hover:text-foreground-muted';\nconst TOOLBAR_BUTTON_ACTIVE_CLASS = 'bg-brand-soft text-brand-emphasis';\nconst ACTION_BUTTON_CLASS =\n 'flex size-8 items-center justify-center rounded-full text-foreground-faint transition-colors hover:bg-muted-hover hover:text-foreground-muted disabled:text-foreground-faint';\nconst ACTION_BUTTON_ACTIVE_CLASS =\n 'flex size-8 items-center justify-center rounded-full bg-brand-soft text-brand-emphasis transition-colors hover:bg-brand-soft';\n\nconst isCommandActive = (command: string, arg?: string): boolean => {\n try {\n if (arg) return document.queryCommandValue(command) === arg.toLowerCase();\n return document.queryCommandState(command);\n } catch {\n return false;\n }\n};\n\nconst RichTextEditor = forwardRef<IRichTextEditorHandle, IRichTextEditorProps>(function RichTextEditor(\n {\n value = '',\n onChange,\n placeholder,\n disabled = false,\n error = false,\n className,\n minHeight = 120,\n toolbarSlot,\n actionsSlot,\n onKeyDown,\n onBlur,\n onCommit,\n variant = 'default',\n showToolbar = true,\n formattingToggle = false,\n attachments,\n inlineUpload,\n },\n ref,\n) {\n const { t } = useTranslation('ui');\n const editorRef = useRef<HTMLDivElement>(null);\n const [activeCommands, setActiveCommands] = useState<Set<string>>(new Set());\n const [activeColor, setActiveColor] = useState<TRichTextColor>('default');\n const [colorOpen, setColorOpen] = useState(false);\n const [showLinkInput, setShowLinkInput] = useState(false);\n const [linkUrl, setLinkUrl] = useState('');\n const [isFocused, setIsFocused] = useState(false);\n const [formattingOpen, setFormattingOpen] = useState(false);\n const savedRangeRef = useRef<Range | null>(null);\n const isInternalUpdateRef = useRef(false);\n const fileInputRef = useRef<HTMLInputElement>(null);\n const imageInputRef = useRef<HTMLInputElement>(null);\n const insertedStagingIdsRef = useRef<Set<string>>(new Set());\n const pendingColorRef = useRef<TRichTextColor>('default');\n\n const inlineController = useFileAttachments({\n uploadFile: inlineUpload?.uploadFile,\n maxFiles: inlineUpload?.maxFiles,\n maxFileSizeBytes: inlineUpload?.maxFileSizeBytes,\n });\n\n const attachmentsController = attachments?.controller ?? (inlineUpload ? inlineController : null);\n const inlineStagedAttachments = inlineController.stagedAttachments;\n const toolbarVisible = formattingToggle ? formattingOpen : showToolbar;\n\n useEffect(() => {\n const editor = editorRef.current;\n if (!editor) return;\n if (isInternalUpdateRef.current) return;\n if (editor.innerHTML !== value) {\n editor.innerHTML = value;\n }\n }, [value]);\n\n const emitChange = useCallback(() => {\n const editor = editorRef.current;\n if (!editor) return;\n isInternalUpdateRef.current = true;\n onChange?.(editor.innerHTML);\n isInternalUpdateRef.current = false;\n }, [onChange]);\n\n const syncActiveCommands = useCallback(() => {\n const active = new Set<string>();\n TOOLBAR_GROUPS.flatMap((group) => group.buttons).forEach(({ command, arg }) => {\n if (isCommandActive(command, arg)) active.add(arg ?? command);\n });\n setActiveCommands(active);\n\n const editor = editorRef.current;\n if (editor) setActiveColor(activeRichTextColor(editor));\n }, []);\n\n const execFormat = useCallback(\n (command: string, arg?: string) => {\n const editor = editorRef.current;\n if (!editor || disabled) return;\n editor.focus();\n document.execCommand(command, false, arg);\n emitChange();\n syncActiveCommands();\n },\n [disabled, emitChange, syncActiveCommands],\n );\n\n const saveRange = useCallback(() => {\n const selection = window.getSelection();\n if (selection && selection.rangeCount > 0) {\n savedRangeRef.current = selection.getRangeAt(0).cloneRange();\n }\n }, []);\n\n const restoreRange = useCallback(() => {\n const range = savedRangeRef.current;\n if (!range) return;\n const selection = window.getSelection();\n if (!selection) return;\n selection.removeAllRanges();\n selection.addRange(range);\n }, []);\n\n const applyLink = useCallback(() => {\n const url = linkUrl.trim();\n restoreRange();\n if (url) execFormat('createLink', url.startsWith('http') ? url : `https://${url}`);\n setShowLinkInput(false);\n setLinkUrl('');\n }, [linkUrl, restoreRange, execFormat]);\n\n const handleApplyColor = useCallback(\n (color: TRichTextColor) => {\n const editor = editorRef.current;\n if (!editor || disabled) return;\n\n editor.focus();\n restoreRange();\n pendingColorRef.current = color;\n applyRichTextColor(editor, color);\n emitChange();\n setActiveColor(color);\n setColorOpen(false);\n },\n [disabled, emitChange, restoreRange],\n );\n\n const insertHtmlAtCaret = useCallback(\n (html: string, commit = false) => {\n const editor = editorRef.current;\n if (!editor || disabled) return;\n\n const previouslyFocused = document.activeElement as HTMLElement | null;\n const editorHadFocus = editor.contains(previouslyFocused);\n\n editor.focus();\n restoreRange();\n\n const selection = window.getSelection();\n const caretIsInside = selection?.anchorNode ? editor.contains(selection.anchorNode) : false;\n\n if (!caretIsInside) {\n const range = document.createRange();\n range.selectNodeContents(editor);\n range.collapse(false);\n selection?.removeAllRanges();\n selection?.addRange(range);\n }\n\n document.execCommand('insertHTML', false, html);\n saveRange();\n emitChange();\n\n if (!editorHadFocus) previouslyFocused?.focus();\n if (commit) onCommit?.(editor.innerHTML);\n },\n [disabled, emitChange, onCommit, restoreRange, saveRange],\n );\n\n const inlineControllerRef = useRef(inlineController);\n inlineControllerRef.current = inlineController;\n\n // An inline upload lands in the body the moment it finishes, and leaves the staging list so\n // the progress card disappears with it.\n useEffect(() => {\n if (!inlineUpload) return;\n\n inlineStagedAttachments.forEach((staged) => {\n const uploaded = staged.uploaded;\n if (staged.status !== 'done' || !uploaded) return;\n\n if (!insertedStagingIdsRef.current.has(staged.stagingId)) {\n insertedStagingIdsRef.current.add(staged.stagingId);\n insertHtmlAtCaret(`${buildFileChipMarkup(uploaded)} `, true);\n }\n inlineControllerRef.current.removeAttachment(staged.stagingId);\n });\n }, [inlineUpload, inlineStagedAttachments, insertHtmlAtCaret]);\n\n const handleInput = useCallback(() => {\n const editor = editorRef.current;\n if (editor) normalizeRichTextColorNodes(editor, pendingColorRef.current);\n emitChange();\n syncActiveCommands();\n }, [emitChange, syncActiveCommands]);\n\n const handleFilesPicked = (event: React.ChangeEvent<HTMLInputElement>) => {\n const files = Array.from(event.target.files ?? []);\n if (files.length) attachmentsController?.addFiles(files);\n event.target.value = '';\n };\n\n const handlePaste = (event: React.ClipboardEvent) => {\n if (!attachmentsController) return;\n\n const files = Array.from(event.clipboardData?.files ?? []);\n if (!files.length) return;\n\n event.preventDefault();\n event.stopPropagation();\n attachmentsController.addFiles(files);\n };\n\n useImperativeHandle(ref, () => ({\n focus: () => editorRef.current?.focus(),\n\n getCaretRect: () => {\n const selection = window.getSelection();\n if (!selection?.rangeCount) return null;\n\n const range = selection.getRangeAt(0).cloneRange();\n range.collapse(false);\n\n const [rect] = Array.from(range.getClientRects());\n if (rect) return rect;\n\n // A collapsed range inside an empty node measures nothing, so a throwaway marker gives it\n // something to measure. Removed in the same tick, before anything can observe it.\n const marker = document.createElement('span');\n marker.textContent = '\\u200b';\n range.insertNode(marker);\n const markerRect = marker.getBoundingClientRect();\n marker.remove();\n\n return markerRect;\n },\n\n getMentionQuery: (trigger) => {\n const selection = window.getSelection();\n if (!selection?.rangeCount) return null;\n\n const range = selection.getRangeAt(0);\n if (!range.collapsed || range.startContainer.nodeType !== Node.TEXT_NODE) return null;\n\n const textBeforeCaret = range.startContainer.textContent?.slice(0, range.startOffset) ?? '';\n const escapedTrigger = trigger.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n const match = new RegExp(`(?:^|\\\\s)${escapedTrigger}([^${escapedTrigger}]*)$`).exec(textBeforeCaret);\n if (!match) return null;\n\n const query = match[1];\n if (query.startsWith(' ') || query.length > MENTION_QUERY_MAX_LENGTH) return null;\n\n return query;\n },\n\n replaceTriggerWith: (trigger, query, html) => {\n const editor = editorRef.current;\n if (!editor || disabled) return;\n\n editor.focus();\n restoreRange();\n\n const selection = window.getSelection();\n const range = selection?.rangeCount ? selection.getRangeAt(0) : null;\n\n if (range?.collapsed && range.startContainer.nodeType === Node.TEXT_NODE) {\n const textBeforeCaret = range.startContainer.textContent?.slice(0, range.startOffset) ?? '';\n const typed = `${trigger}${query}`;\n if (textBeforeCaret.endsWith(typed)) {\n range.setStart(range.startContainer, range.startOffset - typed.length);\n range.deleteContents();\n } else if (textBeforeCaret.endsWith(trigger)) {\n range.setStart(range.startContainer, range.startOffset - trigger.length);\n range.deleteContents();\n }\n }\n\n document.execCommand('insertHTML', false, `${html} `);\n emitChange();\n },\n }));\n\n const isEmpty = !editorRef.current?.textContent?.trim() && !editorRef.current?.querySelector('img, li, blockquote');\n\n const attachMenuActions = useMemo<Array<IRichTextAttachAction>>(\n () => [\n {\n key: 'file',\n icon: 'description',\n label: t('followUp.attachments.pickFile'),\n onClick: () => fileInputRef.current?.click(),\n },\n {\n key: 'image',\n icon: 'image',\n label: t('followUp.attachments.pickImage'),\n onClick: () => imageInputRef.current?.click(),\n },\n ...(attachments?.extraActions ?? []),\n ],\n [attachments?.extraActions, t],\n );\n\n const showPreviews = Boolean(attachmentsController) && !attachments?.hidePreviews;\n const showActionsBar = Boolean(attachmentsController) || Boolean(actionsSlot) || formattingToggle;\n\n const editorShell = (\n <div\n className={classNames(\n 'flex w-full flex-col transition-colors',\n variant === 'default' && 'rounded-xl border bg-surface',\n variant === 'default' &&\n (error\n ? 'border-danger-border'\n : isFocused\n ? 'border-brand-border ring-2 ring-brand-border'\n : 'border-border'),\n className,\n )}\n >\n {toolbarVisible && (\n <div\n className={classNames(\n 'flex flex-wrap items-center gap-px border-b px-2 py-1.5',\n error ? 'border-danger-border' : 'border-border-subtle',\n )}\n >\n {TOOLBAR_GROUPS.map((group, groupIndex) => (\n <div\n key={groupIndex}\n className={classNames(\n 'flex items-center gap-px',\n groupIndex < TOOLBAR_GROUPS.length - 1 && 'mr-1 border-r border-border pr-1',\n )}\n >\n {group.buttons.map(({ command, arg, icon, tooltipKey }) => {\n const key = arg ?? command;\n const isActive = activeCommands.has(key);\n\n return (\n <ControlledTooltip key={key} content={t(tooltipKey)}>\n <ControlledButton\n defaultHtmlButton\n disabled={disabled}\n onMouseDown={(event: React.MouseEvent) => {\n event.preventDefault();\n execFormat(command, arg);\n }}\n className={classNames(\n TOOLBAR_BUTTON_CLASS,\n isActive ? TOOLBAR_BUTTON_ACTIVE_CLASS : TOOLBAR_BUTTON_IDLE_CLASS,\n disabled && 'cursor-not-allowed opacity-40',\n )}\n >\n <MaterialSymbol icon={icon} size={18} />\n </ControlledButton>\n </ControlledTooltip>\n );\n })}\n </div>\n ))}\n\n <div className=\"flex items-center gap-px border-l border-border pl-1\">\n <ControlledPopoverRoot open={colorOpen} handler={setColorOpen} placement=\"bottom-start\">\n <ControlledTooltip content={t('createTask.rich.textColor')}>\n <ControlledPopoverHandler>\n <ControlledButton\n defaultHtmlButton\n disabled={disabled}\n onMouseDown={(event: React.MouseEvent) => {\n event.preventDefault();\n saveRange();\n }}\n className={classNames(\n TOOLBAR_BUTTON_CLASS,\n colorOpen ? TOOLBAR_BUTTON_ACTIVE_CLASS : TOOLBAR_BUTTON_IDLE_CLASS,\n disabled && 'cursor-not-allowed opacity-40',\n )}\n >\n <MaterialSymbol icon=\"format_color_text\" size={18} />\n </ControlledButton>\n </ControlledPopoverHandler>\n </ControlledTooltip>\n\n <ControlledPopoverContent className=\"zIndexMax w-44 p-2\">\n <div className=\"flex flex-wrap gap-1.5\">\n {RICH_TEXT_COLORS.map((color) => (\n <ControlledTooltip key={color} content={t(`createTask.rich.colors.${color}`)}>\n <ControlledButton\n defaultHtmlButton\n aria-pressed={activeColor === color}\n onMouseDown={(event: React.MouseEvent) => {\n event.preventDefault();\n handleApplyColor(color);\n }}\n className={classNames(\n 'flex size-7 items-center justify-center rounded-lg border transition-colors',\n activeColor === color ? 'border-brand-border ring-2 ring-brand-border' : 'border-border',\n )}\n >\n <span\n className={classNames(\n 'size-4 rounded-full',\n RICH_TEXT_COLOR_SWATCH_CLASS[color],\n color === 'default' && 'ring-1 ring-inset ring-border-strong',\n )}\n />\n </ControlledButton>\n </ControlledTooltip>\n ))}\n </div>\n </ControlledPopoverContent>\n </ControlledPopoverRoot>\n\n <ControlledTooltip content={t('createTask.rich.link')}>\n <ControlledButton\n defaultHtmlButton\n disabled={disabled}\n onMouseDown={(event: React.MouseEvent) => {\n event.preventDefault();\n saveRange();\n setShowLinkInput((previous) => !previous);\n }}\n className={classNames(\n TOOLBAR_BUTTON_CLASS,\n showLinkInput ? TOOLBAR_BUTTON_ACTIVE_CLASS : TOOLBAR_BUTTON_IDLE_CLASS,\n disabled && 'cursor-not-allowed opacity-40',\n )}\n >\n <MaterialSymbol icon=\"link\" size={18} />\n </ControlledButton>\n </ControlledTooltip>\n </div>\n\n {toolbarSlot && <div className=\"ml-auto flex items-center gap-x-1\">{toolbarSlot}</div>}\n </div>\n )}\n\n {showLinkInput && (\n <div className=\"flex items-center gap-2 border-b border-border-subtle bg-muted px-3 py-2\">\n <ControlledInput\n autoFocus\n value={linkUrl}\n onChange={(event) => setLinkUrl(event.target.value)}\n placeholder=\"https://\"\n aria-label={t('createTask.rich.link')}\n onKeyDown={(event: React.KeyboardEvent) => {\n if (event.key === 'Enter') applyLink();\n if (event.key === 'Escape') setShowLinkInput(false);\n }}\n />\n <ControlledButton size=\"sm\" onClick={applyLink}>\n {t('actions.apply')}\n </ControlledButton>\n <ControlledButton size=\"sm\" variant=\"outlined\" tone=\"neutral\" onClick={() => setShowLinkInput(false)}>\n {t('actions.cancel')}\n </ControlledButton>\n </div>\n )}\n\n <div className=\"relative\">\n <div\n ref={editorRef}\n contentEditable={!disabled}\n suppressContentEditableWarning\n onInput={handleInput}\n onKeyDown={onKeyDown}\n onPaste={handlePaste}\n onKeyUp={() => {\n saveRange();\n syncActiveCommands();\n }}\n onMouseUp={() => {\n saveRange();\n syncActiveCommands();\n }}\n onFocus={() => setIsFocused(true)}\n onBlur={() => {\n saveRange();\n setIsFocused(false);\n onBlur?.();\n }}\n className={classNames(\n 'w-full px-3 py-2.5 text-sm text-foreground outline-none',\n '[&_ol]:ml-4 [&_ol]:list-decimal [&_ul]:ml-4 [&_ul]:list-disc',\n '[&_blockquote]:border-l-2 [&_blockquote]:border-brand-border [&_blockquote]:pl-3 [&_blockquote]:italic [&_blockquote]:text-foreground-subtle',\n '[&_a]:text-brand-emphasis [&_a]:underline',\n '[&_a.rt-file]:text-foreground-muted [&_a.rt-file]:no-underline',\n '[&_user]:whitespace-nowrap [&_user]:rounded [&_user]:bg-brand-soft [&_user]:px-1 [&_user]:font-medium [&_user]:text-brand-emphasis',\n disabled && 'cursor-not-allowed opacity-60',\n )}\n style={{ minHeight }}\n />\n {isEmpty && !isFocused && placeholder && (\n <span className=\"pointer-events-none absolute left-3 top-2.5 text-sm text-foreground-faint\">\n {placeholder}\n </span>\n )}\n </div>\n\n {showPreviews && attachmentsController && attachmentsController.stagedAttachments.length > 0 && (\n <div className=\"px-3 pb-2\">\n <AttachmentPreviewList\n stagedAttachments={attachmentsController.stagedAttachments}\n onRemove={attachmentsController.removeAttachment}\n onRetry={attachmentsController.retryAttachment}\n />\n </div>\n )}\n\n {showActionsBar && (\n <div className=\"flex items-center gap-x-0.5 px-2 pb-2 pt-0.5\">\n {formattingToggle && (\n <ControlledTooltip content={t('followUp.chat.formatting')} className=\"z-[9999]\">\n <ControlledButton\n defaultHtmlButton\n disabled={disabled}\n onClick={() => setFormattingOpen((previous) => !previous)}\n aria-pressed={formattingOpen}\n className={formattingOpen ? ACTION_BUTTON_ACTIVE_CLASS : ACTION_BUTTON_CLASS}\n >\n <MaterialSymbol icon=\"format_size\" size={18} />\n </ControlledButton>\n </ControlledTooltip>\n )}\n\n {attachmentsController && (\n <ControlledMenuRoot placement=\"top-start\">\n <ControlledTooltip content={t('followUp.attachments.attach')} className=\"z-[9999]\">\n <ControlledMenuHandler>\n <ControlledButton defaultHtmlButton disabled={disabled} className={ACTION_BUTTON_CLASS}>\n <MaterialSymbol icon=\"attach_file\" size={18} />\n </ControlledButton>\n </ControlledMenuHandler>\n </ControlledTooltip>\n <ControlledMenuList className=\"zIndexMax p-1\">\n {attachMenuActions.map((action) => (\n <ControlledMenuItem key={action.key} className=\"flex items-center gap-x-2\" onClick={action.onClick}>\n <MaterialSymbol icon={action.icon} size={18} />\n {action.label}\n </ControlledMenuItem>\n ))}\n </ControlledMenuList>\n </ControlledMenuRoot>\n )}\n\n {actionsSlot}\n </div>\n )}\n\n {attachmentsController && (\n <>\n <input ref={fileInputRef} type=\"file\" multiple hidden onChange={handleFilesPicked} />\n <input\n ref={imageInputRef}\n type=\"file\"\n multiple\n hidden\n accept={IMAGE_INPUT_ACCEPT}\n onChange={handleFilesPicked}\n />\n </>\n )}\n </div>\n );\n\n if (!attachmentsController || attachments?.hideDropzone) return editorShell;\n\n return (\n <FileDropzone\n stopPropagation\n disabled={disabled}\n className=\"flex-none\"\n overlayClassName={DROPZONE_OVERLAY_CLASS}\n onFilesDropped={(files) => attachmentsController.addFiles(files)}\n >\n {editorShell}\n </FileDropzone>\n );\n});\n\nexport default RichTextEditor;\n"],"names":["RichTextEditor"],"mappings":";;;;;;;;;;;;;;AA+HA,MAAM,iBAAuC;AAAA,EAC3C;AAAA,IACE,SAAS;AAAA,MACP,EAAE,SAAS,QAAQ,MAAM,eAAe,YAAY,uBAAA;AAAA,MACpD,EAAE,SAAS,UAAU,MAAM,iBAAiB,YAAY,yBAAA;AAAA,MACxD,EAAE,SAAS,iBAAiB,MAAM,mBAAmB,YAAY,gCAAA;AAAA,IAAgC;AAAA,EACnG;AAAA,EAEF;AAAA,IACE,SAAS;AAAA,MACP;AAAA,QACE,SAAS;AAAA,QACT,MAAM;AAAA,QACN,YAAY;AAAA,QACZ,SAAS;AAAA,MAAA;AAAA,MAEX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cACR,UAAU;AAAA,YAAA;AAAA,UAAA;AAAA,QACZ,EAAA,CACF;AAAA,MAAA;AAAA,IAAA;AAAA,EAAA;AAKN,MAAI,CAAC,yBAAyB,aAAa,aAAc,QAAO;AAEhE,SACE;AAAA,IAAC;AAAA,IAAA;AAAA,MACC,iBAAe;AAAA,MACf;AAAA,MACA,WAAU;AAAA,MACV,kBAAkB;AAAA,MAClB,gBAAgB,CAAC,UAAU,sBAAsB,SAAS,KAAK;AAAA,MAE9D,UAAA;AAAA,IAAA;AAAA,EAAA;AAGP,CAAC;"}
|
|
1
|
+
{"version":3,"file":"RichTextEditor.js","sources":["../../../src/components/Form/RichTextEditor.tsx"],"sourcesContent":["import { forwardRef, useCallback, useEffect, useImperativeHandle, useMemo, useRef, useState } from 'react';\nimport classNames from 'classnames';\nimport { useTranslation } from 'react-i18next';\n\nimport {\n ControlledMenuHandler,\n ControlledMenuItem,\n ControlledMenuList,\n ControlledMenuRoot,\n} from '@/components/UI/ControlledMenu';\nimport {\n ControlledPopoverContent,\n ControlledPopoverHandler,\n ControlledPopoverRoot,\n} from '@/components/UI/ControlledPopover';\nimport ControlledTooltip from '@/components/UI/ControlledTooltip';\nimport {\n activeRichTextColor,\n applyRichTextColor,\n buildFileChipMarkup,\n normalizeRichTextColorNodes,\n RICH_TEXT_COLOR_SWATCH_CLASS,\n RICH_TEXT_COLORS,\n TRichTextColor,\n} from '@/helpers/richText';\nimport { IUseFileAttachmentsResult, TFileUploader, useFileAttachments } from '@/hooks/useFileAttachments';\n\nimport { MaterialSymbol, SymbolCodepoints } from '../UI/MaterialSymbol';\n\nimport AttachmentPreviewList from './attachments/AttachmentPreviewList';\nimport FileDropzone from './attachments/FileDropzone';\nimport ControlledButton from './ControlledButton';\nimport ControlledInput from './ControlledInput';\n\n/** An extra entry in the attach menu, for a source only the host knows about (a camera dialog). */\nexport interface IRichTextAttachAction {\n key: string;\n icon: SymbolCodepoints;\n label: string;\n onClick: () => void;\n}\n\n/**\n * Files travel BESIDE the text: the host owns a list of attachments of its own (a chat message\n * has one) and reads `controller.readyAttachments` when it saves.\n */\nexport interface IRichTextAttachmentsConfig {\n controller: IUseFileAttachmentsResult;\n extraActions?: Array<IRichTextAttachAction>;\n /** The host already renders the staged previews somewhere else. */\n hidePreviews?: boolean;\n /** The host already wraps a wider drop target around this editor. */\n hideDropzone?: boolean;\n}\n\n/**\n * Files travel INSIDE the text: the upload result is written into the body as a chip, so the\n * reference persists anywhere the HTML itself is stored and no host needs a new field.\n */\nexport interface IRichTextInlineUploadConfig {\n uploadFile?: TFileUploader;\n maxFiles?: number;\n maxFileSizeBytes?: number;\n}\n\ninterface IRichTextEditorProps {\n value?: string;\n onChange?: (html: string) => void;\n placeholder?: string;\n disabled?: boolean;\n error?: boolean;\n className?: string;\n minHeight?: number;\n /** Rendered inside the toolbar row, right-aligned: host actions that belong to the field. */\n toolbarSlot?: React.ReactNode;\n /** Rendered in the editor's own bottom bar, after the controls the editor owns. */\n actionsSlot?: React.ReactNode;\n onKeyDown?: (event: React.KeyboardEvent<HTMLDivElement>) => void;\n /** Fires when the editable area loses focus, for hosts that persist on blur. */\n onBlur?: () => void;\n /**\n * Fires with the full HTML when the editor changes the content on its own, which today means\n * an inline upload landing after the field already lost focus. A host that persists on blur\n * would otherwise never hear about the file it just attached.\n */\n onCommit?: (html: string) => void;\n /** 'bare' drops the border and focus ring: the host owns the chrome around the field. */\n variant?: 'default' | 'bare';\n /** Hosts with their own action bar (the chat composer) toggle the formatting row on demand. */\n showToolbar?: boolean;\n /** Renders the formatting toggle in the bottom bar and lets the editor own the row's state. */\n formattingToggle?: boolean;\n attachments?: IRichTextAttachmentsConfig;\n inlineUpload?: IRichTextInlineUploadConfig;\n}\n\nexport interface IRichTextEditorHandle {\n focus: () => void;\n /** Viewport rect of the caret, for anchoring a popover to what is being typed. */\n getCaretRect: () => DOMRect | null;\n /**\n * Text typed after the trigger and before the caret, or null when the caret is not inside a\n * trigger word. Drives both \"is the mention menu relevant\" and \"what is being searched\".\n * Spaces are allowed inside the query (people have compound names); the host decides when a\n * spaced query stopped matching anyone and closes the menu.\n */\n getMentionQuery: (trigger: string) => string | null;\n /**\n * Deletes the trigger AND the query the user typed after it, then writes the markup in their\n * place, so picking someone from a mention menu replaces everything typed since the `@`\n * instead of stacking the mention after it.\n */\n replaceTriggerWith: (trigger: string, query: string, html: string) => void;\n}\n\ninterface IToolbarGroup {\n buttons: Array<IToolbarButton>;\n}\n\ninterface IToolbarButton {\n command: string;\n arg?: string;\n icon: SymbolCodepoints;\n tooltipKey: string;\n isBlock?: boolean;\n}\n\nconst TOOLBAR_GROUPS: Array<IToolbarGroup> = [\n {\n buttons: [\n { command: 'bold', icon: 'format_bold', tooltipKey: 'createTask.rich.bold' },\n { command: 'italic', icon: 'format_italic', tooltipKey: 'createTask.rich.italic' },\n { command: 'strikeThrough', icon: 'strikethrough_s', tooltipKey: 'createTask.rich.strikethrough' },\n ],\n },\n {\n buttons: [\n {\n command: 'insertUnorderedList',\n icon: 'format_list_bulleted',\n tooltipKey: 'createTask.rich.bulletList',\n isBlock: true,\n },\n {\n command: 'insertOrderedList',\n icon: 'format_list_numbered',\n tooltipKey: 'createTask.rich.numberedList',\n isBlock: true,\n },\n {\n command: 'formatBlock',\n arg: 'BLOCKQUOTE',\n icon: 'format_quote',\n tooltipKey: 'createTask.rich.quote',\n isBlock: true,\n },\n ],\n },\n {\n buttons: [\n { command: 'indent', icon: 'format_indent_increase', tooltipKey: 'createTask.rich.indent' },\n { command: 'outdent', icon: 'format_indent_decrease', tooltipKey: 'createTask.rich.outdent' },\n ],\n },\n];\n\nconst MENTION_QUERY_MAX_LENGTH = 40;\nconst IMAGE_INPUT_ACCEPT = 'image/*';\nconst DROPZONE_OVERLAY_CLASS = 'rounded-xl';\n\nconst TOOLBAR_BUTTON_CLASS = 'flex size-7 items-center justify-center rounded-lg transition-colors';\nconst TOOLBAR_BUTTON_IDLE_CLASS = 'text-foreground-subtle hover:bg-muted-hover hover:text-foreground-muted';\nconst TOOLBAR_BUTTON_ACTIVE_CLASS = 'bg-brand-soft text-brand-emphasis';\nconst ACTION_BUTTON_CLASS =\n 'flex size-8 items-center justify-center rounded-full text-foreground-faint transition-colors hover:bg-muted-hover hover:text-foreground-muted disabled:text-foreground-faint';\nconst ACTION_BUTTON_ACTIVE_CLASS =\n 'flex size-8 items-center justify-center rounded-full bg-brand-soft text-brand-emphasis transition-colors hover:bg-brand-soft';\n\nconst isCommandActive = (command: string, arg?: string): boolean => {\n try {\n if (arg) return document.queryCommandValue(command) === arg.toLowerCase();\n return document.queryCommandState(command);\n } catch {\n return false;\n }\n};\n\nconst RichTextEditor = forwardRef<IRichTextEditorHandle, IRichTextEditorProps>(function RichTextEditor(\n {\n value = '',\n onChange,\n placeholder,\n disabled = false,\n error = false,\n className,\n minHeight = 120,\n toolbarSlot,\n actionsSlot,\n onKeyDown,\n onBlur,\n onCommit,\n variant = 'default',\n showToolbar = true,\n formattingToggle = false,\n attachments,\n inlineUpload,\n },\n ref,\n) {\n const { t } = useTranslation('ui');\n const editorRef = useRef<HTMLDivElement>(null);\n const [activeCommands, setActiveCommands] = useState<Set<string>>(new Set());\n const [activeColor, setActiveColor] = useState<TRichTextColor>('default');\n const [colorOpen, setColorOpen] = useState(false);\n const [showLinkInput, setShowLinkInput] = useState(false);\n const [linkUrl, setLinkUrl] = useState('');\n const [isFocused, setIsFocused] = useState(false);\n const [formattingOpen, setFormattingOpen] = useState(false);\n const savedRangeRef = useRef<Range | null>(null);\n const isInternalUpdateRef = useRef(false);\n const fileInputRef = useRef<HTMLInputElement>(null);\n const imageInputRef = useRef<HTMLInputElement>(null);\n const insertedStagingIdsRef = useRef<Set<string>>(new Set());\n const pendingColorRef = useRef<TRichTextColor>('default');\n\n const inlineController = useFileAttachments({\n uploadFile: inlineUpload?.uploadFile,\n maxFiles: inlineUpload?.maxFiles,\n maxFileSizeBytes: inlineUpload?.maxFileSizeBytes,\n });\n\n const attachmentsController = attachments?.controller ?? (inlineUpload ? inlineController : null);\n const inlineStagedAttachments = inlineController.stagedAttachments;\n const toolbarVisible = formattingToggle ? formattingOpen : showToolbar;\n\n useEffect(() => {\n const editor = editorRef.current;\n if (!editor) return;\n if (isInternalUpdateRef.current) return;\n if (editor.innerHTML !== value) {\n editor.innerHTML = value;\n }\n }, [value]);\n\n const emitChange = useCallback(() => {\n const editor = editorRef.current;\n if (!editor) return;\n isInternalUpdateRef.current = true;\n onChange?.(editor.innerHTML);\n isInternalUpdateRef.current = false;\n }, [onChange]);\n\n const syncActiveCommands = useCallback(() => {\n const active = new Set<string>();\n TOOLBAR_GROUPS.flatMap((group) => group.buttons).forEach(({ command, arg }) => {\n if (isCommandActive(command, arg)) active.add(arg ?? command);\n });\n setActiveCommands(active);\n\n const editor = editorRef.current;\n if (editor) setActiveColor(activeRichTextColor(editor));\n }, []);\n\n const execFormat = useCallback(\n (command: string, arg?: string) => {\n const editor = editorRef.current;\n if (!editor || disabled) return;\n editor.focus();\n document.execCommand(command, false, arg);\n emitChange();\n syncActiveCommands();\n },\n [disabled, emitChange, syncActiveCommands],\n );\n\n const saveRange = useCallback(() => {\n const selection = window.getSelection();\n if (selection && selection.rangeCount > 0) {\n savedRangeRef.current = selection.getRangeAt(0).cloneRange();\n }\n }, []);\n\n const restoreRange = useCallback(() => {\n const range = savedRangeRef.current;\n if (!range) return;\n const selection = window.getSelection();\n if (!selection) return;\n selection.removeAllRanges();\n selection.addRange(range);\n }, []);\n\n const applyLink = useCallback(() => {\n const url = linkUrl.trim();\n restoreRange();\n if (url) execFormat('createLink', url.startsWith('http') ? url : `https://${url}`);\n setShowLinkInput(false);\n setLinkUrl('');\n }, [linkUrl, restoreRange, execFormat]);\n\n const handleApplyColor = useCallback(\n (color: TRichTextColor) => {\n const editor = editorRef.current;\n if (!editor || disabled) return;\n\n editor.focus();\n restoreRange();\n pendingColorRef.current = color;\n applyRichTextColor(editor, color);\n emitChange();\n setActiveColor(color);\n setColorOpen(false);\n },\n [disabled, emitChange, restoreRange],\n );\n\n const insertHtmlAtCaret = useCallback(\n (html: string, commit = false) => {\n const editor = editorRef.current;\n if (!editor || disabled) return;\n\n const previouslyFocused = document.activeElement as HTMLElement | null;\n const editorHadFocus = editor.contains(previouslyFocused);\n\n editor.focus();\n restoreRange();\n\n const selection = window.getSelection();\n const caretIsInside = selection?.anchorNode ? editor.contains(selection.anchorNode) : false;\n\n if (!caretIsInside) {\n const range = document.createRange();\n range.selectNodeContents(editor);\n range.collapse(false);\n selection?.removeAllRanges();\n selection?.addRange(range);\n }\n\n document.execCommand('insertHTML', false, html);\n saveRange();\n emitChange();\n\n if (!editorHadFocus) previouslyFocused?.focus();\n if (commit) onCommit?.(editor.innerHTML);\n },\n [disabled, emitChange, onCommit, restoreRange, saveRange],\n );\n\n const inlineControllerRef = useRef(inlineController);\n inlineControllerRef.current = inlineController;\n\n // An inline upload lands in the body the moment it finishes, and leaves the staging list so\n // the progress card disappears with it.\n useEffect(() => {\n if (!inlineUpload) return;\n\n inlineStagedAttachments.forEach((staged) => {\n const uploaded = staged.uploaded;\n if (staged.status !== 'done' || !uploaded) return;\n\n if (!insertedStagingIdsRef.current.has(staged.stagingId)) {\n insertedStagingIdsRef.current.add(staged.stagingId);\n insertHtmlAtCaret(`${buildFileChipMarkup(uploaded)} `, true);\n }\n inlineControllerRef.current.removeAttachment(staged.stagingId);\n });\n }, [inlineUpload, inlineStagedAttachments, insertHtmlAtCaret]);\n\n const handleInput = useCallback(() => {\n const editor = editorRef.current;\n if (editor) normalizeRichTextColorNodes(editor, pendingColorRef.current);\n emitChange();\n syncActiveCommands();\n }, [emitChange, syncActiveCommands]);\n\n const handleFilesPicked = (event: React.ChangeEvent<HTMLInputElement>) => {\n const files = Array.from(event.target.files ?? []);\n if (files.length) attachmentsController?.addFiles(files);\n event.target.value = '';\n };\n\n const handlePaste = (event: React.ClipboardEvent) => {\n if (!attachmentsController) return;\n\n const files = Array.from(event.clipboardData?.files ?? []);\n if (!files.length) return;\n\n event.preventDefault();\n event.stopPropagation();\n attachmentsController.addFiles(files);\n };\n\n useImperativeHandle(ref, () => ({\n focus: () => editorRef.current?.focus(),\n\n getCaretRect: () => {\n const selection = window.getSelection();\n if (!selection?.rangeCount) return null;\n\n const range = selection.getRangeAt(0).cloneRange();\n range.collapse(false);\n\n const [rect] = Array.from(range.getClientRects());\n if (rect) return rect;\n\n // A collapsed range inside an empty node measures nothing, so a throwaway marker gives it\n // something to measure. Removed in the same tick, before anything can observe it.\n const marker = document.createElement('span');\n marker.textContent = '\\u200b';\n range.insertNode(marker);\n const markerRect = marker.getBoundingClientRect();\n marker.remove();\n\n return markerRect;\n },\n\n getMentionQuery: (trigger) => {\n const selection = window.getSelection();\n if (!selection?.rangeCount) return null;\n\n const range = selection.getRangeAt(0);\n if (!range.collapsed || range.startContainer.nodeType !== Node.TEXT_NODE) return null;\n\n const textBeforeCaret = range.startContainer.textContent?.slice(0, range.startOffset) ?? '';\n const escapedTrigger = trigger.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n const match = new RegExp(`(?:^|\\\\s)${escapedTrigger}([^${escapedTrigger}]*)$`).exec(textBeforeCaret);\n if (!match) return null;\n\n const query = match[1];\n if (query.startsWith(' ') || query.length > MENTION_QUERY_MAX_LENGTH) return null;\n\n return query;\n },\n\n replaceTriggerWith: (trigger, query, html) => {\n const editor = editorRef.current;\n if (!editor || disabled) return;\n\n editor.focus();\n restoreRange();\n\n const selection = window.getSelection();\n const range = selection?.rangeCount ? selection.getRangeAt(0) : null;\n\n if (range?.collapsed && range.startContainer.nodeType === Node.TEXT_NODE) {\n const textBeforeCaret = range.startContainer.textContent?.slice(0, range.startOffset) ?? '';\n const typed = `${trigger}${query}`;\n if (textBeforeCaret.endsWith(typed)) {\n range.setStart(range.startContainer, range.startOffset - typed.length);\n range.deleteContents();\n } else if (textBeforeCaret.endsWith(trigger)) {\n range.setStart(range.startContainer, range.startOffset - trigger.length);\n range.deleteContents();\n }\n }\n\n document.execCommand('insertHTML', false, `${html} `);\n emitChange();\n },\n }));\n\n const isEmpty = !editorRef.current?.textContent?.trim() && !editorRef.current?.querySelector('img, li, blockquote');\n\n const attachMenuActions = useMemo<Array<IRichTextAttachAction>>(\n () => [\n {\n key: 'file',\n icon: 'description',\n label: t('followUp.attachments.pickFile'),\n onClick: () => fileInputRef.current?.click(),\n },\n {\n key: 'image',\n icon: 'image',\n label: t('followUp.attachments.pickImage'),\n onClick: () => imageInputRef.current?.click(),\n },\n ...(attachments?.extraActions ?? []),\n ],\n [attachments?.extraActions, t],\n );\n\n const showPreviews = Boolean(attachmentsController) && !attachments?.hidePreviews;\n const showActionsBar = Boolean(attachmentsController) || Boolean(actionsSlot) || formattingToggle;\n\n const editorShell = (\n <div\n className={classNames(\n 'flex w-full flex-col transition-colors',\n variant === 'default' && 'rounded-xl border bg-surface',\n variant === 'default' &&\n (error\n ? 'border-danger-border'\n : isFocused\n ? 'border-brand-border ring-2 ring-brand-border'\n : 'border-border'),\n className,\n )}\n >\n {toolbarVisible && (\n <div\n className={classNames(\n 'flex flex-wrap items-center gap-px border-b px-2 py-1.5',\n error ? 'border-danger-border' : 'border-border-subtle',\n )}\n >\n {TOOLBAR_GROUPS.map((group, groupIndex) => (\n <div\n key={groupIndex}\n className={classNames(\n 'flex items-center gap-px',\n groupIndex < TOOLBAR_GROUPS.length - 1 && 'mr-1 border-r border-border pr-1',\n )}\n >\n {group.buttons.map(({ command, arg, icon, tooltipKey }) => {\n const key = arg ?? command;\n const isActive = activeCommands.has(key);\n\n return (\n <ControlledTooltip key={key} content={t(tooltipKey)}>\n <ControlledButton\n defaultHtmlButton\n disabled={disabled}\n onMouseDown={(event: React.MouseEvent) => {\n event.preventDefault();\n execFormat(command, arg);\n }}\n className={classNames(\n TOOLBAR_BUTTON_CLASS,\n isActive ? TOOLBAR_BUTTON_ACTIVE_CLASS : TOOLBAR_BUTTON_IDLE_CLASS,\n disabled && 'cursor-not-allowed opacity-40',\n )}\n >\n <MaterialSymbol icon={icon} size={18} />\n </ControlledButton>\n </ControlledTooltip>\n );\n })}\n </div>\n ))}\n\n <div className=\"flex items-center gap-px border-l border-border pl-1\">\n <ControlledPopoverRoot open={colorOpen} handler={setColorOpen} placement=\"bottom-start\">\n <ControlledTooltip content={t('createTask.rich.textColor')}>\n <ControlledPopoverHandler>\n <ControlledButton\n defaultHtmlButton\n disabled={disabled}\n onMouseDown={(event: React.MouseEvent) => {\n event.preventDefault();\n saveRange();\n }}\n className={classNames(\n TOOLBAR_BUTTON_CLASS,\n colorOpen ? TOOLBAR_BUTTON_ACTIVE_CLASS : TOOLBAR_BUTTON_IDLE_CLASS,\n disabled && 'cursor-not-allowed opacity-40',\n )}\n >\n <MaterialSymbol icon=\"format_color_text\" size={18} />\n </ControlledButton>\n </ControlledPopoverHandler>\n </ControlledTooltip>\n\n <ControlledPopoverContent className=\"zIndexMax w-44 p-2\">\n <div className=\"flex flex-wrap gap-1.5\">\n {RICH_TEXT_COLORS.map((color) => (\n <ControlledTooltip key={color} content={t(`createTask.rich.colors.${color}`)}>\n <ControlledButton\n defaultHtmlButton\n aria-pressed={activeColor === color}\n onMouseDown={(event: React.MouseEvent) => {\n event.preventDefault();\n handleApplyColor(color);\n }}\n className={classNames(\n 'flex size-7 items-center justify-center rounded-lg border transition-colors',\n activeColor === color ? 'border-brand-border ring-2 ring-brand-border' : 'border-border',\n )}\n >\n <span\n className={classNames(\n 'size-4 rounded-full',\n RICH_TEXT_COLOR_SWATCH_CLASS[color],\n color === 'default' && 'ring-1 ring-inset ring-border-strong',\n )}\n />\n </ControlledButton>\n </ControlledTooltip>\n ))}\n </div>\n </ControlledPopoverContent>\n </ControlledPopoverRoot>\n\n <ControlledTooltip content={t('createTask.rich.link')}>\n <ControlledButton\n defaultHtmlButton\n disabled={disabled}\n onMouseDown={(event: React.MouseEvent) => {\n event.preventDefault();\n saveRange();\n setShowLinkInput((previous) => !previous);\n }}\n className={classNames(\n TOOLBAR_BUTTON_CLASS,\n showLinkInput ? TOOLBAR_BUTTON_ACTIVE_CLASS : TOOLBAR_BUTTON_IDLE_CLASS,\n disabled && 'cursor-not-allowed opacity-40',\n )}\n >\n <MaterialSymbol icon=\"link\" size={18} />\n </ControlledButton>\n </ControlledTooltip>\n </div>\n\n {toolbarSlot && <div className=\"ml-auto flex items-center gap-x-1\">{toolbarSlot}</div>}\n </div>\n )}\n\n {showLinkInput && (\n <div className=\"flex items-center gap-2 border-b border-border-subtle bg-muted px-3 py-2\">\n <ControlledInput\n autoFocus\n value={linkUrl}\n onChange={(event) => setLinkUrl(event.target.value)}\n placeholder=\"https://\"\n aria-label={t('createTask.rich.link')}\n onKeyDown={(event: React.KeyboardEvent) => {\n if (event.key === 'Enter') applyLink();\n if (event.key === 'Escape') setShowLinkInput(false);\n }}\n />\n <ControlledButton size=\"sm\" onClick={applyLink}>\n {t('actions.apply')}\n </ControlledButton>\n <ControlledButton size=\"sm\" variant=\"outlined\" tone=\"neutral\" onClick={() => setShowLinkInput(false)}>\n {t('actions.cancel')}\n </ControlledButton>\n </div>\n )}\n\n <div className=\"relative\">\n <div\n ref={editorRef}\n contentEditable={!disabled}\n suppressContentEditableWarning\n onInput={handleInput}\n onKeyDown={onKeyDown}\n onPaste={handlePaste}\n onKeyUp={() => {\n saveRange();\n syncActiveCommands();\n }}\n onMouseUp={() => {\n saveRange();\n syncActiveCommands();\n }}\n onFocus={() => setIsFocused(true)}\n onBlur={() => {\n saveRange();\n setIsFocused(false);\n onBlur?.();\n }}\n className={classNames(\n 'w-full px-3 py-2.5 text-sm text-foreground outline-none',\n '[&_ol]:ml-4 [&_ol]:list-decimal [&_ul]:ml-4 [&_ul]:list-disc',\n '[&_blockquote]:border-l-2 [&_blockquote]:border-brand-border [&_blockquote]:pl-3 [&_blockquote]:italic [&_blockquote]:text-foreground-subtle',\n '[&_a]:text-brand-emphasis [&_a]:underline',\n '[&_a.rt-file]:text-foreground-muted [&_a.rt-file]:no-underline',\n '[&_a.rt-image-link]:no-underline',\n '[&_user]:whitespace-nowrap [&_user]:rounded [&_user]:bg-brand-soft [&_user]:px-1 [&_user]:font-medium [&_user]:text-brand-emphasis',\n disabled && 'cursor-not-allowed opacity-60',\n )}\n style={{ minHeight }}\n />\n {isEmpty && !isFocused && placeholder && (\n <span className=\"pointer-events-none absolute left-3 top-2.5 text-sm text-foreground-faint\">\n {placeholder}\n </span>\n )}\n </div>\n\n {showPreviews && attachmentsController && attachmentsController.stagedAttachments.length > 0 && (\n <div className=\"px-3 pb-2\">\n <AttachmentPreviewList\n stagedAttachments={attachmentsController.stagedAttachments}\n onRemove={attachmentsController.removeAttachment}\n onRetry={attachmentsController.retryAttachment}\n />\n </div>\n )}\n\n {showActionsBar && (\n <div className=\"flex items-center gap-x-0.5 px-2 pb-2 pt-0.5\">\n {formattingToggle && (\n <ControlledTooltip content={t('followUp.chat.formatting')} className=\"z-[9999]\">\n <ControlledButton\n defaultHtmlButton\n disabled={disabled}\n onClick={() => setFormattingOpen((previous) => !previous)}\n aria-pressed={formattingOpen}\n className={formattingOpen ? ACTION_BUTTON_ACTIVE_CLASS : ACTION_BUTTON_CLASS}\n >\n <MaterialSymbol icon=\"format_size\" size={18} />\n </ControlledButton>\n </ControlledTooltip>\n )}\n\n {attachmentsController && (\n <ControlledMenuRoot placement=\"top-start\">\n <ControlledTooltip content={t('followUp.attachments.attach')} className=\"z-[9999]\">\n <ControlledMenuHandler>\n <ControlledButton defaultHtmlButton disabled={disabled} className={ACTION_BUTTON_CLASS}>\n <MaterialSymbol icon=\"attach_file\" size={18} />\n </ControlledButton>\n </ControlledMenuHandler>\n </ControlledTooltip>\n <ControlledMenuList className=\"zIndexMax p-1\">\n {attachMenuActions.map((action) => (\n <ControlledMenuItem key={action.key} className=\"flex items-center gap-x-2\" onClick={action.onClick}>\n <MaterialSymbol icon={action.icon} size={18} />\n {action.label}\n </ControlledMenuItem>\n ))}\n </ControlledMenuList>\n </ControlledMenuRoot>\n )}\n\n {actionsSlot}\n </div>\n )}\n\n {attachmentsController && (\n <>\n <input ref={fileInputRef} type=\"file\" multiple hidden onChange={handleFilesPicked} />\n <input\n ref={imageInputRef}\n type=\"file\"\n multiple\n hidden\n accept={IMAGE_INPUT_ACCEPT}\n onChange={handleFilesPicked}\n />\n </>\n )}\n </div>\n );\n\n if (!attachmentsController || attachments?.hideDropzone) return editorShell;\n\n return (\n <FileDropzone\n stopPropagation\n disabled={disabled}\n className=\"flex-none\"\n overlayClassName={DROPZONE_OVERLAY_CLASS}\n onFilesDropped={(files) => attachmentsController.addFiles(files)}\n >\n {editorShell}\n </FileDropzone>\n );\n});\n\nexport default RichTextEditor;\n"],"names":["RichTextEditor"],"mappings":";;;;;;;;;;;;;;AA+HA,MAAM,iBAAuC;AAAA,EAC3C;AAAA,IACE,SAAS;AAAA,MACP,EAAE,SAAS,QAAQ,MAAM,eAAe,YAAY,uBAAA;AAAA,MACpD,EAAE,SAAS,UAAU,MAAM,iBAAiB,YAAY,yBAAA;AAAA,MACxD,EAAE,SAAS,iBAAiB,MAAM,mBAAmB,YAAY,gCAAA;AAAA,IAAgC;AAAA,EACnG;AAAA,EAEF;AAAA,IACE,SAAS;AAAA,MACP;AAAA,QACE,SAAS;AAAA,QACT,MAAM;AAAA,QACN,YAAY;AAAA,QACZ,SAAS;AAAA,MAAA;AAAA,MAEX;AAAA,QACE,SAAS;AAAA,QACT,MAAM;AAAA,QACN,YAAY;AAAA,QACZ,SAAS;AAAA,MAAA;AAAA,MAEX;AAAA,QACE,SAAS;AAAA,QACT,KAAK;AAAA,QACL,MAAM;AAAA,QACN,YAAY;AAAA,QACZ,SAAS;AAAA,MAAA;AAAA,IACX;AAAA,EACF;AAAA,EAEF;AAAA,IACE,SAAS;AAAA,MACP,EAAE,SAAS,UAAU,MAAM,0BAA0B,YAAY,yBAAA;AAAA,MACjE,EAAE,SAAS,WAAW,MAAM,0BAA0B,YAAY,0BAAA;AAAA,IAA0B;AAAA,EAC9F;AAEJ;AAEA,MAAM,2BAA2B;AACjC,MAAM,qBAAqB;AAC3B,MAAM,yBAAyB;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|
3
|
+
import { twMerge } from "tailwind-merge";
|
|
3
4
|
import { sanitizeRichText } from "../../helpers/richText.js";
|
|
4
5
|
const RICH_TEXT_CONTENT_CLASS = classNames(
|
|
5
6
|
"break-words text-sm leading-relaxed",
|
|
6
7
|
"[&_a]:text-brand-emphasis [&_a]:underline",
|
|
7
8
|
"[&_a.rt-file]:text-foreground-muted [&_a.rt-file]:no-underline",
|
|
9
|
+
"[&_a.rt-image-link]:no-underline",
|
|
8
10
|
"[&_ol]:ml-4 [&_ol]:list-decimal [&_ul]:ml-4 [&_ul]:list-disc",
|
|
9
11
|
"[&_blockquote]:border-l-2 [&_blockquote]:border-brand-border [&_blockquote]:pl-3 [&_blockquote]:italic [&_blockquote]:text-foreground-subtle",
|
|
10
12
|
"[&_user]:whitespace-nowrap [&_user]:rounded [&_user]:bg-brand-soft [&_user]:px-1 [&_user]:font-medium [&_user]:text-brand-emphasis"
|
|
11
13
|
);
|
|
12
14
|
const RichTextContent = ({ html, className, plainText = false }) => {
|
|
13
15
|
if (plainText) {
|
|
14
|
-
return /* @__PURE__ */ jsx("div", { className:
|
|
16
|
+
return /* @__PURE__ */ jsx("div", { className: twMerge(RICH_TEXT_CONTENT_CLASS, "whitespace-pre-line", className), children: html });
|
|
15
17
|
}
|
|
16
18
|
return /* @__PURE__ */ jsx(
|
|
17
19
|
"div",
|
|
18
20
|
{
|
|
19
|
-
className:
|
|
21
|
+
className: twMerge(RICH_TEXT_CONTENT_CLASS, className),
|
|
20
22
|
dangerouslySetInnerHTML: { __html: sanitizeRichText(html) }
|
|
21
23
|
}
|
|
22
24
|
);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"RichTextContent.js","sources":["../../../src/components/UI/RichTextContent.tsx"],"sourcesContent":["import classNames from 'classnames';\n\nimport { sanitizeRichText } from '@/helpers/richText';\n\ninterface IRichTextContentProps {\n html?: string;\n className?: string;\n /**\n * Reads the value as legacy plain text: real line breaks, no markup. Opt in per surface with\n * `isPlainTextBody`, never by default: a body whose only markup is a `<user>` mention would\n * otherwise render its tags as visible text.\n */\n plainText?: boolean;\n}\n\n/** The typography of a rich text body, shared by every surface that renders one. */\nexport const RICH_TEXT_CONTENT_CLASS = classNames(\n 'break-words text-sm leading-relaxed',\n '[&_a]:text-brand-emphasis [&_a]:underline',\n '[&_a.rt-file]:text-foreground-muted [&_a.rt-file]:no-underline',\n '[&_ol]:ml-4 [&_ol]:list-decimal [&_ul]:ml-4 [&_ul]:list-disc',\n '[&_blockquote]:border-l-2 [&_blockquote]:border-brand-border [&_blockquote]:pl-3 [&_blockquote]:italic [&_blockquote]:text-foreground-subtle',\n '[&_user]:whitespace-nowrap [&_user]:rounded [&_user]:bg-brand-soft [&_user]:px-1 [&_user]:font-medium [&_user]:text-brand-emphasis',\n);\n\nconst RichTextContent: React.FC<IRichTextContentProps> = ({ html, className, plainText = false }) => {\n if (plainText) {\n return <div className={
|
|
1
|
+
{"version":3,"file":"RichTextContent.js","sources":["../../../src/components/UI/RichTextContent.tsx"],"sourcesContent":["import classNames from 'classnames';\nimport { twMerge } from 'tailwind-merge';\n\nimport { sanitizeRichText } from '@/helpers/richText';\n\ninterface IRichTextContentProps {\n html?: string;\n className?: string;\n /**\n * Reads the value as legacy plain text: real line breaks, no markup. Opt in per surface with\n * `isPlainTextBody`, never by default: a body whose only markup is a `<user>` mention would\n * otherwise render its tags as visible text.\n */\n plainText?: boolean;\n}\n\n/** The typography of a rich text body, shared by every surface that renders one. */\nexport const RICH_TEXT_CONTENT_CLASS = classNames(\n 'break-words text-sm leading-relaxed',\n '[&_a]:text-brand-emphasis [&_a]:underline',\n '[&_a.rt-file]:text-foreground-muted [&_a.rt-file]:no-underline',\n '[&_a.rt-image-link]:no-underline',\n '[&_ol]:ml-4 [&_ol]:list-decimal [&_ul]:ml-4 [&_ul]:list-disc',\n '[&_blockquote]:border-l-2 [&_blockquote]:border-brand-border [&_blockquote]:pl-3 [&_blockquote]:italic [&_blockquote]:text-foreground-subtle',\n '[&_user]:whitespace-nowrap [&_user]:rounded [&_user]:bg-brand-soft [&_user]:px-1 [&_user]:font-medium [&_user]:text-brand-emphasis',\n);\n\nconst RichTextContent: React.FC<IRichTextContentProps> = ({ html, className, plainText = false }) => {\n if (plainText) {\n return <div className={twMerge(RICH_TEXT_CONTENT_CLASS, 'whitespace-pre-line', className)}>{html}</div>;\n }\n\n return (\n <div\n className={twMerge(RICH_TEXT_CONTENT_CLASS, className)}\n dangerouslySetInnerHTML={{ __html: sanitizeRichText(html) }}\n />\n );\n};\n\nexport default RichTextContent;\n"],"names":[],"mappings":";;;;AAiBO,MAAM,0BAA0B;AAAA,EACrC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAEA,MAAM,kBAAmD,CAAC,EAAE,MAAM,WAAW,YAAY,YAAY;AACnG,MAAI,WAAW;AACb,WAAO,oBAAC,SAAI,WAAW,QAAQ,yBAAyB,uBAAuB,SAAS,GAAI,UAAA,KAAA,CAAK;AAAA,EACnG;AAEA,SACE;AAAA,IAAC;AAAA,IAAA;AAAA,MACC,WAAW,QAAQ,yBAAyB,SAAS;AAAA,MACrD,yBAAyB,EAAE,QAAQ,iBAAiB,IAAI,EAAA;AAAA,IAAE;AAAA,EAAA;AAGhE;"}
|
|
@@ -5,6 +5,9 @@ export declare const RICH_TEXT_COLOR_CLASS: Record<Exclude<TRichTextColor, 'defa
|
|
|
5
5
|
/** The swatch shown in the palette: a token-driven background, never the stored value. */
|
|
6
6
|
export declare const RICH_TEXT_COLOR_SWATCH_CLASS: Record<TRichTextColor, string>;
|
|
7
7
|
export declare const RICH_TEXT_FILE_CLASS = "rt-file";
|
|
8
|
+
/** An image written INTO the body, as opposed to a file referenced by name. */
|
|
9
|
+
export declare const RICH_TEXT_IMAGE_CLASS = "rt-image";
|
|
10
|
+
export declare const RICH_TEXT_IMAGE_LINK_CLASS = "rt-image-link";
|
|
8
11
|
/**
|
|
9
12
|
* Text written before the rich editor existed is plain text with real line breaks. Rendered as
|
|
10
13
|
* HTML those breaks collapse, so the renderer needs to know which format it is looking at.
|
|
@@ -13,6 +16,10 @@ export declare const isPlainTextBody: (html?: string) => boolean;
|
|
|
13
16
|
export declare const sanitizeRichText: (html?: string) => string;
|
|
14
17
|
/** Emptiness has to be measured on the text: an editor the user only clicked into holds `<br>`. */
|
|
15
18
|
export declare const richTextToPlainText: (html?: string) => string;
|
|
19
|
+
/**
|
|
20
|
+
* A body whose only content is an attachment has no text at all, so measuring emptiness on the
|
|
21
|
+
* text alone would throw away the picture the user just wrote into the field.
|
|
22
|
+
*/
|
|
16
23
|
export declare const isRichTextEmpty: (html?: string) => boolean;
|
|
17
24
|
/**
|
|
18
25
|
* Seeds the editor from a value stored before the field became rich text. The line structure is
|
|
@@ -33,5 +40,7 @@ export declare const activeRichTextColor: (editor: HTMLElement) => TRichTextColo
|
|
|
33
40
|
/**
|
|
34
41
|
* An uploaded file referenced from inside the body. Hosts that have no attachment field of
|
|
35
42
|
* their own still keep the reference, because it travels in the same string the text does.
|
|
43
|
+
* An image is written as the picture itself, wrapped in the link that opens it at full size:
|
|
44
|
+
* a name-only chip hides what was attached, and the reader has no way to look at it.
|
|
36
45
|
*/
|
|
37
46
|
export declare const buildFileChipMarkup: (attachment: IFileAttachment) => string;
|
package/dist/helpers/richText.js
CHANGED
|
@@ -33,8 +33,15 @@ const RICH_TEXT_COLOR_SWATCH_CLASS = {
|
|
|
33
33
|
muted: "bg-foreground-faint"
|
|
34
34
|
};
|
|
35
35
|
const RICH_TEXT_FILE_CLASS = "rt-file";
|
|
36
|
+
const RICH_TEXT_IMAGE_CLASS = "rt-image";
|
|
37
|
+
const RICH_TEXT_IMAGE_LINK_CLASS = "rt-image-link";
|
|
36
38
|
const COLOR_CLASS_LIST = Object.values(RICH_TEXT_COLOR_CLASS);
|
|
37
|
-
const ALLOWED_CLASSES = /* @__PURE__ */ new Set([
|
|
39
|
+
const ALLOWED_CLASSES = /* @__PURE__ */ new Set([
|
|
40
|
+
...COLOR_CLASS_LIST,
|
|
41
|
+
RICH_TEXT_FILE_CLASS,
|
|
42
|
+
RICH_TEXT_IMAGE_CLASS,
|
|
43
|
+
RICH_TEXT_IMAGE_LINK_CLASS
|
|
44
|
+
]);
|
|
38
45
|
const ALLOWED_TAGS = [
|
|
39
46
|
MENTION_TAG,
|
|
40
47
|
"p",
|
|
@@ -52,9 +59,10 @@ const ALLOWED_TAGS = [
|
|
|
52
59
|
"ol",
|
|
53
60
|
"li",
|
|
54
61
|
"blockquote",
|
|
55
|
-
"a"
|
|
62
|
+
"a",
|
|
63
|
+
"img"
|
|
56
64
|
];
|
|
57
|
-
const ALLOWED_ATTR = ["href", "target", "rel", "class"];
|
|
65
|
+
const ALLOWED_ATTR = ["href", "target", "rel", "class", "src", "alt", "width", "height"];
|
|
58
66
|
let hookRegistered = false;
|
|
59
67
|
const registerSanitizerHooks = () => {
|
|
60
68
|
if (hookRegistered) return;
|
|
@@ -89,7 +97,11 @@ const richTextToPlainText = (html) => {
|
|
|
89
97
|
const parsed = new DOMParser().parseFromString(sanitizeRichText(html), "text/html");
|
|
90
98
|
return (parsed.body.textContent ?? "").trim();
|
|
91
99
|
};
|
|
92
|
-
const isRichTextEmpty = (html) =>
|
|
100
|
+
const isRichTextEmpty = (html) => {
|
|
101
|
+
if (richTextToPlainText(html).length > 0) return false;
|
|
102
|
+
const parsed = new DOMParser().parseFromString(sanitizeRichText(html), "text/html");
|
|
103
|
+
return parsed.body.querySelector(`img, .${RICH_TEXT_FILE_CLASS}`) === null;
|
|
104
|
+
};
|
|
93
105
|
const HTML_ESCAPES = {
|
|
94
106
|
"&": "&",
|
|
95
107
|
"<": "<",
|
|
@@ -143,20 +155,34 @@ const activeRichTextColor = (editor) => {
|
|
|
143
155
|
);
|
|
144
156
|
return match?.[0] ?? "default";
|
|
145
157
|
};
|
|
158
|
+
const isImageAttachment = (attachment) => attachment.kind === "image" || attachment.mimeType?.startsWith("image/") === true;
|
|
146
159
|
const buildFileChipMarkup = (attachment) => {
|
|
147
|
-
const
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
160
|
+
const link = document.createElement("a");
|
|
161
|
+
link.setAttribute("href", attachment.url);
|
|
162
|
+
link.setAttribute("target", "_blank");
|
|
163
|
+
link.setAttribute("rel", "noopener noreferrer");
|
|
164
|
+
if (!isImageAttachment(attachment)) {
|
|
165
|
+
link.setAttribute("class", RICH_TEXT_FILE_CLASS);
|
|
166
|
+
link.textContent = attachment.name;
|
|
167
|
+
return link.outerHTML;
|
|
168
|
+
}
|
|
169
|
+
const image = document.createElement("img");
|
|
170
|
+
image.setAttribute("src", attachment.url);
|
|
171
|
+
image.setAttribute("alt", attachment.name);
|
|
172
|
+
image.setAttribute("class", RICH_TEXT_IMAGE_CLASS);
|
|
173
|
+
if (attachment.width) image.setAttribute("width", String(attachment.width));
|
|
174
|
+
if (attachment.height) image.setAttribute("height", String(attachment.height));
|
|
175
|
+
link.setAttribute("class", RICH_TEXT_IMAGE_LINK_CLASS);
|
|
176
|
+
link.appendChild(image);
|
|
177
|
+
return link.outerHTML;
|
|
154
178
|
};
|
|
155
179
|
export {
|
|
156
180
|
RICH_TEXT_COLORS,
|
|
157
181
|
RICH_TEXT_COLOR_CLASS,
|
|
158
182
|
RICH_TEXT_COLOR_SWATCH_CLASS,
|
|
159
183
|
RICH_TEXT_FILE_CLASS,
|
|
184
|
+
RICH_TEXT_IMAGE_CLASS,
|
|
185
|
+
RICH_TEXT_IMAGE_LINK_CLASS,
|
|
160
186
|
activeRichTextColor,
|
|
161
187
|
applyRichTextColor,
|
|
162
188
|
buildFileChipMarkup,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"richText.js","sources":["../../src/helpers/richText.ts"],"sourcesContent":["import DOMPurify from 'dompurify';\n\nimport { IFileAttachment } from '../interfaces/IFileAttachment';\n\n/**\n * Rich text authored in this app is HTML written by a user, so nothing here reaches the DOM\n * without passing through the sanitizer first, and nothing the editor writes may carry a\n * literal colour: a hex picked under the light theme is unreadable under the dark one. Colour\n * travels as one of these class names and the theme resolves it, so the same stored string\n * stays legible in both.\n */\nconst MENTION_TAG = 'user';\n\nexport type TRichTextColor =\n 'default' | 'brand' | 'secondary' | 'accent' | 'success' | 'warning' | 'danger' | 'info' | 'muted';\n\nexport const RICH_TEXT_COLORS: Array<TRichTextColor> = [\n 'default',\n 'brand',\n 'info',\n 'success',\n 'warning',\n 'danger',\n 'accent',\n 'secondary',\n 'muted',\n];\n\nexport const RICH_TEXT_COLOR_CLASS: Record<Exclude<TRichTextColor, 'default'>, string> = {\n brand: 'rt-color-brand',\n secondary: 'rt-color-secondary',\n accent: 'rt-color-accent',\n success: 'rt-color-success',\n warning: 'rt-color-warning',\n danger: 'rt-color-danger',\n info: 'rt-color-info',\n muted: 'rt-color-muted',\n};\n\n/** The swatch shown in the palette: a token-driven background, never the stored value. */\nexport const RICH_TEXT_COLOR_SWATCH_CLASS: Record<TRichTextColor, string> = {\n default: 'bg-foreground',\n brand: 'bg-brand',\n secondary: 'bg-secondary',\n accent: 'bg-accent',\n success: 'bg-success',\n warning: 'bg-warning',\n danger: 'bg-danger',\n info: 'bg-info',\n muted: 'bg-foreground-faint',\n};\n\nexport const RICH_TEXT_FILE_CLASS = 'rt-file';\n\nconst COLOR_CLASS_LIST = Object.values(RICH_TEXT_COLOR_CLASS);\nconst ALLOWED_CLASSES = new Set<string>([...COLOR_CLASS_LIST, RICH_TEXT_FILE_CLASS]);\n\nconst ALLOWED_TAGS = [\n MENTION_TAG,\n 'p',\n 'br',\n 'div',\n 'span',\n 'b',\n 'strong',\n 'i',\n 'em',\n 's',\n 'strike',\n 'u',\n 'ul',\n 'ol',\n 'li',\n 'blockquote',\n 'a',\n];\n\nconst ALLOWED_ATTR = ['href', 'target', 'rel', 'class'];\n\nlet hookRegistered = false;\n\nconst registerSanitizerHooks = (): void => {\n if (hookRegistered) return;\n hookRegistered = true;\n\n DOMPurify.addHook('afterSanitizeAttributes', (node) => {\n const element = node as HTMLElement;\n\n // A link authored by someone else must not be able to reach back into this tab.\n if (element.tagName === 'A') {\n element.setAttribute('target', '_blank');\n element.setAttribute('rel', 'noopener noreferrer');\n }\n\n if (!element.getAttribute?.('class')) return;\n\n const kept = (element.getAttribute('class') ?? '')\n .split(/\\s+/)\n .filter((className) => ALLOWED_CLASSES.has(className));\n\n if (kept.length) element.setAttribute('class', kept.join(' '));\n else element.removeAttribute('class');\n });\n};\n\n/**\n * Text written before the rich editor existed is plain text with real line breaks. Rendered as\n * HTML those breaks collapse, so the renderer needs to know which format it is looking at.\n */\nexport const isPlainTextBody = (html?: string): boolean => {\n if (!html) return true;\n\n return !/<(?!\\/?user\\b)[a-z][^>]*>/i.test(html);\n};\n\nexport const sanitizeRichText = (html?: string): string => {\n if (!html) return '';\n\n registerSanitizerHooks();\n\n return DOMPurify.sanitize(html, {\n ALLOWED_TAGS,\n ALLOWED_ATTR,\n ALLOW_DATA_ATTR: false,\n });\n};\n\n/** Emptiness has to be measured on the text: an editor the user only clicked into holds `<br>`. */\nexport const richTextToPlainText = (html?: string): string => {\n if (!html) return '';\n\n const parsed = new DOMParser().parseFromString(sanitizeRichText(html), 'text/html');\n return (parsed.body.textContent ?? '').trim();\n};\n\nexport const isRichTextEmpty = (html?: string): boolean => richTextToPlainText(html).length === 0;\n\nconst HTML_ESCAPES: Record<string, string> = {\n '&': '&',\n '<': '<',\n '>': '>',\n};\n\n/**\n * Seeds the editor from a value stored before the field became rich text. The line structure is\n * preserved and the text is escaped, so nothing in it is read as markup.\n */\nexport const plainTextToRichHtml = (text?: string): string => {\n if (!text) return '';\n\n return text.replace(/[&<>]/g, (character) => HTML_ESCAPES[character] ?? character).replace(/\\n/g, '<br>');\n};\n\n/** The value as the editor should receive it, whichever format it was stored in. */\nexport const toEditableRichHtml = (value?: string): string =>\n isPlainTextBody(value) ? plainTextToRichHtml(value) : (value ?? '');\n\n/**\n * `foreColor` is the only command that knows how to split a partial selection, so the colour is\n * applied through it with a value nothing else in the app uses, and the nodes it just produced\n * are then rewritten to the theme class. Nothing keeps the literal colour.\n */\nconst COLOR_SENTINEL_HEX = '#010203';\nconst COLOR_SENTINEL_RGB = 'rgb(1,2,3)';\n\nconst stripColorClasses = (element: HTMLElement): void => {\n COLOR_CLASS_LIST.forEach((className) => element.classList.remove(className));\n if (!element.classList.length) element.removeAttribute('class');\n};\n\nconst unwrapIfBare = (element: HTMLElement): void => {\n if (element.tagName !== 'SPAN' || element.attributes.length > 0) return;\n\n const parent = element.parentNode;\n if (!parent) return;\n\n while (element.firstChild) parent.insertBefore(element.firstChild, element);\n parent.removeChild(element);\n};\n\n/**\n * Rewrites whatever `foreColor` just produced. Called again on every input because a colour\n * chosen with no selection only materialises on the next typed character: without this pass\n * that character would keep the literal sentinel colour, which the sanitizer drops.\n */\nexport const normalizeRichTextColorNodes = (editor: HTMLElement, color: TRichTextColor): void => {\n const targetClass = color === 'default' ? '' : RICH_TEXT_COLOR_CLASS[color];\n\n editor.querySelectorAll<HTMLElement>('[style*=\"color\"]').forEach((node) => {\n if (node.style.color.replace(/\\s/g, '') !== COLOR_SENTINEL_RGB) return;\n\n node.style.removeProperty('color');\n if (!node.getAttribute('style')) node.removeAttribute('style');\n\n node.querySelectorAll<HTMLElement>('[class]').forEach(stripColorClasses);\n stripColorClasses(node);\n\n if (targetClass) node.classList.add(targetClass);\n else unwrapIfBare(node);\n });\n};\n\nexport const applyRichTextColor = (editor: HTMLElement, color: TRichTextColor): void => {\n document.execCommand('styleWithCSS', false, 'true');\n document.execCommand('foreColor', false, COLOR_SENTINEL_HEX);\n normalizeRichTextColorNodes(editor, color);\n};\n\n/** The colour of the text under the caret, so the palette can show what is currently applied. */\nexport const activeRichTextColor = (editor: HTMLElement): TRichTextColor => {\n const selection = window.getSelection();\n const anchor = selection?.anchorNode;\n if (!anchor) return 'default';\n\n const element = anchor.nodeType === Node.ELEMENT_NODE ? (anchor as HTMLElement) : anchor.parentElement;\n if (!element || !editor.contains(element)) return 'default';\n\n const colored = element.closest<HTMLElement>(COLOR_CLASS_LIST.map((className) => `.${className}`).join(','));\n if (!colored || !editor.contains(colored)) return 'default';\n\n const match = (Object.entries(RICH_TEXT_COLOR_CLASS) as Array<[Exclude<TRichTextColor, 'default'>, string]>).find(\n ([, className]) => colored.classList.contains(className),\n );\n\n return match?.[0] ?? 'default';\n};\n\n/**\n * An uploaded file referenced from inside the body. Hosts that have no attachment field of\n * their own still keep the reference, because it travels in the same string the text does.\n */\nexport const buildFileChipMarkup = (attachment: IFileAttachment): string => {\n const chip = document.createElement('a');\n chip.setAttribute('href', attachment.url);\n chip.setAttribute('class', RICH_TEXT_FILE_CLASS);\n chip.setAttribute('target', '_blank');\n chip.setAttribute('rel', 'noopener noreferrer');\n chip.textContent = attachment.name;\n return chip.outerHTML;\n};\n"],"names":[],"mappings":";AAWA,MAAM,cAAc;AAKb,MAAM,mBAA0C;AAAA,EACrD;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAEO,MAAM,wBAA4E;AAAA,EACvF,OAAO;AAAA,EACP,WAAW;AAAA,EACX,QAAQ;AAAA,EACR,SAAS;AAAA,EACT,SAAS;AAAA,EACT,QAAQ;AAAA,EACR,MAAM;AAAA,EACN,OAAO;AACT;AAGO,MAAM,+BAA+D;AAAA,EAC1E,SAAS;AAAA,EACT,OAAO;AAAA,EACP,WAAW;AAAA,EACX,QAAQ;AAAA,EACR,SAAS;AAAA,EACT,SAAS;AAAA,EACT,QAAQ;AAAA,EACR,MAAM;AAAA,EACN,OAAO;AACT;AAEO,MAAM,uBAAuB;AAEpC,MAAM,mBAAmB,OAAO,OAAO,qBAAqB;AAC5D,MAAM,kBAAkB,oBAAI,IAAY,CAAC,GAAG,kBAAkB,oBAAoB,CAAC;AAEnF,MAAM,eAAe;AAAA,EACnB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,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,CAAC;AACH;AAEO,MAAM,qBAAqB,CAAC,QAAqB,UAAgC;AACtF,WAAS,YAAY,gBAAgB,OAAO,MAAM;AAClD,WAAS,YAAY,aAAa,OAAO,kBAAkB;AAC3D,8BAA4B,QAAQ,KAAK;AAC3C;AAGO,MAAM,sBAAsB,CAAC,WAAwC;AAC1E,QAAM,YAAY,OAAO,aAAA;AACzB,QAAM,SAAS,WAAW;AAC1B,MAAI,CAAC,OAAQ,QAAO;AAEpB,QAAM,UAAU,OAAO,aAAa,KAAK,eAAgB,SAAyB,OAAO;AACzF,MAAI,CAAC,WAAW,CAAC,OAAO,SAAS,OAAO,EAAG,QAAO;AAElD,QAAM,UAAU,QAAQ,QAAqB,iBAAiB,IAAI,CAAC,cAAc,IAAI,SAAS,EAAE,EAAE,KAAK,GAAG,CAAC;AAC3G,MAAI,CAAC,WAAW,CAAC,OAAO,SAAS,OAAO,EAAG,QAAO;AAElD,QAAM,QAAS,OAAO,QAAQ,qBAAqB,EAA0D;AAAA,IAC3G,CAAC,CAAA,EAAG,SAAS,MAAM,QAAQ,UAAU,SAAS,SAAS;AAAA,EAAA;AAGzD,SAAO,QAAQ,CAAC,KAAK;AACvB;AAMO,MAAM,sBAAsB,CAAC,eAAwC;AAC1E,QAAM,OAAO,SAAS,cAAc,GAAG;AACvC,OAAK,aAAa,QAAQ,WAAW,GAAG;AACxC,OAAK,aAAa,SAAS,oBAAoB;AAC/C,OAAK,aAAa,UAAU,QAAQ;AACpC,OAAK,aAAa,OAAO,qBAAqB;AAC9C,OAAK,cAAc,WAAW;AAC9B,SAAO,KAAK;AACd;"}
|
|
1
|
+
{"version":3,"file":"richText.js","sources":["../../src/helpers/richText.ts"],"sourcesContent":["import DOMPurify from 'dompurify';\n\nimport { IFileAttachment } from '../interfaces/IFileAttachment';\n\n/**\n * Rich text authored in this app is HTML written by a user, so nothing here reaches the DOM\n * without passing through the sanitizer first, and nothing the editor writes may carry a\n * literal colour: a hex picked under the light theme is unreadable under the dark one. Colour\n * travels as one of these class names and the theme resolves it, so the same stored string\n * stays legible in both.\n */\nconst MENTION_TAG = 'user';\n\nexport type TRichTextColor =\n 'default' | 'brand' | 'secondary' | 'accent' | 'success' | 'warning' | 'danger' | 'info' | 'muted';\n\nexport const RICH_TEXT_COLORS: Array<TRichTextColor> = [\n 'default',\n 'brand',\n 'info',\n 'success',\n 'warning',\n 'danger',\n 'accent',\n 'secondary',\n 'muted',\n];\n\nexport const RICH_TEXT_COLOR_CLASS: Record<Exclude<TRichTextColor, 'default'>, string> = {\n brand: 'rt-color-brand',\n secondary: 'rt-color-secondary',\n accent: 'rt-color-accent',\n success: 'rt-color-success',\n warning: 'rt-color-warning',\n danger: 'rt-color-danger',\n info: 'rt-color-info',\n muted: 'rt-color-muted',\n};\n\n/** The swatch shown in the palette: a token-driven background, never the stored value. */\nexport const RICH_TEXT_COLOR_SWATCH_CLASS: Record<TRichTextColor, string> = {\n default: 'bg-foreground',\n brand: 'bg-brand',\n secondary: 'bg-secondary',\n accent: 'bg-accent',\n success: 'bg-success',\n warning: 'bg-warning',\n danger: 'bg-danger',\n info: 'bg-info',\n muted: 'bg-foreground-faint',\n};\n\nexport const RICH_TEXT_FILE_CLASS = 'rt-file';\n/** An image written INTO the body, as opposed to a file referenced by name. */\nexport const RICH_TEXT_IMAGE_CLASS = 'rt-image';\nexport const RICH_TEXT_IMAGE_LINK_CLASS = 'rt-image-link';\n\nconst COLOR_CLASS_LIST = Object.values(RICH_TEXT_COLOR_CLASS);\nconst ALLOWED_CLASSES = new Set<string>([\n ...COLOR_CLASS_LIST,\n RICH_TEXT_FILE_CLASS,\n RICH_TEXT_IMAGE_CLASS,\n RICH_TEXT_IMAGE_LINK_CLASS,\n]);\n\nconst ALLOWED_TAGS = [\n MENTION_TAG,\n 'p',\n 'br',\n 'div',\n 'span',\n 'b',\n 'strong',\n 'i',\n 'em',\n 's',\n 'strike',\n 'u',\n 'ul',\n 'ol',\n 'li',\n 'blockquote',\n 'a',\n 'img',\n];\n\nconst ALLOWED_ATTR = ['href', 'target', 'rel', 'class', 'src', 'alt', 'width', 'height'];\n\nlet hookRegistered = false;\n\nconst registerSanitizerHooks = (): void => {\n if (hookRegistered) return;\n hookRegistered = true;\n\n DOMPurify.addHook('afterSanitizeAttributes', (node) => {\n const element = node as HTMLElement;\n\n // A link authored by someone else must not be able to reach back into this tab.\n if (element.tagName === 'A') {\n element.setAttribute('target', '_blank');\n element.setAttribute('rel', 'noopener noreferrer');\n }\n\n if (!element.getAttribute?.('class')) return;\n\n const kept = (element.getAttribute('class') ?? '')\n .split(/\\s+/)\n .filter((className) => ALLOWED_CLASSES.has(className));\n\n if (kept.length) element.setAttribute('class', kept.join(' '));\n else element.removeAttribute('class');\n });\n};\n\n/**\n * Text written before the rich editor existed is plain text with real line breaks. Rendered as\n * HTML those breaks collapse, so the renderer needs to know which format it is looking at.\n */\nexport const isPlainTextBody = (html?: string): boolean => {\n if (!html) return true;\n\n return !/<(?!\\/?user\\b)[a-z][^>]*>/i.test(html);\n};\n\nexport const sanitizeRichText = (html?: string): string => {\n if (!html) return '';\n\n registerSanitizerHooks();\n\n return DOMPurify.sanitize(html, {\n ALLOWED_TAGS,\n ALLOWED_ATTR,\n ALLOW_DATA_ATTR: false,\n });\n};\n\n/** Emptiness has to be measured on the text: an editor the user only clicked into holds `<br>`. */\nexport const richTextToPlainText = (html?: string): string => {\n if (!html) return '';\n\n const parsed = new DOMParser().parseFromString(sanitizeRichText(html), 'text/html');\n return (parsed.body.textContent ?? '').trim();\n};\n\n/**\n * A body whose only content is an attachment has no text at all, so measuring emptiness on the\n * text alone would throw away the picture the user just wrote into the field.\n */\nexport const isRichTextEmpty = (html?: string): boolean => {\n if (richTextToPlainText(html).length > 0) return false;\n\n const parsed = new DOMParser().parseFromString(sanitizeRichText(html), 'text/html');\n return parsed.body.querySelector(`img, .${RICH_TEXT_FILE_CLASS}`) === null;\n};\n\nconst HTML_ESCAPES: Record<string, string> = {\n '&': '&',\n '<': '<',\n '>': '>',\n};\n\n/**\n * Seeds the editor from a value stored before the field became rich text. The line structure is\n * preserved and the text is escaped, so nothing in it is read as markup.\n */\nexport const plainTextToRichHtml = (text?: string): string => {\n if (!text) return '';\n\n return text.replace(/[&<>]/g, (character) => HTML_ESCAPES[character] ?? character).replace(/\\n/g, '<br>');\n};\n\n/** The value as the editor should receive it, whichever format it was stored in. */\nexport const toEditableRichHtml = (value?: string): string =>\n isPlainTextBody(value) ? plainTextToRichHtml(value) : (value ?? '');\n\n/**\n * `foreColor` is the only command that knows how to split a partial selection, so the colour is\n * applied through it with a value nothing else in the app uses, and the nodes it just produced\n * are then rewritten to the theme class. Nothing keeps the literal colour.\n */\nconst COLOR_SENTINEL_HEX = '#010203';\nconst COLOR_SENTINEL_RGB = 'rgb(1,2,3)';\n\nconst stripColorClasses = (element: HTMLElement): void => {\n COLOR_CLASS_LIST.forEach((className) => element.classList.remove(className));\n if (!element.classList.length) element.removeAttribute('class');\n};\n\nconst unwrapIfBare = (element: HTMLElement): void => {\n if (element.tagName !== 'SPAN' || element.attributes.length > 0) return;\n\n const parent = element.parentNode;\n if (!parent) return;\n\n while (element.firstChild) parent.insertBefore(element.firstChild, element);\n parent.removeChild(element);\n};\n\n/**\n * Rewrites whatever `foreColor` just produced. Called again on every input because a colour\n * chosen with no selection only materialises on the next typed character: without this pass\n * that character would keep the literal sentinel colour, which the sanitizer drops.\n */\nexport const normalizeRichTextColorNodes = (editor: HTMLElement, color: TRichTextColor): void => {\n const targetClass = color === 'default' ? '' : RICH_TEXT_COLOR_CLASS[color];\n\n editor.querySelectorAll<HTMLElement>('[style*=\"color\"]').forEach((node) => {\n if (node.style.color.replace(/\\s/g, '') !== COLOR_SENTINEL_RGB) return;\n\n node.style.removeProperty('color');\n if (!node.getAttribute('style')) node.removeAttribute('style');\n\n node.querySelectorAll<HTMLElement>('[class]').forEach(stripColorClasses);\n stripColorClasses(node);\n\n if (targetClass) node.classList.add(targetClass);\n else unwrapIfBare(node);\n });\n};\n\nexport const applyRichTextColor = (editor: HTMLElement, color: TRichTextColor): void => {\n document.execCommand('styleWithCSS', false, 'true');\n document.execCommand('foreColor', false, COLOR_SENTINEL_HEX);\n normalizeRichTextColorNodes(editor, color);\n};\n\n/** The colour of the text under the caret, so the palette can show what is currently applied. */\nexport const activeRichTextColor = (editor: HTMLElement): TRichTextColor => {\n const selection = window.getSelection();\n const anchor = selection?.anchorNode;\n if (!anchor) return 'default';\n\n const element = anchor.nodeType === Node.ELEMENT_NODE ? (anchor as HTMLElement) : anchor.parentElement;\n if (!element || !editor.contains(element)) return 'default';\n\n const colored = element.closest<HTMLElement>(COLOR_CLASS_LIST.map((className) => `.${className}`).join(','));\n if (!colored || !editor.contains(colored)) return 'default';\n\n const match = (Object.entries(RICH_TEXT_COLOR_CLASS) as Array<[Exclude<TRichTextColor, 'default'>, string]>).find(\n ([, className]) => colored.classList.contains(className),\n );\n\n return match?.[0] ?? 'default';\n};\n\nconst isImageAttachment = (attachment: IFileAttachment): boolean =>\n attachment.kind === 'image' || attachment.mimeType?.startsWith('image/') === true;\n\n/**\n * An uploaded file referenced from inside the body. Hosts that have no attachment field of\n * their own still keep the reference, because it travels in the same string the text does.\n * An image is written as the picture itself, wrapped in the link that opens it at full size:\n * a name-only chip hides what was attached, and the reader has no way to look at it.\n */\nexport const buildFileChipMarkup = (attachment: IFileAttachment): string => {\n const link = document.createElement('a');\n link.setAttribute('href', attachment.url);\n link.setAttribute('target', '_blank');\n link.setAttribute('rel', 'noopener noreferrer');\n\n if (!isImageAttachment(attachment)) {\n link.setAttribute('class', RICH_TEXT_FILE_CLASS);\n link.textContent = attachment.name;\n return link.outerHTML;\n }\n\n const image = document.createElement('img');\n image.setAttribute('src', attachment.url);\n image.setAttribute('alt', attachment.name);\n image.setAttribute('class', RICH_TEXT_IMAGE_CLASS);\n if (attachment.width) image.setAttribute('width', String(attachment.width));\n if (attachment.height) image.setAttribute('height', String(attachment.height));\n\n link.setAttribute('class', RICH_TEXT_IMAGE_LINK_CLASS);\n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"}
|
package/package.json
CHANGED
|
@@ -437,7 +437,7 @@ textarea:focus {
|
|
|
437
437
|
so the same message stays legible after a theme switch. Both the editor and every surface
|
|
438
438
|
that renders the sanitized body share these rules. */
|
|
439
439
|
.rt-color-brand {
|
|
440
|
-
color: rgb(var(--color-
|
|
440
|
+
color: rgb(var(--color-primary-emphasis));
|
|
441
441
|
}
|
|
442
442
|
|
|
443
443
|
.rt-color-secondary {
|
|
@@ -468,6 +468,28 @@ textarea:focus {
|
|
|
468
468
|
color: rgb(var(--color-foreground-muted));
|
|
469
469
|
}
|
|
470
470
|
|
|
471
|
+
.rt-image-link {
|
|
472
|
+
display: inline-block;
|
|
473
|
+
max-width: 100%;
|
|
474
|
+
line-height: 0;
|
|
475
|
+
text-decoration: none;
|
|
476
|
+
}
|
|
477
|
+
|
|
478
|
+
/* An image written into the body shows itself: a name-only chip hides what was attached.
|
|
479
|
+
The cap keeps a full-resolution photo from taking over the field it was written into. */
|
|
480
|
+
.rt-image {
|
|
481
|
+
display: inline-block;
|
|
482
|
+
max-width: 100%;
|
|
483
|
+
max-height: 16rem;
|
|
484
|
+
width: auto;
|
|
485
|
+
height: auto;
|
|
486
|
+
border: 1px solid rgb(var(--color-border));
|
|
487
|
+
border-radius: 0.5rem;
|
|
488
|
+
background-color: rgb(var(--color-muted));
|
|
489
|
+
cursor: zoom-in;
|
|
490
|
+
object-fit: contain;
|
|
491
|
+
}
|
|
492
|
+
|
|
471
493
|
.rt-file {
|
|
472
494
|
display: inline-flex;
|
|
473
495
|
align-items: center;
|