@tc96/cli 0.27.0 → 0.28.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/README.md +4 -4
- package/cli.js +82 -27
- package/package.json +1 -1
- package/registry/agenda-1.json +1297 -0
- package/registry/aggregate.json +1 -1
- package/registry/ai-chat-1.json +91 -0
- package/registry/checklist.json +21 -7
- package/registry/collection.json +624 -351
- package/registry/crm-1.json +1317 -0
- package/registry/crm-2.json +1400 -0
- package/registry/dashboard-5.json +167 -0
- package/registry/dashboard-6.json +143 -0
- package/registry/dashboard-7.json +188 -0
- package/registry/documents-1.json +1322 -0
- package/registry/finance-1.json +845 -0
- package/registry/finance-2.json +973 -0
- package/registry/finance-3.json +1436 -0
- package/registry/{workflow-editor.json → flow-1.json} +37 -37
- package/registry/{agent-builder.json → flow-2.json} +55 -55
- package/registry/{run-monitor.json → flow-3.json} +16 -16
- package/registry/{impact-map.json → flow-4.json} +16 -16
- package/registry/inbox-1.json +1184 -0
- package/registry/inventory-1.json +828 -0
- package/registry/inventory-2.json +956 -0
- package/registry/legal-1.json +1345 -0
- package/registry/legal-2.json +1279 -0
- package/registry/legal-3.json +1273 -0
- package/registry/legal-4.json +1273 -0
- package/registry/legal-5.json +1393 -0
- package/registry/legal-6.json +1309 -0
- package/registry/legal-7.json +1315 -0
- package/registry/legal-8.json +1358 -0
- package/registry/legal-9.json +1381 -0
- package/registry/marketing-1.json +833 -0
- package/registry/marketing-2.json +961 -0
- package/registry/navbar-1.json +6 -6
- package/registry/navbar-10.json +50 -0
- package/registry/navbar-11.json +48 -0
- package/registry/navbar-12.json +48 -0
- package/registry/navbar-6.json +48 -0
- package/registry/navbar-7.json +72 -0
- package/registry/navbar-8.json +50 -0
- package/registry/navbar-9.json +54 -0
- package/registry/projects-1.json +865 -0
- package/registry/projects-2.json +993 -0
- package/registry/projects-3.json +1346 -0
- package/registry/properties.json +65 -58
- package/registry/record-group.json +5 -1
- package/registry/revenue-1.json +834 -0
- package/registry/revenue-2.json +968 -0
- package/registry/revenue-3.json +821 -0
- package/registry/revenue-4.json +949 -0
- package/registry/rich-text-editor-1.json +172 -0
- package/registry/rich-text-editor-2.json +158 -0
- package/registry/rich-text-editor-3.json +198 -0
- package/registry/rich-text-editor-4.json +200 -0
- package/registry/rich-text-editor-5.json +237 -0
- package/registry/rich-text-editor.json +27 -7
- package/registry/{settings-1.json → settings-account-1.json} +17 -17
- package/registry/{settings-23.json → settings-account-2.json} +17 -17
- package/registry/{settings-7.json → settings-catalog-1.json} +17 -17
- package/registry/{settings-16.json → settings-catalog-10.json} +17 -17
- package/registry/{settings-8.json → settings-catalog-2.json} +17 -17
- package/registry/{settings-9.json → settings-catalog-3.json} +17 -17
- package/registry/{settings-10.json → settings-catalog-4.json} +29 -20
- package/registry/{settings-11.json → settings-catalog-5.json} +17 -17
- package/registry/{settings-12.json → settings-catalog-6.json} +17 -17
- package/registry/{settings-13.json → settings-catalog-7.json} +17 -17
- package/registry/{settings-14.json → settings-catalog-8.json} +29 -19
- package/registry/{settings-15.json → settings-catalog-9.json} +28 -18
- package/registry/{settings-19.json → settings-integration-1.json} +17 -17
- package/registry/settings-integration-2.json +122 -0
- package/registry/{settings-22.json → settings-integration-3.json} +17 -17
- package/registry/settings-integration-4.json +129 -0
- package/registry/settings-integration-5.json +122 -0
- package/registry/settings-integration-6.json +92 -0
- package/registry/{settings-21.json → settings-integration-7.json} +23 -17
- package/registry/settings-integration-8.json +593 -0
- package/registry/{settings-20.json → settings-notification-channel-1.json} +17 -17
- package/registry/{settings-2.json → settings-preference-1.json} +17 -17
- package/registry/{settings-3.json → settings-preference-2.json} +17 -17
- package/registry/{settings-4.json → settings-preference-3.json} +17 -17
- package/registry/{settings-18.json → settings-role-permission-1.json} +17 -17
- package/registry/{settings-17.json → settings-security-1.json} +17 -17
- package/registry/{settings-5.json → settings-workspace-1.json} +28 -28
- package/registry/{settings-6.json → settings-workspace-2.json} +31 -31
- package/registry/support-1.json +853 -0
- package/registry/support-2.json +981 -0
- package/registry/support-3.json +762 -0
- package/registry/support-4.json +538 -0
- package/registry/team-1.json +829 -0
- package/registry/team-2.json +957 -0
- package/registry/ui/gauge.json +1 -1
- package/registry/ui/menu.json +1 -1
- package/registry/ui/property-meta.json +16 -0
- package/registry/ui/property-tone.json +12 -0
- package/registry/ui/scroll-area.json +1 -1
- package/registry/ui/select.json +1 -1
- package/registry/view.json +624 -351
- package/registry/app-shell-5.json +0 -106
- package/registry/bulk-import-1.json +0 -151
- package/registry/collection-layouts.json +0 -836
- package/registry/collection-views.json +0 -836
- package/registry/detail-sheet.json +0 -54
- package/registry/icon-row.json +0 -52
- package/registry/lookup-create-1.json +0 -157
- package/registry/next-steps-1.json +0 -147
- package/registry/settings-shell.json +0 -60
|
@@ -0,0 +1,237 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "rich-text-editor-5",
|
|
3
|
+
"type": "registry:block",
|
|
4
|
+
"files": [
|
|
5
|
+
{
|
|
6
|
+
"path": "blocks/application/rich-text-editor/rich-text-editor-5/assistant-chat.tsx",
|
|
7
|
+
"type": "registry:file",
|
|
8
|
+
"content": "import {\n ArrowCounterClockwiseIcon,\n ArrowsInLineHorizontalIcon,\n ArrowUpIcon,\n CaretDownIcon,\n CaretUpIcon,\n LightningIcon,\n ListChecksIcon,\n MinusIcon,\n QuestionIcon,\n SparkleIcon,\n StopIcon,\n TextAaIcon,\n TextAlignLeftIcon,\n UserCircleIcon,\n XIcon,\n} from '@phosphor-icons/react'\nimport { Avatar, AvatarFallback } from '@tc96/ui/avatar'\nimport { Badge } from '@tc96/ui/badge'\nimport { Button } from '@tc96/ui/button'\nimport { ChatConversation } from '@tc96/ui/chat/chat-conversation'\nimport { ChatMessage } from '@tc96/ui/chat/chat-message'\nimport { ChatEmptyState } from '@tc96/ui/chat/chat-states'\nimport { ChatTypingIndicator } from '@tc96/ui/chat/chat-typing-indicator'\nimport { useChatScroll } from '@tc96/ui/chat/hooks/use-chat-scroll'\nimport {\n Composer,\n ComposerActionGroup,\n ComposerActions,\n ComposerInput,\n ComposerItem,\n ComposerList,\n ComposerPopup,\n ComposerSubmit,\n type ComposerTrigger,\n type ComposerValue,\n getComposerText,\n useComposerContext,\n} from '@tc96/ui/composer'\nimport { cn } from '@tc96/utils'\nimport {\n type ReactElement,\n type RefObject,\n useId,\n useMemo,\n useState,\n} from 'react'\nimport {\n type SuggestionChange,\n SuggestionReviewList,\n} from '../shared/suggestions'\nimport { fallbackTasks, matchOrder, selectionTasks } from './planner'\nimport { StepTrace } from './step-trace'\nimport type {\n RichTextEditor5Finding,\n RichTextEditor5Labels,\n RichTextEditor5Task,\n} from './types'\nimport type { Passage, RunState } from './use-assistant-run'\n\nconst taskIcons = {\n checklist: ListChecksIcon,\n owners: UserCircleIcon,\n questions: QuestionIcon,\n spelling: TextAaIcon,\n summary: TextAlignLeftIcon,\n tighten: ArrowsInLineHorizontalIcon,\n} satisfies Record<RichTextEditor5Task, unknown>\n\nconst isTask = (id: string): id is RichTextEditor5Task =>\n (matchOrder as readonly string[]).includes(id)\n\nexport type AssistantTurn =\n | { fallback: string; id: string; kind: 'fallback'; prompt: string }\n | { id: string; kind: 'task'; prompt: string; run?: RunState | undefined }\n\nexport interface AssistantChatProps {\n activeFindingId: string | null\n activeId: string | null\n canUndo: boolean\n changes: readonly SuggestionChange[]\n chatRef: RefObject<HTMLElement | null>\n formatTime?: ((date: Date) => string) | undefined\n labels: RichTextEditor5Labels\n onAccept: (id: string) => void\n onAcceptAll: () => void\n onClearPassage: () => void\n onCollapse: () => void\n onFinding: (finding: RichTextEditor5Finding) => void\n onReject: (id: string) => void\n onRejectAll: () => void\n onRequest: (text: string) => void\n onRun: (task: RichTextEditor5Task) => void\n onSelect: (id: string) => void\n onStep: (direction: 1 | -1) => void\n onStop: () => void\n onUndo: () => void\n passage: Passage | null\n run: RunState | null\n turns: readonly AssistantTurn[]\n}\n\nfunction statusText(run: RunState, labels: RichTextEditor5Labels): string {\n if (run.status === 'running') return labels.running(labels.tasks[run.task])\n if (run.status === 'stopped') return labels.stopped(run.edits)\n if (run.status === 'failed') return labels.failed\n return labels.done(run.edits, run.findings.length)\n}\n\nfunction AssistantAvatar(): ReactElement {\n return (\n <Avatar className=\"[--avatar-size:--spacing(7)]\">\n <AvatarFallback>\n <SparkleIcon aria-hidden=\"true\" />\n </AvatarFallback>\n </Avatar>\n )\n}\n\nfunction TaskMenuButton({ label }: Readonly<{ label: string }>): ReactElement {\n const { insertTrigger } = useComposerContext()\n return (\n <Button\n aria-label={label}\n onClick={() => insertTrigger('/')}\n size=\"icon-sm\"\n type=\"button\"\n variant=\"ghost\"\n >\n <LightningIcon aria-hidden=\"true\" />\n </Button>\n )\n}\n\nfunction Findings({\n activeFindingId,\n labels,\n onFinding,\n run,\n}: Readonly<{\n activeFindingId: string | null\n labels: RichTextEditor5Labels\n onFinding: (finding: RichTextEditor5Finding) => void\n run: RunState\n}>): ReactElement | null {\n const findingsTask = run.task === 'questions' || run.task === 'owners'\n if (!findingsTask || run.status === 'running') return null\n if (run.findings.length === 0)\n return (\n <p\n className=\"text-muted-foreground text-sm\"\n data-slot=\"assistant-findings-empty\"\n >\n {labels.findingsEmpty}\n </p>\n )\n return (\n <ul\n aria-label={labels.findings}\n className=\"flex flex-col gap-2\"\n data-slot=\"assistant-findings\"\n >\n {run.findings.map((finding) => (\n <li\n className={cn(\n 'flex flex-col items-start gap-2 rounded-lg border bg-background p-2 text-sm',\n finding.id === activeFindingId && 'border-ring ring-1 ring-ring',\n )}\n data-finding-id={finding.id}\n data-kind={finding.kind}\n data-slot=\"assistant-finding\"\n key={finding.id}\n >\n <Badge variant=\"secondary\">{labels.findingKinds[finding.kind]}</Badge>\n <span>{finding.text}</span>\n <Button\n aria-label={labels.goToFinding(finding)}\n aria-pressed={finding.id === activeFindingId}\n onClick={() => onFinding(finding)}\n size=\"sm\"\n variant=\"outline\"\n >\n {labels.goTo}\n </Button>\n </li>\n ))}\n </ul>\n )\n}\n\nfunction Review({\n activeId,\n canUndo,\n changes,\n formatTime,\n labels,\n onAccept,\n onAcceptAll,\n onReject,\n onRejectAll,\n onSelect,\n onStep,\n onUndo,\n}: Readonly<\n Pick<\n AssistantChatProps,\n | 'activeId'\n | 'canUndo'\n | 'changes'\n | 'formatTime'\n | 'labels'\n | 'onAccept'\n | 'onAcceptAll'\n | 'onReject'\n | 'onRejectAll'\n | 'onSelect'\n | 'onStep'\n | 'onUndo'\n >\n>): ReactElement {\n const activeIndex = changes.findIndex((change) => change.id === activeId)\n return (\n <section\n aria-label={labels.reviewTitle}\n className=\"flex flex-col gap-2\"\n data-slot=\"assistant-review\"\n >\n <div className=\"flex flex-wrap items-center gap-1\">\n <h3 className=\"font-medium text-sm\">{labels.reviewTitle}</h3>\n <span\n className=\"text-muted-foreground text-xs\"\n data-slot=\"assistant-review-position\"\n >\n {labels.position(Math.max(activeIndex, -1) + 1, changes.length)}\n </span>\n <span className=\"flex-1\" />\n <Button\n aria-label={labels.previous}\n disabled={changes.length === 0}\n onClick={() => onStep(-1)}\n size=\"icon-sm\"\n variant=\"ghost\"\n >\n <CaretUpIcon aria-hidden=\"true\" />\n </Button>\n <Button\n aria-label={labels.next}\n disabled={changes.length === 0}\n onClick={() => onStep(1)}\n size=\"icon-sm\"\n variant=\"ghost\"\n >\n <CaretDownIcon aria-hidden=\"true\" />\n </Button>\n </div>\n <SuggestionReviewList\n activeId={activeId}\n changes={changes}\n {...(formatTime ? { formatTime } : {})}\n labels={labels.review}\n onAccept={onAccept}\n onReject={onReject}\n onSelect={onSelect}\n />\n <div className=\"flex flex-wrap gap-2\">\n <Button\n disabled={!canUndo}\n onClick={onUndo}\n size=\"sm\"\n variant=\"outline\"\n >\n <ArrowCounterClockwiseIcon aria-hidden=\"true\" />\n {labels.undo}\n </Button>\n <Button\n disabled={changes.length === 0}\n onClick={onRejectAll}\n size=\"sm\"\n variant=\"outline\"\n >\n {labels.rejectAll}\n </Button>\n <Button disabled={changes.length === 0} onClick={onAcceptAll} size=\"sm\">\n {labels.acceptAll}\n </Button>\n </div>\n </section>\n )\n}\n\nexport function AssistantChat(\n props: Readonly<AssistantChatProps>,\n): ReactElement {\n const {\n activeFindingId,\n changes,\n chatRef,\n labels,\n onClearPassage,\n onCollapse,\n onFinding,\n onRequest,\n onRun,\n onStop,\n passage,\n run,\n turns,\n } = props\n const titleId = `assistant-chat-title-${useId()}`\n const [draft, setDraft] = useState<ComposerValue>([])\n const running = run?.status === 'running'\n const blocked = (task: RichTextEditor5Task) =>\n running || (passage !== null && !selectionTasks.includes(task))\n const scroll = useChatScroll({\n itemCount: turns.length + (running ? 1 : 0),\n layoutKey: `${run?.steps.length ?? 0}-${run?.status ?? ''}-${changes.length}`,\n })\n const reviewTurnId = [...turns]\n .reverse()\n .find((turn) => turn.kind === 'task')?.id\n const triggers = useMemo<readonly ComposerTrigger[]>(\n () => [\n {\n character: '/',\n items: matchOrder.map((task) => {\n const Icon = taskIcons[task]\n return {\n disabled:\n running || (passage !== null && !selectionTasks.includes(task)),\n icon: <Icon aria-hidden=\"true\" />,\n id: task,\n label: labels.tasks[task],\n type: 'action' as const,\n }\n }),\n },\n ],\n [labels.tasks, passage, running],\n )\n\n const taskButton = (task: RichTextEditor5Task, wide: boolean) => {\n const Icon = taskIcons[task]\n return (\n <Button\n className={wide ? 'w-full justify-start' : undefined}\n data-task={task}\n disabled={blocked(task)}\n key={task}\n onClick={() => onRun(task)}\n size=\"sm\"\n variant=\"outline\"\n >\n <Icon aria-hidden=\"true\" />\n {labels.tasks[task]}\n </Button>\n )\n }\n\n return (\n <section\n aria-labelledby={titleId}\n className=\"flex min-h-0 flex-1 flex-col\"\n data-slot=\"assistant-chat\"\n ref={chatRef}\n >\n <div className=\"flex min-h-12 shrink-0 items-center gap-2 border-b ps-4 pe-2\">\n <h2 className=\"font-semibold text-base\" id={titleId}>\n {labels.assistant}\n </h2>\n <div className=\"ms-auto flex items-center gap-1\">\n {running ? (\n <Button onClick={onStop} size=\"sm\" variant=\"outline\">\n <StopIcon aria-hidden=\"true\" />\n {labels.stop}\n </Button>\n ) : null}\n <Button\n aria-label={labels.collapse}\n onClick={onCollapse}\n size=\"icon-sm\"\n variant=\"ghost\"\n >\n <MinusIcon aria-hidden=\"true\" />\n </Button>\n </div>\n </div>\n {turns.length === 0 ? (\n <div\n className=\"min-h-0 flex-1 overflow-y-auto px-4\"\n data-slot=\"assistant-chat-empty\"\n >\n <ChatEmptyState\n description={labels.emptyDescription}\n icon={<SparkleIcon aria-hidden=\"true\" />}\n title={labels.emptyTitle}\n >\n <fieldset\n className=\"flex w-full min-w-0 flex-col gap-1.5\"\n data-slot=\"assistant-tasks\"\n >\n <legend className=\"sr-only\">{labels.tasksGroup}</legend>\n {matchOrder.map((task) => taskButton(task, true))}\n </fieldset>\n </ChatEmptyState>\n </div>\n ) : (\n <ChatConversation\n jumpLabel={labels.jump}\n label={labels.conversation}\n scroll={scroll}\n >\n <div className=\"flex flex-col gap-4 pt-4\">\n {turns.map((turn, index) => {\n const live = index === turns.length - 1\n const turnRun =\n turn.kind === 'task' ? (turn.run ?? (live ? run : null)) : null\n return (\n <div\n className=\"flex flex-col gap-3\"\n data-slot=\"assistant-turn\"\n key={turn.id}\n >\n <ChatMessage side=\"outgoing\">{turn.prompt}</ChatMessage>\n {turn.kind === 'fallback' ? (\n <ChatMessage\n author={labels.assistant}\n avatar={<AssistantAvatar />}\n side=\"incoming\"\n >\n <fieldset\n className=\"flex min-w-0 flex-col gap-2\"\n data-slot=\"assistant-fallback\"\n >\n <legend className=\"mb-2\">\n {labels.fallback(turn.fallback)}\n </legend>\n <div className=\"flex flex-wrap gap-2\">\n {fallbackTasks.map((task) => taskButton(task, false))}\n </div>\n </fieldset>\n </ChatMessage>\n ) : turnRun ? (\n <ChatMessage\n author={labels.assistant}\n avatar={<AssistantAvatar />}\n bubble={false}\n side=\"incoming\"\n >\n <div\n className=\"flex min-w-0 flex-col gap-3 text-sm\"\n data-slot=\"assistant-reply\"\n >\n {live ? (\n <output\n aria-live=\"polite\"\n data-slot=\"assistant-status\"\n >\n {statusText(turnRun, labels)}\n </output>\n ) : (\n <p>{statusText(turnRun, labels)}</p>\n )}\n <StepTrace label={labels.steps} run={turnRun} />\n <Findings\n activeFindingId={activeFindingId}\n labels={labels}\n onFinding={onFinding}\n run={turnRun}\n />\n {turn.id === reviewTurnId &&\n (changes.length > 0 || props.canUndo) ? (\n <Review {...props} />\n ) : null}\n </div>\n </ChatMessage>\n ) : null}\n </div>\n )\n })}\n <ChatTypingIndicator label={labels.typing} visible={running} />\n </div>\n </ChatConversation>\n )}\n <div className=\"flex shrink-0 flex-col gap-2 px-3 pt-2 pb-3\">\n {passage ? (\n <div\n className=\"flex items-center gap-2 rounded-lg border bg-muted/40 py-1 ps-3 pe-1 text-sm\"\n data-slot=\"assistant-passage\"\n >\n <span className=\"min-w-0 flex-1 truncate\">\n {labels.passage(passage.text)}\n </span>\n <Button\n aria-label={labels.clearPassage}\n onClick={onClearPassage}\n size=\"icon-sm\"\n variant=\"ghost\"\n >\n <XIcon aria-hidden=\"true\" />\n </Button>\n </div>\n ) : null}\n <Composer\n data-slot=\"assistant-composer\"\n onAction={(item) => {\n if (isTask(item.id)) onRun(item.id)\n }}\n onSubmit={(value: ComposerValue) => {\n const text = getComposerText(value).trim()\n if (!text || running) return\n setDraft([])\n scroll.atBottomRef.current = true\n onRequest(text)\n }}\n onValueChange={setDraft}\n submitDisabled={running}\n triggers={triggers}\n value={draft}\n >\n <ComposerInput\n aria-label={labels.request}\n className=\"data-empty:before:text-muted-foreground\"\n placeholder={labels.requestPlaceholder}\n />\n <ComposerPopup>\n <ComposerList>\n {(item) => (\n <ComposerItem key={item.id} value={item}>\n {item.icon}\n {item.label}\n </ComposerItem>\n )}\n </ComposerList>\n </ComposerPopup>\n <ComposerActions>\n <ComposerActionGroup>\n <TaskMenuButton label={labels.taskMenu} />\n </ComposerActionGroup>\n <ComposerActionGroup align=\"end\">\n <ComposerSubmit\n render={\n <Button aria-label={labels.send} size=\"icon-sm\">\n <ArrowUpIcon aria-hidden=\"true\" />\n </Button>\n }\n />\n </ComposerActionGroup>\n </ComposerActions>\n </Composer>\n </div>\n </section>\n )\n}\n",
|
|
9
|
+
"target": "~/packages/ui/src/blocks/application/rich-text-editor/rich-text-editor-5/assistant-chat.tsx"
|
|
10
|
+
},
|
|
11
|
+
{
|
|
12
|
+
"path": "blocks/application/rich-text-editor/rich-text-editor-5/document-text.ts",
|
|
13
|
+
"type": "registry:file",
|
|
14
|
+
"content": "import type { RichTextEditorInstance } from '@tc96/ui/patterns/rich-text-editor'\nimport type { Path, TRange } from 'platejs'\n\ntype AnyNode = { [key: string]: unknown }\n\nexport interface TextBlock {\n path: Path\n segments: { length: number; path: Path; start: number }[]\n text: string\n}\n\nconst isText = (node: AnyNode): node is AnyNode & { text: string } =>\n typeof node.text === 'string'\n\nconst isRemoved = (leaf: AnyNode) =>\n Object.entries(leaf).some(\n ([key, value]) =>\n key.startsWith('suggestion_') &&\n typeof value === 'object' &&\n value !== null &&\n (value as { type?: string }).type === 'remove',\n )\n\nfunction collect(\n nodes: readonly AnyNode[],\n base: Path,\n into: TextBlock[],\n): void {\n nodes.forEach((node, index) => {\n if (isText(node)) return\n const path = [...base, index]\n const children = (node.children ?? []) as AnyNode[]\n if (children.length > 0 && children.every(isText)) {\n const block: TextBlock = { path, segments: [], text: '' }\n children.forEach((leaf, leafIndex) => {\n if (!isText(leaf) || isRemoved(leaf)) return\n block.segments.push({\n length: leaf.text.length,\n path: [...path, leafIndex],\n start: block.text.length,\n })\n block.text += leaf.text\n })\n into.push(block)\n return\n }\n collect(children, path, into)\n })\n}\n\nexport function textBlocks(nodes: readonly unknown[]): TextBlock[] {\n const into: TextBlock[] = []\n collect(nodes as AnyNode[], [], into)\n return into\n}\n\nexport function documentLines(editor: RichTextEditorInstance): string[] {\n return textBlocks(editor.children).map((block) => block.text)\n}\n\nexport function passageLines(\n editor: RichTextEditorInstance,\n range: TRange,\n): string[] {\n const fragment = editor.api.fragment(range) as unknown as AnyNode[]\n return textBlocks(fragment)\n .map((block) => block.text)\n .filter((line) => line.length > 0)\n}\n",
|
|
15
|
+
"target": "~/packages/ui/src/blocks/application/rich-text-editor/rich-text-editor-5/document-text.ts"
|
|
16
|
+
},
|
|
17
|
+
{
|
|
18
|
+
"path": "blocks/application/rich-text-editor/rich-text-editor-5/index.ts",
|
|
19
|
+
"type": "registry:file",
|
|
20
|
+
"content": "export { planAction } from './planner'\nexport type { RichTextEditor5PlannerData } from './planner-data'\nexport { RichTextEditor5 } from './rich-text-editor-5'\nexport type {\n RichTextEditor5Author,\n RichTextEditor5Change,\n RichTextEditor5Decision,\n RichTextEditor5Edit,\n RichTextEditor5Finding,\n RichTextEditor5FindingKind,\n RichTextEditor5Labels,\n RichTextEditor5NavbarContext,\n RichTextEditor5Plan,\n RichTextEditor5PlanEvent,\n RichTextEditor5Planner,\n RichTextEditor5Props,\n RichTextEditor5Request,\n RichTextEditor5Step,\n RichTextEditor5StepKind,\n RichTextEditor5Task,\n} from './types'\n",
|
|
21
|
+
"target": "~/packages/ui/src/blocks/application/rich-text-editor/rich-text-editor-5/index.ts"
|
|
22
|
+
},
|
|
23
|
+
{
|
|
24
|
+
"path": "blocks/application/rich-text-editor/rich-text-editor-5/labels.ts",
|
|
25
|
+
"type": "registry:file",
|
|
26
|
+
"content": "import type { RichTextEditor5Labels } from './types'\n\nconst plural = (count: number, one: string, many: string) =>\n `${count} ${count === 1 ? one : many}`\n\nexport const defaultRichTextEditor5Labels: RichTextEditor5Labels = {\n acceptAll: 'Aceitar tudo',\n assistant: 'Assistente',\n bubble: 'Ações para o trecho selecionado',\n bubbleAsk: 'Pedir ao assistente',\n bubbleSpelling: 'Corrigir ortografia',\n bubbleSummary: 'Resumir',\n clearPassage: 'Remover trecho selecionado',\n collapse: 'Recolher assistente',\n conversation: 'Conversa com o assistente',\n dock: 'Assistente de escrita',\n document: 'Plano de lançamento',\n done: (edits, findings) =>\n findings > 0\n ? `Pronto: ${plural(findings, 'achado', 'achados')}, nenhuma alteração no texto.`\n : edits > 0\n ? `Pronto: ${plural(edits, 'sugestão escrita', 'sugestões escritas')} no texto.`\n : 'Pronto: não havia nada para sugerir.',\n emptyDescription:\n 'Escolha uma tarefa ou digite / no campo abaixo. As alterações entram no texto como sugestões para você aceitar ou rejeitar.',\n emptyTitle: 'Como posso ajudar no plano?',\n failed: 'A tarefa falhou. Nada foi alterado além das sugestões já escritas.',\n fallback: (request) =>\n `Não entendi “${request}”. Experimente uma destas tarefas:`,\n findingKinds: {\n owner: 'Responsável',\n question: 'Pergunta',\n tbd: 'A definir',\n },\n findings: 'Achados',\n findingsEmpty: 'Nada encontrado no texto.',\n goTo: 'Ir para o trecho',\n goToFinding: (finding) => `Ir para o trecho: ${finding.text}`,\n jump: 'Ir para a mais recente',\n next: 'Próxima sugestão',\n passage: (text) => `Trecho: ${text}`,\n pending: (count) =>\n plural(count, 'sugestão para revisar', 'sugestões para revisar'),\n position: (current, total) => `${current} de ${total}`,\n previous: 'Sugestão anterior',\n rejectAll: 'Rejeitar tudo',\n request: 'Peça algo ao assistente',\n requestPlaceholder: 'Peça algo, por exemplo “enxugue o texto”',\n review: {\n accept: 'Aceitar',\n acceptChange: (change) =>\n `Aceitar sugestão de ${change.author.name}: ${change.after || change.before}`,\n empty: 'Nenhuma sugestão para revisar.',\n kind: { delete: 'Exclusão', insert: 'Inserção', replace: 'Substituição' },\n list: 'Sugestões do assistente',\n now: 'Depois',\n reject: 'Rejeitar',\n rejectChange: (change) =>\n `Rejeitar sugestão de ${change.author.name}: ${change.after || change.before}`,\n was: 'Antes',\n },\n reviewTitle: 'Revisão das sugestões',\n running: (task) => `Trabalhando: ${task}`,\n send: 'Enviar pedido',\n steps: 'Etapas da tarefa',\n stop: 'Parar',\n stopped: (edits) =>\n `Interrompido: ${plural(edits, 'sugestão mantida', 'sugestões mantidas')} no texto.`,\n tasks: {\n checklist: 'Adicionar checklist',\n owners: 'Listar responsáveis',\n questions: 'Listar perguntas em aberto',\n spelling: 'Corrigir ortografia',\n summary: 'Escrever resumo',\n tighten: 'Enxugar o texto',\n },\n taskMenu: 'Escolher uma tarefa',\n tasksGroup: 'Tarefas do assistente',\n typing: 'O assistente está trabalhando',\n undo: 'Desfazer última decisão',\n}\n",
|
|
27
|
+
"target": "~/packages/ui/src/blocks/application/rich-text-editor/rich-text-editor-5/labels.ts"
|
|
28
|
+
},
|
|
29
|
+
{
|
|
30
|
+
"path": "blocks/application/rich-text-editor/rich-text-editor-5/planner-data.ts",
|
|
31
|
+
"type": "registry:file",
|
|
32
|
+
"content": "import type { RichTextEditor5Task } from './types'\n\nexport interface RichTextEditor5PlannerData {\n checklist: readonly string[]\n keywords: Record<RichTextEditor5Task, readonly string[]>\n rewrites: readonly { from: string; to: string }[]\n summary: string\n teammates: readonly string[]\n typos: Readonly<Record<string, string>>\n}\n\nexport const defaultPlannerData: RichTextEditor5PlannerData = {\n checklist: [\n 'Migrar os artigos da central antiga',\n 'Validar os fluxos de busca com o suporte',\n 'Revisar os textos jurídicos',\n 'Comunicar o piloto aos clientes',\n ],\n keywords: {\n checklist: ['checklist', 'lista de verificacao', 'passos', 'tarefas'],\n owners: ['responsavel', 'responsaveis', 'dono', 'quem cuida', 'owner'],\n questions: ['pergunta', 'duvida', 'pendencia', 'em aberto', 'questoes'],\n spelling: [\n 'ortografia',\n 'corrig',\n 'typo',\n 'erro de digitacao',\n 'gramatica',\n ],\n summary: ['resum', 'sintese', 'sumario', 'tldr'],\n tighten: ['enxug', 'conciso', 'concis', 'encurt', 'reescrev', 'direto'],\n },\n rewrites: [\n { from: 'em virtude do fato de que', to: 'porque' },\n { from: 'no sentido de realizar a migração', to: 'para migrar' },\n ],\n summary:\n 'Resumo: a nova central de ajuda entra no ar em três ondas, começa por um piloto com clientes selecionados e depende da migração dos artigos e da validação do suporte.',\n teammates: ['Marina', 'Rafael', 'Camila', 'Diego'],\n typos: {\n implantaçao: 'implantação',\n priorirdade: 'prioridade',\n recebimeto: 'recebimento',\n responsavel: 'responsável',\n validaçao: 'validação',\n },\n}\n\nexport const stepText = {\n editing: (count: number) =>\n `Escrevendo ${count === 1 ? '1 sugestão' : `${count} sugestões`} no texto`,\n planning: (task: string) => `Entendendo o pedido: ${task}`,\n readingDocument: (lines: number) =>\n `Lendo o documento (${lines === 1 ? '1 trecho' : `${lines} trechos`})`,\n readingPassage: 'Lendo o trecho selecionado',\n reviewing: {\n checklist: 'Montando a lista de tarefas do lançamento',\n owners: 'Procurando tarefas com responsável',\n questions: 'Procurando perguntas e pontos a definir',\n spelling: 'Conferindo cada palavra com os erros conhecidos',\n summary: 'Condensando as ideias principais',\n tighten: 'Procurando trechos que podem ficar mais curtos',\n } satisfies Record<RichTextEditor5Task, string>,\n}\n",
|
|
33
|
+
"target": "~/packages/ui/src/blocks/application/rich-text-editor/rich-text-editor-5/planner-data.ts"
|
|
34
|
+
},
|
|
35
|
+
{
|
|
36
|
+
"path": "blocks/application/rich-text-editor/rich-text-editor-5/planner.ts",
|
|
37
|
+
"type": "registry:file",
|
|
38
|
+
"content": "import {\n defaultPlannerData,\n type RichTextEditor5PlannerData,\n stepText,\n} from './planner-data'\nimport type {\n RichTextEditor5Edit,\n RichTextEditor5Finding,\n RichTextEditor5Plan,\n RichTextEditor5Planner,\n RichTextEditor5Step,\n RichTextEditor5StepKind,\n RichTextEditor5Task,\n} from './types'\n\nconst taskNames: Record<RichTextEditor5Task, string> = {\n checklist: 'adicionar um checklist',\n owners: 'listar responsáveis',\n questions: 'listar perguntas em aberto',\n spelling: 'corrigir a ortografia',\n summary: 'escrever um resumo',\n tighten: 'enxugar o texto',\n}\n\nexport const matchOrder: readonly RichTextEditor5Task[] = [\n 'spelling',\n 'tighten',\n 'summary',\n 'checklist',\n 'questions',\n 'owners',\n]\n\nexport const selectionTasks: readonly RichTextEditor5Task[] = [\n 'spelling',\n 'tighten',\n 'summary',\n]\n\nexport const fallbackTasks: readonly RichTextEditor5Task[] = [\n 'spelling',\n 'tighten',\n 'summary',\n]\n\nconst normalize = (value: string) =>\n value.normalize('NFD').replace(/[̀-ͯ]/g, '').toLowerCase()\n\nexport function matchTask(\n request: string,\n data: RichTextEditor5PlannerData = defaultPlannerData,\n): RichTextEditor5Task | null {\n const text = normalize(request)\n let best: RichTextEditor5Task | null = null\n let bestHits = 0\n for (const task of matchOrder) {\n const hits = data.keywords[task].filter((word) =>\n text.includes(word),\n ).length\n if (hits > bestHits) {\n best = task\n bestHits = hits\n }\n }\n return best\n}\n\nconst escapePattern = (value: string) =>\n value.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')\n\nconst wordPattern = (word: string, flags = 'gu') =>\n new RegExp(`(?<![\\\\p{L}])${escapePattern(word)}(?![\\\\p{L}])`, flags)\n\nconst step = (\n task: RichTextEditor5Task,\n index: number,\n kind: RichTextEditor5StepKind,\n text: string,\n): RichTextEditor5Step => ({ id: `${task}-${index}`, kind, text })\n\nconst sentencesOf = (line: string) =>\n (line.match(/[^.!?]+[.!?]?/g) ?? [])\n .map((part) => part.trim())\n .filter(Boolean)\n\nfunction spellingEdits(\n lines: readonly string[],\n data: RichTextEditor5PlannerData,\n): RichTextEditor5Edit[] {\n const edits: RichTextEditor5Edit[] = []\n for (const [typo, fix] of Object.entries(data.typos)) {\n const hits = lines.join('\\n').match(wordPattern(typo)) ?? []\n for (let index = 0; index < hits.length; index += 1)\n edits.push({ find: typo, text: fix, type: 'replace' })\n }\n return edits\n}\n\nfunction tightenEdits(\n lines: readonly string[],\n data: RichTextEditor5PlannerData,\n): RichTextEditor5Edit[] {\n const edits: RichTextEditor5Edit[] = []\n for (const { from, to } of data.rewrites) {\n const hits = lines.join('\\n').split(from).length - 1\n for (let index = 0; index < hits; index += 1)\n edits.push({ find: from, text: to, type: 'replace' })\n }\n return edits\n}\n\nfunction summaryEdits(\n lines: readonly string[],\n scoped: boolean,\n data: RichTextEditor5PlannerData,\n): RichTextEditor5Edit[] {\n if (!scoped)\n return [\n {\n after: lines[0] ?? '',\n block: 'p',\n text: data.summary,\n type: 'add-block',\n },\n ]\n const last = [...lines].reverse().find((line) => line.trim().length > 0)\n const first = lines.find((line) => line.trim().length > 0)\n if (!last || !first) return []\n const sentence = sentencesOf(first)[0] ?? first\n const clipped =\n sentence.length > 90 ? `${sentence.slice(0, 87)}...` : sentence\n return [\n {\n after: last.slice(-30),\n text: ` Resumindo: ${clipped}`,\n type: 'insert',\n },\n ]\n}\n\nfunction checklistEdits(\n lines: readonly string[],\n data: RichTextEditor5PlannerData,\n): RichTextEditor5Edit[] {\n const last = lines.at(-1)\n return data.checklist.map((text, index) => {\n const anchor = index === 0 ? last : data.checklist[index - 1]\n return {\n ...(anchor ? { after: anchor } : {}),\n block: 'action_item' as const,\n text,\n type: 'add-block' as const,\n }\n })\n}\n\nfunction questionFindings(lines: readonly string[]): RichTextEditor5Finding[] {\n const found: RichTextEditor5Finding[] = []\n for (const line of lines)\n for (const sentence of sentencesOf(line)) {\n const tbd = /\\b(TBD|a definir|a confirmar|a combinar)\\b/i.test(sentence)\n if (!tbd && !sentence.endsWith('?')) continue\n found.push({\n id: `${tbd ? 'tbd' : 'question'}-${found.length + 1}`,\n kind: tbd ? 'tbd' : 'question',\n quote: sentence,\n text: sentence,\n })\n }\n return found\n}\n\nfunction ownerFindings(\n lines: readonly string[],\n data: RichTextEditor5PlannerData,\n): RichTextEditor5Finding[] {\n const found: RichTextEditor5Finding[] = []\n for (const line of lines)\n for (const name of data.teammates) {\n const acts = new RegExp(\n `${escapePattern(name)}[^.]*\\\\b(fica|cuida|valida|revisa|entrega|prepara|aprova|publica|conduz|lidera|responde)`,\n 'u',\n )\n const owns = new RegExp(`respons[aá]vel[^.]*${escapePattern(name)}`, 'iu')\n if (!acts.test(line) && !owns.test(line)) continue\n found.push({\n id: `owner-${found.length + 1}`,\n kind: 'owner',\n quote: line,\n text: `${name}: ${line}`,\n })\n break\n }\n return found\n}\n\nexport function planAction(\n task: RichTextEditor5Task,\n source: string,\n scoped = false,\n data: RichTextEditor5PlannerData = defaultPlannerData,\n): RichTextEditor5Plan {\n const lines = source.split('\\n')\n const edits: RichTextEditor5Edit[] =\n task === 'spelling'\n ? spellingEdits(lines, data)\n : task === 'tighten'\n ? tightenEdits(lines, data)\n : task === 'summary'\n ? summaryEdits(lines, scoped, data)\n : task === 'checklist'\n ? checklistEdits(lines, data)\n : []\n const findings =\n task === 'questions'\n ? questionFindings(lines)\n : task === 'owners'\n ? ownerFindings(lines, data)\n : []\n const steps: RichTextEditor5Step[] = [\n step(task, 1, 'planning', stepText.planning(taskNames[task])),\n step(\n task,\n 2,\n 'reading',\n scoped\n ? stepText.readingPassage\n : stepText.readingDocument(lines.filter(Boolean).length),\n ),\n step(task, 3, 'reviewing', stepText.reviewing[task]),\n ]\n if (edits.length > 0)\n steps.push(step(task, 4, 'editing', stepText.editing(edits.length)))\n return { edits, findings, steps }\n}\n\nexport const defaultPlanner: RichTextEditor5Planner = (request) =>\n planAction(\n request.task,\n request.selection ?? request.text,\n request.selection !== null,\n )\n",
|
|
39
|
+
"target": "~/packages/ui/src/blocks/application/rich-text-editor/rich-text-editor-5/planner.ts"
|
|
40
|
+
},
|
|
41
|
+
{
|
|
42
|
+
"path": "blocks/application/rich-text-editor/rich-text-editor-5/rich-text-editor-5.tsx",
|
|
43
|
+
"type": "registry:file",
|
|
44
|
+
"content": "'use client'\n\nimport { SparkleIcon } from '@phosphor-icons/react'\nimport {\n CodePlugin,\n HighlightPlugin,\n StrikethroughPlugin,\n} from '@platejs/basic-nodes/react'\nimport { SlashPlugin } from '@platejs/slash-command/react'\nimport { Badge } from '@tc96/ui/badge'\nimport { Button } from '@tc96/ui/button'\nimport {\n RichTextEditor,\n useRichTextEditor,\n} from '@tc96/ui/patterns/rich-text-editor'\nimport { cn } from '@tc96/utils'\nimport type { TRange } from 'platejs'\nimport { RangeApi } from 'platejs'\nimport { useEditorSelector } from 'platejs/react'\nimport { useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react'\nimport {\n acceptAll,\n acceptSuggestion,\n createSuggestionKit,\n goTo,\n rejectAll,\n rejectSuggestion,\n setActiveSuggestion,\n useSuggestionState,\n useSuggestions,\n} from '../shared/suggestions'\nimport { AssistantChat, type AssistantTurn } from './assistant-chat'\nimport { passageLines } from './document-text'\nimport { defaultRichTextEditor5Labels } from './labels'\nimport { defaultPlanner, matchTask, selectionTasks } from './planner'\nimport { SelectionBubble } from './selection-bubble'\nimport type {\n RichTextEditor5Finding,\n RichTextEditor5Labels,\n RichTextEditor5NavbarContext,\n RichTextEditor5Props,\n RichTextEditor5Task,\n} from './types'\nimport { type Passage, useAssistantRun } from './use-assistant-run'\nimport { caretPosition, jumpToText, pruneEmptyBlocks } from './write-edit'\n\nconst assistantId = 'assistente'\n\nfunction SelectionWatcher({\n onSelection,\n}: Readonly<{ onSelection: (selection: TRange | null) => void }>) {\n const selection = useEditorSelector((editor) => editor.selection, [])\n useEffect(() => onSelection(selection), [selection, onSelection])\n return null\n}\n\nexport function RichTextEditor5({\n author,\n className,\n defaultValue,\n formatTime,\n labels: labelsProp,\n navbar,\n onChange,\n onDecision,\n planner = defaultPlanner,\n stepDelay = 450,\n}: Readonly<RichTextEditor5Props>) {\n const labels: RichTextEditor5Labels = {\n ...defaultRichTextEditor5Labels,\n ...labelsProp,\n findingKinds: {\n ...defaultRichTextEditor5Labels.findingKinds,\n ...labelsProp?.findingKinds,\n },\n review: {\n ...defaultRichTextEditor5Labels.review,\n ...labelsProp?.review,\n kind: {\n ...defaultRichTextEditor5Labels.review.kind,\n ...labelsProp?.review?.kind,\n },\n },\n tasks: { ...defaultRichTextEditor5Labels.tasks, ...labelsProp?.tasks },\n }\n const assistant = useMemo(\n () => ({ id: assistantId, name: labels.assistant }),\n [labels.assistant],\n )\n const roster = useMemo(() => [author, assistant], [author, assistant])\n const editor = useRichTextEditor({\n defaultValue,\n features: {\n plugins: [\n ...createSuggestionKit({ author, suggesting: false }),\n StrikethroughPlugin.configure({ enabled: false }),\n CodePlugin.configure({ enabled: false }),\n HighlightPlugin.configure({ enabled: false }),\n SlashPlugin.configure({ enabled: false }),\n ],\n },\n })\n const changes = useSuggestions(editor, roster)\n const { activeId } = useSuggestionState(editor)\n const { caret, created, run, start, stop } = useAssistantRun({\n assistant,\n author,\n editor,\n planner,\n stepDelay,\n })\n const [selection, setSelection] = useState<TRange | null>(null)\n const [focused, setFocused] = useState(false)\n const [passage, setPassage] = useState<Passage | null>(null)\n const [canUndo, setCanUndo] = useState(false)\n const [activeFindingId, setActiveFindingId] = useState<string | null>(null)\n const [caretBox, setCaretBox] = useState<{\n height: number\n left: number\n top: number\n } | null>(null)\n const [turns, setTurns] = useState<AssistantTurn[]>([])\n const [assistantOpen, setAssistantOpen] = useState(true)\n const [composerFocus, setComposerFocus] = useState(0)\n const surface = useRef<HTMLDivElement>(null)\n const chat = useRef<HTMLElement>(null)\n const turnCount = useRef(0)\n const running = run?.status === 'running'\n\n useEffect(() => {\n const element = surface.current\n if (!element) return\n const focusIn = () => setFocused(true)\n const focusOut = (event: FocusEvent) => {\n if (!element.contains(event.relatedTarget as Node | null))\n setFocused(false)\n }\n element.addEventListener('focusin', focusIn)\n element.addEventListener('focusout', focusOut)\n return () => {\n element.removeEventListener('focusin', focusIn)\n element.removeEventListener('focusout', focusOut)\n }\n }, [])\n\n useLayoutEffect(() => {\n if (!running || !caret || !surface.current) {\n setCaretBox(null)\n return\n }\n const frame = requestAnimationFrame(() => {\n if (surface.current)\n setCaretBox(caretPosition(editor, caret, surface.current))\n })\n return () => cancelAnimationFrame(frame)\n }, [caret, editor, running])\n\n const bubbleRange =\n selection && RangeApi.isExpanded(selection) && focused && !running\n ? selection\n : null\n\n const passageFrom = (range: TRange): Passage | null => {\n const text = passageLines(editor, range).join(' ').trim()\n return text ? { range, text } : null\n }\n\n const addTurn = (\n turn:\n | { fallback: string; kind: 'fallback'; prompt: string }\n | { kind: 'task'; prompt: string },\n ) => {\n turnCount.current += 1\n const id = `turn-${turnCount.current}`\n setTurns((current) => [\n ...current.map((previous, index) =>\n index === current.length - 1 &&\n previous.kind === 'task' &&\n !previous.run\n ? { ...previous, run: run ?? undefined }\n : previous,\n ),\n { ...turn, id },\n ])\n }\n\n const run1 = (\n task: RichTextEditor5Task,\n from: Passage | null,\n prompt: string = labels.tasks[task],\n ) => {\n const scoped = from && selectionTasks.includes(task) ? from : null\n addTurn({ kind: 'task', prompt })\n setCanUndo(false)\n setActiveFindingId(null)\n if (!scoped) setPassage(null)\n void start(task, scoped)\n }\n\n const fromBubble = (task: RichTextEditor5Task) => {\n const from = bubbleRange ? passageFrom(bubbleRange) : null\n setPassage(from)\n run1(task, from)\n }\n\n const handOff = () => {\n const from = bubbleRange ? passageFrom(bubbleRange) : null\n if (!from) return\n setPassage(from)\n setAssistantOpen(true)\n setComposerFocus((count) => count + 1)\n }\n\n useEffect(() => {\n if (composerFocus === 0) return\n chat.current\n ?.querySelector<HTMLElement>('[data-slot=\"composer-input\"]')\n ?.focus()\n }, [composerFocus])\n\n const request = (text: string) => {\n const task = matchTask(text)\n if (!task) {\n addTurn({ fallback: text, kind: 'fallback', prompt: text })\n return\n }\n run1(task, passage, text)\n }\n\n const decide = (id: string, action: 'accept' | 'reject') => {\n const change = changes.find((candidate) => candidate.id === id)\n editor.tf.withNewBatch(() => {\n if (action === 'accept') acceptSuggestion(editor, id)\n else {\n rejectSuggestion(editor, id)\n pruneEmptyBlocks(editor, created)\n }\n })\n if (id === activeId) setActiveSuggestion(editor, null)\n setCanUndo(true)\n if (change) onDecision?.({ action, change })\n }\n\n const decideAll = (action: 'accept' | 'reject') => {\n const snapshot = [...changes]\n editor.tf.withNewBatch(() => {\n if (action === 'accept') acceptAll(editor)\n else {\n rejectAll(editor)\n pruneEmptyBlocks(editor, created)\n }\n })\n setActiveSuggestion(editor, null)\n setCanUndo(true)\n onDecision?.({ action: `${action}-all`, changes: snapshot })\n }\n\n const undo = () => {\n editor.undo()\n setActiveSuggestion(editor, null)\n setCanUndo(false)\n }\n\n const step = (direction: 1 | -1) => {\n if (changes.length === 0) return\n const index = changes.findIndex((change) => change.id === activeId)\n const next =\n index < 0\n ? direction === 1\n ? 0\n : changes.length - 1\n : (index + direction + changes.length) % changes.length\n const target = changes[next]\n if (target) goTo(editor, target.id)\n }\n\n const jump = (finding: RichTextEditor5Finding) => {\n setActiveFindingId(finding.id)\n jumpToText(editor, finding.quote)\n }\n\n const context: RichTextEditor5NavbarContext = {\n pending: changes.length,\n running,\n status:\n running || changes.length > 0 ? (\n <Badge data-slot=\"assistant-navbar-status\" variant=\"secondary\">\n {running && run\n ? labels.running(labels.tasks[run.task])\n : labels.pending(changes.length)}\n </Badge>\n ) : null,\n }\n const navbarNode = typeof navbar === 'function' ? navbar(context) : navbar\n\n return (\n <div\n className={cn(\n 'relative flex h-svh w-full flex-col overflow-hidden bg-background text-foreground',\n className,\n )}\n data-slot=\"rich-text-editor-5\"\n >\n {navbarNode}\n <div\n className=\"min-h-0 flex-1 overflow-y-auto px-6 pt-10 pb-24 sm:px-12\"\n data-slot=\"rich-text-editor-5-scroll\"\n >\n <div className=\"relative mx-auto max-w-3xl\" ref={surface}>\n <RichTextEditor\n aria-label={labels.document}\n contentClassName=\"min-h-96 leading-7\"\n editor={editor}\n floatingToolbar={false}\n onValueChange={onChange}\n >\n <SelectionWatcher onSelection={setSelection} />\n </RichTextEditor>\n {caretBox ? (\n <div\n aria-hidden=\"true\"\n className=\"pointer-events-none absolute z-10 w-0.5 bg-primary\"\n data-slot=\"assistant-caret\"\n style={{\n height: caretBox.height,\n left: caretBox.left,\n top: caretBox.top,\n }}\n >\n <span className=\"absolute bottom-full start-0 whitespace-nowrap rounded-sm bg-primary px-1.5 py-0.5 text-primary-foreground text-xs\">\n {labels.assistant}\n </span>\n </div>\n ) : null}\n </div>\n </div>\n {assistantOpen ? (\n <aside\n aria-label={labels.dock}\n className=\"absolute end-4 bottom-4 z-20 flex h-[min(36rem,calc(100%-5rem))] w-[min(24rem,calc(100%-2rem))] flex-col overflow-hidden rounded-2xl border bg-popover text-popover-foreground shadow-lg/10\"\n data-slot=\"assistant-dock\"\n >\n <AssistantChat\n activeFindingId={activeFindingId}\n activeId={activeId}\n canUndo={canUndo}\n changes={changes}\n chatRef={chat}\n formatTime={formatTime}\n labels={labels}\n onAccept={(id) => decide(id, 'accept')}\n onAcceptAll={() => decideAll('accept')}\n onClearPassage={() => setPassage(null)}\n onCollapse={() => setAssistantOpen(false)}\n onFinding={jump}\n onReject={(id) => decide(id, 'reject')}\n onRejectAll={() => decideAll('reject')}\n onRequest={request}\n onRun={(task) => run1(task, passage)}\n onSelect={(id) => goTo(editor, id)}\n onStep={step}\n onStop={stop}\n onUndo={undo}\n passage={passage}\n run={run}\n turns={turns}\n />\n </aside>\n ) : (\n <Button\n className=\"absolute end-4 bottom-4 z-20 shadow-lg/10\"\n data-slot=\"assistant-launcher\"\n onClick={() => setAssistantOpen(true)}\n size=\"sm\"\n variant=\"outline\"\n >\n <SparkleIcon aria-hidden=\"true\" />\n {labels.assistant}\n {changes.length > 0 ? (\n <Badge variant=\"secondary\">{changes.length}</Badge>\n ) : null}\n </Button>\n )}\n <SelectionBubble\n editor={editor}\n labels={labels}\n onAsk={handOff}\n onSpelling={() => fromBubble('spelling')}\n onSummary={() => fromBubble('summary')}\n range={bubbleRange}\n />\n </div>\n )\n}\n",
|
|
45
|
+
"target": "~/packages/ui/src/blocks/application/rich-text-editor/rich-text-editor-5/rich-text-editor-5.tsx"
|
|
46
|
+
},
|
|
47
|
+
{
|
|
48
|
+
"path": "blocks/application/rich-text-editor/rich-text-editor-5/selection-bubble.tsx",
|
|
49
|
+
"type": "registry:file",
|
|
50
|
+
"content": "import { SparkleIcon } from '@phosphor-icons/react'\nimport { Button } from '@tc96/ui/button'\nimport type { RichTextEditorInstance } from '@tc96/ui/patterns/rich-text-editor'\nimport type { TRange } from 'platejs'\nimport { type ReactElement, useLayoutEffect, useState } from 'react'\nimport type { RichTextEditor5Labels } from './types'\n\nexport interface SelectionBubbleProps {\n editor: RichTextEditorInstance\n labels: RichTextEditor5Labels\n onAsk: () => void\n onSpelling: () => void\n onSummary: () => void\n range: TRange | null\n}\n\nexport function SelectionBubble({\n editor,\n labels,\n onAsk,\n onSpelling,\n onSummary,\n range,\n}: Readonly<SelectionBubbleProps>): ReactElement | null {\n const [box, setBox] = useState<{ left: number; top: number } | null>(null)\n\n useLayoutEffect(() => {\n if (!range) {\n setBox(null)\n return\n }\n const update = () => {\n const rect = editor.api.toDOMRange(range)?.getBoundingClientRect()\n setBox(\n rect && (rect.width > 0 || rect.height > 0)\n ? { left: rect.left + rect.width / 2, top: rect.top }\n : null,\n )\n }\n update()\n window.addEventListener('scroll', update, true)\n window.addEventListener('resize', update)\n return () => {\n window.removeEventListener('scroll', update, true)\n window.removeEventListener('resize', update)\n }\n }, [editor, range])\n\n if (!range || !box) return null\n const left = Math.min(Math.max(box.left, 150), window.innerWidth - 150)\n return (\n <fieldset\n className=\"-translate-x-1/2 -translate-y-full fixed z-30 flex flex-wrap items-center gap-1 rounded-lg border bg-popover p-1 text-popover-foreground shadow-lg\"\n data-slot=\"selection-bubble\"\n onMouseDown={(event) => event.preventDefault()}\n style={{ left, top: Math.max(box.top - 8, 48) }}\n >\n <legend className=\"sr-only\">{labels.bubble}</legend>\n <Button onClick={onSummary} size=\"sm\" variant=\"ghost\">\n {labels.bubbleSummary}\n </Button>\n <Button onClick={onSpelling} size=\"sm\" variant=\"ghost\">\n {labels.bubbleSpelling}\n </Button>\n <Button onClick={onAsk} size=\"sm\" variant=\"outline\">\n <SparkleIcon aria-hidden=\"true\" />\n {labels.bubbleAsk}\n </Button>\n </fieldset>\n )\n}\n",
|
|
51
|
+
"target": "~/packages/ui/src/blocks/application/rich-text-editor/rich-text-editor-5/selection-bubble.tsx"
|
|
52
|
+
},
|
|
53
|
+
{
|
|
54
|
+
"path": "blocks/application/rich-text-editor/rich-text-editor-5/step-trace.tsx",
|
|
55
|
+
"type": "registry:file",
|
|
56
|
+
"content": "import {\n CheckCircleIcon,\n CircleNotchIcon,\n StopCircleIcon,\n} from '@phosphor-icons/react'\nimport { cn } from '@tc96/utils'\nimport type { ReactElement } from 'react'\nimport type { RunState } from './use-assistant-run'\n\nexport function StepTrace({\n label,\n run,\n}: Readonly<{ label: string; run: RunState }>): ReactElement | null {\n if (run.steps.length === 0) return null\n const lastIndex = run.steps.length - 1\n return (\n <ol\n aria-label={label}\n className=\"flex flex-col gap-1.5 text-sm\"\n data-slot=\"step-trace\"\n >\n {run.steps.map((step, index) => {\n const state =\n index < lastIndex || run.status === 'done'\n ? 'done'\n : run.status === 'running'\n ? 'active'\n : 'stopped'\n return (\n <li\n className={cn(\n 'flex items-center gap-2',\n state === 'active' ? 'text-foreground' : 'text-muted-foreground',\n )}\n data-kind={step.kind}\n data-slot=\"step-trace-item\"\n data-state={state}\n key={step.id}\n >\n {state === 'done' ? (\n <CheckCircleIcon\n aria-hidden=\"true\"\n className=\"size-4 shrink-0 text-success-foreground\"\n />\n ) : state === 'active' ? (\n <CircleNotchIcon\n aria-hidden=\"true\"\n className=\"size-4 shrink-0 animate-spin motion-reduce:animate-none\"\n />\n ) : (\n <StopCircleIcon aria-hidden=\"true\" className=\"size-4 shrink-0\" />\n )}\n <span>{step.text}</span>\n </li>\n )\n })}\n </ol>\n )\n}\n",
|
|
57
|
+
"target": "~/packages/ui/src/blocks/application/rich-text-editor/rich-text-editor-5/step-trace.tsx"
|
|
58
|
+
},
|
|
59
|
+
{
|
|
60
|
+
"path": "blocks/application/rich-text-editor/rich-text-editor-5/types.ts",
|
|
61
|
+
"type": "registry:file",
|
|
62
|
+
"content": "import type { RichTextValue } from '@tc96/ui/patterns/rich-text-editor'\nimport type { ReactNode } from 'react'\nimport type {\n SuggestionAuthor,\n SuggestionChange,\n SuggestionReviewLabels,\n} from '../shared/suggestions'\n\nexport type RichTextEditor5Author = SuggestionAuthor\n\nexport type RichTextEditor5Change = SuggestionChange\n\nexport type RichTextEditor5Task =\n | 'checklist'\n | 'owners'\n | 'questions'\n | 'spelling'\n | 'summary'\n | 'tighten'\n\nexport type RichTextEditor5StepKind =\n | 'editing'\n | 'planning'\n | 'reading'\n | 'reviewing'\n\nexport interface RichTextEditor5Step {\n id: string\n kind: RichTextEditor5StepKind\n text: string\n}\n\nexport type RichTextEditor5Edit =\n | { find: string; text: string; type: 'replace' }\n | { after: string; text: string; type: 'insert' }\n | {\n after?: string\n block: 'action_item' | 'p'\n text: string\n type: 'add-block'\n }\n\nexport type RichTextEditor5FindingKind = 'owner' | 'question' | 'tbd'\n\nexport interface RichTextEditor5Finding {\n id: string\n kind: RichTextEditor5FindingKind\n quote: string\n text: string\n}\n\nexport interface RichTextEditor5Plan {\n edits: readonly RichTextEditor5Edit[]\n findings: readonly RichTextEditor5Finding[]\n steps: readonly RichTextEditor5Step[]\n}\n\nexport type RichTextEditor5PlanEvent =\n | { edit: RichTextEditor5Edit; type: 'edit' }\n | { finding: RichTextEditor5Finding; type: 'finding' }\n | { step: RichTextEditor5Step; type: 'step' }\n\nexport interface RichTextEditor5Request {\n selection: string | null\n signal: AbortSignal\n task: RichTextEditor5Task\n text: string\n}\n\nexport type RichTextEditor5Planner = (\n request: RichTextEditor5Request,\n) =>\n | AsyncIterable<RichTextEditor5PlanEvent>\n | Promise<RichTextEditor5Plan>\n | RichTextEditor5Plan\n\nexport type RichTextEditor5Decision =\n | { action: 'accept' | 'reject'; change: RichTextEditor5Change }\n | { action: 'accept-all' | 'reject-all'; changes: RichTextEditor5Change[] }\n\nexport interface RichTextEditor5Labels {\n acceptAll: string\n assistant: string\n bubble: string\n bubbleAsk: string\n bubbleSpelling: string\n bubbleSummary: string\n clearPassage: string\n collapse: string\n conversation: string\n dock: string\n done: (edits: number, findings: number) => string\n emptyDescription: string\n emptyTitle: string\n failed: string\n fallback: (request: string) => string\n findingKinds: Record<RichTextEditor5FindingKind, string>\n findings: string\n findingsEmpty: string\n goTo: string\n goToFinding: (finding: RichTextEditor5Finding) => string\n jump: string\n next: string\n passage: (text: string) => string\n pending: (count: number) => string\n position: (current: number, total: number) => string\n previous: string\n rejectAll: string\n request: string\n requestPlaceholder: string\n review: SuggestionReviewLabels\n reviewTitle: string\n running: (task: string) => string\n send: string\n steps: string\n stop: string\n stopped: (edits: number) => string\n tasks: Record<RichTextEditor5Task, string>\n taskMenu: string\n tasksGroup: string\n typing: string\n undo: string\n document: string\n}\n\nexport interface RichTextEditor5NavbarContext {\n pending: number\n running: boolean\n status: ReactNode\n}\n\nexport interface RichTextEditor5Props {\n author: RichTextEditor5Author\n className?: string\n defaultValue: RichTextValue\n formatTime?: (date: Date) => string\n labels?: Partial<RichTextEditor5Labels>\n navbar?: ReactNode | ((context: RichTextEditor5NavbarContext) => ReactNode)\n onChange?: (value: RichTextValue) => void\n onDecision?: (decision: RichTextEditor5Decision) => void\n planner?: RichTextEditor5Planner\n stepDelay?: number\n}\n",
|
|
63
|
+
"target": "~/packages/ui/src/blocks/application/rich-text-editor/rich-text-editor-5/types.ts"
|
|
64
|
+
},
|
|
65
|
+
{
|
|
66
|
+
"path": "blocks/application/rich-text-editor/rich-text-editor-5/use-assistant-run.ts",
|
|
67
|
+
"type": "registry:file",
|
|
68
|
+
"content": "import type { RichTextEditorInstance } from '@tc96/ui/patterns/rich-text-editor'\nimport { type Point, RangeApi, type TRange } from 'platejs'\nimport { useCallback, useEffect, useRef, useState } from 'react'\nimport type { SuggestionAuthor } from '../shared/suggestions'\nimport { documentLines, passageLines } from './document-text'\nimport type {\n RichTextEditor5Finding,\n RichTextEditor5Plan,\n RichTextEditor5PlanEvent,\n RichTextEditor5Planner,\n RichTextEditor5Step,\n RichTextEditor5Task,\n} from './types'\nimport { writeEdit } from './write-edit'\n\nexport interface Passage {\n range: TRange\n text: string\n}\n\nexport interface RunState {\n edits: number\n findings: RichTextEditor5Finding[]\n scope: 'document' | 'passage'\n status: 'done' | 'failed' | 'running' | 'stopped'\n steps: RichTextEditor5Step[]\n task: RichTextEditor5Task\n}\n\nconst isAsyncIterable = (\n value: unknown,\n): value is AsyncIterable<RichTextEditor5PlanEvent> =>\n typeof value === 'object' && value !== null && Symbol.asyncIterator in value\n\nasync function* toEvents(\n result:\n | AsyncIterable<RichTextEditor5PlanEvent>\n | Promise<RichTextEditor5Plan>\n | RichTextEditor5Plan,\n): AsyncGenerator<RichTextEditor5PlanEvent> {\n const resolved = await result\n if (isAsyncIterable(resolved)) {\n yield* resolved\n return\n }\n for (const step of resolved.steps) yield { step, type: 'step' }\n for (const edit of resolved.edits) yield { edit, type: 'edit' }\n for (const finding of resolved.findings) yield { finding, type: 'finding' }\n}\n\nfunction pause(ms: number, signal: AbortSignal): Promise<void> {\n return new Promise((resolve) => {\n if (ms <= 0 || signal.aborted) {\n resolve()\n return\n }\n const done = () => {\n clearTimeout(timer)\n signal.removeEventListener('abort', done)\n resolve()\n }\n const timer = setTimeout(done, ms)\n signal.addEventListener('abort', done, { once: true })\n })\n}\n\nexport interface UseAssistantRunOptions {\n assistant: SuggestionAuthor\n author: SuggestionAuthor\n editor: RichTextEditorInstance\n planner: RichTextEditor5Planner\n stepDelay: number\n}\n\nexport function useAssistantRun({\n assistant,\n author,\n editor,\n planner,\n stepDelay,\n}: UseAssistantRunOptions) {\n const [run, setRun] = useState<RunState | null>(null)\n const [caret, setCaret] = useState<Point | null>(null)\n const controller = useRef<AbortController | null>(null)\n const created = useRef(new Set<string>())\n const latest = useRef({ assistant, author, planner, stepDelay })\n latest.current = { assistant, author, planner, stepDelay }\n\n useEffect(() => () => controller.current?.abort(), [])\n\n const start = useCallback(\n async (task: RichTextEditor5Task, passage: Passage | null) => {\n controller.current?.abort()\n const abort = new AbortController()\n controller.current = abort\n const current = () => controller.current === abort\n const ref = passage\n ? editor.api.rangeRef(passage.range, { affinity: 'inward' })\n : null\n const update = (change: (state: RunState) => RunState) => {\n if (current()) setRun((state) => (state ? change(state) : state))\n }\n setRun({\n edits: 0,\n findings: [],\n scope: passage ? 'passage' : 'document',\n status: 'running',\n steps: [],\n task,\n })\n setCaret(\n passage ? RangeApi.end(passage.range) : (editor.api.start([]) ?? null),\n )\n let written = 0\n try {\n const { planner: plan, stepDelay: delay } = latest.current\n const result = plan({\n selection: passage\n ? passageLines(editor, passage.range).join('\\n')\n : null,\n signal: abort.signal,\n task,\n text: documentLines(editor).join('\\n'),\n })\n for await (const event of toEvents(result)) {\n if (abort.signal.aborted) break\n if (event.type === 'step')\n update((state) => ({\n ...state,\n steps: [...state.steps, event.step],\n }))\n else if (event.type === 'finding')\n update((state) => ({\n ...state,\n findings: [...state.findings, event.finding],\n }))\n else {\n const at = writeEdit(editor, event.edit, {\n assistant: latest.current.assistant,\n author: latest.current.author,\n created: created.current,\n within: () => ref?.current ?? null,\n })\n if (at) {\n written += 1\n setCaret(at.focus)\n const edits = written\n update((state) => ({ ...state, edits }))\n }\n }\n await pause(delay, abort.signal)\n }\n update((state) => ({\n ...state,\n status: abort.signal.aborted ? 'stopped' : 'done',\n }))\n } catch {\n update((state) => ({ ...state, status: 'failed' }))\n } finally {\n ref?.unref()\n if (current()) controller.current = null\n }\n },\n [editor],\n )\n\n const stop = useCallback(() => {\n controller.current?.abort()\n }, [])\n\n const clear = useCallback(() => {\n controller.current?.abort()\n controller.current = null\n setRun(null)\n setCaret(null)\n }, [])\n\n return { caret, clear, created: created.current, run, start, stop }\n}\n",
|
|
69
|
+
"target": "~/packages/ui/src/blocks/application/rich-text-editor/rich-text-editor-5/use-assistant-run.ts"
|
|
70
|
+
},
|
|
71
|
+
{
|
|
72
|
+
"path": "blocks/application/rich-text-editor/rich-text-editor-5/write-edit.ts",
|
|
73
|
+
"type": "registry:file",
|
|
74
|
+
"content": "import { getSuggestionKey } from '@platejs/suggestion'\nimport { SuggestionPlugin } from '@platejs/suggestion/react'\nimport type { RichTextEditorInstance } from '@tc96/ui/patterns/rich-text-editor'\nimport { NodeApi, nanoid, type Point, RangeApi, type TRange } from 'platejs'\nimport {\n applyDirectly,\n type SuggestionAuthor,\n setSuggesting,\n} from '../shared/suggestions'\nimport { type TextBlock, textBlocks } from './document-text'\nimport type { RichTextEditor5Edit } from './types'\n\nexport interface WriteContext {\n assistant: SuggestionAuthor\n author: SuggestionAuthor\n created: Set<string>\n within: () => TRange | null\n}\n\nfunction pointAt(block: TextBlock, offset: number, inclusive: boolean): Point {\n for (const segment of block.segments) {\n const end = segment.start + segment.length\n if (offset < end || (inclusive && offset <= end))\n return { offset: offset - segment.start, path: segment.path }\n }\n return { offset: 0, path: [...block.path, 0] }\n}\n\nexport function findRange(\n editor: RichTextEditorInstance,\n needle: string,\n within: TRange | null,\n): TRange | null {\n if (needle.length === 0) return null\n for (const block of textBlocks(editor.children)) {\n let from = block.text.indexOf(needle)\n while (from >= 0) {\n const range: TRange = {\n anchor: pointAt(block, from, false),\n focus: pointAt(block, from + needle.length, true),\n }\n const inside =\n !within ||\n (RangeApi.includes(within, range.anchor) &&\n RangeApi.includes(within, range.focus))\n if (inside) return range\n from = block.text.indexOf(needle, from + 1)\n }\n }\n return null\n}\n\nfunction asAssistant(\n editor: RichTextEditorInstance,\n context: WriteContext,\n write: () => void,\n): void {\n editor.setOption(SuggestionPlugin, 'currentUserId', context.assistant.id)\n setSuggesting(editor, true)\n try {\n write()\n } finally {\n setSuggesting(editor, false)\n editor.setOption(SuggestionPlugin, 'currentUserId', context.author.id)\n }\n}\n\nexport function writeEdit(\n editor: RichTextEditorInstance,\n edit: RichTextEditor5Edit,\n context: WriteContext,\n): TRange | null {\n const within = context.within()\n if (edit.type === 'replace') {\n const range = findRange(editor, edit.find, within)\n if (!range) return null\n editor.tf.select(range)\n asAssistant(editor, context, () => editor.tf.insertText(edit.text))\n return editor.selection\n }\n if (edit.type === 'insert') {\n const range = findRange(editor, edit.after, within)\n if (!range) return null\n editor.tf.select(range.focus)\n asAssistant(editor, context, () => editor.tf.insertText(edit.text))\n return editor.selection\n }\n let top = editor.children.length - 1\n if (edit.after) {\n const anchor = edit.after\n const hit = textBlocks(editor.children).find((block) =>\n block.text.includes(anchor),\n )\n if (hit) top = hit.path[0] ?? top\n }\n const id = nanoid()\n const suggestionId = nanoid()\n const node = {\n children: [\n {\n [getSuggestionKey(suggestionId)]: {\n createdAt: Date.now(),\n id: suggestionId,\n type: 'insert',\n userId: context.assistant.id,\n },\n suggestion: true,\n text: edit.text,\n },\n ],\n id,\n type: edit.block,\n ...(edit.block === 'action_item' ? { checked: false } : {}),\n }\n applyDirectly(editor, () => editor.tf.insertNodes(node, { at: [top + 1] }))\n context.created.add(id)\n const end = editor.api.end([top + 1])\n if (end) editor.tf.select(end)\n return editor.selection\n}\n\nexport function pruneEmptyBlocks(\n editor: RichTextEditorInstance,\n created: Set<string>,\n): void {\n for (let index = editor.children.length - 1; index >= 0; index -= 1) {\n const node = editor.children[index] as { id?: string } | undefined\n if (!node?.id || !created.has(node.id)) continue\n if (NodeApi.string(node as never).length > 0) continue\n applyDirectly(editor, () => editor.tf.removeNodes({ at: [index] }))\n created.delete(node.id)\n }\n}\n\nexport function jumpToText(\n editor: RichTextEditorInstance,\n quote: string,\n): boolean {\n const range = findRange(editor, quote, null)\n if (!range) return false\n editor.tf.focus()\n editor.tf.select(range)\n const dom = editor.api.toDOMRange(range)\n const target = dom?.startContainer.parentElement\n target?.scrollIntoView({ block: 'center' })\n return true\n}\n\nexport function caretPosition(\n editor: RichTextEditorInstance,\n point: Point,\n container: HTMLElement,\n): { height: number; left: number; top: number } | null {\n try {\n const dom = editor.api.toDOMRange({ anchor: point, focus: point })\n if (!dom) return null\n const rect = dom.getClientRects()[0] ?? dom.getBoundingClientRect()\n const box = container.getBoundingClientRect()\n const fallback = dom.startContainer.parentElement?.getBoundingClientRect()\n const source = rect.height > 0 ? rect : fallback\n if (!source) return null\n return {\n height: source.height,\n left: (rect.height > 0 ? rect.left : source.left) - box.left,\n top: source.top - box.top,\n }\n } catch {\n return null\n }\n}\n",
|
|
75
|
+
"target": "~/packages/ui/src/blocks/application/rich-text-editor/rich-text-editor-5/write-edit.ts"
|
|
76
|
+
},
|
|
77
|
+
{
|
|
78
|
+
"path": "blocks/application/rich-text-editor/shared/actions.ts",
|
|
79
|
+
"type": "registry:file",
|
|
80
|
+
"content": "import {\n getSuggestionKey,\n acceptSuggestion as plateAcceptSuggestion,\n rejectSuggestion as plateRejectSuggestion,\n type TResolvedSuggestion,\n} from '@platejs/suggestion'\nimport { SuggestionPlugin } from '@platejs/suggestion/react'\nimport type {\n RichTextEditorInstance,\n RichTextValue,\n} from '@tc96/ui/patterns/rich-text-editor'\nimport { useMemo, useSyncExternalStore } from 'react'\nimport { collectSuggestions } from './collect'\nimport { setActiveSuggestion, subscribe } from './store'\nimport type { SuggestionAuthor, SuggestionChange } from './types'\n\nconst describe = (id: string): TResolvedSuggestion => ({\n createdAt: new Date(),\n keyId: getSuggestionKey(id),\n suggestionId: id,\n type: 'insert',\n userId: '',\n})\n\n/**\n * Runs an edit as a direct change even while the editor is suggesting, so it\n * is not recorded as a new suggestion.\n */\nexport function applyDirectly(\n editor: RichTextEditorInstance,\n edit: () => void,\n): void {\n editor.getApi(SuggestionPlugin).suggestion.withoutSuggestions(edit)\n}\n\n/**\n * Lists the changes of an editor and re-renders when the document changes.\n * Needs the plugins from `createSuggestionKit` on the editor.\n *\n * @param editor - the editor created with `useRichTextEditor`\n * @param authors - known people, to turn a `userId` into a name\n */\nexport function useSuggestions(\n editor: RichTextEditorInstance,\n authors?: readonly SuggestionAuthor[],\n): SuggestionChange[] {\n const children = useSyncExternalStore(\n (listener) => subscribe(editor, listener),\n () => editor.children,\n () => editor.children,\n )\n return useMemo(\n () => collectSuggestions(children as RichTextValue, authors),\n [children, authors],\n )\n}\n\nexport function acceptSuggestion(\n editor: RichTextEditorInstance,\n id: string,\n): void {\n applyDirectly(editor, () => plateAcceptSuggestion(editor, describe(id)))\n}\n\nexport function rejectSuggestion(\n editor: RichTextEditorInstance,\n id: string,\n): void {\n applyDirectly(editor, () => plateRejectSuggestion(editor, describe(id)))\n}\n\nexport function acceptAll(editor: RichTextEditorInstance): void {\n applyDirectly(editor, () => {\n for (const change of collectSuggestions(editor.children as RichTextValue))\n plateAcceptSuggestion(editor, describe(change.id))\n })\n}\n\nexport function rejectAll(editor: RichTextEditorInstance): void {\n applyDirectly(editor, () => {\n for (const change of collectSuggestions(editor.children as RichTextValue))\n plateRejectSuggestion(editor, describe(change.id))\n })\n}\n\n/**\n * Marks a change as the active one and scrolls it into view.\n */\nexport function goTo(editor: RichTextEditorInstance, id: string): void {\n setActiveSuggestion(editor, id)\n const entry = editor.getApi(SuggestionPlugin).suggestion.node({ at: [], id })\n const dom = entry ? editor.api.toDOMNode(entry[0]) : undefined\n dom?.scrollIntoView({ block: 'center' })\n}\n",
|
|
81
|
+
"target": "~/packages/ui/src/blocks/application/rich-text-editor/shared/actions.ts"
|
|
82
|
+
},
|
|
83
|
+
{
|
|
84
|
+
"path": "blocks/application/rich-text-editor/shared/collect.ts",
|
|
85
|
+
"type": "registry:file",
|
|
86
|
+
"content": "import type { RichTextValue } from '@tc96/ui/patterns/rich-text-editor'\nimport type { SuggestionAuthor, SuggestionChange } from './types'\n\nexport interface SuggestionData {\n createdAt: number\n id: string\n isLineBreak?: boolean\n type: 'insert' | 'remove' | 'update'\n userId: string\n}\n\ntype AnyNode = { [key: string]: unknown }\n\nconst isLeaf = (node: AnyNode): node is AnyNode & { text: string } =>\n typeof node.text === 'string'\n\nconst isSuggestionData = (value: unknown): value is SuggestionData =>\n typeof value === 'object' &&\n value !== null &&\n typeof (value as SuggestionData).id === 'string' &&\n typeof (value as SuggestionData).type === 'string'\n\n/**\n * Reads the suggestion a text leaf carries, from its `suggestion_<id>` key.\n *\n * @param leaf - a Slate text node\n * @returns the data of the first suggestion on the leaf, or `undefined`\n */\nexport function leafSuggestion(leaf: AnyNode): SuggestionData | undefined {\n for (const key of Object.keys(leaf)) {\n if (!key.startsWith('suggestion_')) continue\n const data = leaf[key]\n if (isSuggestionData(data)) return data\n }\n return undefined\n}\n\n/**\n * Reads the suggestion a block element carries in its `suggestion` object.\n *\n * @param element - a Slate element\n * @returns the data, or `undefined` for a plain element or a line break marker\n */\nexport function blockSuggestion(element: AnyNode): SuggestionData | undefined {\n const data = element.suggestion\n return isSuggestionData(data) && !data.isLineBreak ? data : undefined\n}\n\nfunction textOf(node: AnyNode): string {\n if (isLeaf(node)) return node.text\n const children = (node.children ?? []) as AnyNode[]\n return children.map(textOf).join('')\n}\n\ninterface Accumulator {\n after: string[]\n before: string[]\n createdAt: number\n userId: string\n}\n\n/**\n * Lists the changes of a document in reading order. Leaves that share a\n * suggestion id become one change: a removal plus an insertion is a replace.\n *\n * @param value - the editor document, with or without suggestion marks\n * @param authors - known people; an unknown `userId` becomes `{ id, name: id }`\n * @returns one entry per suggestion id, formatting-only updates left out\n */\nexport function collectSuggestions(\n value: RichTextValue,\n authors: readonly SuggestionAuthor[] = [],\n): SuggestionChange[] {\n const found = new Map<string, Accumulator>()\n const add = (data: SuggestionData, text: string) => {\n if (data.type === 'update') return\n const entry = found.get(data.id) ?? {\n after: [],\n before: [],\n createdAt: data.createdAt,\n userId: data.userId,\n }\n entry.createdAt = Math.min(entry.createdAt, data.createdAt)\n const target = data.type === 'insert' ? entry.after : entry.before\n target.push(text)\n found.set(data.id, entry)\n }\n const walk = (nodes: readonly AnyNode[]) => {\n for (const node of nodes) {\n if (isLeaf(node)) {\n const data = leafSuggestion(node)\n if (data) add(data, node.text)\n continue\n }\n const data = blockSuggestion(node)\n if (data) {\n add(data, textOf(node))\n continue\n }\n walk((node.children ?? []) as AnyNode[])\n }\n }\n walk(value as unknown as AnyNode[])\n return [...found].map(([id, entry]) => {\n const before = entry.before.join('')\n const after = entry.after.join('')\n return {\n after,\n author: authors.find((author) => author.id === entry.userId) ?? {\n id: entry.userId,\n name: entry.userId,\n },\n before,\n createdAt: new Date(entry.createdAt),\n id,\n kind:\n entry.before.length > 0 && entry.after.length > 0\n ? 'replace'\n : entry.before.length > 0\n ? 'delete'\n : 'insert',\n }\n })\n}\n",
|
|
87
|
+
"target": "~/packages/ui/src/blocks/application/rich-text-editor/shared/collect.ts"
|
|
88
|
+
},
|
|
89
|
+
{
|
|
90
|
+
"path": "blocks/application/rich-text-editor/shared/serialize.ts",
|
|
91
|
+
"type": "registry:file",
|
|
92
|
+
"content": "import {\n type RichTextNode,\n richTextToHtml,\n richTextToPlainText,\n} from '@tc96/ui/helpers/rich-text'\nimport type { RichTextValue } from '@tc96/ui/patterns/rich-text-editor'\nimport { blockSuggestion, leafSuggestion } from './collect'\nimport type { SuggestionAuthor } from './types'\n\ntype AnyNode = { [key: string]: unknown }\n\nconst isLeaf = (node: AnyNode): node is AnyNode & { text: string } =>\n typeof node.text === 'string'\n\nconst stripSuggestionKeys = (leaf: AnyNode): AnyNode =>\n Object.fromEntries(\n Object.entries(leaf).filter(\n ([key]) => key !== 'suggestion' && !key.startsWith('suggestion_'),\n ),\n )\n\nfunction project(nodes: readonly AnyNode[], hide: 'insert' | 'remove') {\n const result: AnyNode[] = []\n for (const node of nodes) {\n if (isLeaf(node)) {\n const data = leafSuggestion(node)\n if (data?.type === hide) continue\n result.push(data ? stripSuggestionKeys(node) : node)\n continue\n }\n if (blockSuggestion(node)?.type === hide) continue\n const children = project((node.children ?? []) as AnyNode[], hide)\n const { suggestion: _suggestion, ...rest } = node\n result.push({\n ...rest,\n children: children.length > 0 ? children : [{ text: '' }],\n })\n }\n return result\n}\n\n/**\n * Projects a redlined document onto one of its clean versions.\n *\n * @param value - the editor document\n * @param version - `final` keeps insertions and drops deletions, `original` the reverse\n * @returns a plain document with no suggestion marks\n */\nexport function projectSuggestions(\n value: RichTextValue,\n version: 'final' | 'original',\n): RichTextValue {\n return project(\n value as unknown as AnyNode[],\n version === 'final' ? 'remove' : 'insert',\n ) as unknown as RichTextValue\n}\n\n/**\n * The text of the document with every change accepted, one line per block.\n */\nexport function finalText(value: RichTextValue): string {\n return richTextToPlainText(\n projectSuggestions(value, 'final') as unknown as RichTextNode[],\n )\n}\n\n/**\n * The text of the document with every change rejected, one line per block.\n */\nexport function originalText(value: RichTextValue): string {\n return richTextToPlainText(\n projectSuggestions(value, 'original') as unknown as RichTextNode[],\n )\n}\n\nconst escapeAttribute = (text: string) =>\n text\n .replaceAll('&', '&')\n .replaceAll('<', '<')\n .replaceAll('>', '>')\n .replaceAll('\"', '"')\n\ninterface Tag {\n author: string\n createdAt: number\n name: 'del' | 'ins'\n}\n\n/**\n * Serializes the document as an HTML fragment where insertions are `<ins>` and\n * deletions are `<del>`, each with `data-author` and `datetime`.\n *\n * @param value - the editor document\n * @param authors - known people, to turn a `userId` into a name\n */\nexport function suggestionsToHtml(\n value: RichTextValue,\n authors: readonly SuggestionAuthor[] = [],\n): string {\n const tags: Tag[] = []\n const mark = (nodes: readonly AnyNode[]): AnyNode[] =>\n nodes.map((node) => {\n if (isLeaf(node)) {\n const data = leafSuggestion(node)\n if (!data || data.type === 'update' || node.text === '')\n return stripSuggestionKeys(node)\n const name = data.type === 'insert' ? 'ins' : 'del'\n tags.push({\n author:\n authors.find((author) => author.id === data.userId)?.name ??\n data.userId,\n createdAt: data.createdAt,\n name,\n })\n const close = name === 'ins' ? '\\uE002' : '\\uE003'\n return {\n ...stripSuggestionKeys(node),\n text: `\\uE000${tags.length - 1}\\uE001${node.text}${close}`,\n }\n }\n return { ...node, children: mark((node.children ?? []) as AnyNode[]) }\n })\n const html = richTextToHtml(\n mark(value as unknown as AnyNode[]) as unknown as RichTextNode[],\n )\n return html\n .replace(/\\uE000(\\d+)\\uE001/g, (_match, index: string) => {\n const tag = tags[Number(index)]\n if (!tag) return ''\n const datetime = new Date(tag.createdAt).toISOString()\n return `<${tag.name} data-author=\"${escapeAttribute(tag.author)}\" datetime=\"${datetime}\">`\n })\n .replaceAll('\\uE002', '</ins>')\n .replaceAll('\\uE003', '</del>')\n}\n",
|
|
93
|
+
"target": "~/packages/ui/src/blocks/application/rich-text-editor/shared/serialize.ts"
|
|
94
|
+
},
|
|
95
|
+
{
|
|
96
|
+
"path": "blocks/application/rich-text-editor/shared/store.ts",
|
|
97
|
+
"type": "registry:file",
|
|
98
|
+
"content": "import type { RichTextEditorInstance } from '@tc96/ui/patterns/rich-text-editor'\nimport { useSyncExternalStore } from 'react'\nimport type { SuggestionState, SuggestionView } from './types'\n\ninterface Store {\n listeners: Set<() => void>\n scheduled: boolean\n state: SuggestionState\n}\n\nconst stores = new WeakMap<RichTextEditorInstance, Store>()\n\nexport function storeFor(editor: RichTextEditorInstance): Store {\n let store = stores.get(editor)\n if (!store) {\n store = {\n listeners: new Set(),\n scheduled: false,\n state: { activeId: null, view: 'all' },\n }\n stores.set(editor, store)\n }\n return store\n}\n\nexport function notify(editor: RichTextEditorInstance): void {\n const store = storeFor(editor)\n for (const listener of store.listeners) listener()\n}\n\nexport function notifyLater(editor: RichTextEditorInstance): void {\n const store = storeFor(editor)\n if (store.scheduled) return\n store.scheduled = true\n queueMicrotask(() => {\n store.scheduled = false\n notify(editor)\n })\n}\n\nexport function subscribe(\n editor: RichTextEditorInstance,\n listener: () => void,\n): () => void {\n const store = storeFor(editor)\n store.listeners.add(listener)\n return () => {\n store.listeners.delete(listener)\n }\n}\n\nexport function getSuggestionState(\n editor: RichTextEditorInstance,\n): SuggestionState {\n return storeFor(editor).state\n}\n\n/**\n * Subscribes a component to the review state of an editor: the active change\n * and the view. Works inside and outside the editor's `<Plate>` tree.\n */\nexport function useSuggestionState(\n editor: RichTextEditorInstance,\n): SuggestionState {\n return useSyncExternalStore(\n (listener) => subscribe(editor, listener),\n () => storeFor(editor).state,\n () => storeFor(editor).state,\n )\n}\n\nexport function setSuggestionView(\n editor: RichTextEditorInstance,\n view: SuggestionView,\n): void {\n const store = storeFor(editor)\n if (store.state.view === view) return\n store.state = { ...store.state, view }\n notify(editor)\n}\n\nexport function setActiveSuggestion(\n editor: RichTextEditorInstance,\n activeId: string | null,\n): void {\n const store = storeFor(editor)\n if (store.state.activeId === activeId) return\n store.state = { ...store.state, activeId }\n notify(editor)\n}\n",
|
|
99
|
+
"target": "~/packages/ui/src/blocks/application/rich-text-editor/shared/store.ts"
|
|
100
|
+
},
|
|
101
|
+
{
|
|
102
|
+
"path": "blocks/application/rich-text-editor/shared/suggestion-kit.tsx",
|
|
103
|
+
"type": "registry:file",
|
|
104
|
+
"content": "'use client'\n\nimport { SuggestionPlugin } from '@platejs/suggestion/react'\nimport type { RichTextEditorInstance } from '@tc96/ui/patterns/rich-text-editor'\nimport { cn } from '@tc96/utils'\nimport type { AnyPluginConfig } from 'platejs'\nimport {\n createPlatePlugin,\n PlateLeaf,\n type PlateLeafProps,\n useEditorRef,\n} from 'platejs/react'\nimport type { ReactElement } from 'react'\nimport { leafSuggestion } from './collect'\nimport { notifyLater, useSuggestionState } from './store'\nimport type { SuggestionAuthor } from './types'\n\nexport function SuggestionLeaf(props: PlateLeafProps): ReactElement {\n const editor = useEditorRef() as RichTextEditorInstance\n const { activeId, view } = useSuggestionState(editor)\n const data = leafSuggestion(props.leaf as Record<string, unknown>)\n const inserted = data?.type !== 'remove'\n const hidden =\n (view === 'final' && !inserted) || (view === 'original' && inserted)\n const marked = view === 'all'\n return (\n <PlateLeaf\n {...props}\n as={inserted ? 'ins' : 'del'}\n attributes={{\n ...props.attributes,\n ...(data ? { 'data-suggestion-id': data.id } : {}),\n 'data-suggestion-type': data?.type ?? 'insert',\n ...(data && data.id === activeId ? { 'data-active': 'true' } : {}),\n }}\n className={cn(\n 'scroll-mt-32 no-underline',\n hidden && 'hidden',\n marked &&\n inserted &&\n 'rounded-sm bg-success/10 text-success-foreground underline decoration-success/60 underline-offset-2',\n marked &&\n !inserted &&\n 'rounded-sm bg-destructive/10 text-destructive-foreground line-through',\n data &&\n data.id === activeId &&\n !hidden &&\n 'outline-2 outline-ring outline-offset-1',\n )}\n />\n )\n}\n\nconst triggerInputTypes = new Set(['slash_input', 'mention_input'])\n\nconst directEditsPlugin = createPlatePlugin({\n key: 'redline_direct_edits',\n}).overrideEditor(\n ({\n editor,\n tf: {\n addMark,\n deleteBackward,\n deleteForward,\n insertBreak,\n insertText,\n removeMark,\n },\n }) => {\n const direct = (edit: () => void) =>\n (editor as RichTextEditorInstance)\n .getApi(SuggestionPlugin)\n .suggestion.withoutSuggestions(edit)\n const atBlockEdge = (edge: 'end' | 'start') => {\n const selection = editor.selection\n if (!selection || editor.api.isExpanded()) return false\n const block = editor.api.block()\n if (!block) return false\n return edge === 'start'\n ? editor.api.isStart(selection.anchor, block[1])\n : editor.api.isEnd(selection.anchor, block[1])\n }\n const inTriggerInput = () =>\n !!editor.api.above({\n match: (node) =>\n 'type' in node && triggerInputTypes.has(String(node.type)),\n })\n return {\n transforms: {\n insertText(text, options) {\n if (text === '/' || inTriggerInput())\n direct(() => insertText(text, options))\n else insertText(text, options)\n },\n addMark(key, value) {\n direct(() => addMark(key, value))\n },\n deleteBackward(unit) {\n if (atBlockEdge('start')) direct(() => deleteBackward(unit))\n else deleteBackward(unit)\n },\n deleteForward(unit) {\n if (atBlockEdge('end')) direct(() => deleteForward(unit))\n else deleteForward(unit)\n },\n insertBreak() {\n if (editor.api.isExpanded()) editor.tf.collapse({ edge: 'end' })\n direct(() => insertBreak())\n },\n removeMark(key) {\n direct(() => removeMark(key))\n },\n },\n }\n },\n)\n\nconst trackerPlugin = createPlatePlugin({\n key: 'redline_tracker',\n}).overrideEditor(({ editor, tf: { apply } }) => ({\n transforms: {\n apply(operation) {\n apply(operation)\n if (operation.type !== 'set_selection')\n notifyLater(editor as RichTextEditorInstance)\n },\n },\n}))\n\nexport interface SuggestionKitOptions {\n author: SuggestionAuthor\n suggesting?: boolean\n}\n\n/**\n * The Plate plugins of the suggestion engine, to pass as `features.plugins`:\n * the suggestion plugin with its leaf renderer, the plugin that keeps\n * formatting and paragraph splits out of the suggestions, and the change\n * tracker behind `useSuggestions`.\n *\n * @param options.author - stamped on every change the editor records\n * @param options.suggesting - starts in suggesting mode; defaults to `true`\n */\nexport function createSuggestionKit({\n author,\n suggesting = true,\n}: SuggestionKitOptions): AnyPluginConfig[] {\n return [\n SuggestionPlugin.configure({\n options: { currentUserId: author.id, isSuggesting: suggesting },\n }).withComponent(SuggestionLeaf),\n directEditsPlugin,\n trackerPlugin,\n ]\n}\n\n/**\n * Turns suggesting mode on or off. Off writes plain edits.\n */\nexport function setSuggesting(\n editor: RichTextEditorInstance,\n suggesting: boolean,\n): void {\n editor.setOption(SuggestionPlugin, 'isSuggesting', suggesting)\n}\n",
|
|
105
|
+
"target": "~/packages/ui/src/blocks/application/rich-text-editor/shared/suggestion-kit.tsx"
|
|
106
|
+
},
|
|
107
|
+
{
|
|
108
|
+
"path": "blocks/application/rich-text-editor/shared/suggestion-review-list.tsx",
|
|
109
|
+
"type": "registry:file",
|
|
110
|
+
"content": "import { CheckIcon, XIcon } from '@phosphor-icons/react'\nimport { Avatar, AvatarFallback } from '@tc96/ui/avatar'\nimport { Badge } from '@tc96/ui/badge'\nimport { Button } from '@tc96/ui/button'\nimport { getInitials } from '@tc96/ui/helpers/initials'\nimport { cn } from '@tc96/utils'\nimport type { ReactElement } from 'react'\nimport type { SuggestionChange, SuggestionKind } from './types'\n\nexport interface SuggestionReviewLabels {\n accept: string\n acceptChange: (change: SuggestionChange) => string\n empty: string\n kind: Record<SuggestionKind, string>\n list: string\n now: string\n reject: string\n rejectChange: (change: SuggestionChange) => string\n was: string\n}\n\nexport interface SuggestionReviewListProps {\n activeId?: string | null\n changes: readonly SuggestionChange[]\n className?: string\n formatTime?: (date: Date) => string\n labels: SuggestionReviewLabels\n onAccept: (id: string) => void\n onReject: (id: string) => void\n onSelect?: (id: string) => void\n}\n\nconst defaultFormatTime = (date: Date) =>\n new Intl.DateTimeFormat('pt-BR', {\n dateStyle: 'short',\n timeStyle: 'short',\n }).format(date)\n\nconst kindVariant = {\n delete: 'error',\n insert: 'success',\n replace: 'info',\n} as const satisfies Record<SuggestionKind, string>\n\nexport function SuggestionReviewList({\n activeId = null,\n changes,\n className,\n formatTime = defaultFormatTime,\n labels,\n onAccept,\n onReject,\n onSelect,\n}: Readonly<SuggestionReviewListProps>): ReactElement {\n if (changes.length === 0)\n return (\n <p\n className={cn('p-4 text-muted-foreground text-sm', className)}\n data-slot=\"suggestion-review-empty\"\n >\n {labels.empty}\n </p>\n )\n return (\n <ul\n aria-label={labels.list}\n className={cn('flex flex-col gap-2', className)}\n data-slot=\"suggestion-review-list\"\n >\n {changes.map((change) => {\n const active = change.id === activeId\n return (\n <li\n className={cn(\n 'flex flex-col gap-2 rounded-lg border bg-card p-3 text-card-foreground text-sm',\n active && 'border-ring ring-1 ring-ring',\n )}\n data-active={active ? 'true' : undefined}\n data-kind={change.kind}\n data-slot=\"suggestion-review-item\"\n data-suggestion-id={change.id}\n key={change.id}\n >\n <button\n aria-current={active ? 'true' : undefined}\n className=\"flex w-full flex-col gap-2 rounded-md text-start outline-none focus-visible:ring-2 focus-visible:ring-ring\"\n onClick={() => onSelect?.(change.id)}\n type=\"button\"\n >\n <span className=\"flex items-center gap-2\">\n <Avatar className=\"size-6 text-xs\">\n <AvatarFallback>\n {getInitials(change.author.name)}\n </AvatarFallback>\n </Avatar>\n <span className=\"min-w-0 flex-1\">\n <span className=\"block truncate font-medium\">\n {change.author.name}\n </span>\n <time\n className=\"block text-muted-foreground text-xs\"\n dateTime={change.createdAt.toISOString()}\n >\n {formatTime(change.createdAt)}\n </time>\n </span>\n <Badge variant={kindVariant[change.kind]}>\n {labels.kind[change.kind]}\n </Badge>\n </span>\n {change.before ? (\n <span className=\"block\">\n <span className=\"block text-muted-foreground text-xs\">\n {labels.was}\n </span>\n <del\n className=\"line-clamp-3 text-destructive-foreground\"\n data-slot=\"suggestion-review-before\"\n >\n {change.before}\n </del>\n </span>\n ) : null}\n {change.after ? (\n <span className=\"block\">\n <span className=\"block text-muted-foreground text-xs\">\n {labels.now}\n </span>\n <ins\n className=\"line-clamp-3 text-success-foreground no-underline\"\n data-slot=\"suggestion-review-after\"\n >\n {change.after}\n </ins>\n </span>\n ) : null}\n </button>\n <div className=\"flex justify-end gap-2\">\n <Button\n aria-label={labels.rejectChange(change)}\n onClick={() => onReject(change.id)}\n size=\"sm\"\n variant=\"outline\"\n >\n <XIcon aria-hidden=\"true\" />\n {labels.reject}\n </Button>\n <Button\n aria-label={labels.acceptChange(change)}\n onClick={() => onAccept(change.id)}\n size=\"sm\"\n >\n <CheckIcon aria-hidden=\"true\" />\n {labels.accept}\n </Button>\n </div>\n </li>\n )\n })}\n </ul>\n )\n}\n",
|
|
111
|
+
"target": "~/packages/ui/src/blocks/application/rich-text-editor/shared/suggestion-review-list.tsx"
|
|
112
|
+
},
|
|
113
|
+
{
|
|
114
|
+
"path": "blocks/application/rich-text-editor/shared/suggestions.ts",
|
|
115
|
+
"type": "registry:file",
|
|
116
|
+
"content": "export {\n acceptAll,\n acceptSuggestion,\n applyDirectly,\n goTo,\n rejectAll,\n rejectSuggestion,\n useSuggestions,\n} from './actions'\nexport { collectSuggestions } from './collect'\nexport {\n finalText,\n originalText,\n projectSuggestions,\n suggestionsToHtml,\n} from './serialize'\nexport {\n getSuggestionState,\n setActiveSuggestion,\n setSuggestionView,\n useSuggestionState,\n} from './store'\nexport type { SuggestionKitOptions } from './suggestion-kit'\nexport {\n createSuggestionKit,\n SuggestionLeaf,\n setSuggesting,\n} from './suggestion-kit'\nexport type { SuggestionReviewLabels } from './suggestion-review-list'\nexport { SuggestionReviewList } from './suggestion-review-list'\nexport type {\n SuggestionAuthor,\n SuggestionChange,\n SuggestionKind,\n SuggestionState,\n SuggestionView,\n} from './types'\n",
|
|
117
|
+
"target": "~/packages/ui/src/blocks/application/rich-text-editor/shared/suggestions.ts"
|
|
118
|
+
},
|
|
119
|
+
{
|
|
120
|
+
"path": "blocks/application/rich-text-editor/shared/types.ts",
|
|
121
|
+
"type": "registry:file",
|
|
122
|
+
"content": "export interface SuggestionAuthor {\n id: string\n name: string\n}\n\nexport type SuggestionKind = 'delete' | 'insert' | 'replace'\n\nexport type SuggestionView = 'all' | 'final' | 'original'\n\nexport interface SuggestionChange {\n after: string\n author: SuggestionAuthor\n before: string\n createdAt: Date\n id: string\n kind: SuggestionKind\n}\n\nexport interface SuggestionState {\n activeId: string | null\n view: SuggestionView\n}\n",
|
|
123
|
+
"target": "~/packages/ui/src/blocks/application/rich-text-editor/shared/types.ts"
|
|
124
|
+
},
|
|
125
|
+
{
|
|
126
|
+
"path": "helpers/initials.ts",
|
|
127
|
+
"type": "registry:file",
|
|
128
|
+
"content": "/**\n * Builds the initials shown in an avatar fallback: the first letter of the\n * first words of a label, upper-cased.\n *\n * @param label - A person or entity name; surrounding and repeated whitespace is ignored.\n * @param size - How many words contribute a letter. Defaults to two.\n * @returns The initials, or an empty string for a blank label.\n */\nexport function getInitials(label: string, size = 2): string {\n return label\n .split(/\\s+/)\n .filter(Boolean)\n .slice(0, size)\n .map((part) => part[0])\n .join('')\n .toUpperCase()\n}\n\n/**\n * Picks the text of an avatar fallback: the explicit fallback a person carries,\n * or the initials of its label when there is none.\n *\n * @param person - Anything with a `label` and an optional `fallback`.\n * @param size - How many words contribute a letter when the label is used. Defaults to two.\n * @returns The fallback as given (only `undefined` falls through, so an empty\n * string is kept), otherwise the initials of the label.\n */\nexport function resolveInitials(\n person: { label: string; fallback?: string },\n size = 2,\n): string {\n return person.fallback ?? getInitials(person.label, size)\n}\n",
|
|
129
|
+
"target": "~/packages/ui/src/helpers/initials.ts"
|
|
130
|
+
},
|
|
131
|
+
{
|
|
132
|
+
"path": "helpers/rich-text.ts",
|
|
133
|
+
"type": "registry:file",
|
|
134
|
+
"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\nconst WORD_PATTERN = /[\\p{L}\\p{N}]+(?:['’.-][\\p{L}\\p{N}]+)*/gu\n\n/**\n * Counts the words of a text: runs of letters or digits, where an inner\n * apostrophe, dot or hyphen keeps a word whole (\"don't\", \"3.14\", \"e-mail\").\n *\n * @param text - plain text\n * @returns the number of words, 0 for an empty or whitespace-only text\n */\nexport function countWords(text: string): number {\n return text.match(WORD_PATTERN)?.length ?? 0\n}\n\nexport interface RichTextStats {\n characters: number\n charactersWithSpaces: number\n readingMinutes: number\n words: number\n}\n\n/**\n * Counts what a document footer shows: words, characters and reading time.\n *\n * @param value - the Slate-like node tree a rich text editor emits\n * @param wordsPerMinute - the reading speed behind `readingMinutes`\n * @returns `characters` without whitespace, `charactersWithSpaces` with the\n * text as written (blocks joined by one line break counted as one character)\n * and `readingMinutes` rounded up, 0 only for an empty document\n */\nexport function richTextStats(\n value: readonly RichTextNode[],\n wordsPerMinute = 200,\n): RichTextStats {\n const text = richTextToPlainText(value)\n const words = countWords(text)\n return {\n characters: text.replace(/\\s/g, '').length,\n charactersWithSpaces: text.length,\n readingMinutes: words === 0 ? 0 : Math.ceil(words / wordsPerMinute),\n words,\n }\n}\n\nconst escapeHtml = (text: string) =>\n text\n .replaceAll('&', '&')\n .replaceAll('<', '<')\n .replaceAll('>', '>')\n .replaceAll('\"', '"')\n\nconst MARK_TAGS = [\n ['bold', 'strong'],\n ['italic', 'em'],\n ['underline', 'u'],\n ['strikethrough', 's'],\n ['code', 'code'],\n ['highlight', 'mark'],\n] as const\n\nconst BLOCK_TAGS: Record<string, string> = {\n blockquote: 'blockquote',\n h1: 'h1',\n h2: 'h2',\n h3: 'h3',\n li: 'li',\n ol: 'ol',\n p: 'p',\n tr: 'tr',\n ul: 'ul',\n}\n\nfunction leafHtml(leaf: RichTextLeaf): string {\n let html = escapeHtml(leaf.text).replaceAll('\\n', '<br>')\n for (const [mark, tag] of MARK_TAGS)\n if (leaf[mark] === true) html = `<${tag}>${html}</${tag}>`\n return html\n}\n\nfunction elementHtml(element: RichTextElement): string {\n const inner = richTextToHtml(element.children)\n const align = (element as { align?: unknown }).align\n const style =\n typeof align === 'string' && align !== 'left' && align !== 'start'\n ? ` style=\"text-align:${escapeHtml(align)}\"`\n : ''\n const attributes = element as unknown as Record<string, unknown>\n switch (element.type) {\n case 'lic':\n return inner\n case 'a':\n return `<a href=\"${escapeHtml(String(attributes.url ?? ''))}\">${inner}</a>`\n case 'mention':\n return `<span data-mention>@${escapeHtml(String(attributes.value ?? ''))}</span>`\n case 'action_item':\n return `<p><input type=\"checkbox\" disabled${attributes.checked === true ? ' checked' : ''}> ${inner}</p>`\n case 'callout':\n return `<aside>${inner}</aside>`\n case 'code_block':\n return `<pre><code>${inner}</code></pre>`\n case 'hr':\n return '<hr>'\n case 'date':\n return `<time datetime=\"${escapeHtml(String(attributes.date ?? ''))}\">${escapeHtml(String(attributes.date ?? ''))}</time>`\n case 'img':\n return `<img src=\"${escapeHtml(String(attributes.url ?? ''))}\" alt=\"${escapeHtml(String(attributes.alt ?? ''))}\">`\n case 'table':\n return `<table><tbody>${inner}</tbody></table>`\n case 'td':\n return `<td>${inner}</td>`\n case 'th':\n return `<th>${inner}</th>`\n default: {\n const tag = BLOCK_TAGS[element.type] ?? 'div'\n return `<${tag}${style}>${inner}</${tag}>`\n }\n }\n}\n\n/**\n * Serializes a rich text document to an HTML fragment. Text is escaped, marks\n * become `strong`, `em`, `u`, `s`, `code` and `mark`, a non-left `align`\n * becomes an inline `text-align`, and an unknown element type becomes a `div`.\n *\n * @param value - the Slate-like node tree a rich text editor emits\n * @returns the HTML, with no wrapper element and no whitespace between blocks\n */\nexport function richTextToHtml(value: readonly RichTextNode[]): string {\n return value\n .map((node) => (isLeaf(node) ? leafHtml(node) : elementHtml(node)))\n .join('')\n}\n",
|
|
135
|
+
"target": "~/packages/ui/src/helpers/rich-text.ts"
|
|
136
|
+
},
|
|
137
|
+
{
|
|
138
|
+
"path": "patterns/rich-text-editor/block-draggable.tsx",
|
|
139
|
+
"type": "registry:file",
|
|
140
|
+
"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",
|
|
141
|
+
"target": "~/packages/ui/src/patterns/rich-text-editor/block-draggable.tsx"
|
|
142
|
+
},
|
|
143
|
+
{
|
|
144
|
+
"path": "patterns/rich-text-editor/editor-title.tsx",
|
|
145
|
+
"type": "registry:file",
|
|
146
|
+
"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",
|
|
147
|
+
"target": "~/packages/ui/src/patterns/rich-text-editor/editor-title.tsx"
|
|
148
|
+
},
|
|
149
|
+
{
|
|
150
|
+
"path": "patterns/rich-text-editor/extra-blocks.tsx",
|
|
151
|
+
"type": "registry:file",
|
|
152
|
+
"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 { Path, SlateEditor } from 'platejs'\nimport {\n createPlatePlugin,\n PlateElement,\n type PlateElementProps,\n useEditorRef,\n useReadOnly,\n} from 'platejs/react'\nimport type { ReactElement, RefObject } from 'react'\nimport { useRef } from 'react'\nimport { MIN_TABLE_COLUMN_WIDTH, setTableColumnWidth } from './table-actions'\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 const colSizes = props.element.colSizes as number[] | undefined\n return (\n <PlateElement {...props} as=\"div\" className=\"my-2 overflow-x-auto\">\n <table\n className=\"w-full table-fixed border-collapse\"\n style={\n colSizes\n ? { minWidth: colSizes.reduce((sum, size) => sum + size, 0) }\n : undefined\n }\n >\n {colSizes ? (\n <colgroup>\n {colSizes.map((size, index) => (\n // biome-ignore lint/suspicious/noArrayIndexKey: columns have no identity beyond their position\n <col key={index} style={{ width: size }} />\n ))}\n </colgroup>\n ) : null}\n <tbody>{props.children}</tbody>\n </table>\n </PlateElement>\n )\n}\n\nfunction ColumnResizeHandle({\n cell,\n path,\n}: Readonly<{\n cell: RefObject<HTMLElement | null>\n path: Path\n}>): ReactElement | null {\n const editor = useEditorRef()\n const readOnly = useReadOnly()\n if (readOnly) return null\n const colIndex = path.at(-1) ?? 0\n const resizeTo = (width: number) =>\n setTableColumnWidth(editor, path, colIndex, width)\n const current = () => cell.current?.getBoundingClientRect().width ?? 0\n return (\n // biome-ignore lint/a11y/useSemanticElements: a focusable separator is the WAI-ARIA window splitter, an hr cannot take focus or a value\n <div\n aria-label=\"Redimensionar coluna\"\n aria-orientation=\"vertical\"\n aria-valuemin={MIN_TABLE_COLUMN_WIDTH}\n aria-valuenow={Math.round(current())}\n className=\"absolute inset-y-0 -end-1 z-10 flex w-2 cursor-col-resize touch-none justify-center opacity-0 hover:opacity-100 focus-visible:opacity-100 pointer-coarse:opacity-100\"\n contentEditable={false}\n data-slot=\"table-column-resize\"\n onKeyDown={(event) => {\n if (event.key !== 'ArrowLeft' && event.key !== 'ArrowRight') return\n event.preventDefault()\n event.stopPropagation()\n resizeTo(current() + (event.key === 'ArrowRight' ? 16 : -16))\n }}\n onPointerDown={(event) => {\n event.preventDefault()\n event.stopPropagation()\n const startX = event.clientX\n const startWidth = current()\n const move = (next: PointerEvent) =>\n resizeTo(startWidth + next.clientX - startX)\n const stop = () => {\n document.removeEventListener('pointermove', move)\n document.removeEventListener('pointerup', stop)\n }\n document.addEventListener('pointermove', move)\n document.addEventListener('pointerup', stop)\n }}\n role=\"separator\"\n tabIndex={0}\n >\n <span className=\"w-0.5 bg-primary\" />\n </div>\n )\n}\n\nfunction TableRowElement(props: PlateElementProps): ReactElement {\n return <PlateElement {...props} as=\"tr\" />\n}\n\nfunction TableCellElement(props: PlateElementProps): ReactElement {\n const cell = useRef<HTMLElement | null>(null)\n return (\n <PlateElement\n {...props}\n as=\"td\"\n className=\"relative min-w-12 border border-border/80 p-2 align-top\"\n ref={cell}\n >\n {props.children}\n <ColumnResizeHandle cell={cell} path={props.path} />\n </PlateElement>\n )\n}\n\nfunction TableHeaderCellElement(props: PlateElementProps): ReactElement {\n const cell = useRef<HTMLElement | null>(null)\n return (\n <PlateElement\n {...props}\n as=\"th\"\n className=\"relative min-w-12 border border-border/80 bg-muted/48 p-2 text-start align-top font-medium\"\n ref={cell}\n >\n {props.children}\n <ColumnResizeHandle cell={cell} path={props.path} />\n </PlateElement>\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.configure({ options: { disableMerge: true } }).withComponent(\n TableElement,\n ),\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",
|
|
153
|
+
"target": "~/packages/ui/src/patterns/rich-text-editor/extra-blocks.tsx"
|
|
154
|
+
},
|
|
155
|
+
{
|
|
156
|
+
"path": "patterns/rich-text-editor/floating-toolbar.tsx",
|
|
157
|
+
"type": "registry:file",
|
|
158
|
+
"content": "'use client'\n\nimport { Popover, PopoverPopup } from '@tc96/ui/popover'\nimport {\n ToolbarGroup,\n ToolbarPrimitive,\n ToolbarSeparator,\n} from '@tc96/ui/toolbar'\nimport { RangeApi, type SlateEditor, type TRange } from 'platejs'\nimport { useEditorRef, useEditorSelector } from 'platejs/react'\nimport type { ReactElement, ReactNode, RefObject } from 'react'\nimport { useCallback, useEffect, useMemo, useState } from 'react'\nimport { LinkButton, type LinkButtonLabels } from './link-button'\nimport {\n RICH_TEXT_BLOCKS,\n RICH_TEXT_MARKS,\n type RichTextBlock,\n type RichTextMark,\n} from './plugins'\nimport {\n RichTextBlockButton as BlockButton,\n RichTextBlockSelect as BlockTypeSelect,\n RichTextMarkButton as MarkButton,\n} from './toolbar-parts'\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 actions?: ReactNode\n blockLabels: Readonly<Record<RichTextBlock, string>>\n blockTypeLabel: string\n label: string\n linkLabels: LinkButtonLabels\n markLabels: Readonly<Record<RichTextMark, string>>\n marks?: readonly RichTextMark[]\n paragraphLabel: string\n toolbarRef: RefObject<HTMLDivElement | null>\n}\n\nexport function FloatingToolbar({\n actions,\n blockLabels,\n blockTypeLabel,\n label,\n linkLabels,\n markLabels,\n marks = RICH_TEXT_MARKS,\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 inEditable = (node: Node) =>\n editor.api.toDOMNode(editor)?.contains(node) ?? false\n const inside = (node: EventTarget | null) =>\n node instanceof Node &&\n (inEditable(node) ||\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 (event.target instanceof Node && inEditable(event.target))\n 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 {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 {actions ? (\n <>\n <ToolbarSeparator orientation=\"vertical\" />\n <ToolbarGroup className=\"gap-0.5\">{actions}</ToolbarGroup>\n </>\n ) : null}\n </ToolbarPrimitive.Root>\n </PopoverPopup>\n </Popover>\n )\n}\n",
|
|
159
|
+
"target": "~/packages/ui/src/patterns/rich-text-editor/floating-toolbar.tsx"
|
|
160
|
+
},
|
|
161
|
+
{
|
|
162
|
+
"path": "patterns/rich-text-editor/index.ts",
|
|
163
|
+
"type": "registry:file",
|
|
164
|
+
"content": "export type { EditorTitleHandle, EditorTitleProps } from './editor-title'\nexport { EditorTitle } from './editor-title'\nexport type { RichTextExtraBlock, RichTextImage } from './extra-blocks'\nexport {\n applyExtraBlock,\n insertImage,\n RICH_TEXT_EXTRA_BLOCKS,\n} from './extra-blocks'\nexport type { LinkButtonLabels } from './link-button'\nexport { LinkButton as RichTextLinkButton } from './link-button'\nexport type {\n RichTextAlignment,\n RichTextAvatar,\n RichTextBlock,\n RichTextBlockWithTitle,\n RichTextEditorFeatures,\n RichTextMark,\n} from './plugins'\nexport {\n applyBlock,\n RICH_TEXT_ALIGNMENTS,\n RICH_TEXT_BLOCKS,\n RICH_TEXT_ELEMENTS,\n RICH_TEXT_MARKS,\n setAlignment,\n} from './plugins'\nexport type {\n RichTextEditorHandle,\n RichTextEditorInstance,\n RichTextEditorOptions,\n RichTextEditorProps,\n RichTextMention,\n RichTextValue,\n} from './rich-text-editor'\nexport {\n defaultMaxListDepth,\n RichTextEditor,\n useRichTextEditor,\n} from './rich-text-editor'\nexport type { SlashMenuBlock, SlashMenuOption } from './slash-menu'\nexport {\n filterSlashMenuOptions,\n slashMenuOptions,\n} from './slash-menu'\nexport {\n addTableColumn,\n addTableRow,\n hasTableHeaderRow,\n isInTable,\n MIN_TABLE_COLUMN_WIDTH,\n removeTable,\n removeTableColumn,\n removeTableRow,\n setTableColumnWidth,\n toggleTableHeaderRow,\n} from './table-actions'\nexport {\n RichTextAlignButton,\n RichTextBlockButton,\n RichTextBlockSelect,\n RichTextExtraBlockButton,\n RichTextHistoryButton,\n RichTextMarkButton,\n RichTextToolbar,\n RichTextToolbarToggle,\n} from './toolbar-parts'\n",
|
|
165
|
+
"target": "~/packages/ui/src/patterns/rich-text-editor/index.ts"
|
|
166
|
+
},
|
|
167
|
+
{
|
|
168
|
+
"path": "patterns/rich-text-editor/link-button.tsx",
|
|
169
|
+
"type": "registry:file",
|
|
170
|
+
"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",
|
|
171
|
+
"target": "~/packages/ui/src/patterns/rich-text-editor/link-button.tsx"
|
|
172
|
+
},
|
|
173
|
+
{
|
|
174
|
+
"path": "patterns/rich-text-editor/plugins.tsx",
|
|
175
|
+
"type": "registry:file",
|
|
176
|
+
"content": "import {\n BoldRules,\n CodeRules,\n ItalicRules,\n StrikethroughRules,\n} from '@platejs/basic-nodes'\nimport {\n BoldPlugin,\n CodePlugin,\n H1Plugin,\n H2Plugin,\n H3Plugin,\n HighlightPlugin,\n ItalicPlugin,\n StrikethroughPlugin,\n UnderlinePlugin,\n} from '@platejs/basic-nodes/react'\nimport { TextAlignPlugin } from '@platejs/basic-styles/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 { Avatar, AvatarFallback, AvatarImage } from '@tc96/ui/avatar'\nimport { getInitials } from '@tc96/ui/helpers/initials'\nimport { cn } from '@tc96/utils'\nimport {\n type AnyPluginConfig,\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 type RichTextBlockWithTitle = RichTextBlock | 'h1'\n\nexport const RICH_TEXT_ALIGNMENTS = [\n 'left',\n 'center',\n 'right',\n 'justify',\n] as const\n\nexport type RichTextAlignment = (typeof RICH_TEXT_ALIGNMENTS)[number]\n\nexport interface RichTextEditorFeatures {\n align?: boolean\n h1?: boolean\n plugins?: readonly AnyPluginConfig[]\n skipInitialization?: boolean\n}\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 interface RichTextAvatar {\n fallback?: string\n url?: string\n}\n\nexport function MentionAvatar({\n avatar,\n label,\n}: Readonly<{ avatar: RichTextAvatar; label: string }>): ReactElement {\n return (\n <Avatar aria-hidden=\"true\" className=\"size-4 text-[0.5rem]\">\n {avatar.url ? <AvatarImage alt=\"\" src={avatar.url} /> : null}\n <AvatarFallback>\n {avatar.fallback ?? getInitials(label, 2)}\n </AvatarFallback>\n </Avatar>\n )\n}\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 as TElement).type)\n\nconst inListItem = (editor: SlateEditor) =>\n editor.api.some({ match: { type: 'li' } })\n\nexport function setAlignment(\n editor: SlateEditor,\n alignment: RichTextAlignment,\n): void {\n editor.getTransforms(TextAlignPlugin).textAlign.setNodes(alignment)\n}\n\nexport function applyBlock(\n editor: SlateEditor,\n block: RichTextBlockWithTitle | '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: RichTextBlockWithTitle) =>\n ({ editor }: { editor: SlateEditor }) =>\n !editor.api.some({ match: { type: block } })\n\nfunction blockShortcut(\n prefix: RegExp | string,\n block: RichTextBlockWithTitle,\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 H1Element(props: PlateElementProps): ReactElement {\n return (\n <PlateElement\n {...props}\n as=\"h1\"\n className=\"mt-5 mb-2 font-semibold text-2xl first:mt-0\"\n />\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 as TElement).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 const label = String(props.element.value ?? '')\n const avatar = props.element.avatar as RichTextAvatar | undefined\n return (\n <PlateElement\n {...props}\n as=\"span\"\n attributes={{ ...props.attributes, contentEditable: false }}\n className={cn(\n 'rounded-sm bg-primary/12 px-1 font-medium text-primary',\n avatar && 'inline-flex items-center gap-1 align-middle',\n )}\n >\n {avatar ? <MentionAvatar avatar={avatar} label={label} /> : null}@{label}\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 features: RichTextEditorFeatures = {},\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 ...(features.skipInitialization ? { skipInitialization: true } : {}),\n plugins: [\n ParagraphPlugin.withComponent(ParagraphElement),\n ...(features.h1\n ? [\n H1Plugin.withComponent(H1Element).configure({\n inputRules: [blockShortcut('#', 'h1')],\n parsers: {\n html: { deserializer: { rules: [{ validNodeName: 'H1' }] } },\n },\n }),\n ]\n : []),\n H2Plugin.withComponent(H2Element).configure({\n inputRules: features.h1\n ? [blockShortcut('##', 'h2')]\n : [blockShortcut('#', 'h2'), blockShortcut('##', 'h2')],\n parsers: {\n html: {\n deserializer: {\n rules: [{ validNodeName: features.h1 ? ['H2'] : ['H1', 'H2'] }],\n },\n },\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 ...(features.align\n ? [\n TextAlignPlugin.configure({\n inject: {\n targetPlugins: ['p', 'h1', 'h2', 'h3', 'blockquote'],\n },\n }),\n ]\n : []),\n ...(features.plugins ?? []),\n ],\n }\n}\n",
|
|
177
|
+
"target": "~/packages/ui/src/patterns/rich-text-editor/plugins.tsx"
|
|
178
|
+
},
|
|
179
|
+
{
|
|
180
|
+
"path": "patterns/rich-text-editor/rich-text-editor.tsx",
|
|
181
|
+
"type": "registry:file",
|
|
182
|
+
"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 type PlateEditor,\n useEditorReadOnly,\n useEditorRef,\n usePlateEditor,\n} from 'platejs/react'\nimport type {\n KeyboardEvent,\n ReactElement,\n ReactNode,\n Ref,\n RefObject,\n} 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 RichTextAvatar,\n type RichTextBlock,\n type RichTextEditorFeatures,\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 avatar?: RichTextAvatar\n id: string\n label: string\n}\n\nexport type RichTextEditorInstance = PlateEditor\n\nexport interface RichTextEditorHandle {\n editor: RichTextEditorInstance\n focusStart: () => void\n}\n\nexport interface RichTextEditorOptions {\n blockDragLabels?: BlockDragLabels\n defaultValue?: RichTextValue\n draggableBlocks?: boolean\n features?: RichTextEditorFeatures\n maxListDepth?: number\n mentions?: readonly RichTextMention[]\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 children?: ReactNode\n extraBlockLabels?: Readonly<Record<RichTextExtraBlock, string>>\n className?: string\n contentClassName?: string\n defaultValue?: RichTextValue\n draggableBlocks?: boolean\n editor?: RichTextEditorInstance\n features?: RichTextEditorFeatures\n floatingToolbar?: boolean\n floatingToolbarActions?: ReactNode\n floatingToolbarMarks?: readonly RichTextMark[]\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 readOnly?: boolean\n ref?: Ref<RichTextEditorHandle>\n slashMenuEmptyLabel?: string\n slashMenuLabel?: string\n toolbar?: ReactNode\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'\n | 'contentClassName'\n | 'mentions'\n | 'onExitStart'\n | 'onPickImage'\n | 'placeholder'\n > & {\n selectableBlocks: boolean\n toolbarRef: RefObject<HTMLDivElement | null>\n }\n\nfunction EditorContent({\n 'aria-label': ariaLabel,\n autoFocus,\n blockLabels,\n contentClassName,\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 const readOnly = useEditorReadOnly()\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 ...(mention.avatar ? { avatar: mention.avatar } : {}),\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 {\n children: [{ text: '' }],\n type: MENTION_TYPE,\n value: option.label,\n ...(option.avatar ? { avatar: option.avatar } : {}),\n },\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={readOnly ? undefined : activeMenu.activeId}\n aria-controls={activeMenu.open && !readOnly ? activeMenu.id : undefined}\n aria-label={ariaLabel}\n {...(readOnly ? {} : { 'aria-placeholder': placeholder })}\n className={cn(\n 'w-full text-base text-foreground outline-none',\n contentClassName,\n )}\n data-slot=\"rich-text-editor-content\"\n onBlur={(event) => {\n slashMenu.onBlur(event)\n mentionMenu.onBlur(event)\n }}\n onKeyDown={handleKeyDown}\n {...(readOnly ? {} : { placeholder })}\n {...(readOnly ? { role: 'document' } : {})}\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 useRichTextEditor({\n blockDragLabels = defaultBlockDragLabels,\n defaultValue,\n draggableBlocks = false,\n features,\n maxListDepth = defaultMaxListDepth,\n mentions,\n}: Readonly<RichTextEditorOptions> = {}): RichTextEditorInstance {\n return usePlateEditor({\n ...richTextEditorOptions(\n maxListDepth,\n mentions !== undefined,\n draggableBlocks ? blockDragLabels : undefined,\n features,\n ),\n ...(defaultValue ? { value: defaultValue } : {}),\n })\n}\n\ntype EditorViewProps = Omit<RichTextEditorProps, 'editor'> & {\n editor: RichTextEditorInstance\n}\n\nfunction RichTextEditorView({\n 'aria-label': ariaLabel,\n autoFocus = false,\n blockLabels = defaultBlockLabels,\n blockTypeLabel = 'Tipo de bloco',\n children,\n className,\n contentClassName,\n draggableBlocks = false,\n editor,\n extraBlockLabels = defaultExtraBlockLabels,\n floatingToolbar = true,\n floatingToolbarActions,\n floatingToolbarMarks,\n linkLabels = defaultLinkLabels,\n markLabels = defaultMarkLabels,\n mentionEmptyLabel = 'Ninguém com esse nome',\n mentionLabel = 'Pessoas',\n mentions,\n onExitStart,\n onPickImage,\n onValueChange,\n paragraphLabel = 'Texto',\n placeholder,\n readOnly = false,\n ref,\n slashMenuEmptyLabel = 'Nenhum bloco com esse nome',\n slashMenuLabel = 'Blocos',\n toolbar,\n toolbarLabel = 'Formatação',\n}: Readonly<EditorViewProps>): ReactElement {\n const toolbarRef = useRef<HTMLDivElement>(null)\n\n useImperativeHandle(ref, () => ({\n editor,\n focusStart: () => editor.tf.focus({ at: [], edge: 'start' }),\n }))\n\n return (\n <Plate\n editor={editor}\n onValueChange={withoutSlashInput(onValueChange)}\n readOnly={readOnly}\n >\n <div className={cn('w-full', className)} data-slot=\"rich-text-editor\">\n {toolbar}\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 {...(contentClassName ? { contentClassName } : {})}\n {...(mentions ? { mentions } : {})}\n {...(onExitStart ? { onExitStart } : {})}\n {...(onPickImage ? { onPickImage } : {})}\n {...(placeholder ? { placeholder } : {})}\n />\n {floatingToolbar && !readOnly ? (\n <FloatingToolbar\n actions={floatingToolbarActions}\n blockLabels={blockLabels}\n blockTypeLabel={blockTypeLabel}\n label={toolbarLabel}\n linkLabels={linkLabels}\n markLabels={markLabels}\n paragraphLabel={paragraphLabel}\n toolbarRef={toolbarRef}\n {...(floatingToolbarMarks ? { marks: floatingToolbarMarks } : {})}\n />\n ) : null}\n {children}\n </div>\n </Plate>\n )\n}\n\nfunction OwnedRichTextEditor({\n blockDragLabels,\n defaultValue,\n draggableBlocks,\n features,\n maxListDepth,\n mentions,\n ...props\n}: Readonly<Omit<RichTextEditorProps, 'editor'>>): ReactElement {\n const editor = useRichTextEditor({\n ...(blockDragLabels ? { blockDragLabels } : {}),\n ...(defaultValue ? { defaultValue } : {}),\n ...(draggableBlocks === undefined ? {} : { draggableBlocks }),\n ...(features ? { features } : {}),\n ...(maxListDepth === undefined ? {} : { maxListDepth }),\n ...(mentions ? { mentions } : {}),\n })\n return (\n <RichTextEditorView\n {...props}\n {...(draggableBlocks === undefined ? {} : { draggableBlocks })}\n editor={editor}\n {...(mentions ? { mentions } : {})}\n />\n )\n}\n\nexport function RichTextEditor({\n editor,\n ...props\n}: Readonly<RichTextEditorProps>): ReactElement {\n return editor ? (\n <RichTextEditorView {...props} editor={editor} />\n ) : (\n <OwnedRichTextEditor {...props} />\n )\n}\n",
|
|
183
|
+
"target": "~/packages/ui/src/patterns/rich-text-editor/rich-text-editor.tsx"
|
|
184
|
+
},
|
|
185
|
+
{
|
|
186
|
+
"path": "patterns/rich-text-editor/slash-menu.tsx",
|
|
187
|
+
"type": "registry:file",
|
|
188
|
+
"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 {\n applyBlock,\n MENTION_INPUT_TYPE,\n MentionAvatar,\n RICH_TEXT_BLOCKS,\n type RichTextAvatar,\n type RichTextBlock,\n SLASH_INPUT_TYPE,\n} from './plugins'\nimport { blockIcon } from './toolbar-parts'\n\nexport type SlashMenuBlock = RichTextBlock | RichTextExtraBlock | 'p'\n\nexport interface SlashMenuOption {\n avatar?: RichTextAvatar\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: string = 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 {option.avatar ? (\n <MentionAvatar avatar={option.avatar} label={option.label} />\n ) : (\n <Icon\n aria-hidden=\"true\"\n className=\"size-4 shrink-0 opacity-80\"\n />\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",
|
|
189
|
+
"target": "~/packages/ui/src/patterns/rich-text-editor/slash-menu.tsx"
|
|
190
|
+
},
|
|
191
|
+
{
|
|
192
|
+
"path": "patterns/rich-text-editor/table-actions.ts",
|
|
193
|
+
"type": "registry:file",
|
|
194
|
+
"content": "import {\n deleteColumn,\n deleteRow,\n deleteTable,\n getTableAbove,\n insertTableColumn,\n insertTableRow,\n setTableColSize,\n} from '@platejs/table'\nimport type { Path, SlateEditor, TElement } from 'platejs'\n\nexport const MIN_TABLE_COLUMN_WIDTH = 48\n\nexport function isInTable(editor: SlateEditor): boolean {\n return getTableAbove(editor) !== undefined\n}\n\nexport function addTableRow(\n editor: SlateEditor,\n position: 'after' | 'before' = 'after',\n): void {\n insertTableRow(editor, { before: position === 'before' })\n}\n\nexport function addTableColumn(\n editor: SlateEditor,\n position: 'after' | 'before' = 'after',\n): void {\n insertTableColumn(editor, { before: position === 'before' })\n}\n\nexport function removeTableRow(editor: SlateEditor): void {\n deleteRow(editor)\n}\n\nexport function removeTableColumn(editor: SlateEditor): void {\n deleteColumn(editor)\n}\n\nexport function removeTable(editor: SlateEditor): void {\n deleteTable(editor)\n}\n\nexport function hasTableHeaderRow(editor: SlateEditor): boolean {\n const table = getTableAbove(editor)\n const firstRow = table && (table[0].children[0] as TElement | undefined)\n return (\n firstRow?.children.every((cell) => (cell as TElement).type === 'th') ??\n false\n )\n}\n\nexport function toggleTableHeaderRow(editor: SlateEditor): void {\n const table = getTableAbove(editor)\n if (!table) return\n const [node, path] = table\n const firstRow = node.children[0] as TElement | undefined\n if (!firstRow) return\n const next = hasTableHeaderRow(editor) ? 'td' : 'th'\n editor.tf.withoutNormalizing(() => {\n firstRow.children.forEach((_, index) => {\n editor.tf.setNodes({ type: next }, { at: [...path, 0, index] })\n })\n })\n}\n\nexport function setTableColumnWidth(\n editor: SlateEditor,\n at: Path,\n colIndex: number,\n width: number,\n): void {\n setTableColSize(\n editor,\n { colIndex, width: Math.max(MIN_TABLE_COLUMN_WIDTH, Math.round(width)) },\n { at },\n )\n}\n",
|
|
195
|
+
"target": "~/packages/ui/src/patterns/rich-text-editor/table-actions.ts"
|
|
196
|
+
},
|
|
197
|
+
{
|
|
198
|
+
"path": "patterns/rich-text-editor/toolbar-parts.tsx",
|
|
199
|
+
"type": "registry:file",
|
|
200
|
+
"content": "'use client'\n\nimport {\n ArrowUUpLeftIcon,\n ArrowUUpRightIcon,\n CalendarBlankIcon,\n ChatCenteredDotsIcon,\n CodeBlockIcon,\n CodeSimpleIcon,\n HighlighterIcon,\n ImageIcon,\n ListBulletsIcon,\n ListChecksIcon,\n ListNumbersIcon,\n MinusIcon,\n type Icon as PhosphorIcon,\n QuotesIcon,\n TableIcon,\n TextAlignCenterIcon,\n TextAlignJustifyIcon,\n TextAlignLeftIcon,\n TextAlignRightIcon,\n TextBIcon,\n TextHOneIcon,\n TextHThreeIcon,\n TextHTwoIcon,\n TextItalicIcon,\n TextStrikethroughIcon,\n TextUnderlineIcon,\n} from '@phosphor-icons/react'\nimport { unwrapList } from '@platejs/list-classic'\nimport { Button } from '@tc96/ui/button'\nimport {\n Select,\n SelectItem,\n SelectPopup,\n SelectTrigger,\n SelectValue,\n} from '@tc96/ui/select'\nimport { Toggle } from '@tc96/ui/toggle'\nimport { ToolbarButton, ToolbarPrimitive } from '@tc96/ui/toolbar'\nimport { cn } from '@tc96/utils'\nimport {\n useEditorRef,\n useEditorSelector,\n useMarkToolbarButton,\n useMarkToolbarButtonState,\n} from 'platejs/react'\nimport type { ComponentProps, ReactElement } from 'react'\nimport { applyExtraBlock, type RichTextExtraBlock } from './extra-blocks'\nimport {\n applyBlock,\n RICH_TEXT_BLOCKS,\n type RichTextAlignment,\n type RichTextBlockWithTitle,\n type RichTextMark,\n setAlignment,\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 h1: TextHOneIcon,\n h2: TextHTwoIcon,\n h3: TextHThreeIcon,\n ol: ListNumbersIcon,\n ul: ListBulletsIcon,\n} as const satisfies Record<RichTextBlockWithTitle, PhosphorIcon>\n\nconst alignmentIcon = {\n center: TextAlignCenterIcon,\n justify: TextAlignJustifyIcon,\n left: TextAlignLeftIcon,\n right: TextAlignRightIcon,\n} as const satisfies Record<RichTextAlignment, PhosphorIcon>\n\nconst extraBlockIcon = {\n callout: ChatCenteredDotsIcon,\n code: CodeBlockIcon,\n date: CalendarBlankIcon,\n hr: MinusIcon,\n image: ImageIcon,\n table: TableIcon,\n todo: ListChecksIcon,\n} as const satisfies Record<RichTextExtraBlock, PhosphorIcon>\n\nconst extraBlockNodeType = {\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<RichTextExtraBlock, string>\n\nexport function RichTextToolbar({\n className,\n ...props\n}: Readonly<\n ComponentProps<typeof ToolbarPrimitive.Root> & { 'aria-label': string }\n>): ReactElement {\n return (\n <ToolbarPrimitive.Root\n className={cn('flex flex-wrap items-center gap-1', className)}\n data-slot=\"rich-text-toolbar\"\n {...props}\n />\n )\n}\n\nexport function RichTextToolbarToggle({\n disabled = false,\n icon: Icon,\n label,\n onToggle,\n pressed,\n}: Readonly<{\n disabled?: boolean\n icon: PhosphorIcon\n label: string\n onToggle: () => void\n pressed: boolean\n}>): ReactElement {\n return (\n <ToolbarButton\n disabled={disabled}\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\nexport function RichTextMarkButton({\n label,\n mark,\n}: Readonly<{ label: string; mark: RichTextMark }>): ReactElement {\n const { props } = useMarkToolbarButton(\n useMarkToolbarButtonState({ nodeType: mark }),\n )\n\n return (\n <RichTextToolbarToggle\n icon={markIcon[mark]}\n label={label}\n onToggle={props.onClick}\n pressed={props.pressed}\n />\n )\n}\n\nexport function RichTextBlockButton({\n block,\n label,\n}: Readonly<{ block: RichTextBlockWithTitle; 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 <RichTextToolbarToggle\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\nexport function RichTextExtraBlockButton({\n block,\n label,\n}: Readonly<{ block: RichTextExtraBlock; label: string }>): ReactElement {\n const editor = useEditorRef()\n const type = extraBlockNodeType[block]\n const pressed = useEditorSelector(\n (current) => current.api.some({ match: { type } }),\n [type],\n )\n\n return (\n <RichTextToolbarToggle\n icon={extraBlockIcon[block]}\n label={label}\n onToggle={() => {\n applyExtraBlock(editor, block)\n editor.tf.focus()\n }}\n pressed={pressed}\n />\n )\n}\n\nexport function RichTextAlignButton({\n alignment,\n label,\n}: Readonly<{ alignment: RichTextAlignment; label: string }>): ReactElement {\n const editor = useEditorRef()\n const pressed = useEditorSelector(\n (current) => {\n const entry = current.api.block()\n const align = (entry?.[0] as { align?: string } | undefined)?.align\n return (align ?? 'left') === alignment\n },\n [alignment],\n )\n\n return (\n <RichTextToolbarToggle\n icon={alignmentIcon[alignment]}\n label={label}\n onToggle={() => {\n setAlignment(editor, alignment)\n editor.tf.focus()\n }}\n pressed={pressed}\n />\n )\n}\n\nexport function RichTextHistoryButton({\n action,\n label,\n}: Readonly<{ action: 'redo' | 'undo'; label: string }>): ReactElement {\n const editor = useEditorRef()\n const available = useEditorSelector(\n (current) =>\n (action === 'undo'\n ? current.history.undos.length\n : current.history.redos.length) > 0,\n [action],\n )\n\n return (\n <ToolbarButton\n aria-label={label}\n disabled={!available}\n onClick={() => {\n if (action === 'undo') editor.undo()\n else editor.redo()\n editor.tf.focus()\n }}\n onMouseDown={(event) => event.preventDefault()}\n render={<Button size=\"icon-sm\" variant=\"ghost\" />}\n >\n {action === 'undo' ? (\n <ArrowUUpLeftIcon aria-hidden=\"true\" />\n ) : (\n <ArrowUUpRightIcon aria-hidden=\"true\" />\n )}\n </ToolbarButton>\n )\n}\n\ntype BlockType = RichTextBlockWithTitle | 'p'\n\nexport function RichTextBlockSelect({\n blockLabels,\n blocks = RICH_TEXT_BLOCKS,\n label,\n paragraphLabel,\n}: Readonly<{\n blockLabels: Readonly<Partial<Record<RichTextBlockWithTitle, string>>>\n blocks?: readonly RichTextBlockWithTitle[]\n label: string\n paragraphLabel: string\n}>): ReactElement {\n const editor = useEditorRef()\n const types: readonly BlockType[] = ['p', ...blocks]\n const current = useEditorSelector(\n (state) =>\n blocks.find((block) => state.api.some({ match: { type: block } })) ?? 'p',\n [blocks],\n )\n const labelOf = (value: BlockType) =>\n value === 'p' ? paragraphLabel : (blockLabels[value] ?? value)\n\n return (\n <Select<BlockType>\n items={types.map((value) => ({ label: labelOf(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 {types.map((value) => (\n <SelectItem key={value} value={value}>\n {labelOf(value)}\n </SelectItem>\n ))}\n </SelectPopup>\n </Select>\n )\n}\n",
|
|
201
|
+
"target": "~/packages/ui/src/patterns/rich-text-editor/toolbar-parts.tsx"
|
|
202
|
+
}
|
|
203
|
+
],
|
|
204
|
+
"dependencies": [
|
|
205
|
+
"@phosphor-icons/react@2.1.10",
|
|
206
|
+
"@platejs/basic-nodes@53.0.0",
|
|
207
|
+
"@platejs/basic-styles@53.0.0",
|
|
208
|
+
"@platejs/combobox@53.0.0",
|
|
209
|
+
"@platejs/date@53.0.0",
|
|
210
|
+
"@platejs/dnd@53.3.8",
|
|
211
|
+
"@platejs/link@53.3.5",
|
|
212
|
+
"@platejs/list-classic@53.0.0",
|
|
213
|
+
"@platejs/mention@53.0.0",
|
|
214
|
+
"@platejs/selection@53.1.6",
|
|
215
|
+
"@platejs/slash-command@53.0.0",
|
|
216
|
+
"@platejs/suggestion@53.2.3",
|
|
217
|
+
"@platejs/table@53.0.9",
|
|
218
|
+
"platejs@53.3.14",
|
|
219
|
+
"react@19.1.1",
|
|
220
|
+
"react-dnd@^16.0.1",
|
|
221
|
+
"react-dnd-html5-backend@^16.0.1"
|
|
222
|
+
],
|
|
223
|
+
"registryDependencies": [
|
|
224
|
+
"@ui/avatar",
|
|
225
|
+
"@ui/badge",
|
|
226
|
+
"@ui/button",
|
|
227
|
+
"@ui/chat",
|
|
228
|
+
"@ui/checkbox",
|
|
229
|
+
"@ui/composer",
|
|
230
|
+
"@ui/input",
|
|
231
|
+
"@ui/popover",
|
|
232
|
+
"@ui/select",
|
|
233
|
+
"@ui/toggle",
|
|
234
|
+
"@ui/toolbar"
|
|
235
|
+
],
|
|
236
|
+
"$schema": "https://ui.shadcn.com/schema/registry-item.json"
|
|
237
|
+
}
|