@umodeapporg/ui 0.34.1 → 0.34.3
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 -1
- package/dist/components/Form/RichTextEditor.js.map +1 -1
- package/dist/components/Search/filters/FilterChipsRow.js +1 -1
- package/dist/components/Search/filters/FilterChipsRow.js.map +1 -1
- package/dist/components/UI/ControlledMenu.d.ts +13 -0
- package/dist/components/UI/ControlledMenu.js +39 -9
- package/dist/components/UI/ControlledMenu.js.map +1 -1
- package/dist/components/UI/DataTable/DataTable.js +15 -3
- package/dist/components/UI/DataTable/DataTable.js.map +1 -1
- package/package.json +1 -1
|
@@ -538,7 +538,7 @@ const RichTextEditor = forwardRef(function RichTextEditor2({
|
|
|
538
538
|
children: /* @__PURE__ */ jsx(MaterialSymbol, { icon: "attach_file", size: 18 })
|
|
539
539
|
}
|
|
540
540
|
) }) }),
|
|
541
|
-
/* @__PURE__ */ jsx(ControlledMenuList, { className: "zIndexMax p-1", children: attachMenuActions.map((action) => /* @__PURE__ */ jsxs(ControlledMenuItem, { className: "flex items-center gap-x-2", onClick: action.onClick, children: [
|
|
541
|
+
/* @__PURE__ */ jsx(ControlledMenuList, { manageFocus: true, className: "zIndexMax p-1", children: attachMenuActions.map((action) => /* @__PURE__ */ jsxs(ControlledMenuItem, { className: "flex items-center gap-x-2", onClick: action.onClick, children: [
|
|
542
542
|
/* @__PURE__ */ jsx(MaterialSymbol, { icon: action.icon, size: 18 }),
|
|
543
543
|
action.label
|
|
544
544
|
] }, action.key)) })
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"RichTextEditor.js","sources":["../../../src/components/Form/RichTextEditor.tsx"],"sourcesContent":["import { forwardRef, useCallback, useEffect, useImperativeHandle, useMemo, useReducer, 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, { IStagedImageAction } 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 /**\n * Actions offered on a staged IMAGE before it is sent, so a picture is corrected on its way out\n * instead of being sent and then corrected as a second file.\n */\n imageActions?: Array<IStagedImageAction>;\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 [, recheckPlaceholder] = useReducer((checkCount: number) => checkCount + 1, 0);\n const savedRangeRef = useRef<Range | null>(null);\n const caretBelongsAtEndRef = useRef(false);\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 const moveCaretToEnd = useCallback((editor: HTMLElement) => {\n const range = document.createRange();\n range.selectNodeContents(editor);\n range.collapse(false);\n\n const selection = window.getSelection();\n selection?.removeAllRanges();\n selection?.addRange(range);\n savedRangeRef.current = range.cloneRange();\n }, []);\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 // Rewriting the content throws the caret back to the start of the field.\n if (document.activeElement === editor) moveCaretToEnd(editor);\n else caretBelongsAtEndRef.current = true;\n\n // The placeholder reads the field during render, which ran before this write.\n recheckPlaceholder();\n }\n }, [moveCaretToEnd, 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 aria-label={t(tooltipKey)}\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 aria-label={t('createTask.rich.textColor')}\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 aria-label={t(`createTask.rich.colors.${color}`)}\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 aria-label={t('createTask.rich.link')}\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={() => {\n setIsFocused(true);\n if (!caretBelongsAtEndRef.current || !editorRef.current) return;\n caretBelongsAtEndRef.current = false;\n moveCaretToEnd(editorRef.current);\n }}\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 imageActions={attachments?.imageActions}\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 aria-label={t('followUp.chat.formatting')}\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\n defaultHtmlButton\n aria-label={t('followUp.attachments.attach')}\n disabled={disabled}\n className={ACTION_BUTTON_CLASS}\n >\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":";;;;;;;;;;;;;;AAoIA,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,S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A,GAEjD,EAAA,CACF;AAAA,YACA,oBAAC,oBAAA,EAAmB,WAAU,iBAC3B,4BAAkB,IAAI,CAAC,WACtB,qBAAC,oBAAA,EAAoC,WAAU,6BAA4B,SAAS,OAAO,SACzF,UAAA;AAAA,cAAA,oBAAC,gBAAA,EAAe,MAAM,OAAO,MAAM,MAAM,IAAI;AAAA,cAC5C,OAAO;AAAA,YAAA,KAFe,OAAO,GAGhC,CACD,EAAA,CACH;AAAA,UAAA,GACF;AAAA,UAGD;AAAA,QAAA,GACH;AAAA,QAGD,yBACC,qBAAA,UAAA,EACE,UAAA;AAAA,UAAA,oBAAC,SAAA,EAAM,KAAK,cAAc,MAAK,QAAO,UAAQ,MAAC,QAAM,MAAC,UAAU,kBAAA,CAAmB;AAAA,UACnF;AAAA,YAAC;AAAA,YAAA;AAAA,cACC,KAAK;AAAA,cACL,MAAK;AAAA,cACL,UAAQ;AAAA,cACR,QAAM;AAAA,cACN,QAAQ;AAAA,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, useReducer, 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, { IStagedImageAction } 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 /**\n * Actions offered on a staged IMAGE before it is sent, so a picture is corrected on its way out\n * instead of being sent and then corrected as a second file.\n */\n imageActions?: Array<IStagedImageAction>;\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 [, recheckPlaceholder] = useReducer((checkCount: number) => checkCount + 1, 0);\n const savedRangeRef = useRef<Range | null>(null);\n const caretBelongsAtEndRef = useRef(false);\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 const moveCaretToEnd = useCallback((editor: HTMLElement) => {\n const range = document.createRange();\n range.selectNodeContents(editor);\n range.collapse(false);\n\n const selection = window.getSelection();\n selection?.removeAllRanges();\n selection?.addRange(range);\n savedRangeRef.current = range.cloneRange();\n }, []);\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 // Rewriting the content throws the caret back to the start of the field.\n if (document.activeElement === editor) moveCaretToEnd(editor);\n else caretBelongsAtEndRef.current = true;\n\n // The placeholder reads the field during render, which ran before this write.\n recheckPlaceholder();\n }\n }, [moveCaretToEnd, 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 aria-label={t(tooltipKey)}\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 aria-label={t('createTask.rich.textColor')}\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 aria-label={t(`createTask.rich.colors.${color}`)}\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 aria-label={t('createTask.rich.link')}\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={() => {\n setIsFocused(true);\n if (!caretBelongsAtEndRef.current || !editorRef.current) return;\n caretBelongsAtEndRef.current = false;\n moveCaretToEnd(editorRef.current);\n }}\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 imageActions={attachments?.imageActions}\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 aria-label={t('followUp.chat.formatting')}\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\n defaultHtmlButton\n aria-label={t('followUp.attachments.attach')}\n disabled={disabled}\n className={ACTION_BUTTON_CLASS}\n >\n <MaterialSymbol icon=\"attach_file\" size={18} />\n </ControlledButton>\n </ControlledMenuHandler>\n </ControlledTooltip>\n <ControlledMenuList manageFocus 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":";;;;;;;;;;;;;;AAoIA,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,E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,MAAC,WAAU,iBACvC,UAAA,kBAAkB,IAAI,CAAC,gCACrB,oBAAA,EAAoC,WAAU,6BAA4B,SAAS,OAAO,SACzF,UAAA;AAAA,cAAA,oBAAC,gBAAA,EAAe,MAAM,OAAO,MAAM,MAAM,IAAI;AAAA,cAC5C,OAAO;AAAA,YAAA,KAFe,OAAO,GAGhC,CACD,EAAA,CACH;AAAA,UAAA,GACF;AAAA,UAGD;AAAA,QAAA,GACH;AAAA,QAGD,yBACC,qBAAA,UAAA,EACE,UAAA;AAAA,UAAA,oBAAC,SAAA,EAAM,KAAK,cAAc,MAAK,QAAO,UAAQ,MAAC,QAAM,MAAC,UAAU,kBAAA,CAAmB;AAAA,UACnF;AAAA,YAAC;AAAA,YAAA;AAAA,cACC,KAAK;AAAA,cACL,MAAK;AAAA,cACL,UAAQ;AAAA,cACR,QAAM;AAAA,cACN,QAAQ;AAAA,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;"}
|
|
@@ -39,7 +39,7 @@ const FilterChipDropdown = ({
|
|
|
39
39
|
]
|
|
40
40
|
}
|
|
41
41
|
) }),
|
|
42
|
-
/* @__PURE__ */ jsx(ControlledMenuList, { className: "zIndexMax flex max-h-48 min-w-44 flex-col overflow-hidden p-0", children: /* @__PURE__ */ jsx("div", { className: "flex-1 overflow-y-auto p-1 outline-none", children: options.map((option) => /* @__PURE__ */ jsx(
|
|
42
|
+
/* @__PURE__ */ jsx(ControlledMenuList, { manageFocus: true, className: "zIndexMax flex max-h-48 min-w-44 flex-col overflow-hidden p-0", children: /* @__PURE__ */ jsx("div", { className: "flex-1 overflow-y-auto p-1 outline-none", children: options.map((option) => /* @__PURE__ */ jsx(
|
|
43
43
|
ControlledMenuItem,
|
|
44
44
|
{
|
|
45
45
|
onClick: () => onPick(option.value),
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"FilterChipsRow.js","sources":["../../../../src/components/Search/filters/FilterChipsRow.tsx"],"sourcesContent":["import * as React from 'react';\nimport classNames from 'classnames';\nimport { useTranslation } from 'react-i18next';\n\nimport ControlledButton from '@/components/Form/ControlledButton';\nimport ControlledSwitch from '@/components/Form/ControlledSwitch';\nimport {\n ControlledMenuHandler,\n ControlledMenuItem,\n ControlledMenuList,\n ControlledMenuRoot,\n} from '@/components/UI/ControlledMenu';\nimport { MaterialSymbol } from '@/components/UI/MaterialSymbol';\nimport { IFilterOption } from '@/interfaces/IFilterOption';\n\nimport { TFilterField, TFilterValues } from './filterTypes';\nimport { countActiveFilters, isFilterValueEmpty } from './filterValues';\n\ninterface IFilterChipDropdownProps {\n label: string;\n options: Array<IFilterOption>;\n value: string;\n isActive: boolean;\n disabled?: boolean;\n onPick: (value: string) => void;\n}\n\n/**\n * A single dropdown chip. The active state is carried by border, background,\n * weight and the visible value, so it reads without hovering; hover only\n * deepens the same purple.\n */\nconst FilterChipDropdown: React.FC<IFilterChipDropdownProps> = ({\n label,\n options,\n value,\n isActive,\n disabled,\n onPick,\n}) => {\n const currentLabel = options.find((option) => option.value === value)?.label ?? '';\n\n return (\n <ControlledMenuRoot placement=\"bottom-start\" dismiss={{ itemPress: true }}>\n <ControlledMenuHandler>\n <ControlledButton\n defaultHtmlButton\n disabled={disabled}\n className={classNames(\n 'flex h-8 items-center gap-1.5 rounded-lg border px-2.5 text-xs font-medium outline-none transition-colors focus-visible:ring-2 focus-visible:ring-brand-border disabled:text-foreground-faint',\n isActive\n ? 'border-brand-border bg-brand-soft text-brand-emphasis hover:bg-brand-soft'\n : 'border-border bg-surface text-foreground-muted hover:bg-muted',\n )}\n >\n <span className={isActive ? 'text-brand-emphasis' : 'text-foreground-faint'}>{label}</span>\n {isActive && <span className=\"max-w-32 truncate font-semibold\">{currentLabel}</span>}\n <MaterialSymbol\n icon=\"expand_more\"\n size={14}\n className={classNames('shrink-0', isActive ? 'text-brand-emphasis' : 'text-foreground-faint')}\n />\n </ControlledButton>\n </ControlledMenuHandler>\n <ControlledMenuList className=\"zIndexMax flex max-h-48 min-w-44 flex-col overflow-hidden p-0\">\n <div className=\"flex-1 overflow-y-auto p-1 outline-none\">\n {options.map((option) => (\n <ControlledMenuItem\n key={option.value || '__all'}\n onClick={() => onPick(option.value)}\n className={classNames('text-sm', {\n 'bg-brand-soft font-semibold text-brand-emphasis hover:!bg-brand-soft': value === option.value,\n })}\n >\n {option.label}\n </ControlledMenuItem>\n ))}\n </div>\n </ControlledMenuList>\n </ControlledMenuRoot>\n );\n};\n\nexport interface IFilterChipsRowProps {\n fields: Array<TFilterField>;\n values: TFilterValues;\n onValueChange: (key: string, value: unknown) => void;\n onClearAll: () => void;\n disabled?: boolean;\n className?: string;\n}\n\n/**\n * Horizontal chip bar for toolbars with a handful of quick filters. Applies on\n * pick (no draft), which is the interaction users expect from a chip row, and\n * is driven by the same schema as the drawer.\n */\nconst FilterChipsRow: React.FC<IFilterChipsRowProps> = ({\n fields,\n values,\n onValueChange,\n onClearAll,\n disabled,\n className,\n}) => {\n const { t } = useTranslation('ui');\n const safeFields = Array.isArray(fields) ? fields : [];\n const activeCount = countActiveFilters(safeFields, values ?? {});\n\n return (\n <div className={classNames('flex shrink-0 flex-wrap items-center gap-2', className)}>\n {safeFields.map((field) => {\n const value = values?.[field.key];\n const isActive = !isFilterValueEmpty(field, value);\n\n if (field.kind === 'boolean') {\n return (\n <ControlledSwitch\n key={field.key}\n checked={value === true}\n disabled={disabled || field.disabled}\n label={field.label ?? field.title}\n onChange={(checked) => onValueChange(field.key, checked)}\n />\n );\n }\n\n if (field.kind !== 'select' && field.kind !== 'radio') return null;\n\n return (\n <FilterChipDropdown\n key={field.key}\n label={field.title}\n options={field.options ?? []}\n value={typeof value === 'string' ? value : ''}\n isActive={isActive}\n disabled={disabled || field.disabled}\n onPick={(next) => onValueChange(field.key, next)}\n />\n );\n })}\n\n {activeCount > 0 && (\n <ControlledButton\n defaultHtmlButton\n onClick={onClearAll}\n className=\"inline-flex h-8 items-center gap-1 rounded-lg px-2 text-xs font-medium text-foreground-subtle transition-colors hover:bg-muted-hover hover:text-foreground-muted focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-brand-border\"\n >\n <MaterialSymbol icon=\"filter_list_off\" size={14} />\n {t('filters.clearAll')}\n </ControlledButton>\n )}\n </div>\n );\n};\n\nexport default FilterChipsRow;\n"],"names":[],"mappings":";;;;;;;;AAgCA,MAAM,qBAAyD,CAAC;AAAA,EAC9D;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,MAAM;AACJ,QAAM,eAAe,QAAQ,KAAK,CAAC,WAAW,OAAO,UAAU,KAAK,GAAG,SAAS;AAEhF,SACE,qBAAC,sBAAmB,WAAU,gBAAe,SAAS,EAAE,WAAW,QACjE,UAAA;AAAA,IAAA,oBAAC,uBAAA,EACC,UAAA;AAAA,MAAC;AAAA,MAAA;AAAA,QACC,mBAAiB;AAAA,QACjB;AAAA,QACA,WAAW;AAAA,UACT;AAAA,UACA,WACI,8EACA;AAAA,QAAA;AAAA,QAGN,UAAA;AAAA,UAAA,oBAAC,QAAA,EAAK,WAAW,WAAW,wBAAwB,yBAA0B,UAAA,OAAM;AAAA,UACnF,YAAY,oBAAC,QAAA,EAAK,WAAU,mCAAmC,UAAA,cAAa;AAAA,UAC7E;AAAA,YAAC;AAAA,YAAA;AAAA,cACC,MAAK;AAAA,cACL,MAAM;AAAA,cACN,WAAW,WAAW,YAAY,WAAW,wBAAwB,uBAAuB;AAAA,YAAA;AAAA,UAAA;AAAA,QAC9F;AAAA,MAAA;AAAA,IAAA,GAEJ;AAAA,IACA,oBAAC,oBAAA,EAAmB,WAAU,
|
|
1
|
+
{"version":3,"file":"FilterChipsRow.js","sources":["../../../../src/components/Search/filters/FilterChipsRow.tsx"],"sourcesContent":["import * as React from 'react';\nimport classNames from 'classnames';\nimport { useTranslation } from 'react-i18next';\n\nimport ControlledButton from '@/components/Form/ControlledButton';\nimport ControlledSwitch from '@/components/Form/ControlledSwitch';\nimport {\n ControlledMenuHandler,\n ControlledMenuItem,\n ControlledMenuList,\n ControlledMenuRoot,\n} from '@/components/UI/ControlledMenu';\nimport { MaterialSymbol } from '@/components/UI/MaterialSymbol';\nimport { IFilterOption } from '@/interfaces/IFilterOption';\n\nimport { TFilterField, TFilterValues } from './filterTypes';\nimport { countActiveFilters, isFilterValueEmpty } from './filterValues';\n\ninterface IFilterChipDropdownProps {\n label: string;\n options: Array<IFilterOption>;\n value: string;\n isActive: boolean;\n disabled?: boolean;\n onPick: (value: string) => void;\n}\n\n/**\n * A single dropdown chip. The active state is carried by border, background,\n * weight and the visible value, so it reads without hovering; hover only\n * deepens the same purple.\n */\nconst FilterChipDropdown: React.FC<IFilterChipDropdownProps> = ({\n label,\n options,\n value,\n isActive,\n disabled,\n onPick,\n}) => {\n const currentLabel = options.find((option) => option.value === value)?.label ?? '';\n\n return (\n <ControlledMenuRoot placement=\"bottom-start\" dismiss={{ itemPress: true }}>\n <ControlledMenuHandler>\n <ControlledButton\n defaultHtmlButton\n disabled={disabled}\n className={classNames(\n 'flex h-8 items-center gap-1.5 rounded-lg border px-2.5 text-xs font-medium outline-none transition-colors focus-visible:ring-2 focus-visible:ring-brand-border disabled:text-foreground-faint',\n isActive\n ? 'border-brand-border bg-brand-soft text-brand-emphasis hover:bg-brand-soft'\n : 'border-border bg-surface text-foreground-muted hover:bg-muted',\n )}\n >\n <span className={isActive ? 'text-brand-emphasis' : 'text-foreground-faint'}>{label}</span>\n {isActive && <span className=\"max-w-32 truncate font-semibold\">{currentLabel}</span>}\n <MaterialSymbol\n icon=\"expand_more\"\n size={14}\n className={classNames('shrink-0', isActive ? 'text-brand-emphasis' : 'text-foreground-faint')}\n />\n </ControlledButton>\n </ControlledMenuHandler>\n <ControlledMenuList manageFocus className=\"zIndexMax flex max-h-48 min-w-44 flex-col overflow-hidden p-0\">\n <div className=\"flex-1 overflow-y-auto p-1 outline-none\">\n {options.map((option) => (\n <ControlledMenuItem\n key={option.value || '__all'}\n onClick={() => onPick(option.value)}\n className={classNames('text-sm', {\n 'bg-brand-soft font-semibold text-brand-emphasis hover:!bg-brand-soft': value === option.value,\n })}\n >\n {option.label}\n </ControlledMenuItem>\n ))}\n </div>\n </ControlledMenuList>\n </ControlledMenuRoot>\n );\n};\n\nexport interface IFilterChipsRowProps {\n fields: Array<TFilterField>;\n values: TFilterValues;\n onValueChange: (key: string, value: unknown) => void;\n onClearAll: () => void;\n disabled?: boolean;\n className?: string;\n}\n\n/**\n * Horizontal chip bar for toolbars with a handful of quick filters. Applies on\n * pick (no draft), which is the interaction users expect from a chip row, and\n * is driven by the same schema as the drawer.\n */\nconst FilterChipsRow: React.FC<IFilterChipsRowProps> = ({\n fields,\n values,\n onValueChange,\n onClearAll,\n disabled,\n className,\n}) => {\n const { t } = useTranslation('ui');\n const safeFields = Array.isArray(fields) ? fields : [];\n const activeCount = countActiveFilters(safeFields, values ?? {});\n\n return (\n <div className={classNames('flex shrink-0 flex-wrap items-center gap-2', className)}>\n {safeFields.map((field) => {\n const value = values?.[field.key];\n const isActive = !isFilterValueEmpty(field, value);\n\n if (field.kind === 'boolean') {\n return (\n <ControlledSwitch\n key={field.key}\n checked={value === true}\n disabled={disabled || field.disabled}\n label={field.label ?? field.title}\n onChange={(checked) => onValueChange(field.key, checked)}\n />\n );\n }\n\n if (field.kind !== 'select' && field.kind !== 'radio') return null;\n\n return (\n <FilterChipDropdown\n key={field.key}\n label={field.title}\n options={field.options ?? []}\n value={typeof value === 'string' ? value : ''}\n isActive={isActive}\n disabled={disabled || field.disabled}\n onPick={(next) => onValueChange(field.key, next)}\n />\n );\n })}\n\n {activeCount > 0 && (\n <ControlledButton\n defaultHtmlButton\n onClick={onClearAll}\n className=\"inline-flex h-8 items-center gap-1 rounded-lg px-2 text-xs font-medium text-foreground-subtle transition-colors hover:bg-muted-hover hover:text-foreground-muted focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-brand-border\"\n >\n <MaterialSymbol icon=\"filter_list_off\" size={14} />\n {t('filters.clearAll')}\n </ControlledButton>\n )}\n </div>\n );\n};\n\nexport default FilterChipsRow;\n"],"names":[],"mappings":";;;;;;;;AAgCA,MAAM,qBAAyD,CAAC;AAAA,EAC9D;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,MAAM;AACJ,QAAM,eAAe,QAAQ,KAAK,CAAC,WAAW,OAAO,UAAU,KAAK,GAAG,SAAS;AAEhF,SACE,qBAAC,sBAAmB,WAAU,gBAAe,SAAS,EAAE,WAAW,QACjE,UAAA;AAAA,IAAA,oBAAC,uBAAA,EACC,UAAA;AAAA,MAAC;AAAA,MAAA;AAAA,QACC,mBAAiB;AAAA,QACjB;AAAA,QACA,WAAW;AAAA,UACT;AAAA,UACA,WACI,8EACA;AAAA,QAAA;AAAA,QAGN,UAAA;AAAA,UAAA,oBAAC,QAAA,EAAK,WAAW,WAAW,wBAAwB,yBAA0B,UAAA,OAAM;AAAA,UACnF,YAAY,oBAAC,QAAA,EAAK,WAAU,mCAAmC,UAAA,cAAa;AAAA,UAC7E;AAAA,YAAC;AAAA,YAAA;AAAA,cACC,MAAK;AAAA,cACL,MAAM;AAAA,cACN,WAAW,WAAW,YAAY,WAAW,wBAAwB,uBAAuB;AAAA,YAAA;AAAA,UAAA;AAAA,QAC9F;AAAA,MAAA;AAAA,IAAA,GAEJ;AAAA,IACA,oBAAC,oBAAA,EAAmB,aAAW,MAAC,WAAU,iEACxC,UAAA,oBAAC,OAAA,EAAI,WAAU,2CACZ,UAAA,QAAQ,IAAI,CAAC,WACZ;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AC,SAAS,cAAc,MAAM,KAAK,IAAI;AAAA,QAAA;AAAA,QAN1C,MAAM;AAAA,MAAA;AAAA,IASjB,CAAC;AAAA,IAEA,cAAc,KACb;AAAA,MAAC;AAAA,MAAA;AAAA,QACC,mBAAiB;AAAA,QACjB,SAAS;AAAA,QACT,WAAU;AAAA,QAEV,UAAA;AAAA,UAAA,oBAAC,gBAAA,EAAe,MAAK,mBAAkB,MAAM,IAAI;AAAA,UAChD,EAAE,kBAAkB;AAAA,QAAA;AAAA,MAAA;AAAA,IAAA;AAAA,EACvB,GAEJ;AAEJ;"}
|
|
@@ -48,6 +48,14 @@ export declare const ControlledMenuHandler: React.ForwardRefExoticComponent<{
|
|
|
48
48
|
interface IControlledMenuListProps extends Omit<React.HTMLAttributes<HTMLDivElement>, 'className' | 'onDrag' | 'onDragStart' | 'onDragEnd' | 'onAnimationStart' | 'onAnimationEnd' | 'onAnimationIteration'> {
|
|
49
49
|
children: React.ReactNode;
|
|
50
50
|
className?: string;
|
|
51
|
+
/**
|
|
52
|
+
* Keyboard support for a list of items, which portals to the end of the page and is otherwise out
|
|
53
|
+
* of reach: opening moves the focus to the current item (`aria-current` or `aria-checked`) or the
|
|
54
|
+
* first one, Home and End reach the ends, and closing from inside (Escape, picking an item, Tab)
|
|
55
|
+
* gives the focus back to the trigger, so Tab goes on from there. Off by default for surfaces that
|
|
56
|
+
* keep the focus themselves (the select keeps it in its search field).
|
|
57
|
+
*/
|
|
58
|
+
manageFocus?: boolean;
|
|
51
59
|
}
|
|
52
60
|
export declare const ControlledMenuList: React.ForwardRefExoticComponent<IControlledMenuListProps & React.RefAttributes<HTMLDivElement>>;
|
|
53
61
|
interface IControlledMenuItemProps extends Omit<React.HTMLAttributes<HTMLDivElement>, 'className'> {
|
|
@@ -69,6 +77,11 @@ interface IControlledMenuProps {
|
|
|
69
77
|
listClassName?: string;
|
|
70
78
|
tooltipClassName?: string;
|
|
71
79
|
listRef?: React.Ref<HTMLDivElement>;
|
|
80
|
+
/**
|
|
81
|
+
* Moves the focus into the menu on opening and back to the trigger on closing (see
|
|
82
|
+
* `ControlledMenuList`). Turn it off only for a menu opened while the person types elsewhere.
|
|
83
|
+
*/
|
|
84
|
+
manageFocus?: boolean;
|
|
72
85
|
}
|
|
73
86
|
/**
|
|
74
87
|
* A tooltip on the trigger must sit OUTSIDE the handler: the handler clones its child to
|
|
@@ -68,13 +68,33 @@ const ControlledMenuHandler = React.forwardRef(({ children, onClick: onOuterClic
|
|
|
68
68
|
});
|
|
69
69
|
ControlledMenuHandler.displayName = "ControlledMenuHandler";
|
|
70
70
|
const FOCUSABLE_ITEM_SELECTOR = '[role="menuitem"]:not([aria-disabled="true"])';
|
|
71
|
+
const CURRENT_ITEM_SELECTOR = `${FOCUSABLE_ITEM_SELECTOR}[aria-current="true"], ${FOCUSABLE_ITEM_SELECTOR}[aria-checked="true"]`;
|
|
72
|
+
const itemForKey = (key, items, current, reachEnds) => {
|
|
73
|
+
if (key === "ArrowDown") return items[current < 0 ? 0 : (current + 1) % items.length];
|
|
74
|
+
if (key === "ArrowUp") return items[current < 0 ? 0 : (current - 1 + items.length) % items.length];
|
|
75
|
+
if (reachEnds && key === "Home") return items[0];
|
|
76
|
+
if (reachEnds && key === "End") return items[items.length - 1];
|
|
77
|
+
return void 0;
|
|
78
|
+
};
|
|
71
79
|
const ControlledMenuList = React.forwardRef(
|
|
72
|
-
({ children, className, onClick, onKeyDown, ...rest }, forwardedRef) => {
|
|
80
|
+
({ children, className, manageFocus = false, onClick, onKeyDown, ...rest }, forwardedRef) => {
|
|
73
81
|
const { open, setOpen, dismiss, listId, setFloating, floatingRef, referenceRef } = useMenuContext();
|
|
82
|
+
useEffect(() => {
|
|
83
|
+
if (!open || !manageFocus) return void 0;
|
|
84
|
+
const frame = requestAnimationFrame(() => {
|
|
85
|
+
const list = floatingRef.current;
|
|
86
|
+
if (!list || list.contains(document.activeElement)) return;
|
|
87
|
+
(list.querySelector(CURRENT_ITEM_SELECTOR) ?? list.querySelector(FOCUSABLE_ITEM_SELECTOR))?.focus();
|
|
88
|
+
});
|
|
89
|
+
return () => {
|
|
90
|
+
cancelAnimationFrame(frame);
|
|
91
|
+
if (floatingRef.current?.contains(document.activeElement)) referenceRef.current?.focus();
|
|
92
|
+
};
|
|
93
|
+
}, [open, manageFocus, floatingRef, referenceRef]);
|
|
74
94
|
useEffect(() => {
|
|
75
95
|
if (!open) return void 0;
|
|
76
96
|
const handleKeyDown = (event) => {
|
|
77
|
-
if (event.key !== "Escape" || dismiss?.escapeKey === false) return;
|
|
97
|
+
if (event.key !== "Escape" || event.defaultPrevented || dismiss?.escapeKey === false) return;
|
|
78
98
|
setOpen(false);
|
|
79
99
|
};
|
|
80
100
|
const handlePointerDown = (event) => {
|
|
@@ -94,16 +114,25 @@ const ControlledMenuList = React.forwardRef(
|
|
|
94
114
|
}, [open, setOpen, dismiss, floatingRef, referenceRef]);
|
|
95
115
|
const handleListKeyDown = (event) => {
|
|
96
116
|
onKeyDown?.(event);
|
|
97
|
-
if (event.key
|
|
117
|
+
if (event.key === "Escape") {
|
|
118
|
+
if (event.defaultPrevented || dismiss?.escapeKey === false) return;
|
|
119
|
+
event.preventDefault();
|
|
120
|
+
setOpen(false);
|
|
121
|
+
return;
|
|
122
|
+
}
|
|
123
|
+
if (manageFocus && event.key === "Tab") {
|
|
124
|
+
referenceRef.current?.focus();
|
|
125
|
+
setOpen(false);
|
|
126
|
+
return;
|
|
127
|
+
}
|
|
98
128
|
const list = floatingRef.current;
|
|
99
129
|
if (!list) return;
|
|
100
130
|
const items = Array.from(list.querySelectorAll(FOCUSABLE_ITEM_SELECTOR));
|
|
101
131
|
if (items.length === 0) return;
|
|
132
|
+
const next = itemForKey(event.key, items, items.indexOf(document.activeElement), manageFocus);
|
|
133
|
+
if (!next) return;
|
|
102
134
|
event.preventDefault();
|
|
103
|
-
|
|
104
|
-
const step = event.key === "ArrowDown" ? 1 : -1;
|
|
105
|
-
const nextIndex = currentIndex < 0 ? 0 : (currentIndex + step + items.length) % items.length;
|
|
106
|
-
items[nextIndex]?.focus();
|
|
135
|
+
next.focus();
|
|
107
136
|
};
|
|
108
137
|
const portalHost = getPortalHost();
|
|
109
138
|
if (portalHost === null) return null;
|
|
@@ -195,7 +224,8 @@ const ControlledMenu = ({
|
|
|
195
224
|
dismissOnItemClick = true,
|
|
196
225
|
listClassName,
|
|
197
226
|
tooltipClassName,
|
|
198
|
-
listRef
|
|
227
|
+
listRef,
|
|
228
|
+
manageFocus = true
|
|
199
229
|
}) => {
|
|
200
230
|
const menuItems = useMemo(() => Array.isArray(items) ? items : [], [items]);
|
|
201
231
|
const dismiss = useMemo(() => ({ itemPress: dismissOnItemClick }), [dismissOnItemClick]);
|
|
@@ -203,7 +233,7 @@ const ControlledMenu = ({
|
|
|
203
233
|
if (disabled) return /* @__PURE__ */ jsx(Fragment, { children: trigger });
|
|
204
234
|
return /* @__PURE__ */ jsxs(ControlledMenuRoot, { open, handler: onOpenChange, placement, dismiss, children: [
|
|
205
235
|
triggerTooltip ? /* @__PURE__ */ jsx(ControlledTooltip, { content: triggerTooltip, className: tooltipClassName, children: handle }) : handle,
|
|
206
|
-
/* @__PURE__ */ jsx(ControlledMenuList, { ref: listRef, className: listClassName, children: children ?? menuItems.map((item) => {
|
|
236
|
+
/* @__PURE__ */ jsx(ControlledMenuList, { ref: listRef, className: listClassName, manageFocus, children: children ?? menuItems.map((item) => {
|
|
207
237
|
const tone = item.tone ?? "default";
|
|
208
238
|
return /* @__PURE__ */ jsxs(
|
|
209
239
|
ControlledMenuItem,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ControlledMenu.js","sources":["../../../src/components/UI/ControlledMenu.tsx"],"sourcesContent":["import React, {\n cloneElement,\n createContext,\n isValidElement,\n useCallback,\n useContext,\n useEffect,\n useId,\n useMemo,\n useState,\n} from 'react';\nimport classNames from 'classnames';\nimport { AnimatePresence, motion } from 'motion/react';\nimport { createPortal } from 'react-dom';\n\nimport ControlledTooltip from '@/components/UI/ControlledTooltip';\nimport { MaterialSymbol, SymbolCodepoints } from '@/components/UI/MaterialSymbol';\nimport { composeRefs } from '@/helpers/composeRefs';\nimport { isPressOnLayeredSurface, LAYERED_SURFACE_ATTRIBUTE } from '@/helpers/layeredSurfaces';\nimport { mergeClasses } from '@/helpers/mergeClasses';\nimport { getPortalHost } from '@/helpers/portalHost';\nimport { TFloatingPlacement, useAnchoredFloating } from '@/hooks/useAnchoredFloating';\nimport { floatingVariants } from '@/motion';\n\nexport type TMenuPlacement = TFloatingPlacement;\nexport type TMenuItemTone = 'default' | 'danger';\n\nexport interface IMenuDismissConfig {\n /** Closes the menu when an item is pressed. Multi-select surfaces pass false. */\n itemPress?: boolean;\n escapeKey?: boolean;\n outsidePress?: boolean;\n}\n\nexport interface IControlledMenuItem {\n key: string;\n label: string;\n icon?: SymbolCodepoints;\n hint?: string;\n onClick?: () => void;\n disabled?: boolean;\n tone?: TMenuItemTone;\n}\n\ninterface IMenuContext {\n open: boolean;\n setOpen: (open: boolean) => void;\n dismiss?: IMenuDismissConfig;\n listId: string;\n setReference: (node: HTMLElement | null) => void;\n setFloating: (node: HTMLElement | null) => void;\n floatingRef: React.MutableRefObject<HTMLElement | null>;\n referenceRef: React.MutableRefObject<HTMLElement | null>;\n}\n\nconst MenuContext = createContext<IMenuContext | null>(null);\n\nconst useMenuContext = (): IMenuContext => {\n const context = useContext(MenuContext);\n if (!context) throw new Error('Menu parts must be rendered inside ControlledMenuRoot');\n return context;\n};\n\ninterface IControlledMenuRootProps {\n children: React.ReactNode;\n open?: boolean;\n handler?: (open: boolean) => void;\n placement?: TMenuPlacement;\n offsetPx?: number;\n dismiss?: IMenuDismissConfig;\n matchTriggerWidth?: boolean;\n}\n\nexport const ControlledMenuRoot: React.FC<IControlledMenuRootProps> = ({\n children,\n open,\n handler,\n placement = 'bottom-start',\n offsetPx = 6,\n dismiss,\n matchTriggerWidth = false,\n}) => {\n const listId = useId();\n const [uncontrolledOpen, setUncontrolledOpen] = useState(false);\n\n const isControlled = open !== undefined;\n const isOpen = isControlled ? Boolean(open) : uncontrolledOpen;\n\n const setOpen = useCallback(\n (next: boolean) => {\n if (!isControlled) setUncontrolledOpen(next);\n handler?.(next);\n },\n [isControlled, handler],\n );\n\n const { setReference, setFloating, floatingRef, referenceRef } = useAnchoredFloating({\n open: isOpen,\n placement,\n offsetPx,\n matchReferenceWidth: matchTriggerWidth,\n });\n\n const value = useMemo(\n () => ({ open: isOpen, setOpen, dismiss, listId, setReference, setFloating, floatingRef, referenceRef }),\n [isOpen, setOpen, dismiss, listId, setReference, setFloating, floatingRef, referenceRef],\n );\n\n return <MenuContext.Provider value={value}>{children}</MenuContext.Provider>;\n};\n\ninterface IHandlerChildProps {\n onClick?: (event: React.MouseEvent<HTMLElement>) => void;\n ref?: React.Ref<HTMLElement>;\n}\n\n/**\n * Repassa ao filho o que ele recebe de fora, além do que injeta.\n *\n * O gatilho é o alvo natural de um `ControlledTooltip`, e o tooltip se prende clonando o filho e\n * injetando `onPointerEnter`. Aceitando só `children`, este componente engolia essa injeção e o\n * tooltip simplesmente nunca abria, mesmo com a ordem que a documentação manda usar\n * (tooltip POR FORA do handler). Os `onClick` são encadeados: o de fora roda antes de abrir.\n */\nexport const ControlledMenuHandler = React.forwardRef<\n HTMLElement,\n {\n children: React.ReactNode;\n /**\n * Leaves the popup ARIA to the child: set it when the real trigger is an element INSIDE the\n * child that owns its own role (the select's combobox input), so the wrapper does not\n * claim `aria-haspopup=\"menu\"` for a listbox.\n */\n skipTriggerAria?: boolean;\n } & React.HTMLAttributes<HTMLElement>\n>(({ children, onClick: onOuterClick, skipTriggerAria = false, ...rest }, forwardedRef) => {\n const { open, setOpen, setReference, listId } = useMenuContext();\n\n if (!isValidElement(children)) return <>{children}</>;\n\n const child = children as React.ReactElement<IHandlerChildProps>;\n const triggerAria = skipTriggerAria\n ? {}\n : { 'aria-haspopup': 'menu', 'aria-expanded': open, 'aria-controls': open ? listId : undefined };\n\n return cloneElement(child, {\n ...rest,\n ref: composeRefs<HTMLElement>(setReference, forwardedRef, (child as { ref?: React.Ref<HTMLElement> }).ref),\n ...triggerAria,\n onClick: (event: React.MouseEvent<HTMLElement>) => {\n onOuterClick?.(event);\n child.props.onClick?.(event);\n setOpen(!open);\n },\n } as IHandlerChildProps);\n});\n\nControlledMenuHandler.displayName = 'ControlledMenuHandler';\n\ninterface IControlledMenuListProps extends Omit<\n React.HTMLAttributes<HTMLDivElement>,\n 'className' | 'onDrag' | 'onDragStart' | 'onDragEnd' | 'onAnimationStart' | 'onAnimationEnd' | 'onAnimationIteration'\n> {\n children: React.ReactNode;\n className?: string;\n}\n\nconst FOCUSABLE_ITEM_SELECTOR = '[role=\"menuitem\"]:not([aria-disabled=\"true\"])';\n\nexport const ControlledMenuList = React.forwardRef<HTMLDivElement, IControlledMenuListProps>(\n ({ children, className, onClick, onKeyDown, ...rest }, forwardedRef) => {\n const { open, setOpen, dismiss, listId, setFloating, floatingRef, referenceRef } = useMenuContext();\n\n useEffect(() => {\n if (!open) return undefined;\n\n const handleKeyDown = (event: KeyboardEvent) => {\n if (event.key !== 'Escape' || dismiss?.escapeKey === false) return;\n setOpen(false);\n };\n\n const handlePointerDown = (event: PointerEvent) => {\n if (dismiss?.outsidePress === false) return;\n const target = event.target as Node | null;\n if (!target) return;\n if (floatingRef.current?.contains(target) || referenceRef.current?.contains(target)) return;\n if (isPressOnLayeredSurface(target, floatingRef.current)) return;\n setOpen(false);\n };\n\n document.addEventListener('keydown', handleKeyDown);\n document.addEventListener('pointerdown', handlePointerDown, true);\n\n return () => {\n document.removeEventListener('keydown', handleKeyDown);\n document.removeEventListener('pointerdown', handlePointerDown, true);\n };\n }, [open, setOpen, dismiss, floatingRef, referenceRef]);\n\n const handleListKeyDown = (event: React.KeyboardEvent<HTMLDivElement>) => {\n onKeyDown?.(event);\n if (event.key !== 'ArrowDown' && event.key !== 'ArrowUp') return;\n\n const list = floatingRef.current;\n if (!list) return;\n\n const items = Array.from(list.querySelectorAll<HTMLElement>(FOCUSABLE_ITEM_SELECTOR));\n if (items.length === 0) return;\n\n event.preventDefault();\n const currentIndex = items.indexOf(document.activeElement as HTMLElement);\n const step = event.key === 'ArrowDown' ? 1 : -1;\n const nextIndex = currentIndex < 0 ? 0 : (currentIndex + step + items.length) % items.length;\n items[nextIndex]?.focus();\n };\n\n const portalHost = getPortalHost();\n if (portalHost === null) return null;\n\n return createPortal(\n <AnimatePresence>\n {open && (\n <motion.div\n key=\"menu-list\"\n id={listId}\n variants={floatingVariants}\n initial=\"hidden\"\n animate=\"visible\"\n exit=\"exit\"\n role=\"menu\"\n {...LAYERED_SURFACE_ATTRIBUTE}\n ref={(node) => {\n setFloating(node);\n if (typeof forwardedRef === 'function') forwardedRef(node);\n else if (forwardedRef) forwardedRef.current = node;\n }}\n onKeyDown={handleListKeyDown}\n onClick={(event) => {\n onClick?.(event);\n if (dismiss?.itemPress === false) return;\n const target = event.target as HTMLElement | null;\n if (target?.closest('[role=\"menuitem\"]')) setOpen(false);\n }}\n {...rest}\n className={mergeClasses(\n 'fixed left-0 top-0 z-[9999] min-w-44 overflow-auto rounded-lg border border-border p-1 text-sm text-foreground glass',\n className,\n )}\n >\n {children}\n </motion.div>\n )}\n </AnimatePresence>,\n portalHost,\n );\n },\n);\n\nControlledMenuList.displayName = 'ControlledMenuList';\n\ninterface IControlledMenuItemProps extends Omit<React.HTMLAttributes<HTMLDivElement>, 'className'> {\n children: React.ReactNode;\n className?: string;\n disabled?: boolean;\n}\n\nexport const ControlledMenuItem: React.FC<IControlledMenuItemProps> = ({\n children,\n className,\n disabled = false,\n onClick,\n ...rest\n}) => (\n <div\n role=\"menuitem\"\n tabIndex={disabled ? -1 : 0}\n aria-disabled={disabled || undefined}\n onClick={disabled ? undefined : onClick}\n onKeyDown={(event) => {\n if (disabled) return;\n if (event.key !== 'Enter' && event.key !== ' ') return;\n event.preventDefault();\n (event.currentTarget as HTMLElement).click();\n }}\n {...rest}\n className={mergeClasses(\n classNames(\n 'flex w-full cursor-pointer select-none items-center rounded-md px-3 py-2 text-sm outline-none',\n 'transition-colors hover:bg-muted-hover focus:bg-muted-hover',\n { 'pointer-events-none opacity-50': disabled },\n ),\n className,\n )}\n >\n {children}\n </div>\n);\n\ninterface IControlledMenuProps {\n trigger: React.ReactNode;\n items?: Array<IControlledMenuItem>;\n children?: React.ReactNode;\n triggerTooltip?: string;\n placement?: TMenuPlacement;\n open?: boolean;\n onOpenChange?: (open: boolean) => void;\n disabled?: boolean;\n dismissOnItemClick?: boolean;\n listClassName?: string;\n tooltipClassName?: string;\n listRef?: React.Ref<HTMLDivElement>;\n}\n\nconst ITEM_TONE_CLASS: Record<TMenuItemTone, string> = {\n default: 'text-foreground-muted',\n danger: 'text-danger-emphasis',\n};\n\nconst ICON_TONE_CLASS: Record<TMenuItemTone, string> = {\n default: 'text-foreground-subtle',\n danger: 'text-danger-emphasis',\n};\n\n/**\n * A tooltip on the trigger must sit OUTSIDE the handler: the handler clones its child to\n * inject the click handler and the reference ref, and a tooltip in that position swallows\n * both, so the menu stops opening.\n */\nconst ControlledMenu: React.FC<IControlledMenuProps> = ({\n trigger,\n items,\n children,\n triggerTooltip,\n placement = 'bottom-start',\n open,\n onOpenChange,\n disabled = false,\n dismissOnItemClick = true,\n listClassName,\n tooltipClassName,\n listRef,\n}) => {\n const menuItems = useMemo(() => (Array.isArray(items) ? items : []), [items]);\n const dismiss = useMemo(() => ({ itemPress: dismissOnItemClick }), [dismissOnItemClick]);\n const handle = <ControlledMenuHandler>{trigger}</ControlledMenuHandler>;\n\n if (disabled) return <>{trigger}</>;\n\n return (\n <ControlledMenuRoot open={open} handler={onOpenChange} placement={placement} dismiss={dismiss}>\n {triggerTooltip ? (\n <ControlledTooltip content={triggerTooltip} className={tooltipClassName}>\n {handle}\n </ControlledTooltip>\n ) : (\n handle\n )}\n\n <ControlledMenuList ref={listRef} className={listClassName}>\n {children ??\n menuItems.map((item) => {\n const tone = item.tone ?? 'default';\n\n return (\n <ControlledMenuItem\n key={item.key}\n disabled={item.disabled}\n onClick={item.onClick}\n className={classNames('items-start gap-x-2', ITEM_TONE_CLASS[tone])}\n >\n {item.icon && <MaterialSymbol icon={item.icon} size={16} className={ICON_TONE_CLASS[tone]} />}\n\n <span className=\"flex flex-col items-start gap-y-0.5\">\n <span>{item.label}</span>\n {item.hint && <span className=\"text-xs text-foreground-subtle\">{item.hint}</span>}\n </span>\n </ControlledMenuItem>\n );\n })}\n </ControlledMenuList>\n </ControlledMenuRoot>\n );\n};\n\nexport default ControlledMenu;\n"],"names":[],"mappings":";;;;;;;;;;;;;;AAuDA,MAAM,cAAc,cAAmC,IAAI;AAE3D,MAAM,iBAAiB,MAAoB;AACzC,QAAM,UAAU,WAAW,WAAW;AACtC,MAAI,CAAC,QAAS,OAAM,IAAI,MAAM,uDAAuD;AACrF,SAAO;AACT;AAYO,MAAM,qBAAyD,CAAC;AAAA,EACrE;AAAA,EACA;AAAA,EACA;AAAA,EACA,YAAY;AAAA,EACZ,WAAW;AAAA,EACX;AAAA,EACA,oBAAoB;AACtB,MAAM;AACJ,QAAM,SAAS,MAAA;AACf,QAAM,CAAC,kBAAkB,mBAAmB,IAAI,SAAS,KAAK;AAE9D,QAAM,eAAe,SAAS;AAC9B,QAAM,SAAS,eAAe,QAAQ,IAAI,IAAI;AAE9C,QAAM,UAAU;AAAA,IACd,CAAC,SAAkB;AACjB,UAAI,CAAC,aAAc,qBAAoB,IAAI;AAC3C,gBAAU,IAAI;AAAA,IAChB;AAAA,IACA,CAAC,cAAc,OAAO;AAAA,EAAA;AAGxB,QAAM,EAAE,cAAc,aAAa,aAAa,aAAA,IAAiB,oBAAoB;AAAA,IACnF,MAAM;AAAA,IACN;AAAA,IACA;AAAA,IACA,qBAAqB;AAAA,EAAA,CACtB;AAED,QAAM,QAAQ;AAAA,IACZ,OAAO,EAAE,MAAM,QAAQ,SAAS,SAAS,QAAQ,cAAc,aAAa,aAAa;IACzF,CAAC,QAAQ,SAAS,SAAS,QAAQ,cAAc,aA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IAAI,QAAQ,CAAA,GAAK,CAAC,KAAK,CAAC;AAC5E,QAAM,UAAU,QAAQ,OAAO,EAAE,WAAW,uBAAuB,CAAC,kBAAkB,CAAC;AACvF,QAAM,SAAS,oBAAC,uBAAA,EAAuB,UAAA,QAAA,CAAQ;AAE/C,MAAI,SAAU,QAAO,oBAAA,UAAA,EAAG,UAAA,SAAQ;AAEhC,8BACG,oBAAA,EAAmB,MAAY,SAAS,cAAc,WAAsB,SAC1E,UAAA;AAAA,IAAA,qCACE,mBAAA,EAAkB,SAAS,gBAAgB,WAAW,kBACpD,kBACH,IAEA;AAAA,IAGF,oBAAC,oBAAA,EAAmB,KAAK,SAAS,WAAW,eAC1C,UAAA,YACC,UAAU,IAAI,CAAC,SAAS;AACtB,YAAM,OAAO,KAAK,QAAQ;AAE1B,aACE;AAAA,QAAC;AAAA,QAAA;AAAA,UAEC,UAAU,KAAK;AAAA,UACf,SAAS,KAAK;AAAA,UACd,WAAW,WAAW,uBAAuB,gBAAgB,IAAI,CAAC;AAAA,UAEjE,UAAA;AAAA,YAAA,KAAK,QAAQ,oBAAC,gBAAA,EAAe,MAAM,KAAK,MAAM,MAAM,IAAI,WAAW,gBAAgB,IAAI,EAAA,CAAG;AAAA,YAE3F,qBAAC,QAAA,EAAK,WAAU,uCACd,UAAA;AAAA,cAAA,oBAAC,QAAA,EAAM,eAAK,MAAA,CAAM;AAAA,cACjB,KAAK,QAAQ,oBAAC,UAAK,WAAU,kCAAkC,eAAK,KAAA,CAAK;AAAA,YAAA,EAAA,CAC5E;AAAA,UAAA;AAAA,QAAA;AAAA,QAVK,KAAK;AAAA,MAAA;AAAA,IAahB,CAAC,EAAA,CACL;AAAA,EAAA,GACF;AAEJ;"}
|
|
1
|
+
{"version":3,"file":"ControlledMenu.js","sources":["../../../src/components/UI/ControlledMenu.tsx"],"sourcesContent":["import React, {\n cloneElement,\n createContext,\n isValidElement,\n useCallback,\n useContext,\n useEffect,\n useId,\n useMemo,\n useState,\n} from 'react';\nimport classNames from 'classnames';\nimport { AnimatePresence, motion } from 'motion/react';\nimport { createPortal } from 'react-dom';\n\nimport ControlledTooltip from '@/components/UI/ControlledTooltip';\nimport { MaterialSymbol, SymbolCodepoints } from '@/components/UI/MaterialSymbol';\nimport { composeRefs } from '@/helpers/composeRefs';\nimport { isPressOnLayeredSurface, LAYERED_SURFACE_ATTRIBUTE } from '@/helpers/layeredSurfaces';\nimport { mergeClasses } from '@/helpers/mergeClasses';\nimport { getPortalHost } from '@/helpers/portalHost';\nimport { TFloatingPlacement, useAnchoredFloating } from '@/hooks/useAnchoredFloating';\nimport { floatingVariants } from '@/motion';\n\nexport type TMenuPlacement = TFloatingPlacement;\nexport type TMenuItemTone = 'default' | 'danger';\n\nexport interface IMenuDismissConfig {\n /** Closes the menu when an item is pressed. Multi-select surfaces pass false. */\n itemPress?: boolean;\n escapeKey?: boolean;\n outsidePress?: boolean;\n}\n\nexport interface IControlledMenuItem {\n key: string;\n label: string;\n icon?: SymbolCodepoints;\n hint?: string;\n onClick?: () => void;\n disabled?: boolean;\n tone?: TMenuItemTone;\n}\n\ninterface IMenuContext {\n open: boolean;\n setOpen: (open: boolean) => void;\n dismiss?: IMenuDismissConfig;\n listId: string;\n setReference: (node: HTMLElement | null) => void;\n setFloating: (node: HTMLElement | null) => void;\n floatingRef: React.MutableRefObject<HTMLElement | null>;\n referenceRef: React.MutableRefObject<HTMLElement | null>;\n}\n\nconst MenuContext = createContext<IMenuContext | null>(null);\n\nconst useMenuContext = (): IMenuContext => {\n const context = useContext(MenuContext);\n if (!context) throw new Error('Menu parts must be rendered inside ControlledMenuRoot');\n return context;\n};\n\ninterface IControlledMenuRootProps {\n children: React.ReactNode;\n open?: boolean;\n handler?: (open: boolean) => void;\n placement?: TMenuPlacement;\n offsetPx?: number;\n dismiss?: IMenuDismissConfig;\n matchTriggerWidth?: boolean;\n}\n\nexport const ControlledMenuRoot: React.FC<IControlledMenuRootProps> = ({\n children,\n open,\n handler,\n placement = 'bottom-start',\n offsetPx = 6,\n dismiss,\n matchTriggerWidth = false,\n}) => {\n const listId = useId();\n const [uncontrolledOpen, setUncontrolledOpen] = useState(false);\n\n const isControlled = open !== undefined;\n const isOpen = isControlled ? Boolean(open) : uncontrolledOpen;\n\n const setOpen = useCallback(\n (next: boolean) => {\n if (!isControlled) setUncontrolledOpen(next);\n handler?.(next);\n },\n [isControlled, handler],\n );\n\n const { setReference, setFloating, floatingRef, referenceRef } = useAnchoredFloating({\n open: isOpen,\n placement,\n offsetPx,\n matchReferenceWidth: matchTriggerWidth,\n });\n\n const value = useMemo(\n () => ({ open: isOpen, setOpen, dismiss, listId, setReference, setFloating, floatingRef, referenceRef }),\n [isOpen, setOpen, dismiss, listId, setReference, setFloating, floatingRef, referenceRef],\n );\n\n return <MenuContext.Provider value={value}>{children}</MenuContext.Provider>;\n};\n\ninterface IHandlerChildProps {\n onClick?: (event: React.MouseEvent<HTMLElement>) => void;\n ref?: React.Ref<HTMLElement>;\n}\n\n/**\n * Repassa ao filho o que ele recebe de fora, além do que injeta.\n *\n * O gatilho é o alvo natural de um `ControlledTooltip`, e o tooltip se prende clonando o filho e\n * injetando `onPointerEnter`. Aceitando só `children`, este componente engolia essa injeção e o\n * tooltip simplesmente nunca abria, mesmo com a ordem que a documentação manda usar\n * (tooltip POR FORA do handler). Os `onClick` são encadeados: o de fora roda antes de abrir.\n */\nexport const ControlledMenuHandler = React.forwardRef<\n HTMLElement,\n {\n children: React.ReactNode;\n /**\n * Leaves the popup ARIA to the child: set it when the real trigger is an element INSIDE the\n * child that owns its own role (the select's combobox input), so the wrapper does not\n * claim `aria-haspopup=\"menu\"` for a listbox.\n */\n skipTriggerAria?: boolean;\n } & React.HTMLAttributes<HTMLElement>\n>(({ children, onClick: onOuterClick, skipTriggerAria = false, ...rest }, forwardedRef) => {\n const { open, setOpen, setReference, listId } = useMenuContext();\n\n if (!isValidElement(children)) return <>{children}</>;\n\n const child = children as React.ReactElement<IHandlerChildProps>;\n const triggerAria = skipTriggerAria\n ? {}\n : { 'aria-haspopup': 'menu', 'aria-expanded': open, 'aria-controls': open ? listId : undefined };\n\n return cloneElement(child, {\n ...rest,\n ref: composeRefs<HTMLElement>(setReference, forwardedRef, (child as { ref?: React.Ref<HTMLElement> }).ref),\n ...triggerAria,\n onClick: (event: React.MouseEvent<HTMLElement>) => {\n onOuterClick?.(event);\n child.props.onClick?.(event);\n setOpen(!open);\n },\n } as IHandlerChildProps);\n});\n\nControlledMenuHandler.displayName = 'ControlledMenuHandler';\n\ninterface IControlledMenuListProps extends Omit<\n React.HTMLAttributes<HTMLDivElement>,\n 'className' | 'onDrag' | 'onDragStart' | 'onDragEnd' | 'onAnimationStart' | 'onAnimationEnd' | 'onAnimationIteration'\n> {\n children: React.ReactNode;\n className?: string;\n /**\n * Keyboard support for a list of items, which portals to the end of the page and is otherwise out\n * of reach: opening moves the focus to the current item (`aria-current` or `aria-checked`) or the\n * first one, Home and End reach the ends, and closing from inside (Escape, picking an item, Tab)\n * gives the focus back to the trigger, so Tab goes on from there. Off by default for surfaces that\n * keep the focus themselves (the select keeps it in its search field).\n */\n manageFocus?: boolean;\n}\n\nconst FOCUSABLE_ITEM_SELECTOR = '[role=\"menuitem\"]:not([aria-disabled=\"true\"])';\nconst CURRENT_ITEM_SELECTOR = `${FOCUSABLE_ITEM_SELECTOR}[aria-current=\"true\"], ${FOCUSABLE_ITEM_SELECTOR}[aria-checked=\"true\"]`;\n\n/** The item a key moves to among the enabled ones; undefined for a key that moves nothing. */\nconst itemForKey = (\n key: string,\n items: Array<HTMLElement>,\n current: number,\n reachEnds: boolean,\n): HTMLElement | undefined => {\n if (key === 'ArrowDown') return items[current < 0 ? 0 : (current + 1) % items.length];\n if (key === 'ArrowUp') return items[current < 0 ? 0 : (current - 1 + items.length) % items.length];\n if (reachEnds && key === 'Home') return items[0];\n if (reachEnds && key === 'End') return items[items.length - 1];\n return undefined;\n};\n\nexport const ControlledMenuList = React.forwardRef<HTMLDivElement, IControlledMenuListProps>(\n ({ children, className, manageFocus = false, onClick, onKeyDown, ...rest }, forwardedRef) => {\n const { open, setOpen, dismiss, listId, setFloating, floatingRef, referenceRef } = useMenuContext();\n\n useEffect(() => {\n if (!open || !manageFocus) return undefined;\n\n // The list mounts with this update: wait for the frame that paints it.\n const frame = requestAnimationFrame(() => {\n const list = floatingRef.current;\n if (!list || list.contains(document.activeElement)) return;\n (\n list.querySelector<HTMLElement>(CURRENT_ITEM_SELECTOR) ??\n list.querySelector<HTMLElement>(FOCUSABLE_ITEM_SELECTOR)\n )?.focus();\n });\n\n return () => {\n cancelAnimationFrame(frame);\n // The list is still mounted here, playing its exit.\n if (floatingRef.current?.contains(document.activeElement)) referenceRef.current?.focus();\n };\n }, [open, manageFocus, floatingRef, referenceRef]);\n\n useEffect(() => {\n if (!open) return undefined;\n\n const handleKeyDown = (event: KeyboardEvent) => {\n // A layer that consumed the ESC (the list itself, a select inside it) marks it handled.\n if (event.key !== 'Escape' || event.defaultPrevented || dismiss?.escapeKey === false) return;\n setOpen(false);\n };\n\n const handlePointerDown = (event: PointerEvent) => {\n if (dismiss?.outsidePress === false) return;\n const target = event.target as Node | null;\n if (!target) return;\n if (floatingRef.current?.contains(target) || referenceRef.current?.contains(target)) return;\n if (isPressOnLayeredSurface(target, floatingRef.current)) return;\n setOpen(false);\n };\n\n document.addEventListener('keydown', handleKeyDown);\n document.addEventListener('pointerdown', handlePointerDown, true);\n\n return () => {\n document.removeEventListener('keydown', handleKeyDown);\n document.removeEventListener('pointerdown', handlePointerDown, true);\n };\n }, [open, setOpen, dismiss, floatingRef, referenceRef]);\n\n const handleListKeyDown = (event: React.KeyboardEvent<HTMLDivElement>) => {\n onKeyDown?.(event);\n\n if (event.key === 'Escape') {\n // Handled here, before any ancestor: marking it keeps an enclosing dialog open, and an\n // ancestor in the React tree that stops the key (a tab's trailing slot) cannot swallow it.\n if (event.defaultPrevented || dismiss?.escapeKey === false) return;\n event.preventDefault();\n setOpen(false);\n return;\n }\n\n if (manageFocus && event.key === 'Tab') {\n // From the trigger, the browser's own Tab reaches the next stop after it instead of the end\n // of the page, where the list is portaled.\n referenceRef.current?.focus();\n setOpen(false);\n return;\n }\n\n const list = floatingRef.current;\n if (!list) return;\n\n const items = Array.from(list.querySelectorAll<HTMLElement>(FOCUSABLE_ITEM_SELECTOR));\n if (items.length === 0) return;\n\n const next = itemForKey(event.key, items, items.indexOf(document.activeElement as HTMLElement), manageFocus);\n if (!next) return;\n\n event.preventDefault();\n next.focus();\n };\n\n const portalHost = getPortalHost();\n if (portalHost === null) return null;\n\n return createPortal(\n <AnimatePresence>\n {open && (\n <motion.div\n key=\"menu-list\"\n id={listId}\n variants={floatingVariants}\n initial=\"hidden\"\n animate=\"visible\"\n exit=\"exit\"\n role=\"menu\"\n {...LAYERED_SURFACE_ATTRIBUTE}\n ref={(node) => {\n setFloating(node);\n if (typeof forwardedRef === 'function') forwardedRef(node);\n else if (forwardedRef) forwardedRef.current = node;\n }}\n onKeyDown={handleListKeyDown}\n onClick={(event) => {\n onClick?.(event);\n if (dismiss?.itemPress === false) return;\n const target = event.target as HTMLElement | null;\n if (target?.closest('[role=\"menuitem\"]')) setOpen(false);\n }}\n {...rest}\n className={mergeClasses(\n 'fixed left-0 top-0 z-[9999] min-w-44 overflow-auto rounded-lg border border-border p-1 text-sm text-foreground glass',\n className,\n )}\n >\n {children}\n </motion.div>\n )}\n </AnimatePresence>,\n portalHost,\n );\n },\n);\n\nControlledMenuList.displayName = 'ControlledMenuList';\n\ninterface IControlledMenuItemProps extends Omit<React.HTMLAttributes<HTMLDivElement>, 'className'> {\n children: React.ReactNode;\n className?: string;\n disabled?: boolean;\n}\n\nexport const ControlledMenuItem: React.FC<IControlledMenuItemProps> = ({\n children,\n className,\n disabled = false,\n onClick,\n ...rest\n}) => (\n <div\n role=\"menuitem\"\n tabIndex={disabled ? -1 : 0}\n aria-disabled={disabled || undefined}\n onClick={disabled ? undefined : onClick}\n onKeyDown={(event) => {\n if (disabled) return;\n if (event.key !== 'Enter' && event.key !== ' ') return;\n event.preventDefault();\n (event.currentTarget as HTMLElement).click();\n }}\n {...rest}\n className={mergeClasses(\n classNames(\n 'flex w-full cursor-pointer select-none items-center rounded-md px-3 py-2 text-sm outline-none',\n 'transition-colors hover:bg-muted-hover focus:bg-muted-hover',\n { 'pointer-events-none opacity-50': disabled },\n ),\n className,\n )}\n >\n {children}\n </div>\n);\n\ninterface IControlledMenuProps {\n trigger: React.ReactNode;\n items?: Array<IControlledMenuItem>;\n children?: React.ReactNode;\n triggerTooltip?: string;\n placement?: TMenuPlacement;\n open?: boolean;\n onOpenChange?: (open: boolean) => void;\n disabled?: boolean;\n dismissOnItemClick?: boolean;\n listClassName?: string;\n tooltipClassName?: string;\n listRef?: React.Ref<HTMLDivElement>;\n /**\n * Moves the focus into the menu on opening and back to the trigger on closing (see\n * `ControlledMenuList`). Turn it off only for a menu opened while the person types elsewhere.\n */\n manageFocus?: boolean;\n}\n\nconst ITEM_TONE_CLASS: Record<TMenuItemTone, string> = {\n default: 'text-foreground-muted',\n danger: 'text-danger-emphasis',\n};\n\nconst ICON_TONE_CLASS: Record<TMenuItemTone, string> = {\n default: 'text-foreground-subtle',\n danger: 'text-danger-emphasis',\n};\n\n/**\n * A tooltip on the trigger must sit OUTSIDE the handler: the handler clones its child to\n * inject the click handler and the reference ref, and a tooltip in that position swallows\n * both, so the menu stops opening.\n */\nconst ControlledMenu: React.FC<IControlledMenuProps> = ({\n trigger,\n items,\n children,\n triggerTooltip,\n placement = 'bottom-start',\n open,\n onOpenChange,\n disabled = false,\n dismissOnItemClick = true,\n listClassName,\n tooltipClassName,\n listRef,\n manageFocus = true,\n}) => {\n const menuItems = useMemo(() => (Array.isArray(items) ? items : []), [items]);\n const dismiss = useMemo(() => ({ itemPress: dismissOnItemClick }), [dismissOnItemClick]);\n const handle = <ControlledMenuHandler>{trigger}</ControlledMenuHandler>;\n\n if (disabled) return <>{trigger}</>;\n\n return (\n <ControlledMenuRoot open={open} handler={onOpenChange} placement={placement} dismiss={dismiss}>\n {triggerTooltip ? (\n <ControlledTooltip content={triggerTooltip} className={tooltipClassName}>\n {handle}\n </ControlledTooltip>\n ) : (\n handle\n )}\n\n <ControlledMenuList ref={listRef} className={listClassName} manageFocus={manageFocus}>\n {children ??\n menuItems.map((item) => {\n const tone = item.tone ?? 'default';\n\n return (\n <ControlledMenuItem\n key={item.key}\n disabled={item.disabled}\n onClick={item.onClick}\n className={classNames('items-start gap-x-2', ITEM_TONE_CLASS[tone])}\n >\n {item.icon && <MaterialSymbol icon={item.icon} size={16} className={ICON_TONE_CLASS[tone]} />}\n\n <span className=\"flex flex-col items-start gap-y-0.5\">\n <span>{item.label}</span>\n {item.hint && <span className=\"text-xs text-foreground-subtle\">{item.hint}</span>}\n </span>\n </ControlledMenuItem>\n );\n })}\n </ControlledMenuList>\n </ControlledMenuRoot>\n );\n};\n\nexport default ControlledMenu;\n"],"names":[],"mappings":";;;;;;;;;;;;;;AAuDA,MAAM,cAAc,cAAmC,IAAI;AAE3D,MAAM,iBAAiB,MAAoB;AACzC,QAAM,UAAU,WAAW,WAAW;AACtC,MAAI,CAAC,QAAS,OAAM,IAAI,MAAM,uDAAuD;AACrF,SAAO;AACT;AAYO,MAAM,qBAAyD,CAAC;AAAA,EACrE;AAAA,EACA;AAAA,EACA;AAAA,EACA,YAAY;AAAA,EACZ,WAAW;AAAA,EACX;AAAA,EACA,oBAAoB;AACtB,MAAM;AACJ,QAAM,SAAS,MAAA;AACf,QAAM,CAAC,kBAAkB,mBAAmB,IAAI,SAAS,KAAK;AAE9D,QAAM,eAAe,SAAS;AAC9B,QAAM,SAAS,eAAe,QAAQ,IAAI,IAAI;AAE9C,QAAM,UAAU;AAAA,IACd,CAAC,SAAkB;AACjB,UAAI,CAAC,aAAc,qBAAoB,IAAI;AAC3C,gBAAU,IAAI;AAAA,IAChB;AAAA,IACA,CAAC,cAAc,OAAO;AAAA,EAAA;AAGxB,QAAM,EAAE,cAAc,aAAa,aAAa,aAAA,IAAiB,oBA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GAAK,CAAC,KAAK,CAAC;AAC5E,QAAM,UAAU,QAAQ,OAAO,EAAE,WAAW,uBAAuB,CAAC,kBAAkB,CAAC;AACvF,QAAM,SAAS,oBAAC,uBAAA,EAAuB,UAAA,QAAA,CAAQ;AAE/C,MAAI,SAAU,QAAO,oBAAA,UAAA,EAAG,UAAA,SAAQ;AAEhC,8BACG,oBAAA,EAAmB,MAAY,SAAS,cAAc,WAAsB,SAC1E,UAAA;AAAA,IAAA,qCACE,mBAAA,EAAkB,SAAS,gBAAgB,WAAW,kBACpD,kBACH,IAEA;AAAA,IAGF,oBAAC,oBAAA,EAAmB,KAAK,SAAS,WAAW,eAAe,aACzD,UAAA,YACC,UAAU,IAAI,CAAC,SAAS;AACtB,YAAM,OAAO,KAAK,QAAQ;AAE1B,aACE;AAAA,QAAC;AAAA,QAAA;AAAA,UAEC,UAAU,KAAK;AAAA,UACf,SAAS,KAAK;AAAA,UACd,WAAW,WAAW,uBAAuB,gBAAgB,IAAI,CAAC;AAAA,UAEjE,UAAA;AAAA,YAAA,KAAK,QAAQ,oBAAC,gBAAA,EAAe,MAAM,KAAK,MAAM,MAAM,IAAI,WAAW,gBAAgB,IAAI,EAAA,CAAG;AAAA,YAE3F,qBAAC,QAAA,EAAK,WAAU,uCACd,UAAA;AAAA,cAAA,oBAAC,QAAA,EAAM,eAAK,MAAA,CAAM;AAAA,cACjB,KAAK,QAAQ,oBAAC,UAAK,WAAU,kCAAkC,eAAK,KAAA,CAAK;AAAA,YAAA,EAAA,CAC5E;AAAA,UAAA;AAAA,QAAA;AAAA,QAVK,KAAK;AAAA,MAAA;AAAA,IAahB,CAAC,EAAA,CACL;AAAA,EAAA,GACF;AAEJ;"}
|
|
@@ -54,6 +54,18 @@ import { useColumnVisibility, useDetailColumnVisibility } from "./useColumnVisib
|
|
|
54
54
|
import { useDataTableInstance } from "./useDataTableInstance.js";
|
|
55
55
|
import { useDataTableUndoHistory } from "./useDataTableUndoHistory.js";
|
|
56
56
|
const FOOTER_CONTROL_TOOLTIP_PLACEMENT = "bottom";
|
|
57
|
+
const CARDS_LOAD_MORE_MARGIN = "300px";
|
|
58
|
+
const isScrollingOverflow = (overflowY) => overflowY === "auto" || overflowY === "scroll" || overflowY === "overlay";
|
|
59
|
+
const findCardsScrollRoot = (cardsBox) => {
|
|
60
|
+
let current = cardsBox;
|
|
61
|
+
while (current) {
|
|
62
|
+
if (isScrollingOverflow(getComputedStyle(current).overflowY) && current.scrollHeight > current.clientHeight) {
|
|
63
|
+
return current;
|
|
64
|
+
}
|
|
65
|
+
current = current.parentElement;
|
|
66
|
+
}
|
|
67
|
+
return null;
|
|
68
|
+
};
|
|
57
69
|
const DataTable = ({
|
|
58
70
|
config: configProp,
|
|
59
71
|
rows,
|
|
@@ -317,14 +329,14 @@ const DataTable = ({
|
|
|
317
329
|
const cardsHasMore = cardsInfiniteScroll?.hasMore ?? false;
|
|
318
330
|
useEffect(() => {
|
|
319
331
|
if (!isCardsView || !cardsHasMore || !cardsLoadMore) return;
|
|
320
|
-
const
|
|
332
|
+
const cardsBox = cardsScrollRef.current;
|
|
321
333
|
const sentinel = cardsSentinelRef.current;
|
|
322
|
-
if (!
|
|
334
|
+
if (!cardsBox || !sentinel) return;
|
|
323
335
|
const observer = new IntersectionObserver(
|
|
324
336
|
(entries) => {
|
|
325
337
|
if (entries.some((entry) => entry.isIntersecting)) cardsLoadMore();
|
|
326
338
|
},
|
|
327
|
-
{ root, rootMargin:
|
|
339
|
+
{ root: findCardsScrollRoot(cardsBox), rootMargin: CARDS_LOAD_MORE_MARGIN }
|
|
328
340
|
);
|
|
329
341
|
observer.observe(sentinel);
|
|
330
342
|
return () => observer.disconnect();
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"DataTable.js","sources":["../../../../src/components/UI/DataTable/DataTable.tsx"],"sourcesContent":["import { Fragment, JSX, KeyboardEvent, ReactNode, useCallback, useEffect, useMemo, useRef, useState } from 'react';\nimport classNames from 'classnames';\nimport { useTranslation } from 'react-i18next';\n\nimport ControlledButton from '@/components/Form/ControlledButton';\nimport { ActiveFiltersBar, buildEmptyFilterValues, emptyValueForKind } from '@/components/Search/filters';\nimport LoadingSpinner from '@/components/UI/LoadingSpinner';\nimport { MaterialSymbol } from '@/components/UI/MaterialSymbol';\nimport { useBreakpoint } from '@/hooks/useBreakpoint';\n\nimport GridProvider from './grid/GridProvider';\nimport { type IGridCellCoord } from './grid/gridTypes';\nimport { useGridFillApply } from './grid/useGridFillApply';\nimport { useGridEditMode, useGridInstance, useGridMatrixSync } from './grid/useGridInstance';\nimport { useGridKeyboard } from './grid/useGridKeyboard';\nimport DataTableAutoCard from './DataTableAutoCard';\nimport DataTableBody from './DataTableBody';\nimport DataTableBulkEditButton from './DataTableBulkEditButton';\nimport DataTableBulkEditDialog from './DataTableBulkEditDialog';\nimport { isBadgeColumnType } from './dataTableClasses';\nimport DataTableColumnToggle from './DataTableColumnToggle';\nimport { type IDataTableDetailColumnsState } from './DataTableDetailTable';\nimport DataTableEditModeButton from './DataTableEditModeButton';\nimport DataTableHead from './DataTableHead';\nimport DataTablePaginationBar, { DATA_TABLE_MIN_PAGE_SIZE } from './DataTablePagination';\nimport {\n DataTableCardsSkeletonState,\n DataTableEmptyState,\n DataTableErrorState,\n DataTableSkeletonState,\n} from './DataTableStates';\nimport DataTableToolbar from './DataTableToolbar';\nimport {\n DATA_TABLE_REMOVE_COLUMN_ID,\n type IDataTableColumnConfig,\n type IDataTableConfig,\n type IDataTableRow,\n type IDataTableSortState,\n type IDataTableSpreadsheetConfig,\n isDataTableDetailTableExpansion,\n type TDataTableFilterValues,\n type TDataTableViewMode,\n} from './types';\nimport DataTableCellEditingProvider from './useCellEditingState';\nimport { useColumnOrder, useDetailColumnOrder } from './useColumnOrder';\nimport { useColumnSizing } from './useColumnSizing';\nimport { useColumnVisibility, useDetailColumnVisibility } from './useColumnVisibility';\nimport {\n type IDataTableClientPaginationState,\n type IDataTablePagination,\n useDataTableInstance,\n} from './useDataTableInstance';\nimport { useDataTableUndoHistory } from './useDataTableUndoHistory';\n\n// The add-row control sits right above the footer controls, so an upward hint covers it and swallows\n// the next click; `flip` still lifts the hint when the table ends at the bottom of the viewport.\nconst FOOTER_CONTROL_TOOLTIP_PLACEMENT = 'bottom';\n\ninterface IDataTableProps<T extends IDataTableRow, C extends IDataTableRow = IDataTableRow> {\n config: IDataTableConfig<T, C>;\n rows: Array<T>;\n loading?: boolean;\n error?: boolean;\n /** Cause behind `error`, so the empty state can name a denial instead of a system failure. */\n errorCause?: unknown;\n onRetry?: () => void;\n emptyMessage?: string;\n searchLabel?: string;\n onSearch?: (value: string) => void;\n initialSearch?: string;\n onSearchTermChange?: (value: string) => void;\n searchDisabled?: boolean;\n searchDebounceTime?: number;\n searchMinLength?: number;\n /** Renders the search input in the toolbar's start (left) group instead of the end. */\n searchAtStart?: boolean;\n sort?: IDataTableSortState | null;\n onSortChange?: (sort: IDataTableSortState | null) => void;\n pagination?: IDataTablePagination;\n /** Client mode: seeds page/pageSize (1-based page), e.g. from the URL. */\n initialClientPagination?: IDataTableClientPaginationState;\n /** Client mode: reports page/pageSize changes and keeps the page across in-place row updates. */\n onClientPaginationChange?: (pagination: IDataTableClientPaginationState) => void;\n toolbarSlot?: JSX.Element;\n /**\n * Extra controls rendered in the footer's left group, right after the table's\n * own buttons (columns, edit mode, bulk edit). For an action that belongs to\n * the list itself rather than to the page header, so it sits beside the\n * controls it relates to instead of competing with the page actions. The\n * footer row renders for this slot alone when the table has no other control.\n */\n footerActionsSlot?: ReactNode;\n /**\n * Applied filter values. Passing them (together with `config.filters`) makes\n * the table render the always-visible active-filter chips above the toolbar,\n * so the user never has to hover the button to see what is filtering.\n */\n filterValues?: TDataTableFilterValues;\n onFilterValuesChange?: (values: TDataTableFilterValues) => void;\n /** Rendered at the start (left) of the toolbar, before tabs and view toggle. */\n toolbarStartSlot?: JSX.Element;\n /**\n * Full-width band rendered as the first row of the list body, spanning every\n * column (below the header, above the data rows). Opt-in: omit for a normal\n * table. When set, the empty state is skipped so the band stays visible even\n * with zero data rows (e.g. an inline \"create the first record\" editor).\n */\n bodyTopRow?: ReactNode;\n /** Client mode: reports the filtered (post-search) row count on every change. */\n onFilteredCountChange?: (count: number) => void;\n /**\n * Controlled view mode. When provided, the host owns the state (e.g. to persist\n * it) and must update it via `onViewModeChange`; omit for internal state.\n */\n viewMode?: TDataTableViewMode;\n /**\n * Fired on every view-toggle click, including re-selecting the active mode\n * (hosts use it e.g. to reopen the grouping dialog).\n */\n onViewModeChange?: (mode: TDataTableViewMode) => void;\n /**\n * Where the \"Columns\" toggle renders: `header` (default, inside the table\n * header), `toolbar` (next to the view toggle) or `footer` (bottom-left,\n * on the same row as the pagination).\n */\n columnTogglePlacement?: 'header' | 'toolbar' | 'footer';\n /**\n * Enables infinite scroll in the Cards view: the table observes a bottom\n * sentinel and calls `loadMore` while `hasMore`. Pass `source.cardsInfinite`\n * from `useDataTableSource`. The Lista view keeps its pagination bar.\n */\n cardsInfiniteScroll?: {\n hasMore: boolean;\n loadingMore: boolean;\n loadMore: () => void;\n };\n /**\n * Hides the built-in segmented view toggle. Use when the host renders its own\n * Cards/Lista switcher (e.g. a page-level `ControlledTabs`) and drives `viewMode`\n * itself. Other consumers keep the default toggle.\n */\n hideViewToggle?: boolean;\n /**\n * Layout mode. `page` (default): the table owns a bounded, vertically-scrolling\n * region (`flex-1 min-h-0`) for full-page lists. `fit`: the table sizes to its\n * content and scrolls only horizontally — for embedding inside a dialog / card /\n * editor grid where the host container owns vertical scroll. In `fit` mode the\n * empty state is compact (no full illustration) so surrounding controls such as\n * the add-row button stay visible.\n */\n layout?: 'page' | 'fit';\n /** Reduces cell vertical padding for more visible rows per viewport. */\n dense?: boolean;\n /** Roomier cell padding and type scale, for tables that need to read bigger. */\n spacious?: boolean;\n /**\n * Per-cell persistence state (`statuses` from `useDataTableCommitQueue`), painted\n * on the cells so the user sees what is saving and what failed.\n */\n commitStatuses?: ReadonlyMap<string, string>;\n}\n\nconst DataTable = <T extends IDataTableRow, C extends IDataTableRow = IDataTableRow>({\n config: configProp,\n rows,\n loading = false,\n error = false,\n errorCause,\n onRetry,\n emptyMessage,\n searchLabel,\n onSearch,\n initialSearch = '',\n onSearchTermChange,\n searchDisabled = false,\n searchDebounceTime = 400,\n searchMinLength = 1,\n searchAtStart = false,\n sort,\n onSortChange,\n pagination,\n initialClientPagination,\n onClientPaginationChange,\n toolbarSlot,\n footerActionsSlot,\n filterValues,\n onFilterValuesChange,\n toolbarStartSlot,\n bodyTopRow,\n onFilteredCountChange,\n viewMode: controlledViewMode,\n onViewModeChange,\n columnTogglePlacement = 'header',\n cardsInfiniteScroll,\n hideViewToggle = false,\n layout = 'page',\n dense: denseProp = false,\n spacious = false,\n commitStatuses,\n}: IDataTableProps<T, C>) => {\n const { t } = useTranslation('ui');\n\n const isFit = layout === 'fit';\n const dense = !spacious && (isFit || denseProp);\n const editingRows = configProp.editing?.rows;\n const showAddRow = !!editingRows?.canAdd && !!editingRows.onAddRow;\n\n const hostFillCells = configProp.spreadsheet ? configProp.spreadsheet.fill?.onFillCells : undefined;\n const isUndoEnabled = !!configProp.editing?.onCellChange && configProp.editing.undo !== false;\n const { recordedOnCellChange, recordedOnFillCells, handleUndoShortcut } = useDataTableUndoHistory<T>({\n enabled: isUndoEnabled,\n rows,\n columns: configProp.columns,\n onCellChange: configProp.editing?.onCellChange,\n onFillCells: hostFillCells,\n });\n\n const configWithUndo = useMemo<IDataTableConfig<T, C>>(() => {\n if (!isUndoEnabled || !configProp.editing) return configProp;\n\n const spreadsheetConfig = configProp.spreadsheet;\n return {\n ...configProp,\n editing: { ...configProp.editing, onCellChange: recordedOnCellChange },\n spreadsheet:\n spreadsheetConfig && spreadsheetConfig.fill?.onFillCells\n ? { ...spreadsheetConfig, fill: { ...spreadsheetConfig.fill, onFillCells: recordedOnFillCells } }\n : spreadsheetConfig,\n };\n }, [configProp, isUndoEnabled, recordedOnCellChange, recordedOnFillCells]);\n\n // When `editing.rows.onRemoveRow` is set, append a synthetic trailing actions\n // column carrying a per-row delete control. It is a real `actions` column, so\n // it flows through the existing sizing / sticky-right / flex-exclusion / order\n // paths unchanged (see useColumnOrder: actions columns are pinned to the end).\n const config = useMemo<IDataTableConfig<T, C>>(() => {\n if (!editingRows?.onRemoveRow) return configWithUndo;\n\n const removeColumn: IDataTableColumnConfig<T> = {\n id: DATA_TABLE_REMOVE_COLUMN_ID,\n header: '',\n type: 'actions',\n hideable: false,\n resizable: false,\n actions: [\n {\n key: 'remove',\n label: t('dataTable.removeRow'),\n icon: 'delete',\n danger: true,\n hidden: (row) => (editingRows.canRemove ? !editingRows.canRemove(row) : false),\n onClick: (row) => editingRows.onRemoveRow?.(row),\n },\n ],\n };\n\n return { ...configWithUndo, columns: [...configWithUndo.columns, removeColumn] };\n }, [configWithUndo, editingRows, t]);\n\n const { columnVisibility, onColumnVisibilityChange } = useColumnVisibility(config);\n const { columnOrder, onColumnOrderChange, resetColumnOrder } = useColumnOrder(config);\n const { columnSizing, onColumnSizingChange, resetColumnSizing } = useColumnSizing(config);\n\n // Every table restores the persisted column order back to the config default\n // on mount (equivalent to firing \"Restaurar ordem padrão\" from the columns\n // menu), so a stale/incompatible persisted order never sticks. Does not touch\n // column widths or visibility, and does not affect the Cards view.\n useEffect(() => {\n resetColumnOrder();\n }, []);\n\n const detailExpansionColumns =\n config.expansion && isDataTableDetailTableExpansion(config.expansion) && Array.isArray(config.expansion.columns)\n ? config.expansion.columns\n : null;\n const { detailColumnVisibility, toggleDetailColumn } = useDetailColumnVisibility(\n config.entityKey,\n detailExpansionColumns,\n );\n const { detailColumnOrder, onDetailColumnOrderChange, resetDetailColumnOrder } = useDetailColumnOrder(\n config.entityKey,\n detailExpansionColumns,\n );\n\n const detailColumnsState: IDataTableDetailColumnsState | undefined = detailExpansionColumns\n ? {\n visibility: detailColumnVisibility,\n toggleVisibility: toggleDetailColumn,\n order: detailColumnOrder,\n onOrderChange: onDetailColumnOrderChange,\n resetOrder: resetDetailColumnOrder,\n }\n : undefined;\n\n const { isMobile } = useBreakpoint();\n\n const hasCardView = !!config.renderCard;\n const hasGroupedView = !!config.renderGroupedBody;\n const hasKanbanView = !!config.renderKanbanBody;\n // Fixed behaviour: card-capable tables always open on Cards (first), Lista second.\n // The toggle switches within the session and resets to Cards on remount, unless\n // the host controls the mode via the `viewMode` prop (e.g. persisted preference).\n const [internalViewMode, setInternalViewMode] = useState<TDataTableViewMode>('cards');\n const viewMode = controlledViewMode ?? internalViewMode;\n\n const [isBulkEditOpen, setIsBulkEditOpen] = useState(false);\n\n const handleViewModeChange = (mode: TDataTableViewMode) => {\n if (controlledViewMode === undefined) setInternalViewMode(mode);\n onViewModeChange?.(mode);\n };\n\n const {\n table,\n isClientMode,\n columnContentWidths,\n registerRow,\n beginRowsExit,\n visibleRows,\n activeTab,\n tabs,\n handleTabChange,\n handleSearchInput,\n handleHeaderSortClick,\n resolveSortDirection,\n clientPaginationProps,\n showUpdatingBar,\n contentOpacityStyle,\n dataTableOpacityTransitionClass,\n showSkeleton,\n hasRows,\n clientSearchDebounceMs,\n } = useDataTableInstance({\n config,\n rows,\n loading,\n sort,\n onSortChange,\n onSearch,\n initialSearch,\n onSearchTermChange,\n pagination,\n initialClientPagination,\n onClientPaginationChange,\n columnVisibility,\n onColumnVisibilityChange,\n columnOrder,\n onColumnOrderChange,\n columnSizing,\n onColumnSizingChange,\n onFilteredCountChange,\n });\n\n const columnConfigById = useMemo(\n () => new Map(config.columns.map((columnConfig) => [columnConfig.id, columnConfig])),\n [config.columns],\n );\n\n // Under `table-fixed` one column absorbs leftover horizontal space. The last\n // visible non-actions, non-badge, non-first column is the flex column.\n const visibleLeafColumns = table.getVisibleLeafColumns();\n const flexColumnId = useMemo(() => {\n if (config.flexColumnId && visibleLeafColumns.some((leafColumn) => leafColumn.id === config.flexColumnId)) {\n return config.flexColumnId;\n }\n\n const candidates = visibleLeafColumns.filter((leafColumn, index) => {\n if (index === 0) return false;\n const type = columnConfigById.get(leafColumn.id)?.type;\n return type !== 'actions' && !isBadgeColumnType(type);\n });\n return candidates[candidates.length - 1]?.id ?? null;\n }, [visibleLeafColumns, columnConfigById, config.flexColumnId]);\n\n // `table-fixed` sizes columns from the table width, so the table must be at\n // least the sum of ALL column widths (including the absorber's seed) for their\n // widths to be honored; below that the browser shrinks them proportionally.\n // `min-w-full` still lets the table stretch to fill the container, and the\n // auto-width absorber soaks the surplus (never shrinking below its own seed,\n // because its seed is part of this total).\n const totalTableWidth = useMemo(\n () => visibleLeafColumns.reduce((sum, leafColumn) => sum + leafColumn.getSize(), 0),\n [visibleLeafColumns, columnSizing],\n );\n\n // ----- Spreadsheet layer -----\n // Toda tabela com coluna editável ganha a camada de planilha sem configuração, ativa\n // desde a montagem. Numa tabela com `onRowClick` a célula editável é dona do próprio\n // clique (abre o editor) e o resto da linha continua abrindo o registro.\n const spreadsheet = useMemo<IDataTableSpreadsheetConfig<T> | undefined>(() => {\n if (config.spreadsheet === false) return undefined;\n return config.spreadsheet ?? { selection: 'range', fill: {} };\n }, [config.spreadsheet]);\n\n const hasEditableColumns = useMemo(\n () => !!config.editing?.onCellChange && config.columns.some((columnConfig) => !!columnConfig.editable),\n [config.editing, config.columns],\n );\n\n const editModeBehavior = spreadsheet?.mode ?? 'always';\n const gridEnabled = !!spreadsheet && (hasEditableColumns || !!config.spreadsheet);\n\n const gridStore = useGridInstance({\n spreadsheet,\n enabled: gridEnabled,\n startsInEditMode: editModeBehavior === 'always',\n });\n\n const isEditMode = useGridEditMode(gridStore);\n const showEditModeToggle = gridEnabled && editModeBehavior === 'toggle';\n\n // Below the tablet edge a real table is unreadable: even the narrowest column\n // set overflows and the user reads it through a horizontal scrollbar. Cards are\n // the readable shape there, so the narrow viewport takes over the choice.\n // Excluded: `fit` layouts without a bespoke card (their cell geometry IS the\n // feature) and a table whose reason to exist is editing. Merely being able to edit\n // is not enough: a table that opens a record on row click is a reading surface\n // first, unless the user turned its edit toggle on. A `fit` table that ships\n // `renderCard` opted into a narrow shape, so it takes over as well.\n const isEditingSurface = isEditMode && (editModeBehavior === 'toggle' || !config.onRowClick);\n const forceCardsOnMobile = isMobile && (!isFit || hasCardView) && !isEditingSurface;\n\n const isGroupedView = hasGroupedView && viewMode === 'grouped';\n const isKanbanView = hasKanbanView && viewMode === 'kanban';\n // Grouped and kanban both hand the whole body to the host, so everything the\n // table draws around a real row list is off in either of them.\n const isDelegatedView = isGroupedView || isKanbanView;\n const isCardsView = hasCardView && (viewMode === 'cards' || (forceCardsOnMobile && !isDelegatedView));\n const useAutoCards = forceCardsOnMobile && !hasCardView && !isDelegatedView;\n\n useEffect(() => {\n if (!gridStore || !commitStatuses) return;\n gridStore.getState().setCellStatuses(commitStatuses);\n }, [gridStore, commitStatuses]);\n\n const navigableColumnIds = useMemo(\n () =>\n visibleLeafColumns\n .filter((leafColumn) => columnConfigById.get(leafColumn.id)?.type !== 'actions')\n .map((leafColumn) => leafColumn.id),\n [visibleLeafColumns, columnConfigById],\n );\n const gridRowIds = useMemo(() => visibleRows.map((row) => row.id), [visibleRows]);\n\n useGridMatrixSync(gridStore, gridRowIds, navigableColumnIds);\n\n // Read through a ref so the callback stays stable while the rows change on\n // every edit: an unstable handler would re-bind the grid keyboard each render.\n const visibleRowsRef = useRef(visibleRows);\n visibleRowsRef.current = visibleRows;\n\n const canEditCell = useCallback(\n ({ rowId, columnId }: IGridCellCoord) => {\n if (!config.editing?.onCellChange) return false;\n\n const editable = columnConfigById.get(columnId)?.editable;\n if (!editable) return false;\n\n const row = visibleRowsRef.current.find((candidate) => candidate.id === rowId);\n if (!row) return false;\n\n return !(editable.disabled?.(row.original) ?? false);\n },\n [config.editing, columnConfigById],\n );\n\n const acceptsTypedValue = useCallback(\n ({ columnId }: IGridCellCoord) => {\n const editable = columnConfigById.get(columnId)?.editable;\n if (!editable || editable.renderEditor) return false;\n\n return editable.type === 'text' || editable.type === 'number';\n },\n [columnConfigById],\n );\n\n const handleGridKeyDown = useGridKeyboard({\n store: gridStore,\n canEditCell: hasEditableColumns ? canEditCell : undefined,\n acceptsTypedValue,\n onSave: spreadsheet?.onSave,\n });\n\n const handleFillCommit = useGridFillApply<T>({\n visibleRows,\n columnConfigById,\n spreadsheet,\n onCellChange: config.editing?.onCellChange,\n });\n\n // After an undo in the spreadsheet grid the restored cell becomes the active one, so\n // the user sees which cell changed, even when it sits on another row of the page.\n const handleTableKeyDown = useCallback(\n (event: KeyboardEvent<HTMLDivElement>) => {\n const restoredCell = handleUndoShortcut(event);\n if (!restoredCell || !gridStore || !gridStore.getState().isEditMode) return;\n\n const restoredGridRow = visibleRowsRef.current.find((candidate) => candidate.original.id === restoredCell.row.id);\n if (!restoredGridRow) return;\n gridStore.getState().setActiveCell({ rowId: restoredGridRow.id, columnId: restoredCell.columnId });\n },\n [handleUndoShortcut, gridStore],\n );\n\n const handleEditModeToggle = useCallback(() => {\n const store = gridStore;\n if (!store) return;\n store.getState().setEditMode(!store.getState().isEditMode);\n }, [gridStore]);\n\n const cardsScrollRef = useRef<HTMLDivElement | null>(null);\n const cardsSentinelRef = useRef<HTMLDivElement | null>(null);\n const cardsLoadMore = cardsInfiniteScroll?.loadMore;\n const cardsHasMore = cardsInfiniteScroll?.hasMore ?? false;\n\n // Cards infinite scroll: load the next page when the bottom sentinel enters the\n // cards scroll container. `loadMore` is stable and self-guards while a page is\n // in flight; re-running on row count keeps the observer bound after each append.\n useEffect(() => {\n if (!isCardsView || !cardsHasMore || !cardsLoadMore) return;\n\n const root = cardsScrollRef.current;\n const sentinel = cardsSentinelRef.current;\n if (!root || !sentinel) return;\n\n const observer = new IntersectionObserver(\n (entries) => {\n if (entries.some((entry) => entry.isIntersecting)) cardsLoadMore();\n },\n { root, rootMargin: '300px' },\n );\n observer.observe(sentinel);\n\n return () => observer.disconnect();\n }, [isCardsView, cardsHasMore, cardsLoadMore, visibleRows.length]);\n\n const listScrollRef = useRef<HTMLDivElement | null>(null);\n const [detailSlotWidth, setDetailSlotWidth] = useState<number | undefined>(undefined);\n const [parentHasHorizontalOverflow, setParentHasHorizontalOverflow] = useState(false);\n\n // Track the list scrollport: its clientWidth sizes the detail panel to the\n // visible area (detailTable expansion), and its horizontal overflow toggles the\n // frozen actions-column shadow (shown only while columns scroll under it, so\n // there is no always-on divider line otherwise). Observing the inner table too\n // keeps both in sync when columns are toggled or the layout reflows. The\n // branch-state deps re-bind when the scroller remounts (view/skeleton/error/\n // empty transitions swap the rendered subtree).\n useEffect(() => {\n const scroller = listScrollRef.current;\n if (!scroller) return undefined;\n\n const measure = () => {\n setDetailSlotWidth(scroller.clientWidth || undefined);\n setParentHasHorizontalOverflow(scroller.scrollWidth > scroller.clientWidth + 1);\n };\n measure();\n\n const observer = new ResizeObserver(measure);\n observer.observe(scroller);\n const parentTable = scroller.querySelector('table');\n if (parentTable) observer.observe(parentTable);\n\n return () => observer.disconnect();\n }, [isCardsView, isDelegatedView, showSkeleton, error, hasRows]);\n\n const renderBody = () => {\n // Grouped view delegates the whole body to the host (it owns fetching,\n // accordions, loading and empty states for each group).\n if (isGroupedView && config.renderGroupedBody) return config.renderGroupedBody();\n if (isKanbanView && config.renderKanbanBody) return config.renderKanbanBody();\n\n if (showSkeleton)\n return isCardsView ? (\n <DataTableCardsSkeletonState cardClassName={config.cardSkeletonClassName} />\n ) : (\n <DataTableSkeletonState rows={config.skeletonRows} />\n );\n\n if (error) return <DataTableErrorState onRetry={onRetry} errorCause={errorCause} />;\n\n // A `bodyTopRow` (e.g. an inline create editor) must stay visible even with\n // zero data rows, so it takes precedence over the empty state.\n if (!hasRows && !bodyTopRow) {\n if (isFit) {\n // Embedded/editor context: skip the full illustration so surrounding\n // controls (e.g. the add-row button) stay visible in a compact dialog.\n return emptyMessage ? (\n <div className=\"py-6 text-center text-sm text-foreground-faint\">{emptyMessage}</div>\n ) : null;\n }\n return <DataTableEmptyState emptyMessage={emptyMessage} />;\n }\n\n if (isCardsView && config.renderCard) {\n // Cards render from the SAME visible rows the table uses (already searched,\n // filtered, sorted and paginated), so both views share one source. No grid:\n // flex-wrap keeps the layout responsive per the project's no-CSS-grid rule.\n return (\n <div ref={cardsScrollRef} className=\"relative min-h-0 flex-1 overflow-y-auto @container\">\n {showUpdatingBar && (\n <div className=\"absolute inset-x-0 top-0 z-10 h-0.5 animate-pulse bg-brand-hover\" aria-hidden />\n )}\n {/* Cards têm largura fixa, então uma faixa estreita demais para duas colunas\n deixa a sobra toda de um lado. Abaixo disso eles se centram; a partir de\n duas colunas o alinhamento à esquerda volta a ser o que lê melhor. */}\n <div\n className={classNames(\n 'flex flex-wrap justify-center gap-4 @md:justify-start',\n dataTableOpacityTransitionClass,\n config.cardGridClassName,\n )}\n style={contentOpacityStyle}\n >\n {visibleRows\n .filter((row) => row.depth === 0)\n .map((row) => (\n <Fragment key={row.id}>{config.renderCard?.(row.original)}</Fragment>\n ))}\n </div>\n\n {cardsInfiniteScroll?.loadingMore && (\n <div className=\"flex justify-center py-4\">\n <LoadingSpinner size={6} />\n </div>\n )}\n\n {cardsHasMore && <div ref={cardsSentinelRef} className=\"h-px w-full\" aria-hidden />}\n </div>\n );\n }\n\n // Narrow viewport with no bespoke card renderer: stack each row into a card\n // derived from the same columns, so the list stays readable without the host\n // authoring a second renderer.\n if (useAutoCards) {\n return (\n <div className=\"flex min-h-0 flex-1 flex-col gap-2 overflow-y-auto\">\n {visibleRows\n .filter((row) => row.depth === 0)\n .map((row) => (\n <DataTableAutoCard key={row.id} row={row} columnConfigById={columnConfigById} />\n ))}\n </div>\n );\n }\n\n // The table scrolls inside this bounded region (flex-1 + min-h-0). The sticky\n // header pins to the top of the data area; the region also scrolls horizontally\n // so columns keep a minimum readable width instead of being crushed. The first\n // column and the actions column are frozen (sticky left/right) so navigation\n // anchors stay visible while the middle columns scroll past.\n return (\n <div\n ref={listScrollRef}\n onKeyDown={gridStore ? handleGridKeyDown : undefined}\n className={classNames(\n 'relative [&::-webkit-scrollbar-thumb]:rounded-full [&::-webkit-scrollbar-thumb]:bg-border-emphasis hover:[&::-webkit-scrollbar-thumb]:bg-foreground-faint [&::-webkit-scrollbar-track]:bg-transparent [&::-webkit-scrollbar]:h-2.5 [&::-webkit-scrollbar]:w-2.5',\n // The rows scroll inside this bounded region (flex-1 + min-h-0), so the\n // host provides the height (a full page, or a bounded flex parent like a\n // fixed-size dialog) and the add-row/footer below stay pinned outside it.\n 'min-h-0 flex-1 overflow-auto',\n )}\n >\n {showUpdatingBar && (\n <div className=\"absolute inset-x-0 top-0 z-10 h-0.5 animate-pulse bg-brand-hover\" aria-hidden />\n )}\n <table\n role={gridStore ? 'grid' : undefined}\n aria-multiselectable={gridStore && spreadsheet?.selection === 'range' ? true : undefined}\n className={classNames(\n // `table-fixed`: column widths come exclusively from the colgroup so\n // user resizes are honored exactly (under `table-auto` the browser\n // ignores explicit col widths and sizes by content). The slack\n // absorber (auto-width col) still soaks any leftover space.\n 'min-w-full table-fixed border-separate border-spacing-0 rounded-md border-y border-border-subtle',\n dataTableOpacityTransitionClass,\n )}\n style={{ ...contentOpacityStyle, width: totalTableWidth || undefined }}\n >\n <DataTableHead\n table={table}\n columns={config.columns}\n columnConfigById={columnConfigById}\n columnContentWidths={columnContentWidths}\n columnOrder={columnOrder}\n onColumnOrderChange={onColumnOrderChange}\n resetColumnOrder={resetColumnOrder}\n resetColumnSizing={resetColumnSizing}\n onHeaderSortClick={handleHeaderSortClick}\n resolveSortDirection={resolveSortDirection}\n hideColumnToggle={columnTogglePlacement !== 'header'}\n flexColumnId={flexColumnId}\n showActionsShadow={parentHasHorizontalOverflow}\n dense={dense}\n spacious={spacious}\n />\n\n <DataTableBody\n config={config}\n visibleRows={visibleRows}\n columnConfigById={columnConfigById}\n columnContentWidths={columnContentWidths}\n registerRow={registerRow}\n onCollapseStart={beginRowsExit}\n detailColumnsState={detailColumnsState}\n detailSlotWidth={detailSlotWidth}\n showActionsShadow={parentHasHorizontalOverflow}\n dense={dense}\n spacious={spacious}\n fillEnabled={!!spreadsheet?.fill}\n editMode={isEditMode}\n canEditCell={canEditCell}\n bodyTopRow={bodyTopRow}\n bodyTopRowColSpan={table.getVisibleLeafColumns().length}\n />\n </table>\n </div>\n );\n };\n\n // Cards normally page themselves through infinite scroll, so the pager is\n // hidden. When the narrow viewport takes the choice over, the host is still in\n // list mode and its `cardsInfiniteScroll` is not wired: without the pager the\n // user would be stranded on the first page.\n const isMobileCardsTakeover = isCardsView && viewMode !== 'cards' && !cardsInfiniteScroll;\n\n const showPagination =\n (!isCardsView || isMobileCardsTakeover) &&\n !isDelegatedView &&\n !!clientPaginationProps &&\n !showSkeleton &&\n !error &&\n hasRows &&\n clientPaginationProps.numberOfPages > 0 &&\n !(clientPaginationProps.numberOfPages === 1 && clientPaginationProps.pageSize <= DATA_TABLE_MIN_PAGE_SIZE);\n\n // The toolbar only skeletons on the very first load: a refetch (tab switch,\n // filter, search) keeps the real controls mounted, so the search term and the\n // focus survive and the row never changes height.\n const [hasLoadedOnce, setHasLoadedOnce] = useState(!loading);\n\n useEffect(() => {\n if (!loading) setHasLoadedOnce(true);\n }, [loading]);\n\n const showSearch = (!!onSearch || isClientMode) && config.searchable !== false;\n const showToolbar =\n (tabs?.length ?? 0) > 0 ||\n hasCardView ||\n showSearch ||\n !!toolbarSlot ||\n !!toolbarStartSlot ||\n columnTogglePlacement === 'toolbar';\n\n const columnToggleSlot =\n columnTogglePlacement === 'toolbar' ? (\n <DataTableColumnToggle\n table={table}\n columns={config.columns}\n columnOrder={columnOrder}\n onColumnOrderChange={onColumnOrderChange}\n resetColumnOrder={resetColumnOrder}\n resetColumnSizing={resetColumnSizing}\n variant=\"toolbar\"\n />\n ) : undefined;\n\n // O rodapé é o lugar dos controles da própria tabela (colunas e modo de edição),\n // ao lado da paginação. Ambos só existem sobre uma lista real.\n const showTableControls = !isCardsView && !isDelegatedView && !showSkeleton && !error && hasRows;\n const showFooterColumnToggle = columnTogglePlacement === 'footer' && showTableControls;\n const showFooterEditToggle = showEditModeToggle && showTableControls;\n\n // A edição em massa não depende do modo de exibição: em cards ela é a única\n // forma de editar, já que não existe célula para clicar.\n const showBulkEdit =\n hasEditableColumns && !!spreadsheet?.fill?.onFillCells && !isDelegatedView && !showSkeleton && !error && hasRows;\n\n const showFooterControls = showFooterColumnToggle || showFooterEditToggle || showBulkEdit || !!footerActionsSlot;\n const bulkEditRows = useMemo(\n () => visibleRows.filter((row) => row.depth === 0).map((row) => row.original),\n [visibleRows],\n );\n\n const activeFiltersBar =\n config.filters && filterValues && onFilterValuesChange ? (\n <ActiveFiltersBar\n fields={config.filters.fields ?? []}\n values={filterValues}\n onRemove={(key) =>\n onFilterValuesChange({\n ...filterValues,\n [key]: emptyValueForKind((config.filters?.fields ?? []).find((field) => field.key === key)?.kind ?? 'text'),\n })\n }\n onClearAll={() => onFilterValuesChange(buildEmptyFilterValues(config.filters?.fields ?? []))}\n />\n ) : null;\n\n const content = (\n <div\n className=\"flex min-h-0 w-full flex-1 flex-col gap-4\"\n onKeyDown={isUndoEnabled ? handleTableKeyDown : undefined}\n >\n {activeFiltersBar}\n {showToolbar && (\n <DataTableToolbar\n tabs={tabs}\n activeTab={activeTab}\n onTabChange={handleTabChange}\n showViewToggle={hasCardView && !hideViewToggle && !forceCardsOnMobile}\n showGroupedView={hasGroupedView}\n showKanbanView={hasKanbanView}\n viewMode={viewMode}\n onViewModeChange={handleViewModeChange}\n showSearch={showSearch}\n searchLabel={searchLabel}\n initialSearch={initialSearch}\n searchDisabled={searchDisabled}\n searchDebounceTime={isClientMode ? clientSearchDebounceMs : searchDebounceTime}\n searchMinLength={searchMinLength}\n searchAtStart={searchAtStart}\n onSearchInput={handleSearchInput}\n toolbarSlot={toolbarSlot}\n toolbarStartSlot={toolbarStartSlot}\n columnToggleSlot={columnToggleSlot}\n showSkeleton={loading && !hasLoadedOnce}\n />\n )}\n\n <div key={viewMode} className=\"flex min-h-0 flex-1 animate-fade-in flex-col\">\n {renderBody()}\n </div>\n\n {showAddRow && (\n // Sibling of the scrolling rows region, so it stays pinned below the grid\n // (outside its scroll) — the rows scroll, this control does not move.\n <div className=\"flex\">\n <ControlledButton\n variant=\"outlined\"\n className=\"flex items-center gap-1.5\"\n onClick={() => editingRows?.onAddRow?.()}\n >\n <MaterialSymbol icon=\"add\" size={16} />\n {t('dataTable.addRow')}\n </ControlledButton>\n </div>\n )}\n\n {(showFooterControls || showPagination) && (\n <div className=\"flex items-center justify-between gap-4\">\n {showFooterControls && (\n <div className=\"flex flex-wrap items-center gap-2 pb-3\">\n {showFooterColumnToggle && (\n <DataTableColumnToggle\n table={table}\n columns={config.columns}\n columnOrder={columnOrder}\n onColumnOrderChange={onColumnOrderChange}\n resetColumnOrder={resetColumnOrder}\n resetColumnSizing={resetColumnSizing}\n variant=\"toolbar\"\n tooltipPlacement={FOOTER_CONTROL_TOOLTIP_PLACEMENT}\n />\n )}\n {showFooterEditToggle && (\n <DataTableEditModeButton\n active={isEditMode}\n onToggle={handleEditModeToggle}\n tooltipPlacement={FOOTER_CONTROL_TOOLTIP_PLACEMENT}\n />\n )}\n {showBulkEdit && (\n <DataTableBulkEditButton\n onClick={() => setIsBulkEditOpen(true)}\n tooltipPlacement={FOOTER_CONTROL_TOOLTIP_PLACEMENT}\n />\n )}\n {footerActionsSlot}\n </div>\n )}\n\n {showPagination && (\n <div className=\"flex-1\">\n <DataTablePaginationBar\n pageSize={clientPaginationProps.pageSize}\n numberOfPages={clientPaginationProps.numberOfPages}\n currentPage={clientPaginationProps.currentPage}\n setCurrentPage={clientPaginationProps.setCurrentPage}\n onPageSizeChange={clientPaginationProps.onPageSizeChange}\n totalItems={clientPaginationProps.totalItems}\n />\n </div>\n )}\n </div>\n )}\n\n {showBulkEdit && (\n <DataTableBulkEditDialog\n open={isBulkEditOpen}\n onClose={() => setIsBulkEditOpen(false)}\n columns={config.columns}\n rows={bulkEditRows}\n getRowLabel={config.getRowLabel}\n onApply={(changes) => spreadsheet?.fill?.onFillCells?.(changes)}\n />\n )}\n </div>\n );\n\n // Os providers ficam por fora do conteúdo já montado: abrir ou fechar uma célula re-renderiza\n // apenas as células editáveis, não a tabela inteira.\n const editableContent = config.editing?.clickToEdit ? (\n <DataTableCellEditingProvider>{content}</DataTableCellEditingProvider>\n ) : (\n content\n );\n\n if (!gridStore) return editableContent;\n\n return (\n <GridProvider\n store={gridStore}\n gridAreaRef={listScrollRef}\n canEditCell={canEditCell}\n onFillCommit={handleFillCommit}\n >\n {editableContent}\n </GridProvider>\n );\n};\n\nexport default DataTable;\n"],"names":["DataTablePaginationBar"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwDA,MAAM,mCAAmC;AA0GzC,MAAM,YAAY,CAAmE;AAAA,EACnF,QAAQ;AAAA,EACR;AAAA,EACA,UAAU;AAAA,EACV,QAAQ;AAAA,EACR;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,gBAAgB;AAAA,EAChB;AAAA,EACA,iBAAiB;AAAA,EACjB,qBAAqB;AAAA,EACrB,kBAAkB;AAAA,EAClB,gBAAgB;AAAA,EAChB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,UAAU;AAAA,EACV;AAAA,EACA,wBAAwB;AAAA,EACxB;AAAA,EACA,iBAAiB;AAAA,EACjB,SAAS;AAAA,EACT,OAAO,YAAY;AAAA,EACnB,WAAW;AAAA,EACX;AACF,MAA6B;AAC3B,QAAM,EAAE,EAAA,IAAM,eAAe,IAAI;AAEjC,QAAM,QAAQ,WAAW;AACzB,QAAM,QAAQ,CAAC,aAAa,SAAS;AACrC,QAAM,cAAc,WAAW,SAAS;AACxC,QAAM,aAAa,CAAC,CAAC,aAAa,UAAU,CAAC,CAAC,YAAY;AAE1D,QAAM,gBAAgB,WAAW,cAAc,WAAW,YAAY,MAAM,cAAc;AAC1F,QAAM,gBAAgB,CAAC,CAAC,WAAW,SAAS,gBAAgB,WAAW,QAAQ,SAAS;AAC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OAAO;AAAA,YAChB,MAAM;AAAA,YACN,aAAa,OAAO;AAAA,YACpB,SAAS,CAAC,YAAY,aAAa,MAAM,cAAc,OAAO;AAAA,UAAA;AAAA,QAAA;AAAA,MAChE;AAAA,IAAA;AAAA,EAAA;AAON,QAAM,kBAAkB,OAAO,SAAS,cACtC,oBAAC,8BAAA,EAA8B,mBAAQ,IAEvC;AAGF,MAAI,CAAC,UAAW,QAAO;AAEvB,SACE;AAAA,IAAC;AAAA,IAAA;AAAA,MACC,OAAO;AAAA,MACP,aAAa;AAAA,MACb;AAAA,MACA,cAAc;AAAA,MAEb,UAAA;AAAA,IAAA;AAAA,EAAA;AAGP;"}
|
|
1
|
+
{"version":3,"file":"DataTable.js","sources":["../../../../src/components/UI/DataTable/DataTable.tsx"],"sourcesContent":["import { Fragment, JSX, KeyboardEvent, ReactNode, useCallback, useEffect, useMemo, useRef, useState } from 'react';\nimport classNames from 'classnames';\nimport { useTranslation } from 'react-i18next';\n\nimport ControlledButton from '@/components/Form/ControlledButton';\nimport { ActiveFiltersBar, buildEmptyFilterValues, emptyValueForKind } from '@/components/Search/filters';\nimport LoadingSpinner from '@/components/UI/LoadingSpinner';\nimport { MaterialSymbol } from '@/components/UI/MaterialSymbol';\nimport { useBreakpoint } from '@/hooks/useBreakpoint';\n\nimport GridProvider from './grid/GridProvider';\nimport { type IGridCellCoord } from './grid/gridTypes';\nimport { useGridFillApply } from './grid/useGridFillApply';\nimport { useGridEditMode, useGridInstance, useGridMatrixSync } from './grid/useGridInstance';\nimport { useGridKeyboard } from './grid/useGridKeyboard';\nimport DataTableAutoCard from './DataTableAutoCard';\nimport DataTableBody from './DataTableBody';\nimport DataTableBulkEditButton from './DataTableBulkEditButton';\nimport DataTableBulkEditDialog from './DataTableBulkEditDialog';\nimport { isBadgeColumnType } from './dataTableClasses';\nimport DataTableColumnToggle from './DataTableColumnToggle';\nimport { type IDataTableDetailColumnsState } from './DataTableDetailTable';\nimport DataTableEditModeButton from './DataTableEditModeButton';\nimport DataTableHead from './DataTableHead';\nimport DataTablePaginationBar, { DATA_TABLE_MIN_PAGE_SIZE } from './DataTablePagination';\nimport {\n DataTableCardsSkeletonState,\n DataTableEmptyState,\n DataTableErrorState,\n DataTableSkeletonState,\n} from './DataTableStates';\nimport DataTableToolbar from './DataTableToolbar';\nimport {\n DATA_TABLE_REMOVE_COLUMN_ID,\n type IDataTableColumnConfig,\n type IDataTableConfig,\n type IDataTableRow,\n type IDataTableSortState,\n type IDataTableSpreadsheetConfig,\n isDataTableDetailTableExpansion,\n type TDataTableFilterValues,\n type TDataTableViewMode,\n} from './types';\nimport DataTableCellEditingProvider from './useCellEditingState';\nimport { useColumnOrder, useDetailColumnOrder } from './useColumnOrder';\nimport { useColumnSizing } from './useColumnSizing';\nimport { useColumnVisibility, useDetailColumnVisibility } from './useColumnVisibility';\nimport {\n type IDataTableClientPaginationState,\n type IDataTablePagination,\n useDataTableInstance,\n} from './useDataTableInstance';\nimport { useDataTableUndoHistory } from './useDataTableUndoHistory';\n\n// The add-row control sits right above the footer controls, so an upward hint covers it and swallows\n// the next click; `flip` still lifts the hint when the table ends at the bottom of the viewport.\nconst FOOTER_CONTROL_TOOLTIP_PLACEMENT = 'bottom';\n\nconst CARDS_LOAD_MORE_MARGIN = '300px';\n\nconst isScrollingOverflow = (overflowY: string): boolean =>\n overflowY === 'auto' || overflowY === 'scroll' || overflowY === 'overlay';\n\n/**\n * The element that really scrolls the cards. The cards box only clips when its parent bounds its\n * height; on a page that scrolls as a whole the box grows with every page, never scrolls, and an\n * observer rooted on it sees the sentinel all the time. `null` stands for the viewport.\n */\nconst findCardsScrollRoot = (cardsBox: HTMLElement): HTMLElement | null => {\n let current: HTMLElement | null = cardsBox;\n while (current) {\n if (isScrollingOverflow(getComputedStyle(current).overflowY) && current.scrollHeight > current.clientHeight) {\n return current;\n }\n current = current.parentElement;\n }\n return null;\n};\n\ninterface IDataTableProps<T extends IDataTableRow, C extends IDataTableRow = IDataTableRow> {\n config: IDataTableConfig<T, C>;\n rows: Array<T>;\n loading?: boolean;\n error?: boolean;\n /** Cause behind `error`, so the empty state can name a denial instead of a system failure. */\n errorCause?: unknown;\n onRetry?: () => void;\n emptyMessage?: string;\n searchLabel?: string;\n onSearch?: (value: string) => void;\n initialSearch?: string;\n onSearchTermChange?: (value: string) => void;\n searchDisabled?: boolean;\n searchDebounceTime?: number;\n searchMinLength?: number;\n /** Renders the search input in the toolbar's start (left) group instead of the end. */\n searchAtStart?: boolean;\n sort?: IDataTableSortState | null;\n onSortChange?: (sort: IDataTableSortState | null) => void;\n pagination?: IDataTablePagination;\n /** Client mode: seeds page/pageSize (1-based page), e.g. from the URL. */\n initialClientPagination?: IDataTableClientPaginationState;\n /** Client mode: reports page/pageSize changes and keeps the page across in-place row updates. */\n onClientPaginationChange?: (pagination: IDataTableClientPaginationState) => void;\n toolbarSlot?: JSX.Element;\n /**\n * Extra controls rendered in the footer's left group, right after the table's\n * own buttons (columns, edit mode, bulk edit). For an action that belongs to\n * the list itself rather than to the page header, so it sits beside the\n * controls it relates to instead of competing with the page actions. The\n * footer row renders for this slot alone when the table has no other control.\n */\n footerActionsSlot?: ReactNode;\n /**\n * Applied filter values. Passing them (together with `config.filters`) makes\n * the table render the always-visible active-filter chips above the toolbar,\n * so the user never has to hover the button to see what is filtering.\n */\n filterValues?: TDataTableFilterValues;\n onFilterValuesChange?: (values: TDataTableFilterValues) => void;\n /** Rendered at the start (left) of the toolbar, before tabs and view toggle. */\n toolbarStartSlot?: JSX.Element;\n /**\n * Full-width band rendered as the first row of the list body, spanning every\n * column (below the header, above the data rows). Opt-in: omit for a normal\n * table. When set, the empty state is skipped so the band stays visible even\n * with zero data rows (e.g. an inline \"create the first record\" editor).\n */\n bodyTopRow?: ReactNode;\n /** Client mode: reports the filtered (post-search) row count on every change. */\n onFilteredCountChange?: (count: number) => void;\n /**\n * Controlled view mode. When provided, the host owns the state (e.g. to persist\n * it) and must update it via `onViewModeChange`; omit for internal state.\n */\n viewMode?: TDataTableViewMode;\n /**\n * Fired on every view-toggle click, including re-selecting the active mode\n * (hosts use it e.g. to reopen the grouping dialog).\n */\n onViewModeChange?: (mode: TDataTableViewMode) => void;\n /**\n * Where the \"Columns\" toggle renders: `header` (default, inside the table\n * header), `toolbar` (next to the view toggle) or `footer` (bottom-left,\n * on the same row as the pagination).\n */\n columnTogglePlacement?: 'header' | 'toolbar' | 'footer';\n /**\n * Enables infinite scroll in the Cards view: the table observes a bottom\n * sentinel and calls `loadMore` while `hasMore`. Pass `source.cardsInfinite`\n * from `useDataTableSource`. The Lista view keeps its pagination bar.\n */\n cardsInfiniteScroll?: {\n hasMore: boolean;\n loadingMore: boolean;\n loadMore: () => void;\n };\n /**\n * Hides the built-in segmented view toggle. Use when the host renders its own\n * Cards/Lista switcher (e.g. a page-level `ControlledTabs`) and drives `viewMode`\n * itself. Other consumers keep the default toggle.\n */\n hideViewToggle?: boolean;\n /**\n * Layout mode. `page` (default): the table owns a bounded, vertically-scrolling\n * region (`flex-1 min-h-0`) for full-page lists. `fit`: the table sizes to its\n * content and scrolls only horizontally — for embedding inside a dialog / card /\n * editor grid where the host container owns vertical scroll. In `fit` mode the\n * empty state is compact (no full illustration) so surrounding controls such as\n * the add-row button stay visible.\n */\n layout?: 'page' | 'fit';\n /** Reduces cell vertical padding for more visible rows per viewport. */\n dense?: boolean;\n /** Roomier cell padding and type scale, for tables that need to read bigger. */\n spacious?: boolean;\n /**\n * Per-cell persistence state (`statuses` from `useDataTableCommitQueue`), painted\n * on the cells so the user sees what is saving and what failed.\n */\n commitStatuses?: ReadonlyMap<string, string>;\n}\n\nconst DataTable = <T extends IDataTableRow, C extends IDataTableRow = IDataTableRow>({\n config: configProp,\n rows,\n loading = false,\n error = false,\n errorCause,\n onRetry,\n emptyMessage,\n searchLabel,\n onSearch,\n initialSearch = '',\n onSearchTermChange,\n searchDisabled = false,\n searchDebounceTime = 400,\n searchMinLength = 1,\n searchAtStart = false,\n sort,\n onSortChange,\n pagination,\n initialClientPagination,\n onClientPaginationChange,\n toolbarSlot,\n footerActionsSlot,\n filterValues,\n onFilterValuesChange,\n toolbarStartSlot,\n bodyTopRow,\n onFilteredCountChange,\n viewMode: controlledViewMode,\n onViewModeChange,\n columnTogglePlacement = 'header',\n cardsInfiniteScroll,\n hideViewToggle = false,\n layout = 'page',\n dense: denseProp = false,\n spacious = false,\n commitStatuses,\n}: IDataTableProps<T, C>) => {\n const { t } = useTranslation('ui');\n\n const isFit = layout === 'fit';\n const dense = !spacious && (isFit || denseProp);\n const editingRows = configProp.editing?.rows;\n const showAddRow = !!editingRows?.canAdd && !!editingRows.onAddRow;\n\n const hostFillCells = configProp.spreadsheet ? configProp.spreadsheet.fill?.onFillCells : undefined;\n const isUndoEnabled = !!configProp.editing?.onCellChange && configProp.editing.undo !== false;\n const { recordedOnCellChange, recordedOnFillCells, handleUndoShortcut } = useDataTableUndoHistory<T>({\n enabled: isUndoEnabled,\n rows,\n columns: configProp.columns,\n onCellChange: configProp.editing?.onCellChange,\n onFillCells: hostFillCells,\n });\n\n const configWithUndo = useMemo<IDataTableConfig<T, C>>(() => {\n if (!isUndoEnabled || !configProp.editing) return configProp;\n\n const spreadsheetConfig = configProp.spreadsheet;\n return {\n ...configProp,\n editing: { ...configProp.editing, onCellChange: recordedOnCellChange },\n spreadsheet:\n spreadsheetConfig && spreadsheetConfig.fill?.onFillCells\n ? { ...spreadsheetConfig, fill: { ...spreadsheetConfig.fill, onFillCells: recordedOnFillCells } }\n : spreadsheetConfig,\n };\n }, [configProp, isUndoEnabled, recordedOnCellChange, recordedOnFillCells]);\n\n // When `editing.rows.onRemoveRow` is set, append a synthetic trailing actions\n // column carrying a per-row delete control. It is a real `actions` column, so\n // it flows through the existing sizing / sticky-right / flex-exclusion / order\n // paths unchanged (see useColumnOrder: actions columns are pinned to the end).\n const config = useMemo<IDataTableConfig<T, C>>(() => {\n if (!editingRows?.onRemoveRow) return configWithUndo;\n\n const removeColumn: IDataTableColumnConfig<T> = {\n id: DATA_TABLE_REMOVE_COLUMN_ID,\n header: '',\n type: 'actions',\n hideable: false,\n resizable: false,\n actions: [\n {\n key: 'remove',\n label: t('dataTable.removeRow'),\n icon: 'delete',\n danger: true,\n hidden: (row) => (editingRows.canRemove ? !editingRows.canRemove(row) : false),\n onClick: (row) => editingRows.onRemoveRow?.(row),\n },\n ],\n };\n\n return { ...configWithUndo, columns: [...configWithUndo.columns, removeColumn] };\n }, [configWithUndo, editingRows, t]);\n\n const { columnVisibility, onColumnVisibilityChange } = useColumnVisibility(config);\n const { columnOrder, onColumnOrderChange, resetColumnOrder } = useColumnOrder(config);\n const { columnSizing, onColumnSizingChange, resetColumnSizing } = useColumnSizing(config);\n\n // Every table restores the persisted column order back to the config default\n // on mount (equivalent to firing \"Restaurar ordem padrão\" from the columns\n // menu), so a stale/incompatible persisted order never sticks. Does not touch\n // column widths or visibility, and does not affect the Cards view.\n useEffect(() => {\n resetColumnOrder();\n }, []);\n\n const detailExpansionColumns =\n config.expansion && isDataTableDetailTableExpansion(config.expansion) && Array.isArray(config.expansion.columns)\n ? config.expansion.columns\n : null;\n const { detailColumnVisibility, toggleDetailColumn } = useDetailColumnVisibility(\n config.entityKey,\n detailExpansionColumns,\n );\n const { detailColumnOrder, onDetailColumnOrderChange, resetDetailColumnOrder } = useDetailColumnOrder(\n config.entityKey,\n detailExpansionColumns,\n );\n\n const detailColumnsState: IDataTableDetailColumnsState | undefined = detailExpansionColumns\n ? {\n visibility: detailColumnVisibility,\n toggleVisibility: toggleDetailColumn,\n order: detailColumnOrder,\n onOrderChange: onDetailColumnOrderChange,\n resetOrder: resetDetailColumnOrder,\n }\n : undefined;\n\n const { isMobile } = useBreakpoint();\n\n const hasCardView = !!config.renderCard;\n const hasGroupedView = !!config.renderGroupedBody;\n const hasKanbanView = !!config.renderKanbanBody;\n // Fixed behaviour: card-capable tables always open on Cards (first), Lista second.\n // The toggle switches within the session and resets to Cards on remount, unless\n // the host controls the mode via the `viewMode` prop (e.g. persisted preference).\n const [internalViewMode, setInternalViewMode] = useState<TDataTableViewMode>('cards');\n const viewMode = controlledViewMode ?? internalViewMode;\n\n const [isBulkEditOpen, setIsBulkEditOpen] = useState(false);\n\n const handleViewModeChange = (mode: TDataTableViewMode) => {\n if (controlledViewMode === undefined) setInternalViewMode(mode);\n onViewModeChange?.(mode);\n };\n\n const {\n table,\n isClientMode,\n columnContentWidths,\n registerRow,\n beginRowsExit,\n visibleRows,\n activeTab,\n tabs,\n handleTabChange,\n handleSearchInput,\n handleHeaderSortClick,\n resolveSortDirection,\n clientPaginationProps,\n showUpdatingBar,\n contentOpacityStyle,\n dataTableOpacityTransitionClass,\n showSkeleton,\n hasRows,\n clientSearchDebounceMs,\n } = useDataTableInstance({\n config,\n rows,\n loading,\n sort,\n onSortChange,\n onSearch,\n initialSearch,\n onSearchTermChange,\n pagination,\n initialClientPagination,\n onClientPaginationChange,\n columnVisibility,\n onColumnVisibilityChange,\n columnOrder,\n onColumnOrderChange,\n columnSizing,\n onColumnSizingChange,\n onFilteredCountChange,\n });\n\n const columnConfigById = useMemo(\n () => new Map(config.columns.map((columnConfig) => [columnConfig.id, columnConfig])),\n [config.columns],\n );\n\n // Under `table-fixed` one column absorbs leftover horizontal space. The last\n // visible non-actions, non-badge, non-first column is the flex column.\n const visibleLeafColumns = table.getVisibleLeafColumns();\n const flexColumnId = useMemo(() => {\n if (config.flexColumnId && visibleLeafColumns.some((leafColumn) => leafColumn.id === config.flexColumnId)) {\n return config.flexColumnId;\n }\n\n const candidates = visibleLeafColumns.filter((leafColumn, index) => {\n if (index === 0) return false;\n const type = columnConfigById.get(leafColumn.id)?.type;\n return type !== 'actions' && !isBadgeColumnType(type);\n });\n return candidates[candidates.length - 1]?.id ?? null;\n }, [visibleLeafColumns, columnConfigById, config.flexColumnId]);\n\n // `table-fixed` sizes columns from the table width, so the table must be at\n // least the sum of ALL column widths (including the absorber's seed) for their\n // widths to be honored; below that the browser shrinks them proportionally.\n // `min-w-full` still lets the table stretch to fill the container, and the\n // auto-width absorber soaks the surplus (never shrinking below its own seed,\n // because its seed is part of this total).\n const totalTableWidth = useMemo(\n () => visibleLeafColumns.reduce((sum, leafColumn) => sum + leafColumn.getSize(), 0),\n [visibleLeafColumns, columnSizing],\n );\n\n // ----- Spreadsheet layer -----\n // Toda tabela com coluna editável ganha a camada de planilha sem configuração, ativa\n // desde a montagem. Numa tabela com `onRowClick` a célula editável é dona do próprio\n // clique (abre o editor) e o resto da linha continua abrindo o registro.\n const spreadsheet = useMemo<IDataTableSpreadsheetConfig<T> | undefined>(() => {\n if (config.spreadsheet === false) return undefined;\n return config.spreadsheet ?? { selection: 'range', fill: {} };\n }, [config.spreadsheet]);\n\n const hasEditableColumns = useMemo(\n () => !!config.editing?.onCellChange && config.columns.some((columnConfig) => !!columnConfig.editable),\n [config.editing, config.columns],\n );\n\n const editModeBehavior = spreadsheet?.mode ?? 'always';\n const gridEnabled = !!spreadsheet && (hasEditableColumns || !!config.spreadsheet);\n\n const gridStore = useGridInstance({\n spreadsheet,\n enabled: gridEnabled,\n startsInEditMode: editModeBehavior === 'always',\n });\n\n const isEditMode = useGridEditMode(gridStore);\n const showEditModeToggle = gridEnabled && editModeBehavior === 'toggle';\n\n // Below the tablet edge a real table is unreadable: even the narrowest column\n // set overflows and the user reads it through a horizontal scrollbar. Cards are\n // the readable shape there, so the narrow viewport takes over the choice.\n // Excluded: `fit` layouts without a bespoke card (their cell geometry IS the\n // feature) and a table whose reason to exist is editing. Merely being able to edit\n // is not enough: a table that opens a record on row click is a reading surface\n // first, unless the user turned its edit toggle on. A `fit` table that ships\n // `renderCard` opted into a narrow shape, so it takes over as well.\n const isEditingSurface = isEditMode && (editModeBehavior === 'toggle' || !config.onRowClick);\n const forceCardsOnMobile = isMobile && (!isFit || hasCardView) && !isEditingSurface;\n\n const isGroupedView = hasGroupedView && viewMode === 'grouped';\n const isKanbanView = hasKanbanView && viewMode === 'kanban';\n // Grouped and kanban both hand the whole body to the host, so everything the\n // table draws around a real row list is off in either of them.\n const isDelegatedView = isGroupedView || isKanbanView;\n const isCardsView = hasCardView && (viewMode === 'cards' || (forceCardsOnMobile && !isDelegatedView));\n const useAutoCards = forceCardsOnMobile && !hasCardView && !isDelegatedView;\n\n useEffect(() => {\n if (!gridStore || !commitStatuses) return;\n gridStore.getState().setCellStatuses(commitStatuses);\n }, [gridStore, commitStatuses]);\n\n const navigableColumnIds = useMemo(\n () =>\n visibleLeafColumns\n .filter((leafColumn) => columnConfigById.get(leafColumn.id)?.type !== 'actions')\n .map((leafColumn) => leafColumn.id),\n [visibleLeafColumns, columnConfigById],\n );\n const gridRowIds = useMemo(() => visibleRows.map((row) => row.id), [visibleRows]);\n\n useGridMatrixSync(gridStore, gridRowIds, navigableColumnIds);\n\n // Read through a ref so the callback stays stable while the rows change on\n // every edit: an unstable handler would re-bind the grid keyboard each render.\n const visibleRowsRef = useRef(visibleRows);\n visibleRowsRef.current = visibleRows;\n\n const canEditCell = useCallback(\n ({ rowId, columnId }: IGridCellCoord) => {\n if (!config.editing?.onCellChange) return false;\n\n const editable = columnConfigById.get(columnId)?.editable;\n if (!editable) return false;\n\n const row = visibleRowsRef.current.find((candidate) => candidate.id === rowId);\n if (!row) return false;\n\n return !(editable.disabled?.(row.original) ?? false);\n },\n [config.editing, columnConfigById],\n );\n\n const acceptsTypedValue = useCallback(\n ({ columnId }: IGridCellCoord) => {\n const editable = columnConfigById.get(columnId)?.editable;\n if (!editable || editable.renderEditor) return false;\n\n return editable.type === 'text' || editable.type === 'number';\n },\n [columnConfigById],\n );\n\n const handleGridKeyDown = useGridKeyboard({\n store: gridStore,\n canEditCell: hasEditableColumns ? canEditCell : undefined,\n acceptsTypedValue,\n onSave: spreadsheet?.onSave,\n });\n\n const handleFillCommit = useGridFillApply<T>({\n visibleRows,\n columnConfigById,\n spreadsheet,\n onCellChange: config.editing?.onCellChange,\n });\n\n // After an undo in the spreadsheet grid the restored cell becomes the active one, so\n // the user sees which cell changed, even when it sits on another row of the page.\n const handleTableKeyDown = useCallback(\n (event: KeyboardEvent<HTMLDivElement>) => {\n const restoredCell = handleUndoShortcut(event);\n if (!restoredCell || !gridStore || !gridStore.getState().isEditMode) return;\n\n const restoredGridRow = visibleRowsRef.current.find((candidate) => candidate.original.id === restoredCell.row.id);\n if (!restoredGridRow) return;\n gridStore.getState().setActiveCell({ rowId: restoredGridRow.id, columnId: restoredCell.columnId });\n },\n [handleUndoShortcut, gridStore],\n );\n\n const handleEditModeToggle = useCallback(() => {\n const store = gridStore;\n if (!store) return;\n store.getState().setEditMode(!store.getState().isEditMode);\n }, [gridStore]);\n\n const cardsScrollRef = useRef<HTMLDivElement | null>(null);\n const cardsSentinelRef = useRef<HTMLDivElement | null>(null);\n const cardsLoadMore = cardsInfiniteScroll?.loadMore;\n const cardsHasMore = cardsInfiniteScroll?.hasMore ?? false;\n\n // Cards infinite scroll: load the next page when the bottom sentinel nears the edge of whatever\n // scrolls the cards. `loadMore` is stable and self-guards while a page is in flight; re-running\n // on row count rebinds the observer after each append, when the scroll root may have changed.\n useEffect(() => {\n if (!isCardsView || !cardsHasMore || !cardsLoadMore) return;\n\n const cardsBox = cardsScrollRef.current;\n const sentinel = cardsSentinelRef.current;\n if (!cardsBox || !sentinel) return;\n\n const observer = new IntersectionObserver(\n (entries) => {\n if (entries.some((entry) => entry.isIntersecting)) cardsLoadMore();\n },\n { root: findCardsScrollRoot(cardsBox), rootMargin: CARDS_LOAD_MORE_MARGIN },\n );\n observer.observe(sentinel);\n\n return () => observer.disconnect();\n }, [isCardsView, cardsHasMore, cardsLoadMore, visibleRows.length]);\n\n const listScrollRef = useRef<HTMLDivElement | null>(null);\n const [detailSlotWidth, setDetailSlotWidth] = useState<number | undefined>(undefined);\n const [parentHasHorizontalOverflow, setParentHasHorizontalOverflow] = useState(false);\n\n // Track the list scrollport: its clientWidth sizes the detail panel to the\n // visible area (detailTable expansion), and its horizontal overflow toggles the\n // frozen actions-column shadow (shown only while columns scroll under it, so\n // there is no always-on divider line otherwise). Observing the inner table too\n // keeps both in sync when columns are toggled or the layout reflows. The\n // branch-state deps re-bind when the scroller remounts (view/skeleton/error/\n // empty transitions swap the rendered subtree).\n useEffect(() => {\n const scroller = listScrollRef.current;\n if (!scroller) return undefined;\n\n const measure = () => {\n setDetailSlotWidth(scroller.clientWidth || undefined);\n setParentHasHorizontalOverflow(scroller.scrollWidth > scroller.clientWidth + 1);\n };\n measure();\n\n const observer = new ResizeObserver(measure);\n observer.observe(scroller);\n const parentTable = scroller.querySelector('table');\n if (parentTable) observer.observe(parentTable);\n\n return () => observer.disconnect();\n }, [isCardsView, isDelegatedView, showSkeleton, error, hasRows]);\n\n const renderBody = () => {\n // Grouped view delegates the whole body to the host (it owns fetching,\n // accordions, loading and empty states for each group).\n if (isGroupedView && config.renderGroupedBody) return config.renderGroupedBody();\n if (isKanbanView && config.renderKanbanBody) return config.renderKanbanBody();\n\n if (showSkeleton)\n return isCardsView ? (\n <DataTableCardsSkeletonState cardClassName={config.cardSkeletonClassName} />\n ) : (\n <DataTableSkeletonState rows={config.skeletonRows} />\n );\n\n if (error) return <DataTableErrorState onRetry={onRetry} errorCause={errorCause} />;\n\n // A `bodyTopRow` (e.g. an inline create editor) must stay visible even with\n // zero data rows, so it takes precedence over the empty state.\n if (!hasRows && !bodyTopRow) {\n if (isFit) {\n // Embedded/editor context: skip the full illustration so surrounding\n // controls (e.g. the add-row button) stay visible in a compact dialog.\n return emptyMessage ? (\n <div className=\"py-6 text-center text-sm text-foreground-faint\">{emptyMessage}</div>\n ) : null;\n }\n return <DataTableEmptyState emptyMessage={emptyMessage} />;\n }\n\n if (isCardsView && config.renderCard) {\n // Cards render from the SAME visible rows the table uses (already searched,\n // filtered, sorted and paginated), so both views share one source. No grid:\n // flex-wrap keeps the layout responsive per the project's no-CSS-grid rule.\n return (\n <div ref={cardsScrollRef} className=\"relative min-h-0 flex-1 overflow-y-auto @container\">\n {showUpdatingBar && (\n <div className=\"absolute inset-x-0 top-0 z-10 h-0.5 animate-pulse bg-brand-hover\" aria-hidden />\n )}\n {/* Cards têm largura fixa, então uma faixa estreita demais para duas colunas\n deixa a sobra toda de um lado. Abaixo disso eles se centram; a partir de\n duas colunas o alinhamento à esquerda volta a ser o que lê melhor. */}\n <div\n className={classNames(\n 'flex flex-wrap justify-center gap-4 @md:justify-start',\n dataTableOpacityTransitionClass,\n config.cardGridClassName,\n )}\n style={contentOpacityStyle}\n >\n {visibleRows\n .filter((row) => row.depth === 0)\n .map((row) => (\n <Fragment key={row.id}>{config.renderCard?.(row.original)}</Fragment>\n ))}\n </div>\n\n {cardsInfiniteScroll?.loadingMore && (\n <div className=\"flex justify-center py-4\">\n <LoadingSpinner size={6} />\n </div>\n )}\n\n {cardsHasMore && <div ref={cardsSentinelRef} className=\"h-px w-full\" aria-hidden />}\n </div>\n );\n }\n\n // Narrow viewport with no bespoke card renderer: stack each row into a card\n // derived from the same columns, so the list stays readable without the host\n // authoring a second renderer.\n if (useAutoCards) {\n return (\n <div className=\"flex min-h-0 flex-1 flex-col gap-2 overflow-y-auto\">\n {visibleRows\n .filter((row) => row.depth === 0)\n .map((row) => (\n <DataTableAutoCard key={row.id} row={row} columnConfigById={columnConfigById} />\n ))}\n </div>\n );\n }\n\n // The table scrolls inside this bounded region (flex-1 + min-h-0). The sticky\n // header pins to the top of the data area; the region also scrolls horizontally\n // so columns keep a minimum readable width instead of being crushed. The first\n // column and the actions column are frozen (sticky left/right) so navigation\n // anchors stay visible while the middle columns scroll past.\n return (\n <div\n ref={listScrollRef}\n onKeyDown={gridStore ? handleGridKeyDown : undefined}\n className={classNames(\n 'relative [&::-webkit-scrollbar-thumb]:rounded-full [&::-webkit-scrollbar-thumb]:bg-border-emphasis hover:[&::-webkit-scrollbar-thumb]:bg-foreground-faint [&::-webkit-scrollbar-track]:bg-transparent [&::-webkit-scrollbar]:h-2.5 [&::-webkit-scrollbar]:w-2.5',\n // The rows scroll inside this bounded region (flex-1 + min-h-0), so the\n // host provides the height (a full page, or a bounded flex parent like a\n // fixed-size dialog) and the add-row/footer below stay pinned outside it.\n 'min-h-0 flex-1 overflow-auto',\n )}\n >\n {showUpdatingBar && (\n <div className=\"absolute inset-x-0 top-0 z-10 h-0.5 animate-pulse bg-brand-hover\" aria-hidden />\n )}\n <table\n role={gridStore ? 'grid' : undefined}\n aria-multiselectable={gridStore && spreadsheet?.selection === 'range' ? true : undefined}\n className={classNames(\n // `table-fixed`: column widths come exclusively from the colgroup so\n // user resizes are honored exactly (under `table-auto` the browser\n // ignores explicit col widths and sizes by content). The slack\n // absorber (auto-width col) still soaks any leftover space.\n 'min-w-full table-fixed border-separate border-spacing-0 rounded-md border-y border-border-subtle',\n dataTableOpacityTransitionClass,\n )}\n style={{ ...contentOpacityStyle, width: totalTableWidth || undefined }}\n >\n <DataTableHead\n table={table}\n columns={config.columns}\n columnConfigById={columnConfigById}\n columnContentWidths={columnContentWidths}\n columnOrder={columnOrder}\n onColumnOrderChange={onColumnOrderChange}\n resetColumnOrder={resetColumnOrder}\n resetColumnSizing={resetColumnSizing}\n onHeaderSortClick={handleHeaderSortClick}\n resolveSortDirection={resolveSortDirection}\n hideColumnToggle={columnTogglePlacement !== 'header'}\n flexColumnId={flexColumnId}\n showActionsShadow={parentHasHorizontalOverflow}\n dense={dense}\n spacious={spacious}\n />\n\n <DataTableBody\n config={config}\n visibleRows={visibleRows}\n columnConfigById={columnConfigById}\n columnContentWidths={columnContentWidths}\n registerRow={registerRow}\n onCollapseStart={beginRowsExit}\n detailColumnsState={detailColumnsState}\n detailSlotWidth={detailSlotWidth}\n showActionsShadow={parentHasHorizontalOverflow}\n dense={dense}\n spacious={spacious}\n fillEnabled={!!spreadsheet?.fill}\n editMode={isEditMode}\n canEditCell={canEditCell}\n bodyTopRow={bodyTopRow}\n bodyTopRowColSpan={table.getVisibleLeafColumns().length}\n />\n </table>\n </div>\n );\n };\n\n // Cards normally page themselves through infinite scroll, so the pager is\n // hidden. When the narrow viewport takes the choice over, the host is still in\n // list mode and its `cardsInfiniteScroll` is not wired: without the pager the\n // user would be stranded on the first page.\n const isMobileCardsTakeover = isCardsView && viewMode !== 'cards' && !cardsInfiniteScroll;\n\n const showPagination =\n (!isCardsView || isMobileCardsTakeover) &&\n !isDelegatedView &&\n !!clientPaginationProps &&\n !showSkeleton &&\n !error &&\n hasRows &&\n clientPaginationProps.numberOfPages > 0 &&\n !(clientPaginationProps.numberOfPages === 1 && clientPaginationProps.pageSize <= DATA_TABLE_MIN_PAGE_SIZE);\n\n // The toolbar only skeletons on the very first load: a refetch (tab switch,\n // filter, search) keeps the real controls mounted, so the search term and the\n // focus survive and the row never changes height.\n const [hasLoadedOnce, setHasLoadedOnce] = useState(!loading);\n\n useEffect(() => {\n if (!loading) setHasLoadedOnce(true);\n }, [loading]);\n\n const showSearch = (!!onSearch || isClientMode) && config.searchable !== false;\n const showToolbar =\n (tabs?.length ?? 0) > 0 ||\n hasCardView ||\n showSearch ||\n !!toolbarSlot ||\n !!toolbarStartSlot ||\n columnTogglePlacement === 'toolbar';\n\n const columnToggleSlot =\n columnTogglePlacement === 'toolbar' ? (\n <DataTableColumnToggle\n table={table}\n columns={config.columns}\n columnOrder={columnOrder}\n onColumnOrderChange={onColumnOrderChange}\n resetColumnOrder={resetColumnOrder}\n resetColumnSizing={resetColumnSizing}\n variant=\"toolbar\"\n />\n ) : undefined;\n\n // O rodapé é o lugar dos controles da própria tabela (colunas e modo de edição),\n // ao lado da paginação. Ambos só existem sobre uma lista real.\n const showTableControls = !isCardsView && !isDelegatedView && !showSkeleton && !error && hasRows;\n const showFooterColumnToggle = columnTogglePlacement === 'footer' && showTableControls;\n const showFooterEditToggle = showEditModeToggle && showTableControls;\n\n // A edição em massa não depende do modo de exibição: em cards ela é a única\n // forma de editar, já que não existe célula para clicar.\n const showBulkEdit =\n hasEditableColumns && !!spreadsheet?.fill?.onFillCells && !isDelegatedView && !showSkeleton && !error && hasRows;\n\n const showFooterControls = showFooterColumnToggle || showFooterEditToggle || showBulkEdit || !!footerActionsSlot;\n const bulkEditRows = useMemo(\n () => visibleRows.filter((row) => row.depth === 0).map((row) => row.original),\n [visibleRows],\n );\n\n const activeFiltersBar =\n config.filters && filterValues && onFilterValuesChange ? (\n <ActiveFiltersBar\n fields={config.filters.fields ?? []}\n values={filterValues}\n onRemove={(key) =>\n onFilterValuesChange({\n ...filterValues,\n [key]: emptyValueForKind((config.filters?.fields ?? []).find((field) => field.key === key)?.kind ?? 'text'),\n })\n }\n onClearAll={() => onFilterValuesChange(buildEmptyFilterValues(config.filters?.fields ?? []))}\n />\n ) : null;\n\n const content = (\n <div\n className=\"flex min-h-0 w-full flex-1 flex-col gap-4\"\n onKeyDown={isUndoEnabled ? handleTableKeyDown : undefined}\n >\n {activeFiltersBar}\n {showToolbar && (\n <DataTableToolbar\n tabs={tabs}\n activeTab={activeTab}\n onTabChange={handleTabChange}\n showViewToggle={hasCardView && !hideViewToggle && !forceCardsOnMobile}\n showGroupedView={hasGroupedView}\n showKanbanView={hasKanbanView}\n viewMode={viewMode}\n onViewModeChange={handleViewModeChange}\n showSearch={showSearch}\n searchLabel={searchLabel}\n initialSearch={initialSearch}\n searchDisabled={searchDisabled}\n searchDebounceTime={isClientMode ? clientSearchDebounceMs : searchDebounceTime}\n searchMinLength={searchMinLength}\n searchAtStart={searchAtStart}\n onSearchInput={handleSearchInput}\n toolbarSlot={toolbarSlot}\n toolbarStartSlot={toolbarStartSlot}\n columnToggleSlot={columnToggleSlot}\n showSkeleton={loading && !hasLoadedOnce}\n />\n )}\n\n <div key={viewMode} className=\"flex min-h-0 flex-1 animate-fade-in flex-col\">\n {renderBody()}\n </div>\n\n {showAddRow && (\n // Sibling of the scrolling rows region, so it stays pinned below the grid\n // (outside its scroll) — the rows scroll, this control does not move.\n <div className=\"flex\">\n <ControlledButton\n variant=\"outlined\"\n className=\"flex items-center gap-1.5\"\n onClick={() => editingRows?.onAddRow?.()}\n >\n <MaterialSymbol icon=\"add\" size={16} />\n {t('dataTable.addRow')}\n </ControlledButton>\n </div>\n )}\n\n {(showFooterControls || showPagination) && (\n <div className=\"flex items-center justify-between gap-4\">\n {showFooterControls && (\n <div className=\"flex flex-wrap items-center gap-2 pb-3\">\n {showFooterColumnToggle && (\n <DataTableColumnToggle\n table={table}\n columns={config.columns}\n columnOrder={columnOrder}\n onColumnOrderChange={onColumnOrderChange}\n resetColumnOrder={resetColumnOrder}\n resetColumnSizing={resetColumnSizing}\n variant=\"toolbar\"\n tooltipPlacement={FOOTER_CONTROL_TOOLTIP_PLACEMENT}\n />\n )}\n {showFooterEditToggle && (\n <DataTableEditModeButton\n active={isEditMode}\n onToggle={handleEditModeToggle}\n tooltipPlacement={FOOTER_CONTROL_TOOLTIP_PLACEMENT}\n />\n )}\n {showBulkEdit && (\n <DataTableBulkEditButton\n onClick={() => setIsBulkEditOpen(true)}\n tooltipPlacement={FOOTER_CONTROL_TOOLTIP_PLACEMENT}\n />\n )}\n {footerActionsSlot}\n </div>\n )}\n\n {showPagination && (\n <div className=\"flex-1\">\n <DataTablePaginationBar\n pageSize={clientPaginationProps.pageSize}\n numberOfPages={clientPaginationProps.numberOfPages}\n currentPage={clientPaginationProps.currentPage}\n setCurrentPage={clientPaginationProps.setCurrentPage}\n onPageSizeChange={clientPaginationProps.onPageSizeChange}\n totalItems={clientPaginationProps.totalItems}\n />\n </div>\n )}\n </div>\n )}\n\n {showBulkEdit && (\n <DataTableBulkEditDialog\n open={isBulkEditOpen}\n onClose={() => setIsBulkEditOpen(false)}\n columns={config.columns}\n rows={bulkEditRows}\n getRowLabel={config.getRowLabel}\n onApply={(changes) => spreadsheet?.fill?.onFillCells?.(changes)}\n />\n )}\n </div>\n );\n\n // Os providers ficam por fora do conteúdo já montado: abrir ou fechar uma célula re-renderiza\n // apenas as células editáveis, não a tabela inteira.\n const editableContent = config.editing?.clickToEdit ? (\n <DataTableCellEditingProvider>{content}</DataTableCellEditingProvider>\n ) : (\n content\n );\n\n if (!gridStore) return editableContent;\n\n return (\n <GridProvider\n store={gridStore}\n gridAreaRef={listScrollRef}\n canEditCell={canEditCell}\n onFillCommit={handleFillCommit}\n >\n {editableContent}\n </GridProvider>\n );\n};\n\nexport default DataTable;\n"],"names":["DataTablePaginationBar"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwDA,MAAM,mCAAmC;AAEzC,MAAM,yBAAyB;AAE/B,MAAM,sBAAsB,CAAC,cAC3B,cAAc,UAAU,cAAc,YAAY,cAAc;AAOlE,MAAM,sBAAsB,CAAC,aAA8C;AACzE,MAAI,UAA8B;AAClC,SAAO,SAAS;AACd,QAAI,oBAAoB,iBAAiB,OAAO,EAAE,SAAS,KAAK,QAAQ,eAAe,QAAQ,cAAc;AAC3G,aAAO;AAAA,IACT;AACA,cAAU,QAAQ;AAAA,EACpB;AACA,SAAO;AACT;AA0GA,MAAM,YAAY,CAAmE;AAAA,EACnF,QAAQ;AAAA,EACR;AAAA,EACA,UAAU;AAAA,EACV,QAAQ;AAAA,EACR;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,gBAAgB;AAAA,EAChB;AAAA,EACA,iBAAiB;AAAA,EACjB,qBAAqB;AAAA,EACrB,kBAAkB;AAAA,EAClB,gBAAgB;AAAA,EAChB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,UAAU;AAAA,EACV;AAAA,EACA,wBAAwB;AAAA,EACxB;AAAA,EACA,iBAAiB;AAAA,EACjB,SAAS;AAAA,EACT,OAAO,YAAY;AAAA,EACnB,WAAW;AAAA,EACX;AACF,MAA6B;AAC3B,QAAM,EAAE,EAAA,IAAM,eAAe,IAAI;AAEjC,QAAM,QAAQ,WAAW;AACzB,QAAM,QAAQ,CAAC,aAAa,SAAS;AACrC,QAAM,cAAc,WAAW,SAAS;AACxC,QAAM,aAAa,CAAC,CAAC,aAAa,UAAU,CAAC,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