@tc96/cli 0.0.0-stage → 0.27.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +213 -2
- package/cli.js +1395 -0
- package/package.json +35 -4
- package/registry/agent-builder.json +503 -0
- package/registry/aggregate.json +4 -0
- package/registry/app-shell-1.json +81 -0
- package/registry/app-shell-2.json +89 -0
- package/registry/app-shell-3.json +109 -0
- package/registry/app-shell-4.json +104 -0
- package/registry/app-shell-5.json +106 -0
- package/registry/bulk-import-1.json +151 -0
- package/registry/card-1.json +104 -0
- package/registry/card-2.json +97 -0
- package/registry/card-3.json +104 -0
- package/registry/card-4.json +98 -0
- package/registry/card-5.json +85 -0
- package/registry/card-6.json +98 -0
- package/registry/card-7.json +104 -0
- package/registry/card-8.json +106 -0
- package/registry/card-9.json +92 -0
- package/registry/charts.json +30 -0
- package/registry/chat-assistant.json +110 -0
- package/registry/chats-panel.json +97 -0
- package/registry/checklist.json +307 -0
- package/registry/collection-layouts.json +836 -0
- package/registry/collection-views.json +836 -0
- package/registry/collection.json +831 -0
- package/registry/dashboard-1.json +160 -0
- package/registry/dashboard-2.json +153 -0
- package/registry/dashboard-3.json +154 -0
- package/registry/dashboard-4.json +168 -0
- package/registry/detail-sheet.json +54 -0
- package/registry/editable.json +36 -0
- package/registry/empty-state-1.json +40 -0
- package/registry/empty-state-2.json +39 -0
- package/registry/empty-state-3.json +61 -0
- package/registry/empty-state-4.json +39 -0
- package/registry/empty-state-5.json +47 -0
- package/registry/empty-state-6.json +40 -0
- package/registry/flow-canvas.json +198 -0
- package/registry/flow-inspector.json +151 -0
- package/registry/flow-step-library.json +112 -0
- package/registry/forgot-password-1.json +73 -0
- package/registry/forgot-password-2.json +73 -0
- package/registry/icon-row.json +52 -0
- package/registry/impact-map.json +75 -0
- package/registry/list-1.json +129 -0
- package/registry/list-2.json +117 -0
- package/registry/list-3.json +129 -0
- package/registry/list-4.json +105 -0
- package/registry/list-5.json +98 -0
- package/registry/list-6.json +92 -0
- package/registry/list.json +52 -0
- package/registry/login-1.json +89 -0
- package/registry/login-10.json +88 -0
- package/registry/login-2.json +81 -0
- package/registry/login-3.json +90 -0
- package/registry/login-4.json +81 -0
- package/registry/login-5.json +82 -0
- package/registry/login-6.json +88 -0
- package/registry/login-7.json +83 -0
- package/registry/login-8.json +81 -0
- package/registry/login-9.json +88 -0
- package/registry/lookup-create-1.json +157 -0
- package/registry/magic-link-6.json +79 -0
- package/registry/navbar-1.json +66 -0
- package/registry/navbar-2.json +48 -0
- package/registry/navbar-3.json +50 -0
- package/registry/navbar-4.json +39 -0
- package/registry/navbar-5.json +50 -0
- package/registry/next-steps-1.json +147 -0
- package/registry/onboarding-1.json +114 -0
- package/registry/onboarding-2.json +78 -0
- package/registry/onboarding-3.json +71 -0
- package/registry/otp-1.json +73 -0
- package/registry/properties.json +523 -0
- package/registry/record-dialog.json +88 -0
- package/registry/record-group.json +190 -0
- package/registry/record-preview.json +70 -0
- package/registry/record-status-list.json +70 -0
- package/registry/reset-password-1.json +92 -0
- package/registry/reset-password-2.json +98 -0
- package/registry/reset-password-6.json +91 -0
- package/registry/rich-text-editor.json +93 -0
- package/registry/run-monitor.json +198 -0
- package/registry/settings-1.json +119 -0
- package/registry/settings-10.json +218 -0
- package/registry/settings-11.json +129 -0
- package/registry/settings-12.json +130 -0
- package/registry/settings-13.json +130 -0
- package/registry/settings-14.json +173 -0
- package/registry/settings-15.json +149 -0
- package/registry/settings-16.json +129 -0
- package/registry/settings-17.json +117 -0
- package/registry/settings-18.json +117 -0
- package/registry/settings-19.json +125 -0
- package/registry/settings-2.json +123 -0
- package/registry/settings-20.json +112 -0
- package/registry/settings-21.json +116 -0
- package/registry/settings-22.json +118 -0
- package/registry/settings-23.json +118 -0
- package/registry/settings-3.json +123 -0
- package/registry/settings-4.json +116 -0
- package/registry/settings-5.json +119 -0
- package/registry/settings-6.json +125 -0
- package/registry/settings-7.json +128 -0
- package/registry/settings-8.json +116 -0
- package/registry/settings-9.json +118 -0
- package/registry/settings-shell.json +60 -0
- package/registry/settings.json +82 -0
- package/registry/signup-1.json +100 -0
- package/registry/signup-2.json +93 -0
- package/registry/signup-3.json +83 -0
- package/registry/signup-6.json +99 -0
- package/registry/state-surface.json +58 -0
- package/registry/stats-1.json +116 -0
- package/registry/stats-2.json +115 -0
- package/registry/stats-3.json +97 -0
- package/registry/stats-4.json +92 -0
- package/registry/stats-5.json +103 -0
- package/registry/stats-6.json +105 -0
- package/registry/stats-7.json +103 -0
- package/registry/stats.json +64 -0
- package/registry/timeline-1.json +97 -0
- package/registry/timeline-2.json +102 -0
- package/registry/timeline-3.json +68 -0
- package/registry/timeline-4.json +86 -0
- package/registry/ui/accordion.json +15 -0
- package/registry/ui/alert-dialog.json +14 -0
- package/registry/ui/alert.json +50 -0
- package/registry/ui/autocomplete.json +18 -0
- package/registry/ui/avatar.json +14 -0
- package/registry/ui/badge.json +51 -0
- package/registry/ui/breadcrumb.json +15 -0
- package/registry/ui/button.json +25 -0
- package/registry/ui/calendar.json +15 -0
- package/registry/ui/card.json +14 -0
- package/registry/ui/chat.json +115 -0
- package/registry/ui/checkbox-group.json +14 -0
- package/registry/ui/checkbox.json +14 -0
- package/registry/ui/collapsible.json +14 -0
- package/registry/ui/combobox.json +18 -0
- package/registry/ui/command.json +17 -0
- package/registry/ui/composer-clipboard.json +14 -0
- package/registry/ui/composer-document.json +14 -0
- package/registry/ui/composer-editor.json +16 -0
- package/registry/ui/composer-query.json +12 -0
- package/registry/ui/composer.json +17 -0
- package/registry/ui/context-menu.json +23 -0
- package/registry/ui/dialog.json +18 -0
- package/registry/ui/drawer.json +18 -0
- package/registry/ui/empty.json +14 -0
- package/registry/ui/field.json +22 -0
- package/registry/ui/fieldset.json +14 -0
- package/registry/ui/form.json +14 -0
- package/registry/ui/frame.json +12 -0
- package/registry/ui/gauge.json +31 -0
- package/registry/ui/group.json +17 -0
- package/registry/ui/icon-frame.json +31 -0
- package/registry/ui/input-group.json +17 -0
- package/registry/ui/input.json +14 -0
- package/registry/ui/kbd.json +12 -0
- package/registry/ui/label.json +14 -0
- package/registry/ui/menu.json +39 -0
- package/registry/ui/meter.json +14 -0
- package/registry/ui/number-field.json +17 -0
- package/registry/ui/otp-field.json +31 -0
- package/registry/ui/pagination.json +17 -0
- package/registry/ui/popover.json +14 -0
- package/registry/ui/preview-card.json +14 -0
- package/registry/ui/progress.json +14 -0
- package/registry/ui/radio-group.json +14 -0
- package/registry/ui/render-anchor.json +12 -0
- package/registry/ui/scroll-area.json +14 -0
- package/registry/ui/segmented-control.json +14 -0
- package/registry/ui/select.json +16 -0
- package/registry/ui/separator.json +14 -0
- package/registry/ui/sheet.json +18 -0
- package/registry/ui/sidebar.json +25 -0
- package/registry/ui/skeleton.json +24 -0
- package/registry/ui/slider.json +14 -0
- package/registry/ui/spinner.json +14 -0
- package/registry/ui/switch.json +14 -0
- package/registry/ui/table.json +14 -0
- package/registry/ui/tabs.json +16 -0
- package/registry/ui/text.json +31 -0
- package/registry/ui/textarea.json +14 -0
- package/registry/ui/toast.json +89 -0
- package/registry/ui/toggle-group.json +18 -0
- package/registry/ui/toggle.json +15 -0
- package/registry/ui/toolbar.json +14 -0
- package/registry/ui/tooltip.json +14 -0
- package/registry/ui/use-composer-editor.json +17 -0
- package/registry/ui/use-copy-to-clipboard.json +12 -0
- package/registry/ui/use-media-query.json +12 -0
- package/registry/view.json +831 -0
- package/registry/widgets.json +319 -0
- package/registry/wizard.json +89 -0
- package/registry/workflow-editor.json +460 -0
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "rich-text-editor",
|
|
3
|
+
"type": "registry:block",
|
|
4
|
+
"files": [
|
|
5
|
+
{
|
|
6
|
+
"path": "helpers/rich-text.ts",
|
|
7
|
+
"type": "registry:file",
|
|
8
|
+
"content": "export interface RichTextLeaf {\n text: string\n [mark: string]: unknown\n}\n\nexport interface RichTextElement {\n children: readonly RichTextNode[]\n type: string\n}\n\nexport type RichTextNode = RichTextElement | RichTextLeaf\n\n/**\n * Collapses every run of line breaks into one space, so a title is always a\n * single line, whatever line ending the text came with.\n */\nexport function flattenTitle(value: string): string {\n return value.replace(/(?:\\r\\n|[\\r\\n])+/g, ' ')\n}\n\n/**\n * Formats the \"current over limit\" counter shown next to a bounded field.\n */\nexport function formatTitleCounter(length: number, max: number): string {\n return `${length}/${max}`\n}\n\nfunction isLeaf(node: RichTextNode): node is RichTextLeaf {\n return typeof (node as RichTextLeaf).text === 'string'\n}\n\nfunction leafText(nodes: readonly RichTextNode[]): string {\n return nodes.map((node) => (isLeaf(node) ? node.text : '')).join('')\n}\n\nfunction collectLines(nodes: readonly RichTextNode[], lines: string[]): void {\n for (const node of nodes) {\n if (isLeaf(node)) continue\n if (node.children.every((child) => isLeaf(child))) {\n lines.push(leafText(node.children))\n continue\n }\n const inlineText = leafText(node.children)\n if (inlineText) lines.push(inlineText)\n collectLines(node.children, lines)\n }\n}\n\n/**\n * Turns a rich text document into plain text: one line per text block or list\n * item, in document order, with every mark dropped.\n *\n * @param value - the Slate-like node tree a rich text editor emits\n * @returns the lines joined by `\\n`\n */\nexport function richTextToPlainText(value: readonly RichTextNode[]): string {\n const lines: string[] = []\n collectLines(value, lines)\n return lines.join('\\n')\n}\n\n/**\n * Element types found anywhere in the tree, in document order and with\n * repeats, so a consumer can check a document against its own vocabulary.\n */\nexport function richTextElementTypes(value: readonly RichTextNode[]): string[] {\n return value.flatMap((node) =>\n isLeaf(node) ? [] : [node.type, ...richTextElementTypes(node.children)],\n )\n}\n\n/**\n * Whether any node in the tree carries an `id`, which an editor configured\n * without node ids must never produce.\n */\nexport function richTextHasNodeId(value: readonly RichTextNode[]): boolean {\n return value.some(\n (node) =>\n 'id' in node || (!isLeaf(node) && richTextHasNodeId(node.children)),\n )\n}\n\n/**\n * Copy of the tree with every element `id` removed, so a document that an\n * editor tagged internally can leave it without carrying node ids.\n *\n * @param value - the Slate-like node tree, possibly carrying `id` on elements\n * @returns a new tree of the same shape, with no `id` on any element\n */\nexport function stripRichTextNodeIds(\n value: readonly RichTextNode[],\n): RichTextNode[] {\n return value.map((node) => {\n if (isLeaf(node)) return node\n const { id: _id, ...rest } = node as RichTextElement & { id?: unknown }\n return { ...rest, children: stripRichTextNodeIds(node.children) }\n })\n}\n",
|
|
9
|
+
"target": "~/packages/ui/src/helpers/rich-text.ts"
|
|
10
|
+
},
|
|
11
|
+
{
|
|
12
|
+
"path": "patterns/rich-text-editor/block-draggable.tsx",
|
|
13
|
+
"type": "registry:file",
|
|
14
|
+
"content": "'use client'\n\nimport { DotsSixVerticalIcon } from '@phosphor-icons/react'\nimport { DndPlugin, useDraggable, useDropLine } from '@platejs/dnd'\nimport {\n BlockSelectionAfterEditable,\n BlockSelectionPlugin,\n useBlockSelected,\n} from '@platejs/selection/react'\nimport { Button } from '@tc96/ui/button'\nimport { cn } from '@tc96/utils'\nimport type { SlateEditor, TElement } from 'platejs'\nimport type { RenderNodeWrapper } from 'platejs/react'\nimport { useEditorRef, usePluginOption } from 'platejs/react'\nimport type { KeyboardEvent, ReactElement, ReactNode } from 'react'\nimport { useEffect } from 'react'\nimport { DndProvider } from 'react-dnd'\nimport { HTML5Backend } from 'react-dnd-html5-backend'\n\nexport interface BlockDragLabels {\n handle: string\n selection: string\n}\n\nexport const defaultBlockDragLabels = {\n handle: 'Mover bloco',\n selection: 'Blocos selecionados',\n} as const satisfies BlockDragLabels\n\nfunction DraggableBlock({\n children,\n element,\n label,\n}: Readonly<{\n children: ReactNode\n element: TElement\n label: string\n}>): ReactElement {\n const editor = useEditorRef()\n const { handleRef, isDragging, nodeRef } = useDraggable({ element })\n const { dropLine } = useDropLine()\n const selected = useBlockSelected(\n typeof element.id === 'string' ? element.id : undefined,\n )\n\n const moveByKeyboard = (event: KeyboardEvent<HTMLButtonElement>) => {\n if (!event.altKey) return\n if (event.key !== 'ArrowUp' && event.key !== 'ArrowDown') return\n event.preventDefault()\n const path = editor.api.findPath(element)\n if (!path) return\n const index = path[0] ?? 0\n const target = event.key === 'ArrowUp' ? index - 1 : index + 1\n if (target < 0 || target >= editor.children.length) return\n editor.tf.moveNodes({ at: path, to: [target] })\n }\n\n return (\n <div\n className={cn(\n 'slate-selectable group/block relative',\n isDragging && 'opacity-50',\n )}\n data-block-selected={selected || undefined}\n data-slot=\"rich-text-block\"\n ref={nodeRef}\n >\n <div\n className=\"absolute inset-s-0 top-0 z-10 -translate-x-full pe-1 pointer-coarse:opacity-100 opacity-0 transition-opacity focus-within:opacity-100 group-hover/block:opacity-100\"\n contentEditable={false}\n >\n <Button\n aria-label={label}\n onKeyDown={moveByKeyboard}\n onMouseDown={(event) => event.stopPropagation()}\n ref={handleRef}\n size=\"icon-xs\"\n type=\"button\"\n variant=\"ghost\"\n >\n <DotsSixVerticalIcon aria-hidden=\"true\" />\n </Button>\n </div>\n {children}\n {selected ? (\n <div\n aria-hidden=\"true\"\n className=\"pointer-events-none absolute -inset-x-1 inset-y-0 rounded-md bg-primary/12\"\n contentEditable={false}\n />\n ) : null}\n {dropLine ? (\n <div\n aria-hidden=\"true\"\n className={cn(\n 'absolute inset-x-0 h-0.5 bg-primary',\n dropLine === 'top' ? '-top-px' : '-bottom-px',\n )}\n contentEditable={false}\n />\n ) : null}\n </div>\n )\n}\n\nconst blockDraggable =\n (label: string): RenderNodeWrapper =>\n ({ element, path }) => {\n if (path.length !== 1) return undefined\n return ({ children }) => (\n <DraggableBlock element={element} label={label}>\n {children}\n </DraggableBlock>\n )\n }\n\nfunction removeSelectedBlocks(editor: SlateEditor): void {\n const api = editor.getApi(BlockSelectionPlugin).blockSelection\n const nodes = api.getNodes()\n const first = nodes[0]?.[1]\n if (!first) return\n editor.tf.withoutNormalizing(() => {\n for (const [, path] of [...nodes].reverse())\n editor.tf.removeNodes({ at: path })\n })\n api.deselect()\n if (editor.children.length === 0)\n editor.tf.insertNodes(editor.api.create.block(), { at: [0] })\n const index = Math.min(first[0] ?? 0, editor.children.length - 1)\n editor.tf.select(editor.api.end([index]) ?? [])\n editor.tf.focus()\n}\n\nfunction LabeledBlockSelection({\n label,\n}: Readonly<{ label: string }>): ReactElement {\n const editor = useEditorRef()\n const shadowInput = usePluginOption(BlockSelectionPlugin, 'shadowInputRef')\n\n useEffect(() => {\n const input = shadowInput?.current\n if (!input) return\n input.setAttribute('aria-label', label)\n const onKeyDown = (event: globalThis.KeyboardEvent) => {\n const api = editor.getApi(BlockSelectionPlugin).blockSelection\n if (api.getNodes().length === 0) return\n const handled = () => {\n event.preventDefault()\n event.stopPropagation()\n }\n switch (event.key) {\n case 'Backspace':\n case 'Delete':\n handled()\n removeSelectedBlocks(editor)\n break\n case 'Escape':\n handled()\n api.deselect()\n editor.tf.focus()\n break\n case 'ArrowUp':\n case 'ArrowDown':\n handled()\n api.moveSelection(event.key === 'ArrowUp' ? 'up' : 'down')\n break\n case 'Enter':\n handled()\n api.deselect()\n editor.tf.focus()\n break\n }\n }\n input.addEventListener('keydown', onKeyDown)\n return () => input.removeEventListener('keydown', onKeyDown)\n }, [editor, label, shadowInput])\n\n return <BlockSelectionAfterEditable />\n}\n\nexport function selectCurrentBlock(editor: SlateEditor): boolean {\n const index = editor.selection?.anchor.path[0]\n const id = index === undefined ? undefined : editor.children[index]?.id\n if (typeof id !== 'string') return false\n editor.getApi(BlockSelectionPlugin).blockSelection.set(id)\n return true\n}\n\nexport const blockDragPlugins = (label: string, selectionLabel: string) => [\n BlockSelectionPlugin.configure({\n options: {\n enableContextMenu: false,\n isSelectable: (_element, path) => path.length === 1,\n },\n render: {\n afterEditable: () => <LabeledBlockSelection label={selectionLabel} />,\n },\n }),\n DndPlugin.configure({\n options: { enableScroller: false },\n render: {\n aboveNodes: blockDraggable(label),\n aboveSlate: ({ children }) => (\n <DndProvider backend={HTML5Backend}>{children}</DndProvider>\n ),\n },\n }),\n]\n",
|
|
15
|
+
"target": "~/packages/ui/src/patterns/rich-text-editor/block-draggable.tsx"
|
|
16
|
+
},
|
|
17
|
+
{
|
|
18
|
+
"path": "patterns/rich-text-editor/editor-title.tsx",
|
|
19
|
+
"type": "registry:file",
|
|
20
|
+
"content": "'use client'\n\nimport { flattenTitle, formatTitleCounter } from '@tc96/ui/helpers/rich-text'\nimport { cn } from '@tc96/utils'\nimport type { ChangeEvent, KeyboardEvent, ReactElement, Ref } from 'react'\nimport { useEffect, useId, useImperativeHandle, useRef, useState } from 'react'\n\nexport interface EditorTitleHandle {\n focusEnd: () => void\n}\n\nexport interface EditorTitleProps {\n autoFocus?: boolean\n className?: string\n counterFrom?: number\n defaultValue?: string\n emptyLabel: string\n label?: string\n max?: number\n onArrowDownAtEnd?: () => void\n onChange?: (value: string) => void\n onEnter?: () => void\n ref?: Ref<EditorTitleHandle>\n}\n\nexport function EditorTitle({\n autoFocus = false,\n className,\n counterFrom,\n defaultValue = '',\n emptyLabel,\n label = 'Título',\n max,\n onArrowDownAtEnd,\n onChange,\n onEnter,\n ref,\n}: Readonly<EditorTitleProps>): ReactElement {\n const counterId = useId()\n const fieldRef = useRef<HTMLTextAreaElement>(null)\n const [value, setValue] = useState(() => flattenTitle(defaultValue))\n const showCounter =\n max !== undefined &&\n counterFrom !== undefined &&\n value.length >= counterFrom\n\n useImperativeHandle(ref, () => ({\n focusEnd: () => {\n const field = fieldRef.current\n if (!field) return\n field.focus()\n field.setSelectionRange(field.value.length, field.value.length)\n },\n }))\n\n useEffect(() => {\n const field = fieldRef.current\n if (!autoFocus || !field) return\n field.focus()\n field.setSelectionRange(field.value.length, field.value.length)\n }, [autoFocus])\n\n const handleChange = (event: ChangeEvent<HTMLTextAreaElement>) => {\n const raw = event.target.value\n const next = flattenTitle(raw)\n if (next !== raw) {\n const caret = flattenTitle(\n raw.slice(0, event.target.selectionStart),\n ).length\n event.target.value = next\n event.target.setSelectionRange(caret, caret)\n }\n setValue(next)\n onChange?.(next)\n }\n\n const handleKeyDown = (event: KeyboardEvent<HTMLTextAreaElement>) => {\n if (event.nativeEvent.isComposing) return\n if (event.key === 'Enter') {\n event.preventDefault()\n onEnter?.()\n return\n }\n if (event.key === 'ArrowDown') {\n const {\n selectionStart,\n selectionEnd,\n value: current,\n } = event.currentTarget\n if (\n selectionStart === current.length &&\n selectionEnd === current.length\n ) {\n event.preventDefault()\n onArrowDownAtEnd?.()\n }\n }\n }\n\n return (\n <div\n className={cn('flex flex-col gap-1', className)}\n data-slot=\"editor-title\"\n >\n <h1\n className=\"font-semibold text-2xl text-foreground tracking-tight\"\n data-slot=\"editor-title-heading\"\n >\n {value === '' ? <span className=\"sr-only\">{emptyLabel}</span> : null}\n <textarea\n aria-describedby={showCounter ? counterId : undefined}\n aria-label={label}\n className=\"field-sizing-content block w-full resize-none bg-transparent outline-none placeholder:text-muted-foreground\"\n data-slot=\"editor-title-field\"\n maxLength={max}\n onChange={handleChange}\n onKeyDown={handleKeyDown}\n placeholder={emptyLabel}\n ref={fieldRef}\n rows={1}\n value={value}\n />\n </h1>\n {showCounter && max !== undefined ? (\n <span\n className=\"self-end text-muted-foreground text-xs tabular-nums\"\n data-slot=\"editor-title-counter\"\n id={counterId}\n >\n {formatTitleCounter(value.length, max)}\n </span>\n ) : null}\n </div>\n )\n}\n",
|
|
21
|
+
"target": "~/packages/ui/src/patterns/rich-text-editor/editor-title.tsx"
|
|
22
|
+
},
|
|
23
|
+
{
|
|
24
|
+
"path": "patterns/rich-text-editor/extra-blocks.tsx",
|
|
25
|
+
"type": "registry:file",
|
|
26
|
+
"content": "'use client'\n\nimport { HorizontalRulePlugin } from '@platejs/basic-nodes/react'\nimport { DatePlugin } from '@platejs/date/react'\nimport { unwrapList } from '@platejs/list-classic'\nimport { insertTable } from '@platejs/table'\nimport {\n TableCellHeaderPlugin,\n TableCellPlugin,\n TablePlugin,\n TableRowPlugin,\n} from '@platejs/table/react'\nimport { Checkbox } from '@tc96/ui/checkbox'\nimport { cn } from '@tc96/utils'\nimport type { SlateEditor } from 'platejs'\nimport {\n createPlatePlugin,\n PlateElement,\n type PlateElementProps,\n} from 'platejs/react'\nimport type { ReactElement } from 'react'\n\nexport const RICH_TEXT_EXTRA_BLOCKS = [\n 'todo',\n 'callout',\n 'code',\n 'hr',\n 'date',\n 'table',\n 'image',\n] as const\n\nexport type RichTextExtraBlock = (typeof RICH_TEXT_EXTRA_BLOCKS)[number]\n\nexport const RICH_TEXT_EXTRA_ELEMENTS = [\n 'action_item',\n 'callout',\n 'code_block',\n 'hr',\n 'date',\n 'table',\n 'tr',\n 'td',\n 'th',\n 'img',\n] as const\n\nconst extraType = {\n callout: 'callout',\n code: 'code_block',\n date: 'date',\n hr: 'hr',\n image: 'img',\n table: 'table',\n todo: 'action_item',\n} as const satisfies Record<\n RichTextExtraBlock,\n (typeof RICH_TEXT_EXTRA_ELEMENTS)[number]\n>\n\nexport function applyExtraBlock(\n editor: SlateEditor,\n block: RichTextExtraBlock,\n): void {\n const type = extraType[block]\n if (block === 'date') {\n editor.tf.insertNodes(\n {\n children: [{ text: '' }],\n date: new Date().toISOString().slice(0, 10),\n type,\n },\n { select: true },\n )\n editor.tf.insertText(' ')\n return\n }\n if (block === 'image') return\n if (block === 'table') {\n insertTable(editor, { colCount: 3, rowCount: 3 })\n return\n }\n if (editor.api.some({ match: { type: 'li' } })) unwrapList(editor)\n if (block === 'hr') {\n editor.tf.insertNodes({ children: [{ text: '' }], type }, { select: false })\n editor.tf.insertNodes(editor.api.create.block(), { select: true })\n return\n }\n const active = editor.api.some({ match: { type } })\n editor.tf.setNodes(\n active\n ? { type: 'p' }\n : { type, ...(block === 'todo' ? { checked: false } : {}) },\n )\n}\n\nfunction TodoElement(props: PlateElementProps): ReactElement {\n const { editor, element, path } = props\n const checked = element.checked === true\n return (\n <PlateElement {...props} as=\"div\" className=\"my-1 flex items-start gap-2\">\n <span className=\"mt-1 flex shrink-0 select-none\" contentEditable={false}>\n <Checkbox\n aria-label=\"Concluída\"\n checked={checked}\n onCheckedChange={(next) =>\n editor.tf.setNodes({ checked: next === true }, { at: path })\n }\n />\n </span>\n <span\n className={cn(\n 'min-w-0 flex-1',\n checked && 'text-muted-foreground line-through',\n )}\n >\n {props.children}\n </span>\n </PlateElement>\n )\n}\n\nfunction CalloutElement(props: PlateElementProps): ReactElement {\n return (\n <PlateElement\n {...props}\n as=\"div\"\n className=\"my-2 flex gap-3 rounded-lg border border-border/80 bg-muted/48 p-3\"\n >\n <span\n aria-hidden=\"true\"\n className=\"select-none leading-6\"\n contentEditable={false}\n >\n {String(props.element.icon ?? '💡')}\n </span>\n <div className=\"min-w-0 flex-1\">{props.children}</div>\n </PlateElement>\n )\n}\n\nfunction CodeBlockElement(props: PlateElementProps): ReactElement {\n return (\n <PlateElement\n {...props}\n as=\"pre\"\n className=\"my-2 overflow-x-auto whitespace-pre-wrap rounded-lg bg-muted p-3 font-mono text-sm\"\n />\n )\n}\n\nfunction HrElement(props: PlateElementProps): ReactElement {\n return (\n <PlateElement {...props} as=\"div\" className=\"my-3\">\n <div contentEditable={false}>\n <hr className=\"border-border\" />\n </div>\n {props.children}\n </PlateElement>\n )\n}\n\nfunction DateElement(props: PlateElementProps): ReactElement {\n const iso = String(props.element.date ?? '')\n const parsed = new Date(`${iso}T00:00:00`)\n const label = Number.isNaN(parsed.getTime())\n ? iso\n : new Intl.DateTimeFormat('pt-BR', { dateStyle: 'medium' }).format(parsed)\n return (\n <PlateElement\n {...props}\n as=\"span\"\n attributes={{ ...props.attributes, contentEditable: false }}\n className=\"rounded-sm bg-muted px-1 text-sm\"\n >\n <time dateTime={iso}>{label}</time>\n {props.children}\n </PlateElement>\n )\n}\n\nfunction ImageElement(props: PlateElementProps): ReactElement {\n const url = String(props.element.url ?? '')\n const alt = String(props.element.alt ?? '')\n return (\n <PlateElement {...props} as=\"div\" className=\"my-3\">\n <figure contentEditable={false}>\n <img\n alt={alt}\n className=\"max-h-96 max-w-full rounded-lg border border-border/80\"\n src={url}\n />\n </figure>\n {props.children}\n </PlateElement>\n )\n}\n\nfunction TableElement(props: PlateElementProps): ReactElement {\n return (\n <PlateElement {...props} as=\"div\" className=\"my-2 overflow-x-auto\">\n <table className=\"w-full table-fixed border-collapse\">\n <tbody>{props.children}</tbody>\n </table>\n </PlateElement>\n )\n}\n\nfunction TableRowElement(props: PlateElementProps): ReactElement {\n return <PlateElement {...props} as=\"tr\" />\n}\n\nfunction TableCellElement(props: PlateElementProps): ReactElement {\n return (\n <PlateElement\n {...props}\n as=\"td\"\n className=\"min-w-12 border border-border/80 p-2 align-top\"\n />\n )\n}\n\nfunction TableHeaderCellElement(props: PlateElementProps): ReactElement {\n return (\n <PlateElement\n {...props}\n as=\"th\"\n className=\"min-w-12 border border-border/80 bg-muted/48 p-2 text-start align-top font-medium\"\n />\n )\n}\n\nconst resetOnEmpty = {\n break: { empty: 'reset' },\n delete: { start: 'reset' },\n} as const\n\nexport const extraBlockPlugins = [\n createPlatePlugin({\n key: 'img',\n node: { component: ImageElement, isElement: true, isVoid: true },\n }),\n createPlatePlugin({\n key: 'action_item',\n node: { component: TodoElement, isElement: true },\n rules: resetOnEmpty,\n }),\n createPlatePlugin({\n key: 'callout',\n node: { component: CalloutElement, isElement: true },\n rules: resetOnEmpty,\n }),\n createPlatePlugin({\n key: 'code_block',\n node: { component: CodeBlockElement, isElement: true },\n rules: {\n break: { default: 'lineBreak', empty: 'reset' },\n delete: { start: 'reset' },\n },\n }),\n HorizontalRulePlugin.withComponent(HrElement),\n DatePlugin.withComponent(DateElement),\n TablePlugin.withComponent(TableElement),\n TableRowPlugin.withComponent(TableRowElement),\n TableCellPlugin.withComponent(TableCellElement),\n TableCellHeaderPlugin.withComponent(TableHeaderCellElement),\n]\n\nexport interface RichTextImage {\n alt?: string\n url: string\n}\n\nexport function insertImage(editor: SlateEditor, image: RichTextImage): void {\n editor.tf.insertNodes(\n {\n alt: image.alt ?? '',\n children: [{ text: '' }],\n type: extraType.image,\n url: image.url,\n },\n { select: true },\n )\n}\n",
|
|
27
|
+
"target": "~/packages/ui/src/patterns/rich-text-editor/extra-blocks.tsx"
|
|
28
|
+
},
|
|
29
|
+
{
|
|
30
|
+
"path": "patterns/rich-text-editor/floating-toolbar.tsx",
|
|
31
|
+
"type": "registry:file",
|
|
32
|
+
"content": "'use client'\n\nimport {\n CodeSimpleIcon,\n HighlighterIcon,\n ListBulletsIcon,\n ListNumbersIcon,\n type Icon as PhosphorIcon,\n QuotesIcon,\n TextBIcon,\n TextHThreeIcon,\n TextHTwoIcon,\n TextItalicIcon,\n TextStrikethroughIcon,\n TextUnderlineIcon,\n} from '@phosphor-icons/react'\nimport { unwrapList } from '@platejs/list-classic'\nimport { Popover, PopoverPopup } from '@tc96/ui/popover'\nimport {\n Select,\n SelectItem,\n SelectPopup,\n SelectTrigger,\n SelectValue,\n} from '@tc96/ui/select'\nimport { Toggle } from '@tc96/ui/toggle'\nimport {\n ToolbarButton,\n ToolbarGroup,\n ToolbarPrimitive,\n ToolbarSeparator,\n} from '@tc96/ui/toolbar'\nimport { RangeApi, type SlateEditor, type TRange } from 'platejs'\nimport {\n useEditorRef,\n useEditorSelector,\n useMarkToolbarButton,\n useMarkToolbarButtonState,\n} from 'platejs/react'\nimport type { ReactElement, RefObject } from 'react'\nimport { useCallback, useEffect, useMemo, useState } from 'react'\nimport { LinkButton, type LinkButtonLabels } from './link-button'\nimport {\n applyBlock,\n RICH_TEXT_BLOCKS,\n RICH_TEXT_MARKS,\n type RichTextBlock,\n type RichTextMark,\n} from './plugins'\n\nconst markIcon = {\n bold: TextBIcon,\n code: CodeSimpleIcon,\n highlight: HighlighterIcon,\n italic: TextItalicIcon,\n strikethrough: TextStrikethroughIcon,\n underline: TextUnderlineIcon,\n} as const satisfies Record<RichTextMark, PhosphorIcon>\n\nexport const blockIcon = {\n blockquote: QuotesIcon,\n h2: TextHTwoIcon,\n h3: TextHThreeIcon,\n ol: ListNumbersIcon,\n ul: ListBulletsIcon,\n} as const satisfies Record<RichTextBlock, PhosphorIcon>\n\nfunction ToolbarToggle({\n icon: Icon,\n label,\n onToggle,\n pressed,\n}: Readonly<{\n icon: PhosphorIcon\n label: string\n onToggle: () => void\n pressed: boolean\n}>): ReactElement {\n return (\n <ToolbarButton\n onMouseDown={(event) => event.preventDefault()}\n render={\n <Toggle\n aria-label={label}\n onPressedChange={onToggle}\n pressed={pressed}\n size=\"sm\"\n />\n }\n >\n <Icon aria-hidden=\"true\" />\n </ToolbarButton>\n )\n}\n\nfunction MarkButton({\n label,\n mark,\n}: Readonly<{ label: string; mark: RichTextMark }>): ReactElement {\n const { props } = useMarkToolbarButton(\n useMarkToolbarButtonState({ nodeType: mark }),\n )\n\n return (\n <ToolbarToggle\n icon={markIcon[mark]}\n label={label}\n onToggle={props.onClick}\n pressed={props.pressed}\n />\n )\n}\n\nfunction BlockButton({\n block,\n label,\n}: Readonly<{ block: RichTextBlock; label: string }>): ReactElement {\n const editor = useEditorRef()\n const pressed = useEditorSelector(\n (current) => current.api.some({ match: { type: block } }),\n [block],\n )\n\n return (\n <ToolbarToggle\n icon={blockIcon[block]}\n label={label}\n onToggle={() => {\n applyBlock(editor, block)\n editor.tf.focus()\n }}\n pressed={pressed}\n />\n )\n}\n\ntype BlockType = RichTextBlock | 'p'\n\nconst blockTypes: readonly BlockType[] = ['p', ...RICH_TEXT_BLOCKS]\n\nfunction BlockTypeSelect({\n blockLabels,\n label,\n paragraphLabel,\n}: Readonly<{\n blockLabels: Readonly<Record<RichTextBlock, string>>\n label: string\n paragraphLabel: string\n}>): ReactElement {\n const editor = useEditorRef()\n const current = useEditorSelector(\n (state) =>\n RICH_TEXT_BLOCKS.find((block) =>\n state.api.some({ match: { type: block } }),\n ) ?? 'p',\n [],\n )\n const labels = { ...blockLabels, p: paragraphLabel }\n\n return (\n <Select<BlockType>\n items={blockTypes.map((value) => ({ label: labels[value], value }))}\n onValueChange={(next) => {\n if (next === null || next === current) return\n if (next === 'p') {\n if (current === 'ul' || current === 'ol') unwrapList(editor)\n else editor.tf.toggleBlock(current)\n } else applyBlock(editor, next)\n editor.tf.focus()\n }}\n value={current}\n >\n <ToolbarButton\n aria-label={label}\n onMouseDown={(event) => event.preventDefault()}\n render={<SelectTrigger className=\"min-w-32\" size=\"sm\" />}\n >\n <SelectValue />\n </ToolbarButton>\n <SelectPopup alignItemWithTrigger={false} sideOffset={8}>\n {blockTypes.map((value) => (\n <SelectItem key={value} value={value}>\n {labels[value]}\n </SelectItem>\n ))}\n </SelectPopup>\n </Select>\n )\n}\n\nconst sameRange = (a: TRange | null, b: TRange | null) =>\n a === b || (a !== null && b !== null && RangeApi.equals(a, b))\n\nfunction selectionAnchor(editor: SlateEditor, selection: TRange) {\n return {\n contextElement: editor.api.toDOMNode(editor) as Element | undefined,\n getBoundingClientRect: () =>\n editor.api.toDOMRange(selection)?.getBoundingClientRect() ??\n new DOMRect(),\n }\n}\n\nexport interface FloatingToolbarProps {\n blockLabels: Readonly<Record<RichTextBlock, string>>\n blockTypeLabel: string\n label: string\n linkLabels: LinkButtonLabels\n markLabels: Readonly<Record<RichTextMark, string>>\n paragraphLabel: string\n toolbarRef: RefObject<HTMLDivElement | null>\n}\n\nexport function FloatingToolbar({\n blockLabels,\n blockTypeLabel,\n label,\n linkLabels,\n markLabels,\n paragraphLabel,\n toolbarRef,\n}: Readonly<FloatingToolbarProps>): ReactElement {\n const editor = useEditorRef()\n const selection = useEditorSelector(\n (current) => current.selection as TRange | null,\n [],\n { equalityFn: sameRange },\n )\n const [pointerDown, setPointerDown] = useState(false)\n const [focusWithin, setFocusWithin] = useState(false)\n const [dismissed, setDismissed] = useState<TRange | null>(null)\n\n useEffect(() => {\n const editable = editor.api.toDOMNode(editor)\n const inside = (node: EventTarget | null) =>\n node instanceof Node &&\n ((editable?.contains(node) ?? false) ||\n (toolbarRef.current?.contains(node) ?? false) ||\n (node instanceof Element &&\n node.closest('[data-slot=select-popup],[data-slot=popover-popup]') !==\n null))\n const down = (event: PointerEvent) => {\n if (editable?.contains(event.target as Node)) setPointerDown(true)\n }\n const up = () => setPointerDown(false)\n const focusIn = (event: FocusEvent) => setFocusWithin(inside(event.target))\n const focusOut = (event: FocusEvent) =>\n setFocusWithin(inside(event.relatedTarget))\n document.addEventListener('pointerdown', down)\n document.addEventListener('pointerup', up)\n document.addEventListener('pointercancel', up)\n document.addEventListener('focusin', focusIn)\n document.addEventListener('focusout', focusOut)\n return () => {\n document.removeEventListener('pointerdown', down)\n document.removeEventListener('pointerup', up)\n document.removeEventListener('pointercancel', up)\n document.removeEventListener('focusin', focusIn)\n document.removeEventListener('focusout', focusOut)\n }\n }, [editor, toolbarRef])\n\n const expanded =\n selection !== null &&\n RangeApi.isExpanded(selection) &&\n editor.api.string(selection) !== ''\n const open =\n expanded && !pointerDown && focusWithin && !sameRange(dismissed, selection)\n\n const anchor = useMemo(\n () => (selection ? selectionAnchor(editor, selection) : null),\n [editor, selection],\n )\n\n const dismiss = useCallback(() => {\n setDismissed(selection)\n if (toolbarRef.current?.contains(document.activeElement)) editor.tf.focus()\n }, [editor, selection, toolbarRef])\n\n return (\n <Popover\n onOpenChange={(next, details) => {\n if (next) return\n if (\n details.reason === 'escape-key' ||\n details.reason === 'outside-press'\n )\n dismiss()\n }}\n open={open}\n >\n <PopoverPopup\n anchor={anchor}\n finalFocus={false}\n initialFocus={false}\n role=\"presentation\"\n side=\"top\"\n sideOffset={8}\n tooltipStyle\n >\n <ToolbarPrimitive.Root\n aria-label={label}\n className=\"relative flex items-center gap-1 text-foreground\"\n data-slot=\"floating-toolbar\"\n onKeyDown={(event) => {\n if (event.key !== 'Escape') return\n event.preventDefault()\n dismiss()\n }}\n ref={toolbarRef}\n >\n <BlockTypeSelect\n blockLabels={blockLabels}\n label={blockTypeLabel}\n paragraphLabel={paragraphLabel}\n />\n <ToolbarSeparator orientation=\"vertical\" />\n <ToolbarGroup className=\"gap-0.5\">\n {RICH_TEXT_MARKS.map((mark) => (\n <MarkButton key={mark} label={markLabels[mark]} mark={mark} />\n ))}\n </ToolbarGroup>\n <ToolbarGroup className=\"gap-0.5\">\n <LinkButton labels={linkLabels} />\n </ToolbarGroup>\n <ToolbarSeparator orientation=\"vertical\" />\n <ToolbarGroup className=\"gap-0.5\">\n {RICH_TEXT_BLOCKS.map((block) => (\n <BlockButton\n block={block}\n key={block}\n label={blockLabels[block]}\n />\n ))}\n </ToolbarGroup>\n </ToolbarPrimitive.Root>\n </PopoverPopup>\n </Popover>\n )\n}\n",
|
|
33
|
+
"target": "~/packages/ui/src/patterns/rich-text-editor/floating-toolbar.tsx"
|
|
34
|
+
},
|
|
35
|
+
{
|
|
36
|
+
"path": "patterns/rich-text-editor/index.ts",
|
|
37
|
+
"type": "registry:file",
|
|
38
|
+
"content": "export type { EditorTitleHandle, EditorTitleProps } from './editor-title'\nexport { EditorTitle } from './editor-title'\nexport type { RichTextExtraBlock, RichTextImage } from './extra-blocks'\nexport { RICH_TEXT_EXTRA_BLOCKS } from './extra-blocks'\nexport type { LinkButtonLabels } from './link-button'\nexport type { RichTextBlock, RichTextMark } from './plugins'\nexport {\n applyBlock,\n RICH_TEXT_BLOCKS,\n RICH_TEXT_ELEMENTS,\n RICH_TEXT_MARKS,\n} from './plugins'\nexport type {\n RichTextEditorHandle,\n RichTextEditorProps,\n RichTextMention,\n RichTextValue,\n} from './rich-text-editor'\nexport { defaultMaxListDepth, RichTextEditor } from './rich-text-editor'\nexport type { SlashMenuBlock, SlashMenuOption } from './slash-menu'\nexport {\n filterSlashMenuOptions,\n slashMenuOptions,\n} from './slash-menu'\n",
|
|
39
|
+
"target": "~/packages/ui/src/patterns/rich-text-editor/index.ts"
|
|
40
|
+
},
|
|
41
|
+
{
|
|
42
|
+
"path": "patterns/rich-text-editor/link-button.tsx",
|
|
43
|
+
"type": "registry:file",
|
|
44
|
+
"content": "'use client'\n\nimport { LinkIcon } from '@phosphor-icons/react'\nimport { unwrapLink, upsertLink, validateUrl } from '@platejs/link'\nimport { Button } from '@tc96/ui/button'\nimport { Input } from '@tc96/ui/input'\nimport { Popover, PopoverPopup } from '@tc96/ui/popover'\nimport { Toggle } from '@tc96/ui/toggle'\nimport { ToolbarButton } from '@tc96/ui/toolbar'\nimport type { TRange } from 'platejs'\nimport { useEditorRef, useEditorSelector } from 'platejs/react'\nimport type { FormEvent, ReactElement } from 'react'\nimport { useState } from 'react'\n\nexport interface LinkButtonLabels {\n apply: string\n button: string\n remove: string\n url: string\n}\n\nexport function LinkButton({\n labels,\n}: Readonly<{ labels: LinkButtonLabels }>): ReactElement {\n const editor = useEditorRef()\n const active = useEditorSelector(\n (state) => state.api.some({ match: { type: 'a' } }),\n [],\n )\n const currentUrl = useEditorSelector((state) => {\n const entry = state.api.above({ match: { type: 'a' } })\n return entry ? String(entry[0].url ?? '') : ''\n }, [])\n const [open, setOpen] = useState(false)\n const [draft, setDraft] = useState('')\n const [at, setAt] = useState<TRange | null>(null)\n\n const finish = () => {\n setOpen(false)\n editor.tf.focus()\n }\n\n const submit = (event: FormEvent) => {\n event.preventDefault()\n const url = draft.trim()\n if (!url || !validateUrl(editor, url) || !at) return\n editor.tf.select(at)\n upsertLink(editor, { url })\n finish()\n }\n\n return (\n <Popover\n onOpenChange={(next) => {\n if (next) {\n setAt(editor.selection)\n setDraft(currentUrl)\n }\n setOpen(next)\n }}\n open={open}\n >\n <ToolbarButton\n onMouseDown={(event) => event.preventDefault()}\n render={\n <Toggle\n aria-label={labels.button}\n onPressedChange={(next) => {\n setAt(editor.selection)\n setDraft(currentUrl)\n setOpen(next)\n }}\n pressed={active}\n size=\"sm\"\n />\n }\n >\n <LinkIcon aria-hidden=\"true\" />\n </ToolbarButton>\n <PopoverPopup\n finalFocus={false}\n side=\"top\"\n sideOffset={8}\n tooltipStyle={false}\n >\n <form className=\"flex items-center gap-2\" onSubmit={submit}>\n <Input\n aria-label={labels.url}\n autoFocus\n inputMode=\"url\"\n onChange={(event) => setDraft(event.target.value)}\n placeholder=\"https://\"\n type=\"url\"\n value={draft}\n />\n <Button size=\"sm\" type=\"submit\">\n {labels.apply}\n </Button>\n {active ? (\n <Button\n onClick={() => {\n if (at) editor.tf.select(at)\n unwrapLink(editor)\n finish()\n }}\n size=\"sm\"\n type=\"button\"\n variant=\"outline\"\n >\n {labels.remove}\n </Button>\n ) : null}\n </form>\n </PopoverPopup>\n </Popover>\n )\n}\n",
|
|
45
|
+
"target": "~/packages/ui/src/patterns/rich-text-editor/link-button.tsx"
|
|
46
|
+
},
|
|
47
|
+
{
|
|
48
|
+
"path": "patterns/rich-text-editor/plugins.tsx",
|
|
49
|
+
"type": "registry:file",
|
|
50
|
+
"content": "import {\n BoldRules,\n CodeRules,\n ItalicRules,\n StrikethroughRules,\n} from '@platejs/basic-nodes'\nimport {\n BoldPlugin,\n CodePlugin,\n H2Plugin,\n H3Plugin,\n HighlightPlugin,\n ItalicPlugin,\n StrikethroughPlugin,\n UnderlinePlugin,\n} from '@platejs/basic-nodes/react'\nimport { LinkPlugin } from '@platejs/link/react'\nimport { toggleList, unwrapList } from '@platejs/list-classic'\nimport {\n BulletedListPlugin,\n ListItemPlugin,\n ListPlugin,\n NumberedListPlugin,\n TaskListPlugin,\n} from '@platejs/list-classic/react'\nimport { MentionInputPlugin, MentionPlugin } from '@platejs/mention/react'\nimport { SlashInputPlugin, SlashPlugin } from '@platejs/slash-command/react'\nimport {\n createBlockStartInputRule,\n type Descendant,\n ElementApi,\n KEYS,\n NodeApi,\n type Path,\n PathApi,\n RangeApi,\n type SlateEditor,\n type TElement,\n} from 'platejs'\nimport {\n createPlatePlugin,\n Key,\n ParagraphPlugin,\n PlateElement,\n type PlateElementProps,\n PlateLeaf,\n type PlateLeafProps,\n} from 'platejs/react'\nimport type { ReactElement } from 'react'\nimport { type BlockDragLabels, blockDragPlugins } from './block-draggable'\nimport { extraBlockPlugins, RICH_TEXT_EXTRA_ELEMENTS } from './extra-blocks'\n\nexport const RICH_TEXT_MARKS = [\n 'bold',\n 'italic',\n 'underline',\n 'strikethrough',\n 'code',\n 'highlight',\n] as const\n\nexport type RichTextMark = (typeof RICH_TEXT_MARKS)[number]\n\nexport const RICH_TEXT_BLOCKS = ['h2', 'h3', 'blockquote', 'ul', 'ol'] as const\n\nexport type RichTextBlock = (typeof RICH_TEXT_BLOCKS)[number]\n\nexport const RICH_TEXT_ELEMENTS = [\n 'p',\n 'h2',\n 'h3',\n 'blockquote',\n 'ul',\n 'ol',\n 'li',\n 'lic',\n 'a',\n 'mention',\n ...RICH_TEXT_EXTRA_ELEMENTS,\n] as const\n\nexport const SLASH_INPUT_TYPE = KEYS.slashInput\n\nexport const MENTION_INPUT_TYPE = KEYS.mentionInput\n\nexport const MENTION_TYPE = KEYS.mention\n\nconst LIST_TYPES: readonly string[] = ['ul', 'ol']\n\nconst isList = (node: unknown): node is TElement =>\n ElementApi.isElement(node) && LIST_TYPES.includes(node.type)\n\nconst inListItem = (editor: SlateEditor) =>\n editor.api.some({ match: { type: 'li' } })\n\nexport function applyBlock(\n editor: SlateEditor,\n block: RichTextBlock | 'p',\n): void {\n if (block === 'ul' || block === 'ol') {\n toggleList(editor, { type: block })\n return\n }\n if (!editor.api.some({ match: { type: block } }) && inListItem(editor))\n unwrapList(editor)\n editor.tf.toggleBlock(block)\n}\n\nconst outsideList = ({ editor }: { editor: SlateEditor }) => !inListItem(editor)\n\nconst notAlready =\n (block: RichTextBlock) =>\n ({ editor }: { editor: SlateEditor }) =>\n !editor.api.some({ match: { type: block } })\n\nfunction blockShortcut(\n prefix: RegExp | string,\n block: RichTextBlock,\n enabled?: (context: { editor: SlateEditor }) => boolean,\n) {\n return createBlockStartInputRule({\n apply: ({ editor }, match) => {\n editor.tf.delete({ at: match.range })\n applyBlock(editor, block)\n return true\n },\n enabled: (context) =>\n notAlready(block)(context) && (enabled?.(context) ?? true),\n match: prefix,\n trigger: ' ',\n })\n}\n\nfunction ParagraphElement(props: PlateElementProps): ReactElement {\n return (\n <PlateElement {...props} as=\"p\" className=\"my-2 first:mt-0 last:mb-0\" />\n )\n}\n\nfunction H2Element(props: PlateElementProps): ReactElement {\n return (\n <PlateElement\n {...props}\n as=\"h2\"\n className=\"mt-4 mb-2 font-semibold text-lg first:mt-0\"\n />\n )\n}\n\nfunction H3Element(props: PlateElementProps): ReactElement {\n return (\n <PlateElement\n {...props}\n as=\"h3\"\n className=\"mt-3 mb-1 font-semibold text-base first:mt-0\"\n />\n )\n}\n\nfunction BlockquoteElement(props: PlateElementProps): ReactElement {\n return (\n <PlateElement\n {...props}\n as=\"blockquote\"\n className=\"my-2 border-border border-s-2 ps-4 italic\"\n />\n )\n}\n\nfunction BulletedListElement(props: PlateElementProps): ReactElement {\n return <PlateElement {...props} as=\"ul\" className=\"my-2 list-disc ps-6\" />\n}\n\nfunction NumberedListElement(props: PlateElementProps): ReactElement {\n return <PlateElement {...props} as=\"ol\" className=\"my-2 list-decimal ps-6\" />\n}\n\nfunction ListItemElement(props: PlateElementProps): ReactElement {\n return <PlateElement {...props} as=\"li\" />\n}\n\nfunction LinkElement(props: PlateElementProps): ReactElement {\n const url = String(props.element.url ?? '')\n return (\n <PlateElement\n {...props}\n as=\"a\"\n attributes={{\n ...props.attributes,\n href: url,\n rel: 'noopener noreferrer',\n target: '_blank',\n }}\n className=\"text-primary underline underline-offset-2\"\n />\n )\n}\n\nfunction HighlightLeaf(props: PlateLeafProps): ReactElement {\n return (\n <PlateLeaf\n {...props}\n as=\"mark\"\n className=\"rounded-sm bg-warning/30 text-foreground dark:bg-warning/25\"\n />\n )\n}\n\nfunction CodeLeaf(props: PlateLeafProps): ReactElement {\n return (\n <PlateLeaf\n {...props}\n as=\"code\"\n className=\"rounded-sm bg-muted px-1 font-mono text-sm\"\n />\n )\n}\n\nfunction SlashInputElement(props: PlateElementProps): ReactElement {\n return <PlateElement {...props} as=\"span\" className=\"rounded-sm bg-muted\" />\n}\n\nconst TRIGGER_INPUT_TYPES: readonly string[] = [\n SLASH_INPUT_TYPE,\n MENTION_INPUT_TYPE,\n]\n\nexport const hasTriggerInput = (nodes: readonly Descendant[]): boolean =>\n nodes.some(\n (node) =>\n ElementApi.isElement(node) &&\n (TRIGGER_INPUT_TYPES.includes(node.type) ||\n hasTriggerInput(node.children as Descendant[])),\n )\n\nexport const hasSlashInput = hasTriggerInput\n\nfunction unwrapStaleTriggerInputs(editor: SlateEditor): void {\n const { selection } = editor\n const current =\n selection && !RangeApi.isExpanded(selection)\n ? editor.api.above({\n at: selection,\n match: (node) =>\n ElementApi.isElement(node) &&\n TRIGGER_INPUT_TYPES.includes(node.type),\n })\n : undefined\n if (current) return\n const leftovers = [\n ...editor.api.nodes({\n at: [],\n match: (node) =>\n ElementApi.isElement(node) && TRIGGER_INPUT_TYPES.includes(node.type),\n }),\n ]\n for (const [, path] of leftovers.reverse())\n editor.tf.unwrapNodes({ at: path })\n}\n\nconst triggerNormalizer =\n (type: string, prefix: string) =>\n ({\n editor,\n tf: { normalizeNode },\n }: {\n editor: SlateEditor\n tf: { normalizeNode: (entry: [unknown, Path]) => void }\n }) => ({\n transforms: {\n normalizeNode(entry: [unknown, Path]) {\n const [node, path] = entry\n if (ElementApi.isElement(node) && node.type === type) {\n const text = NodeApi.string(node)\n if (text === '') {\n editor.tf.removeNodes({ at: path })\n return\n }\n if (!text.startsWith(prefix)) {\n editor.tf.unwrapNodes({ at: path })\n return\n }\n }\n normalizeNode(entry)\n },\n },\n })\n\nconst slashPlugin = SlashPlugin.configure({\n handlers: {\n onChange: ({ editor }: { editor: SlateEditor }) =>\n unwrapStaleTriggerInputs(editor),\n },\n options: {\n createComboboxInput: () => ({\n children: [{ text: '/' }],\n type: SLASH_INPUT_TYPE,\n }),\n },\n})\n .configurePlugin(SlashInputPlugin, {\n node: { component: SlashInputElement, isVoid: false },\n })\n .overrideEditor(triggerNormalizer(SLASH_INPUT_TYPE, '/') as never)\n\nfunction MentionElement(props: PlateElementProps): ReactElement {\n return (\n <PlateElement\n {...props}\n as=\"span\"\n attributes={{ ...props.attributes, contentEditable: false }}\n className=\"rounded-sm bg-primary/12 px-1 font-medium text-primary\"\n >\n @{String(props.element.value ?? '')}\n {props.children}\n </PlateElement>\n )\n}\n\nconst mentionPlugin = MentionPlugin.configure({\n node: { component: MentionElement },\n options: {\n createComboboxInput: () => ({\n children: [{ text: '@' }],\n type: MENTION_INPUT_TYPE,\n }),\n trigger: '@',\n triggerPreviousCharPattern: /^\\s?$/,\n },\n})\n .configurePlugin(MentionInputPlugin, {\n node: { component: SlashInputElement, isVoid: false },\n })\n .overrideEditor(triggerNormalizer(MENTION_INPUT_TYPE, '@') as never)\n\nconst BlockquotePlugin = createPlatePlugin({\n inputRules: [blockShortcut('>', 'blockquote')],\n key: 'blockquote',\n node: { component: BlockquoteElement, isElement: true },\n parsers: {\n html: { deserializer: { rules: [{ validNodeName: 'BLOCKQUOTE' }] } },\n },\n rules: { break: { empty: 'reset' }, delete: { start: 'reset' } },\n}).overrideEditor(({ editor, type, tf: { normalizeNode } }) => ({\n transforms: {\n normalizeNode(entry) {\n const [node, path] = entry\n const isBlockChild = (child: unknown) =>\n ElementApi.isElement(child) && !editor.api.isInline(child)\n if (\n ElementApi.isElement(node) &&\n node.type === type &&\n node.children.some(isBlockChild)\n ) {\n editor.tf.withoutNormalizing(() => {\n for (let index = node.children.length - 1; index > 0; index -= 1) {\n if (isBlockChild(node.children[index])) {\n editor.tf.insertNodes({ text: '\\n' }, { at: [...path, index, 0] })\n }\n }\n editor.tf.unwrapNodes({\n at: path,\n match: (child: unknown, childPath: Path) =>\n isBlockChild(child) && childPath.length === path.length + 1,\n mode: 'all',\n })\n })\n return\n }\n normalizeNode(entry)\n },\n },\n}))\n\nfunction listDepthAt(editor: SlateEditor, path: Path): number {\n let depth = 0\n for (let length = 1; length <= path.length; length += 1) {\n if (isList(NodeApi.get(editor, path.slice(0, length)))) depth += 1\n }\n return depth\n}\n\nfunction nestedDepth(listItem: TElement): number {\n let deepest = 0\n for (const child of listItem.children) {\n if (!isList(child)) continue\n for (const item of child.children) {\n if (ElementApi.isElement(item))\n deepest = Math.max(deepest, 1 + nestedDepth(item))\n }\n }\n return deepest\n}\n\ntype ListDepthConfig = { maxDepth: number }\n\nconst ListDepthPlugin = createPlatePlugin({\n key: 'listDepth',\n options: { maxDepth: Number.POSITIVE_INFINITY } as ListDepthConfig,\n}).overrideEditor(({ editor, getOption, tf: { normalizeNode, tab } }) => ({\n transforms: {\n normalizeNode(entry) {\n const [node, path] = entry\n if (isList(node) && listDepthAt(editor, path) > getOption('maxDepth')) {\n const parentItemPath = PathApi.parent(path)\n const outerListPath = PathApi.parent(parentItemPath)\n const firstTarget = (parentItemPath.at(-1) ?? 0) + 1\n editor.tf.withoutNormalizing(() => {\n node.children.forEach((_: unknown, offset: number) => {\n editor.tf.moveNodes({\n at: [...path, 0],\n to: [...outerListPath, firstTarget + offset],\n })\n })\n editor.tf.removeNodes({ at: path })\n })\n return\n }\n normalizeNode(entry)\n },\n tab(options) {\n const items = [\n ...(editor as SlateEditor).api.nodes({ match: { type: 'lic' } }),\n ].map(([, licPath]) => PathApi.parent(licPath))\n if (items.length === 0) return tab(options)\n\n const depths = items.map((itemPath) => listDepthAt(editor, itemPath))\n if (options.reverse) {\n return depths.every((depth) => depth <= 1) ? false : tab(options)\n }\n\n const canIndent = items.every((itemPath, index) => {\n const item = NodeApi.get(editor, itemPath) as TElement\n const hasPrevious = (itemPath.at(-1) ?? 0) > 0\n return (\n hasPrevious &&\n (depths[index] ?? 0) + 1 + nestedDepth(item) <= getOption('maxDepth')\n )\n })\n return canIndent ? tab(options) : false\n },\n },\n}))\n\nconst listPlugin = ListPlugin.configure({\n inputRules: [\n blockShortcut('-', 'ul', outsideList),\n blockShortcut('*', 'ul', outsideList),\n blockShortcut(/^\\d+\\.$/, 'ol', outsideList),\n ],\n})\n .configurePlugin(TaskListPlugin, { enabled: false })\n .configurePlugin(BulletedListPlugin, {\n node: { component: BulletedListElement },\n })\n .configurePlugin(NumberedListPlugin, {\n node: { component: NumberedListElement },\n })\n .configurePlugin(ListItemPlugin, { node: { component: ListItemElement } })\n\nexport function richTextEditorOptions(\n maxListDepth: number,\n withMentions = false,\n blockDragLabels?: BlockDragLabels,\n) {\n if (!Number.isInteger(maxListDepth) || maxListDepth < 1) {\n throw new RangeError(\n `maxListDepth must be an integer of at least 1; received ${maxListDepth}.`,\n )\n }\n return {\n nodeId: { initialValueIds: 'always' as const },\n plugins: [\n ParagraphPlugin.withComponent(ParagraphElement),\n H2Plugin.withComponent(H2Element).configure({\n inputRules: [blockShortcut('#', 'h2'), blockShortcut('##', 'h2')],\n parsers: {\n html: { deserializer: { rules: [{ validNodeName: ['H1', 'H2'] }] } },\n },\n }),\n H3Plugin.withComponent(H3Element).configure({\n inputRules: [blockShortcut('###', 'h3')],\n parsers: {\n html: {\n deserializer: {\n rules: [{ validNodeName: ['H3', 'H4', 'H5', 'H6'] }],\n },\n },\n },\n }),\n BlockquotePlugin,\n listPlugin,\n ListDepthPlugin.configure({ options: { maxDepth: maxListDepth } }),\n LinkPlugin.configure({ node: { component: LinkElement } }),\n ...extraBlockPlugins,\n slashPlugin,\n ...(withMentions ? [mentionPlugin] : []),\n ...(blockDragLabels === undefined\n ? []\n : blockDragPlugins(blockDragLabels.handle, blockDragLabels.selection)),\n BoldPlugin.configure({ inputRules: [BoldRules.markdown()] }),\n ItalicPlugin.configure({\n inputRules: [\n ItalicRules.markdown(),\n ItalicRules.markdown({ variant: '_' }),\n ],\n }),\n UnderlinePlugin,\n HighlightPlugin.configure({\n node: { component: HighlightLeaf },\n shortcuts: { toggle: { keys: [[Key.Mod, Key.Shift, 'h']] } },\n }),\n StrikethroughPlugin.configure({\n inputRules: [StrikethroughRules.markdown()],\n shortcuts: { toggle: { keys: [[Key.Mod, Key.Shift, 'x']] } },\n }),\n CodePlugin.configure({\n inputRules: [CodeRules.markdown()],\n node: { component: CodeLeaf },\n shortcuts: { toggle: { keys: [[Key.Mod, 'e']] } },\n }),\n ],\n }\n}\n",
|
|
51
|
+
"target": "~/packages/ui/src/patterns/rich-text-editor/plugins.tsx"
|
|
52
|
+
},
|
|
53
|
+
{
|
|
54
|
+
"path": "patterns/rich-text-editor/rich-text-editor.tsx",
|
|
55
|
+
"type": "registry:file",
|
|
56
|
+
"content": "'use client'\n\nimport { AtIcon } from '@phosphor-icons/react'\nimport { stripRichTextNodeIds } from '@tc96/ui/helpers/rich-text'\nimport { cn } from '@tc96/utils'\nimport {\n PointApi,\n RangeApi,\n type SlateEditor,\n type TRange,\n type Value,\n} from 'platejs'\nimport {\n Plate,\n PlateContent,\n type PlateContentProps,\n useEditorRef,\n usePlateEditor,\n} from 'platejs/react'\nimport type { KeyboardEvent, ReactElement, Ref, RefObject } from 'react'\nimport { useEffect, useId, useImperativeHandle, useMemo, useRef } from 'react'\nimport {\n type BlockDragLabels,\n defaultBlockDragLabels,\n selectCurrentBlock,\n} from './block-draggable'\nimport {\n insertImage,\n type RichTextExtraBlock,\n type RichTextImage,\n} from './extra-blocks'\nimport { FloatingToolbar } from './floating-toolbar'\nimport type { LinkButtonLabels } from './link-button'\nimport {\n hasTriggerInput,\n MENTION_INPUT_TYPE,\n MENTION_TYPE,\n type RichTextBlock,\n type RichTextMark,\n richTextEditorOptions,\n} from './plugins'\nimport {\n applySlashMenuOption,\n SlashMenu,\n type SlashMenuBlock,\n type SlashMenuOption,\n slashMenuOptions,\n useSlashMenu,\n} from './slash-menu'\n\nexport type RichTextValue = Value\n\nexport interface RichTextMention {\n id: string\n label: string\n}\n\nexport interface RichTextEditorHandle {\n focusStart: () => void\n}\n\nexport interface RichTextEditorProps {\n 'aria-label': string\n autoFocus?: boolean\n blockLabels?: Readonly<Record<RichTextBlock, string>>\n blockDragLabels?: BlockDragLabels\n blockTypeLabel?: string\n extraBlockLabels?: Readonly<Record<RichTextExtraBlock, string>>\n className?: string\n defaultValue?: RichTextValue\n draggableBlocks?: boolean\n linkLabels?: LinkButtonLabels\n markLabels?: Readonly<Record<RichTextMark, string>>\n maxListDepth?: number\n mentionEmptyLabel?: string\n mentionLabel?: string\n mentions?: readonly RichTextMention[]\n onExitStart?: () => void\n onPickImage?: () => Promise<RichTextImage | null>\n onValueChange?: (value: RichTextValue) => void\n paragraphLabel?: string\n placeholder?: string\n ref?: Ref<RichTextEditorHandle>\n slashMenuEmptyLabel?: string\n slashMenuLabel?: string\n toolbarLabel?: string\n}\n\nexport const defaultMaxListDepth = 4\n\nconst defaultLinkLabels = {\n apply: 'Aplicar',\n button: 'Link',\n remove: 'Remover',\n url: 'Endereço do link',\n} as const satisfies LinkButtonLabels\n\nconst defaultMarkLabels = {\n bold: 'Negrito',\n code: 'Código',\n highlight: 'Destaque de texto',\n italic: 'Itálico',\n strikethrough: 'Tachado',\n underline: 'Sublinhado',\n} as const satisfies Record<RichTextMark, string>\n\nexport const defaultExtraBlockLabels = {\n callout: 'Destaque',\n code: 'Bloco de código',\n date: 'Data de hoje',\n hr: 'Divisor',\n image: 'Imagem',\n table: 'Tabela',\n todo: 'Lista de tarefas',\n} as const satisfies Record<RichTextExtraBlock, string>\n\nconst defaultBlockLabels = {\n blockquote: 'Citação',\n h2: 'Título de seção',\n h3: 'Subtítulo',\n ol: 'Lista numerada',\n ul: 'Lista com marcadores',\n} as const satisfies Record<RichTextBlock, string>\n\ntype PlaceholderProps = Parameters<\n NonNullable<PlateContentProps['renderPlaceholder']>\n>[0]\n\nfunction renderPlaceholder({\n attributes,\n children,\n}: PlaceholderProps): ReactElement {\n return (\n <span\n {...attributes}\n aria-hidden=\"true\"\n className=\"text-muted-foreground\"\n style={{ ...attributes.style, opacity: 1 }}\n >\n {children}\n </span>\n )\n}\n\nfunction domCaret(\n editor: SlateEditor,\n): { range: TRange; rect: DOMRect } | null {\n const domSelection = editor.api\n .toDOMNode(editor)\n ?.ownerDocument.getSelection()\n if (!domSelection || domSelection.rangeCount === 0) return null\n const range = editor.api.toSlateRange(domSelection, {\n exactMatch: false,\n suppressThrow: true,\n })\n if (!range || RangeApi.isExpanded(range)) return null\n const domRange = domSelection.getRangeAt(0)\n const rect = domRange.getClientRects()[0] ?? domRange.getBoundingClientRect()\n return { range, rect }\n}\n\nexport function withoutSlashInput(\n onValueChange?: (value: RichTextValue) => void,\n) {\n return ({ value }: { value: RichTextValue }) => {\n if (!hasTriggerInput(value))\n onValueChange?.(stripRichTextNodeIds(value) as RichTextValue)\n }\n}\n\nfunction atDocumentStart(editor: SlateEditor, range: TRange): boolean {\n const start = editor.api.start([])\n return start !== undefined && PointApi.equals(range.anchor, start)\n}\n\nfunction onFirstLine(\n editor: SlateEditor,\n range: TRange,\n caret: DOMRect,\n): boolean {\n if (range.anchor.path[0] !== 0) return false\n const first = editor.children[0]\n const block = first && editor.api.toDOMNode(first)?.getBoundingClientRect()\n if (!block || caret.height === 0) return false\n return caret.top < block.top + caret.height\n}\n\ntype EditorContentProps = Required<\n Pick<\n RichTextEditorProps,\n | 'aria-label'\n | 'blockLabels'\n | 'extraBlockLabels'\n | 'mentionEmptyLabel'\n | 'mentionLabel'\n | 'paragraphLabel'\n | 'slashMenuEmptyLabel'\n | 'slashMenuLabel'\n >\n> &\n Pick<\n RichTextEditorProps,\n 'autoFocus' | 'mentions' | 'onExitStart' | 'onPickImage' | 'placeholder'\n > & {\n selectableBlocks: boolean\n toolbarRef: RefObject<HTMLDivElement | null>\n }\n\nfunction EditorContent({\n 'aria-label': ariaLabel,\n autoFocus,\n blockLabels,\n extraBlockLabels,\n mentionEmptyLabel,\n mentionLabel,\n mentions,\n onExitStart,\n onPickImage,\n paragraphLabel,\n placeholder,\n selectableBlocks,\n slashMenuEmptyLabel,\n slashMenuLabel,\n toolbarRef,\n}: EditorContentProps): ReactElement {\n const editor = useEditorRef()\n useEffect(() => {\n if (autoFocus) editor.tf.focus({ edge: 'endEditor' })\n }, [autoFocus, editor])\n const options = useMemo(\n () =>\n slashMenuOptions({\n ...blockLabels,\n ...extraBlockLabels,\n p: paragraphLabel,\n }).filter((option) => option.block !== 'image' || onPickImage),\n [blockLabels, extraBlockLabels, onPickImage, paragraphLabel],\n )\n const slashMenu = useSlashMenu({\n id: useId(),\n onSelect: (current, input, option) => {\n if (option.block !== 'image') {\n applySlashMenuOption(current, input, option.block as SlashMenuBlock)\n return\n }\n current.tf.removeNodes({ at: input.path })\n onPickImage?.().then((image: RichTextImage | null) => {\n if (image) insertImage(current, image)\n current.tf.focus()\n })\n },\n options,\n })\n const mentionOptions = useMemo<SlashMenuOption[]>(\n () =>\n (mentions ?? []).map((mention) => ({\n block: mention.id,\n icon: AtIcon,\n keywords: [],\n label: mention.label,\n })),\n [mentions],\n )\n const mentionMenu = useSlashMenu({\n id: useId(),\n inputType: MENTION_INPUT_TYPE,\n onSelect: (current, input, option) => {\n current.tf.removeNodes({ at: input.path })\n current.tf.insertNodes(\n { children: [{ text: '' }], type: MENTION_TYPE, value: option.label },\n { select: true },\n )\n current.tf.insertText(' ')\n },\n options: mentionOptions,\n })\n const activeMenu = mentionMenu.open ? mentionMenu : slashMenu\n\n const handleKeyDown = (event: KeyboardEvent<HTMLDivElement>) => {\n if (event.nativeEvent.isComposing) return\n if (mentionMenu.onKeyDown(event)) return\n if (slashMenu.onKeyDown(event)) return\n if (event.key === 'Escape' && selectableBlocks) {\n if (selectCurrentBlock(editor)) event.preventDefault()\n return\n }\n if (event.key === 'F10' && event.altKey) {\n const first = toolbarRef.current?.querySelector<HTMLElement>(\n '[data-slot=toolbar-button]',\n )\n if (!first) return\n event.preventDefault()\n first.focus()\n return\n }\n if (!onExitStart || (event.key !== 'ArrowUp' && event.key !== 'Backspace'))\n return\n const caret = domCaret(editor)\n if (!caret) return\n if (\n event.key === 'ArrowUp' &&\n onFirstLine(editor, caret.range, caret.rect)\n ) {\n event.preventDefault()\n onExitStart()\n return\n }\n if (\n event.key === 'Backspace' &&\n editor.children[0]?.type === 'p' &&\n atDocumentStart(editor, caret.range)\n ) {\n event.preventDefault()\n onExitStart()\n }\n }\n\n return (\n <>\n <PlateContent\n aria-activedescendant={activeMenu.activeId}\n aria-controls={activeMenu.open ? activeMenu.id : undefined}\n aria-label={ariaLabel}\n aria-placeholder={placeholder}\n className=\"w-full text-base text-foreground outline-none\"\n data-slot=\"rich-text-editor-content\"\n onBlur={(event) => {\n slashMenu.onBlur(event)\n mentionMenu.onBlur(event)\n }}\n onKeyDown={handleKeyDown}\n placeholder={placeholder}\n renderPlaceholder={renderPlaceholder}\n />\n <SlashMenu\n emptyLabel={slashMenuEmptyLabel}\n label={slashMenuLabel}\n menu={slashMenu}\n />\n <SlashMenu\n emptyLabel={mentionEmptyLabel}\n label={mentionLabel}\n menu={mentionMenu}\n />\n </>\n )\n}\n\nexport function RichTextEditor({\n 'aria-label': ariaLabel,\n autoFocus = false,\n blockLabels = defaultBlockLabels,\n blockDragLabels = defaultBlockDragLabels,\n blockTypeLabel = 'Tipo de bloco',\n className,\n defaultValue,\n draggableBlocks = false,\n extraBlockLabels = defaultExtraBlockLabels,\n linkLabels = defaultLinkLabels,\n markLabels = defaultMarkLabels,\n maxListDepth = defaultMaxListDepth,\n mentionEmptyLabel = 'Ninguém com esse nome',\n mentionLabel = 'Pessoas',\n mentions,\n onExitStart,\n onPickImage,\n onValueChange,\n paragraphLabel = 'Texto',\n placeholder,\n ref,\n slashMenuEmptyLabel = 'Nenhum bloco com esse nome',\n slashMenuLabel = 'Blocos',\n toolbarLabel = 'Formatação',\n}: Readonly<RichTextEditorProps>): ReactElement {\n const editor = usePlateEditor({\n ...richTextEditorOptions(\n maxListDepth,\n mentions !== undefined,\n draggableBlocks ? blockDragLabels : undefined,\n ),\n ...(defaultValue ? { value: defaultValue } : {}),\n })\n const toolbarRef = useRef<HTMLDivElement>(null)\n\n useImperativeHandle(ref, () => ({\n focusStart: () => editor.tf.focus({ at: [], edge: 'start' }),\n }))\n\n return (\n <Plate editor={editor} onValueChange={withoutSlashInput(onValueChange)}>\n <div className={cn('w-full', className)} data-slot=\"rich-text-editor\">\n <EditorContent\n aria-label={ariaLabel}\n autoFocus={autoFocus}\n blockLabels={blockLabels}\n extraBlockLabels={extraBlockLabels}\n mentionEmptyLabel={mentionEmptyLabel}\n mentionLabel={mentionLabel}\n paragraphLabel={paragraphLabel}\n selectableBlocks={draggableBlocks}\n slashMenuEmptyLabel={slashMenuEmptyLabel}\n slashMenuLabel={slashMenuLabel}\n toolbarRef={toolbarRef}\n {...(mentions ? { mentions } : {})}\n {...(onExitStart ? { onExitStart } : {})}\n {...(onPickImage ? { onPickImage } : {})}\n {...(placeholder ? { placeholder } : {})}\n />\n <FloatingToolbar\n blockLabels={blockLabels}\n blockTypeLabel={blockTypeLabel}\n label={toolbarLabel}\n linkLabels={linkLabels}\n markLabels={markLabels}\n paragraphLabel={paragraphLabel}\n toolbarRef={toolbarRef}\n />\n </div>\n </Plate>\n )\n}\n",
|
|
57
|
+
"target": "~/packages/ui/src/patterns/rich-text-editor/rich-text-editor.tsx"
|
|
58
|
+
},
|
|
59
|
+
{
|
|
60
|
+
"path": "patterns/rich-text-editor/slash-menu.tsx",
|
|
61
|
+
"type": "registry:file",
|
|
62
|
+
"content": "'use client'\n\nimport {\n CalendarBlankIcon,\n ChatCenteredDotsIcon,\n CodeBlockIcon,\n ImageIcon,\n ListChecksIcon,\n MinusIcon,\n type Icon as PhosphorIcon,\n TableIcon,\n TextAaIcon,\n} from '@phosphor-icons/react'\nimport { filterWords } from '@platejs/combobox'\nimport { Popover, PopoverPopup } from '@tc96/ui/popover'\nimport { cn } from '@tc96/utils'\nimport {\n ElementApi,\n NodeApi,\n type Path,\n PathApi,\n RangeApi,\n type SlateEditor,\n} from 'platejs'\nimport { useEditorRef, useEditorSelector } from 'platejs/react'\nimport type { FocusEvent, KeyboardEvent, ReactElement } from 'react'\nimport { useMemo, useState } from 'react'\nimport {\n applyExtraBlock,\n RICH_TEXT_EXTRA_BLOCKS,\n type RichTextExtraBlock,\n} from './extra-blocks'\nimport { blockIcon } from './floating-toolbar'\nimport {\n applyBlock,\n MENTION_INPUT_TYPE,\n RICH_TEXT_BLOCKS,\n type RichTextBlock,\n SLASH_INPUT_TYPE,\n} from './plugins'\n\nexport type SlashMenuBlock = RichTextBlock | RichTextExtraBlock | 'p'\n\nexport interface SlashMenuOption {\n block: SlashMenuBlock | (string & {})\n icon?: PhosphorIcon\n keywords: readonly string[]\n label: string\n}\n\nconst keywords = {\n blockquote: ['citacao', 'quote'],\n callout: ['destaque', 'aviso', 'nota', 'callout'],\n code: ['codigo', 'code', 'bloco'],\n date: ['data', 'hoje', 'date'],\n hr: ['divisor', 'linha', 'separador', 'divider'],\n image: ['imagem', 'foto', 'figura', 'image'],\n table: ['tabela', 'grade', 'table'],\n todo: ['tarefa', 'checklist', 'todo', 'checkbox'],\n h2: ['titulo', 'secao', 'heading'],\n h3: ['subtitulo', 'heading'],\n ol: ['lista', 'numerada', 'ordenada', 'numeros'],\n p: ['texto', 'paragrafo', 'normal'],\n ul: ['lista', 'marcadores', 'topicos', 'bullet'],\n} as const satisfies Record<SlashMenuBlock, readonly string[]>\n\nconst optionIcon = {\n ...blockIcon,\n callout: ChatCenteredDotsIcon,\n code: CodeBlockIcon,\n date: CalendarBlankIcon,\n hr: MinusIcon,\n image: ImageIcon,\n table: TableIcon,\n p: TextAaIcon,\n todo: ListChecksIcon,\n} as const satisfies Record<SlashMenuBlock, PhosphorIcon>\n\nexport function slashMenuOptions(\n labels: Readonly<Record<SlashMenuBlock, string>>,\n): SlashMenuOption[] {\n return (['p', ...RICH_TEXT_BLOCKS, ...RICH_TEXT_EXTRA_BLOCKS] as const).map(\n (block) => ({\n block,\n keywords: keywords[block],\n label: labels[block],\n }),\n )\n}\n\nexport function filterSlashMenuOptions(\n options: readonly SlashMenuOption[],\n query: string,\n): SlashMenuOption[] {\n const needle = query.trim()\n if (needle === '') return [...options]\n return options.filter((option) =>\n filterWords(`${option.label} ${option.keywords.join(' ')}`, needle),\n )\n}\n\nexport interface SlashInput {\n path: Path\n query: string\n}\n\nexport function currentSlashInput(\n editor: SlateEditor,\n inputType: string = SLASH_INPUT_TYPE,\n): SlashInput | null {\n const { selection } = editor\n if (!selection || RangeApi.isExpanded(selection)) return null\n const entry = editor.api.above({\n at: selection,\n match: { type: inputType },\n })\n if (!entry) return null\n const [node, path] = entry\n return { path, query: NodeApi.string(node).slice(1) }\n}\n\nexport function applySlashMenuOption(\n editor: SlateEditor,\n input: SlashInput,\n block: SlashMenuBlock,\n): void {\n editor.tf.removeNodes({ at: input.path })\n if ((RICH_TEXT_EXTRA_BLOCKS as readonly string[]).includes(block))\n applyExtraBlock(editor, block as RichTextExtraBlock)\n else applyBlock(editor, block as RichTextBlock | 'p')\n}\n\nexport function dismissSlashInput(\n editor: SlateEditor,\n input: SlashInput,\n): void {\n editor.tf.unwrapNodes({ at: input.path })\n}\n\nfunction unwrapSlashInputs(editor: SlateEditor): void {\n const leftovers = [\n ...editor.api.nodes({\n at: [],\n match: (node) =>\n ElementApi.isElement(node) &&\n (node.type === SLASH_INPUT_TYPE || node.type === MENTION_INPUT_TYPE),\n }),\n ]\n for (const [, path] of leftovers.reverse())\n editor.tf.unwrapNodes({ at: path })\n}\n\nconst sameInput = (a: SlashInput | null, b: SlashInput | null) =>\n a === b ||\n (a !== null &&\n b !== null &&\n a.query === b.query &&\n PathApi.equals(a.path, b.path))\n\nexport interface SlashMenuState {\n activeId: string | undefined\n activeIndex: number\n anchor: {\n contextElement?: Element\n getBoundingClientRect: () => DOMRect\n } | null\n id: string\n matches: SlashMenuOption[]\n open: boolean\n apply: (option: SlashMenuOption) => void\n onBlur: (event: FocusEvent) => void\n onKeyDown: (event: KeyboardEvent) => boolean\n optionId: (option: SlashMenuOption) => string\n setActiveIndex: (index: number) => void\n}\n\nexport function useSlashMenu({\n id,\n inputType = SLASH_INPUT_TYPE,\n onSelect,\n options,\n}: Readonly<{\n id: string\n inputType?: string\n onSelect?: (\n editor: SlateEditor,\n input: SlashInput,\n option: SlashMenuOption,\n ) => void\n options: readonly SlashMenuOption[]\n}>): SlashMenuState {\n const editor = useEditorRef()\n const input = useEditorSelector(\n (current) => currentSlashInput(current, inputType),\n [inputType],\n { equalityFn: sameInput },\n )\n const select = (option: SlashMenuOption) => {\n if (!input) return\n if (onSelect) onSelect(editor, input, option)\n else applySlashMenuOption(editor, input, option.block as SlashMenuBlock)\n }\n const [active, setActive] = useState<{\n index: number\n query: string\n } | null>(null)\n\n const query = input?.query ?? ''\n const matches = useMemo(\n () => filterSlashMenuOptions(options, query),\n [options, query],\n )\n const activeIndex =\n active?.query === query\n ? Math.max(0, Math.min(active.index, matches.length - 1))\n : 0\n const activeOption = matches[activeIndex]\n const open = input !== null\n\n const anchor = useMemo(() => {\n if (!input) return null\n return {\n contextElement: editor.api.toDOMNode(editor) as Element | undefined,\n getBoundingClientRect: () => {\n const node = NodeApi.get(editor, input.path)\n return (\n (node && editor.api.toDOMNode(node)?.getBoundingClientRect()) ||\n new DOMRect()\n )\n },\n }\n }, [editor, input])\n\n const optionId = (option: SlashMenuOption) => `${id}-${option.block}`\n\n const apply = (option: SlashMenuOption) => {\n select(option)\n }\n\n const onKeyDown = (event: KeyboardEvent): boolean => {\n if (!open || !input) return false\n switch (event.key) {\n case 'ArrowDown':\n case 'ArrowUp': {\n if (matches.length === 0) return false\n event.preventDefault()\n const step = event.key === 'ArrowDown' ? 1 : -1\n setActive({\n index: (activeIndex + step + matches.length) % matches.length,\n query,\n })\n return true\n }\n case 'Enter': {\n if (!activeOption) {\n dismissSlashInput(editor, input)\n return false\n }\n event.preventDefault()\n select(activeOption)\n return true\n }\n case 'Escape': {\n event.preventDefault()\n dismissSlashInput(editor, input)\n return true\n }\n case ' ': {\n if (query === '' || matches.length === 0)\n dismissSlashInput(editor, input)\n return false\n }\n default:\n return false\n }\n }\n\n return {\n activeId: open && activeOption ? optionId(activeOption) : undefined,\n activeIndex,\n anchor,\n apply,\n id,\n matches,\n onBlur: (event) => {\n if (\n event.currentTarget.ownerDocument.activeElement === event.currentTarget\n )\n return\n unwrapSlashInputs(editor)\n },\n onKeyDown,\n open,\n optionId,\n setActiveIndex: (index) => setActive({ index, query }),\n }\n}\n\nexport interface SlashMenuProps {\n emptyLabel: string\n label: string\n menu: SlashMenuState\n}\n\nexport function SlashMenu({\n emptyLabel,\n label,\n menu,\n}: Readonly<SlashMenuProps>): ReactElement {\n const empty = menu.matches.length === 0\n return (\n <Popover onOpenChange={() => undefined} open={menu.open}>\n <PopoverPopup\n align=\"start\"\n anchor={menu.anchor}\n className=\"min-w-56\"\n finalFocus={false}\n initialFocus={false}\n role=\"presentation\"\n side=\"bottom\"\n sideOffset={4}\n tooltipStyle\n >\n <div\n aria-label={label}\n className=\"flex flex-col gap-0.5\"\n data-slot=\"slash-menu\"\n id={menu.id}\n role=\"listbox\"\n >\n {menu.matches.map((option, index) => {\n const Icon =\n option.icon ??\n optionIcon[option.block as SlashMenuBlock] ??\n TextAaIcon\n const active = index === menu.activeIndex\n return (\n <button\n aria-selected={active}\n className=\"flex min-h-8 w-full cursor-default select-none items-center gap-2 rounded-sm px-2 py-1 text-start text-foreground text-sm outline-none data-highlighted:bg-accent data-highlighted:text-accent-foreground sm:min-h-7\"\n data-highlighted={active || undefined}\n data-slot=\"slash-menu-option\"\n id={menu.optionId(option)}\n key={option.block}\n onClick={() => menu.apply(option)}\n onMouseDown={(event) => event.preventDefault()}\n onPointerMove={() => menu.setActiveIndex(index)}\n role=\"option\"\n tabIndex={-1}\n type=\"button\"\n >\n <Icon\n aria-hidden=\"true\"\n className=\"size-4 shrink-0 opacity-80\"\n />\n {option.label}\n </button>\n )\n })}\n </div>\n <output\n className={cn(\n 'block text-muted-foreground text-sm',\n empty ? 'px-2 py-1' : 'sr-only',\n )}\n data-slot=\"slash-menu-status\"\n >\n {empty ? emptyLabel : ''}\n </output>\n </PopoverPopup>\n </Popover>\n )\n}\n",
|
|
63
|
+
"target": "~/packages/ui/src/patterns/rich-text-editor/slash-menu.tsx"
|
|
64
|
+
}
|
|
65
|
+
],
|
|
66
|
+
"dependencies": [
|
|
67
|
+
"@phosphor-icons/react@2.1.10",
|
|
68
|
+
"@platejs/basic-nodes@53.0.0",
|
|
69
|
+
"@platejs/combobox@53.0.0",
|
|
70
|
+
"@platejs/date@53.0.0",
|
|
71
|
+
"@platejs/dnd@53.3.8",
|
|
72
|
+
"@platejs/link@53.3.5",
|
|
73
|
+
"@platejs/list-classic@53.0.0",
|
|
74
|
+
"@platejs/mention@53.0.0",
|
|
75
|
+
"@platejs/selection@53.1.6",
|
|
76
|
+
"@platejs/slash-command@53.0.0",
|
|
77
|
+
"@platejs/table@53.0.9",
|
|
78
|
+
"platejs@53.3.14",
|
|
79
|
+
"react@19.1.1",
|
|
80
|
+
"react-dnd@^16.0.1",
|
|
81
|
+
"react-dnd-html5-backend@^16.0.1"
|
|
82
|
+
],
|
|
83
|
+
"registryDependencies": [
|
|
84
|
+
"@ui/button",
|
|
85
|
+
"@ui/checkbox",
|
|
86
|
+
"@ui/input",
|
|
87
|
+
"@ui/popover",
|
|
88
|
+
"@ui/select",
|
|
89
|
+
"@ui/toggle",
|
|
90
|
+
"@ui/toolbar"
|
|
91
|
+
],
|
|
92
|
+
"$schema": "https://ui.shadcn.com/schema/registry-item.json"
|
|
93
|
+
}
|