@tc96/cli 0.0.0-stage → 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/LICENSE +21 -0
- package/README.md +213 -2
- package/cli.js +1450 -0
- package/package.json +35 -4
- package/registry/agenda-1.json +1297 -0
- package/registry/aggregate.json +4 -0
- package/registry/ai-chat-1.json +91 -0
- package/registry/app-shell-1.json +81 -0
- package/registry/app-shell-2.json +89 -0
- package/registry/app-shell-3.json +109 -0
- package/registry/app-shell-4.json +104 -0
- package/registry/card-1.json +104 -0
- package/registry/card-2.json +97 -0
- package/registry/card-3.json +104 -0
- package/registry/card-4.json +98 -0
- package/registry/card-5.json +85 -0
- package/registry/card-6.json +98 -0
- package/registry/card-7.json +104 -0
- package/registry/card-8.json +106 -0
- package/registry/card-9.json +92 -0
- package/registry/charts.json +30 -0
- package/registry/chat-assistant.json +110 -0
- package/registry/chats-panel.json +97 -0
- package/registry/checklist.json +321 -0
- package/registry/collection.json +1104 -0
- package/registry/crm-1.json +1317 -0
- package/registry/crm-2.json +1400 -0
- package/registry/dashboard-1.json +160 -0
- package/registry/dashboard-2.json +153 -0
- package/registry/dashboard-3.json +154 -0
- package/registry/dashboard-4.json +168 -0
- package/registry/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/editable.json +36 -0
- package/registry/empty-state-1.json +40 -0
- package/registry/empty-state-2.json +39 -0
- package/registry/empty-state-3.json +61 -0
- package/registry/empty-state-4.json +39 -0
- package/registry/empty-state-5.json +47 -0
- package/registry/empty-state-6.json +40 -0
- package/registry/finance-1.json +845 -0
- package/registry/finance-2.json +973 -0
- package/registry/finance-3.json +1436 -0
- package/registry/flow-1.json +460 -0
- package/registry/flow-2.json +503 -0
- package/registry/flow-3.json +198 -0
- package/registry/flow-4.json +75 -0
- package/registry/flow-canvas.json +198 -0
- package/registry/flow-inspector.json +151 -0
- package/registry/flow-step-library.json +112 -0
- package/registry/forgot-password-1.json +73 -0
- package/registry/forgot-password-2.json +73 -0
- package/registry/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/list-1.json +129 -0
- package/registry/list-2.json +117 -0
- package/registry/list-3.json +129 -0
- package/registry/list-4.json +105 -0
- package/registry/list-5.json +98 -0
- package/registry/list-6.json +92 -0
- package/registry/list.json +52 -0
- package/registry/login-1.json +89 -0
- package/registry/login-10.json +88 -0
- package/registry/login-2.json +81 -0
- package/registry/login-3.json +90 -0
- package/registry/login-4.json +81 -0
- package/registry/login-5.json +82 -0
- package/registry/login-6.json +88 -0
- package/registry/login-7.json +83 -0
- package/registry/login-8.json +81 -0
- package/registry/login-9.json +88 -0
- package/registry/magic-link-6.json +79 -0
- package/registry/marketing-1.json +833 -0
- package/registry/marketing-2.json +961 -0
- package/registry/navbar-1.json +66 -0
- package/registry/navbar-10.json +50 -0
- package/registry/navbar-11.json +48 -0
- package/registry/navbar-12.json +48 -0
- package/registry/navbar-2.json +48 -0
- package/registry/navbar-3.json +50 -0
- package/registry/navbar-4.json +39 -0
- package/registry/navbar-5.json +50 -0
- package/registry/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/onboarding-1.json +114 -0
- package/registry/onboarding-2.json +78 -0
- package/registry/onboarding-3.json +71 -0
- package/registry/otp-1.json +73 -0
- package/registry/projects-1.json +865 -0
- package/registry/projects-2.json +993 -0
- package/registry/projects-3.json +1346 -0
- package/registry/properties.json +530 -0
- package/registry/record-dialog.json +88 -0
- package/registry/record-group.json +194 -0
- package/registry/record-preview.json +70 -0
- package/registry/record-status-list.json +70 -0
- package/registry/reset-password-1.json +92 -0
- package/registry/reset-password-2.json +98 -0
- package/registry/reset-password-6.json +91 -0
- package/registry/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 +113 -0
- package/registry/settings-account-1.json +119 -0
- package/registry/settings-account-2.json +118 -0
- package/registry/settings-catalog-1.json +128 -0
- package/registry/settings-catalog-10.json +129 -0
- package/registry/settings-catalog-2.json +116 -0
- package/registry/settings-catalog-3.json +118 -0
- package/registry/settings-catalog-4.json +227 -0
- package/registry/settings-catalog-5.json +129 -0
- package/registry/settings-catalog-6.json +130 -0
- package/registry/settings-catalog-7.json +130 -0
- package/registry/settings-catalog-8.json +183 -0
- package/registry/settings-catalog-9.json +159 -0
- package/registry/settings-integration-1.json +125 -0
- package/registry/settings-integration-2.json +122 -0
- package/registry/settings-integration-3.json +118 -0
- 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-integration-7.json +122 -0
- package/registry/settings-integration-8.json +593 -0
- package/registry/settings-notification-channel-1.json +112 -0
- package/registry/settings-preference-1.json +123 -0
- package/registry/settings-preference-2.json +123 -0
- package/registry/settings-preference-3.json +116 -0
- package/registry/settings-role-permission-1.json +117 -0
- package/registry/settings-security-1.json +117 -0
- package/registry/settings-workspace-1.json +119 -0
- package/registry/settings-workspace-2.json +125 -0
- package/registry/settings.json +82 -0
- package/registry/signup-1.json +100 -0
- package/registry/signup-2.json +93 -0
- package/registry/signup-3.json +83 -0
- package/registry/signup-6.json +99 -0
- package/registry/state-surface.json +58 -0
- package/registry/stats-1.json +116 -0
- package/registry/stats-2.json +115 -0
- package/registry/stats-3.json +97 -0
- package/registry/stats-4.json +92 -0
- package/registry/stats-5.json +103 -0
- package/registry/stats-6.json +105 -0
- package/registry/stats-7.json +103 -0
- package/registry/stats.json +64 -0
- package/registry/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/timeline-1.json +97 -0
- package/registry/timeline-2.json +102 -0
- package/registry/timeline-3.json +68 -0
- package/registry/timeline-4.json +86 -0
- package/registry/ui/accordion.json +15 -0
- package/registry/ui/alert-dialog.json +14 -0
- package/registry/ui/alert.json +50 -0
- package/registry/ui/autocomplete.json +18 -0
- package/registry/ui/avatar.json +14 -0
- package/registry/ui/badge.json +51 -0
- package/registry/ui/breadcrumb.json +15 -0
- package/registry/ui/button.json +25 -0
- package/registry/ui/calendar.json +15 -0
- package/registry/ui/card.json +14 -0
- package/registry/ui/chat.json +115 -0
- package/registry/ui/checkbox-group.json +14 -0
- package/registry/ui/checkbox.json +14 -0
- package/registry/ui/collapsible.json +14 -0
- package/registry/ui/combobox.json +18 -0
- package/registry/ui/command.json +17 -0
- package/registry/ui/composer-clipboard.json +14 -0
- package/registry/ui/composer-document.json +14 -0
- package/registry/ui/composer-editor.json +16 -0
- package/registry/ui/composer-query.json +12 -0
- package/registry/ui/composer.json +17 -0
- package/registry/ui/context-menu.json +23 -0
- package/registry/ui/dialog.json +18 -0
- package/registry/ui/drawer.json +18 -0
- package/registry/ui/empty.json +14 -0
- package/registry/ui/field.json +22 -0
- package/registry/ui/fieldset.json +14 -0
- package/registry/ui/form.json +14 -0
- package/registry/ui/frame.json +12 -0
- package/registry/ui/gauge.json +31 -0
- package/registry/ui/group.json +17 -0
- package/registry/ui/icon-frame.json +31 -0
- package/registry/ui/input-group.json +17 -0
- package/registry/ui/input.json +14 -0
- package/registry/ui/kbd.json +12 -0
- package/registry/ui/label.json +14 -0
- package/registry/ui/menu.json +39 -0
- package/registry/ui/meter.json +14 -0
- package/registry/ui/number-field.json +17 -0
- package/registry/ui/otp-field.json +31 -0
- package/registry/ui/pagination.json +17 -0
- package/registry/ui/popover.json +14 -0
- package/registry/ui/preview-card.json +14 -0
- package/registry/ui/progress.json +14 -0
- package/registry/ui/property-meta.json +16 -0
- package/registry/ui/property-tone.json +12 -0
- package/registry/ui/radio-group.json +14 -0
- package/registry/ui/render-anchor.json +12 -0
- package/registry/ui/scroll-area.json +14 -0
- package/registry/ui/segmented-control.json +14 -0
- package/registry/ui/select.json +16 -0
- package/registry/ui/separator.json +14 -0
- package/registry/ui/sheet.json +18 -0
- package/registry/ui/sidebar.json +25 -0
- package/registry/ui/skeleton.json +24 -0
- package/registry/ui/slider.json +14 -0
- package/registry/ui/spinner.json +14 -0
- package/registry/ui/switch.json +14 -0
- package/registry/ui/table.json +14 -0
- package/registry/ui/tabs.json +16 -0
- package/registry/ui/text.json +31 -0
- package/registry/ui/textarea.json +14 -0
- package/registry/ui/toast.json +89 -0
- package/registry/ui/toggle-group.json +18 -0
- package/registry/ui/toggle.json +15 -0
- package/registry/ui/toolbar.json +14 -0
- package/registry/ui/tooltip.json +14 -0
- package/registry/ui/use-composer-editor.json +17 -0
- package/registry/ui/use-copy-to-clipboard.json +12 -0
- package/registry/ui/use-media-query.json +12 -0
- package/registry/view.json +1104 -0
- package/registry/widgets.json +319 -0
- package/registry/wizard.json +89 -0
|
@@ -0,0 +1,200 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "rich-text-editor-4",
|
|
3
|
+
"type": "registry:block",
|
|
4
|
+
"files": [
|
|
5
|
+
{
|
|
6
|
+
"path": "blocks/application/rich-text-editor/rich-text-editor-4/colors.ts",
|
|
7
|
+
"type": "registry:file",
|
|
8
|
+
"content": "import type { RichTextEditor4Color } from './types'\n\nexport const richTextEditor4Colors = {\n 'chart-1': {\n bar: 'bg-chart-1',\n dot: 'bg-chart-1',\n fill: 'bg-chart-1/20',\n ring: 'ring-chart-1',\n },\n 'chart-2': {\n bar: 'bg-chart-2',\n dot: 'bg-chart-2',\n fill: 'bg-chart-2/20',\n ring: 'ring-chart-2',\n },\n 'chart-3': {\n bar: 'bg-chart-3',\n dot: 'bg-chart-3',\n fill: 'bg-chart-3/20',\n ring: 'ring-chart-3',\n },\n 'chart-4': {\n bar: 'bg-chart-4',\n dot: 'bg-chart-4',\n fill: 'bg-chart-4/20',\n ring: 'ring-chart-4',\n },\n 'chart-5': {\n bar: 'bg-chart-5',\n dot: 'bg-chart-5',\n fill: 'bg-chart-5/20',\n ring: 'ring-chart-5',\n },\n primary: {\n bar: 'bg-primary',\n dot: 'bg-primary',\n fill: 'bg-primary/20',\n ring: 'ring-primary',\n },\n} as const satisfies Record<\n RichTextEditor4Color,\n { bar: string; dot: string; fill: string; ring: string }\n>\n",
|
|
9
|
+
"target": "~/packages/ui/src/blocks/application/rich-text-editor/rich-text-editor-4/colors.ts"
|
|
10
|
+
},
|
|
11
|
+
{
|
|
12
|
+
"path": "blocks/application/rich-text-editor/rich-text-editor-4/comments-store.ts",
|
|
13
|
+
"type": "registry:file",
|
|
14
|
+
"content": "import * as Y from 'yjs'\nimport type {\n RichTextEditor4Message,\n RichTextEditor4Thread,\n RichTextEditor4User,\n} from './types'\n\nexport const COMMENTS_KEY = 'comments'\nexport const MEMBERS_KEY = 'members'\n\nexport const getComments = (doc: Y.Doc): Y.Map<Y.Map<unknown>> =>\n doc.getMap(COMMENTS_KEY)\n\nexport const getMembers = (doc: Y.Doc): Y.Map<RichTextEditor4User> =>\n doc.getMap(MEMBERS_KEY)\n\nexport function registerMember(doc: Y.Doc, user: RichTextEditor4User) {\n getMembers(doc).set(String(doc.clientID), user)\n}\n\nexport function createThread(\n doc: Y.Doc,\n input: {\n author: RichTextEditor4User\n body: string\n createdAt: number\n id: string\n quote: string\n },\n) {\n doc.transact(() => {\n const thread = new Y.Map<unknown>()\n const messages = new Y.Array<RichTextEditor4Message>()\n thread.set('id', input.id)\n thread.set('quote', input.quote)\n thread.set('createdAt', input.createdAt)\n thread.set('resolved', false)\n thread.set('messages', messages)\n messages.push([\n {\n author: input.author,\n body: input.body,\n createdAt: input.createdAt,\n id: `${input.id}-m1`,\n },\n ])\n getComments(doc).set(input.id, thread)\n })\n}\n\nexport function addReply(\n doc: Y.Doc,\n threadId: string,\n message: Omit<RichTextEditor4Message, 'id'>,\n) {\n const messages = getComments(doc).get(threadId)?.get('messages')\n if (!(messages instanceof Y.Array)) return\n messages.push([\n { ...message, id: `${threadId}-${doc.clientID}-${messages.length + 1}` },\n ])\n}\n\nexport function setResolved(\n doc: Y.Doc,\n threadId: string,\n resolved: boolean,\n by?: RichTextEditor4User,\n) {\n const thread = getComments(doc).get(threadId)\n if (!thread) return\n doc.transact(() => {\n thread.set('resolved', resolved)\n if (resolved && by) thread.set('resolvedBy', by)\n else thread.delete('resolvedBy')\n })\n}\n\nexport function clearThreads(doc: Y.Doc) {\n doc.transact(() => {\n for (const key of [...getComments(doc).keys()]) getComments(doc).delete(key)\n })\n}\n\nexport function readThreads(\n doc: Y.Doc,\n anchored: (id: string) => boolean,\n): RichTextEditor4Thread[] {\n const threads: RichTextEditor4Thread[] = []\n getComments(doc).forEach((thread, id) => {\n const messages = thread.get('messages')\n const resolvedBy = thread.get('resolvedBy') as\n | RichTextEditor4User\n | undefined\n threads.push({\n anchored: anchored(id),\n createdAt: Number(thread.get('createdAt') ?? 0),\n id,\n messages: messages instanceof Y.Array ? messages.toArray() : [],\n quote: String(thread.get('quote') ?? ''),\n resolved: thread.get('resolved') === true,\n ...(resolvedBy ? { resolvedBy } : {}),\n })\n })\n return threads.sort((a, b) => a.createdAt - b.createdAt)\n}\n",
|
|
15
|
+
"target": "~/packages/ui/src/blocks/application/rich-text-editor/rich-text-editor-4/comments-store.ts"
|
|
16
|
+
},
|
|
17
|
+
{
|
|
18
|
+
"path": "blocks/application/rich-text-editor/rich-text-editor-4/comments.tsx",
|
|
19
|
+
"type": "registry:file",
|
|
20
|
+
"content": "'use client'\n\nimport { ChatCenteredDotsIcon } from '@phosphor-icons/react'\nimport { getCommentKey, getCommentKeyId, isCommentKey } from '@platejs/comment'\nimport { CommentPlugin } from '@platejs/comment/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 { Label } from '@tc96/ui/label'\nimport {\n Popover,\n PopoverDescription,\n PopoverPopup,\n PopoverTitle,\n} from '@tc96/ui/popover'\nimport { Switch } from '@tc96/ui/switch'\nimport { Textarea } from '@tc96/ui/textarea'\nimport { toastManager } from '@tc96/ui/toast'\nimport { ToolbarButton } from '@tc96/ui/toolbar'\nimport { cn } from '@tc96/utils'\nimport { KEYS, RangeApi, type RangeRef, TextApi } from 'platejs'\nimport {\n type PlateEditor,\n PlateLeaf,\n type PlateLeafProps,\n useEditorRef,\n useEditorSelector,\n} from 'platejs/react'\nimport {\n createContext,\n type ReactElement,\n useCallback,\n useContext,\n useEffect,\n useMemo,\n useRef,\n useState,\n} from 'react'\nimport type * as Y from 'yjs'\nimport {\n addReply,\n createThread,\n getComments,\n readThreads,\n setResolved,\n} from './comments-store'\nimport type {\n RichTextEditor4Labels,\n RichTextEditor4Thread,\n RichTextEditor4User,\n} from './types'\n\ntype CommentLabels = RichTextEditor4Labels['comments']\n\ntype PopoverState =\n | { kind: 'compose'; ref: RangeRef }\n | { anchor: Element | null; id: string; kind: 'thread' }\n | null\n\ninterface CommentsContextValue {\n activeId: string | null\n beginCompose: () => void\n labels: CommentLabels\n openThread: (id: string, anchor?: Element | null) => void\n popover: PopoverState\n resolvedIds: ReadonlySet<string>\n threads: RichTextEditor4Thread[]\n user: RichTextEditor4User\n}\n\nconst CommentsContext = createContext<CommentsContextValue | null>(null)\n\nconst useComments = (): CommentsContextValue => {\n const value = useContext(CommentsContext)\n if (!value) throw new Error('Comments parts need the comments provider')\n return value\n}\n\nconst draftKey = 'comment_draft'\n\nconst idsOf = (leaf: Record<string, unknown>): string[] =>\n Object.keys(leaf)\n .filter((key) => isCommentKey(key) && key !== draftKey)\n .map((key) => getCommentKeyId(key))\n\nexport function CommentLeaf(props: PlateLeafProps): ReactElement {\n const context = useContext(CommentsContext)\n const ids = idsOf(props.leaf as Record<string, unknown>)\n const open = ids.some((id) => !context?.resolvedIds.has(id))\n const active = ids.some((id) => id === context?.activeId)\n return (\n <PlateLeaf\n {...props}\n as=\"mark\"\n className={cn(\n 'rounded-xs text-inherit',\n open\n ? 'border-primary/60 border-b-2 bg-primary/15'\n : 'border-muted-foreground/60 border-b border-dashed bg-transparent',\n active && 'bg-primary/30',\n )}\n attributes={{ ...props.attributes, 'data-comment-id': ids.join(' ') }}\n />\n )\n}\n\nexport function commentPlugins() {\n return [CommentPlugin.withComponent(CommentLeaf)]\n}\n\nconst initialsOf = (name: string) => getInitials(name)\n\nconst timeFormat = new Intl.DateTimeFormat('pt-BR', {\n hour: '2-digit',\n minute: '2-digit',\n})\n\nexport interface CommentsController {\n context: CommentsContextValue\n threads: RichTextEditor4Thread[]\n}\n\nexport function useCommentsController({\n doc,\n editor,\n labels,\n now,\n onCommentsChange,\n user,\n}: Readonly<{\n doc: Y.Doc\n editor: PlateEditor\n labels: CommentLabels\n now: () => number\n onCommentsChange?: (threads: RichTextEditor4Thread[]) => void\n user: RichTextEditor4User\n}>) {\n const [threads, setThreads] = useState<RichTextEditor4Thread[]>([])\n const [popover, setPopover] = useState<PopoverState>(null)\n const counter = useRef(0)\n const signature = useRef('')\n const onChangeRef = useRef(onCommentsChange)\n onChangeRef.current = onCommentsChange\n\n const refresh = useCallback(() => {\n const next = readThreads(doc, (id) =>\n editor.getApi(CommentPlugin).comment.has({ id }),\n )\n const key = JSON.stringify(next)\n if (key === signature.current) return\n signature.current = key\n setThreads(next)\n onChangeRef.current?.(next)\n }, [doc, editor])\n\n useEffect(() => {\n const comments = getComments(doc)\n comments.observeDeep(refresh)\n doc.on('update', refresh)\n refresh()\n return () => {\n comments.unobserveDeep(refresh)\n doc.off('update', refresh)\n }\n }, [doc, refresh])\n\n const closePopover = useCallback(() => {\n setPopover((current) => {\n if (current?.kind === 'compose') current.ref.unref()\n return null\n })\n }, [])\n\n const beginCompose = useCallback(() => {\n const selection = editor.selection\n if (!selection || RangeApi.isCollapsed(selection)) return\n setPopover((current) => {\n if (current?.kind === 'compose') current.ref.unref()\n return {\n kind: 'compose',\n ref: editor.api.rangeRef(selection, { affinity: 'inward' }),\n }\n })\n }, [editor])\n\n const openThread = useCallback(\n (id: string, anchor?: Element | null) => {\n const root = editor.api.toDOMNode(editor)\n const element =\n anchor ??\n root?.querySelector(`[data-comment-id~=\"${CSS.escape(id)}\"]`) ??\n null\n setPopover((current) => {\n if (current?.kind === 'compose') current.ref.unref()\n return { anchor: element, id, kind: 'thread' }\n })\n },\n [editor],\n )\n\n useEffect(() => {\n const root = editor.api.toDOMNode(editor)\n if (!root) return\n const onClick = (event: MouseEvent) => {\n const target = (event.target as Element | null)?.closest(\n '[data-comment-id]',\n )\n const id = target?.getAttribute('data-comment-id')?.split(' ')[0]\n if (target && id) openThread(id, target)\n }\n root.addEventListener('click', onClick)\n return () => root.removeEventListener('click', onClick)\n })\n\n const submitThread = useCallback(\n (body: string) => {\n if (popover?.kind !== 'compose') return\n const range = popover.ref.current\n if (!range) {\n closePopover()\n return\n }\n counter.current += 1\n const id = `thread-${doc.clientID}-${counter.current}-${now()}`\n const quote = editor.api.string(range)\n editor.tf.setNodes(\n { [KEYS.comment]: true, [getCommentKey(id)]: true },\n { at: range, match: (node) => TextApi.isText(node), split: true },\n )\n createThread(doc, { author: user, body, createdAt: now(), id, quote })\n closePopover()\n },\n [closePopover, doc, editor, now, popover, user],\n )\n\n const reply = useCallback(\n (id: string, body: string) =>\n addReply(doc, id, { author: user, body, createdAt: now() }),\n [doc, now, user],\n )\n\n const resolve = useCallback(\n (id: string) => {\n setResolved(doc, id, true, user)\n const toast = toastManager.add({\n actionProps: {\n children: labels.undo,\n onClick: () => {\n setResolved(doc, id, false)\n toastManager.close(toast)\n },\n },\n title: labels.resolved,\n })\n closePopover()\n },\n [closePopover, doc, labels, user],\n )\n\n const reopen = useCallback(\n (id: string) => {\n setResolved(doc, id, false)\n toastManager.add({ title: labels.reopened })\n },\n [doc, labels],\n )\n\n const resolvedIds = useMemo(\n () => new Set(threads.filter((t) => t.resolved).map((t) => t.id)),\n [threads],\n )\n\n const context = useMemo<CommentsContextValue>(\n () => ({\n activeId: popover?.kind === 'thread' ? popover.id : null,\n beginCompose,\n labels,\n openThread,\n popover,\n resolvedIds,\n threads,\n user,\n }),\n [beginCompose, labels, openThread, popover, resolvedIds, threads, user],\n )\n\n return {\n actions: { closePopover, reopen, reply, resolve, submitThread },\n context,\n threads,\n }\n}\n\nexport type CommentsActions = ReturnType<\n typeof useCommentsController\n>['actions']\n\nexport const CommentsProvider = CommentsContext.Provider\n\nexport function CommentToolbarButton({\n label,\n}: Readonly<{ label: string }>): ReactElement {\n const { beginCompose } = useComments()\n const canComment = useEditorSelector(\n (editor) => !!editor.selection && RangeApi.isExpanded(editor.selection),\n [],\n )\n return (\n <ToolbarButton\n aria-label={label}\n disabled={!canComment}\n onClick={beginCompose}\n onMouseDown={(event) => event.preventDefault()}\n render={<Button size=\"icon-sm\" variant=\"ghost\" />}\n >\n <ChatCenteredDotsIcon aria-hidden=\"true\" />\n </ToolbarButton>\n )\n}\n\nfunction Message({\n author,\n body,\n createdAt,\n}: Readonly<{\n author: RichTextEditor4User\n body: string\n createdAt: number\n}>): ReactElement {\n return (\n <li className=\"flex gap-2\" data-slot=\"comment-message\">\n <Avatar className=\"[--avatar-size:--spacing(6)]\">\n <AvatarFallback>{initialsOf(author.name)}</AvatarFallback>\n </Avatar>\n <div className=\"flex min-w-0 flex-1 flex-col gap-0.5\">\n <p className=\"flex items-baseline gap-2 text-sm\">\n <span className=\"font-medium\">{author.name}</span>\n <time\n className=\"text-muted-foreground text-xs\"\n dateTime={new Date(createdAt).toISOString()}\n >\n {timeFormat.format(createdAt)}\n </time>\n </p>\n <p className=\"whitespace-pre-wrap break-words text-sm\">{body}</p>\n </div>\n </li>\n )\n}\n\nfunction Quote({ children }: Readonly<{ children: string }>): ReactElement {\n return (\n <blockquote className=\"line-clamp-3 border-primary/60 border-s-2 ps-2 text-muted-foreground text-sm\">\n {children}\n </blockquote>\n )\n}\n\nfunction ComposePanel({\n actions,\n labels,\n quote,\n}: Readonly<{\n actions: CommentsActions\n labels: CommentLabels\n quote: string\n}>): ReactElement {\n const [body, setBody] = useState('')\n return (\n <form\n className=\"flex w-72 flex-col gap-3\"\n onSubmit={(event) => {\n event.preventDefault()\n if (body.trim()) actions.submitThread(body.trim())\n }}\n >\n <PopoverTitle className=\"text-sm\">{labels.newThread}</PopoverTitle>\n <Quote>{quote}</Quote>\n <Textarea\n aria-label={labels.composer}\n autoFocus\n onChange={(event) => setBody(event.target.value)}\n placeholder={labels.composer}\n value={body}\n />\n <div className=\"flex justify-end gap-2\">\n <Button onClick={actions.closePopover} size=\"sm\" variant=\"ghost\">\n {labels.cancel}\n </Button>\n <Button disabled={!body.trim()} size=\"sm\" type=\"submit\">\n {labels.send}\n </Button>\n </div>\n </form>\n )\n}\n\nfunction ThreadPanel({\n actions,\n labels,\n thread,\n}: Readonly<{\n actions: CommentsActions\n labels: CommentLabels\n thread: RichTextEditor4Thread\n}>): ReactElement {\n const [body, setBody] = useState('')\n return (\n <div className=\"flex w-80 flex-col gap-3\">\n <div className=\"flex items-start justify-between gap-2\">\n <PopoverTitle className=\"text-sm\">{labels.thread}</PopoverTitle>\n <Badge variant={thread.resolved ? 'success' : 'info'}>\n {thread.resolved ? labels.resolvedBadge : labels.open}\n </Badge>\n </div>\n <PopoverDescription className=\"sr-only\">\n {thread.quote}\n </PopoverDescription>\n <Quote>{thread.quote}</Quote>\n <ol className=\"flex flex-col gap-3\">\n {thread.messages.map((message) => (\n <Message key={message.id} {...message} />\n ))}\n </ol>\n {thread.resolved ? (\n <div className=\"flex justify-end\">\n <Button\n onClick={() => actions.reopen(thread.id)}\n size=\"sm\"\n variant=\"outline\"\n >\n {labels.reopen}\n </Button>\n </div>\n ) : (\n <form\n className=\"flex flex-col gap-2\"\n onSubmit={(event) => {\n event.preventDefault()\n if (!body.trim()) return\n actions.reply(thread.id, body.trim())\n setBody('')\n }}\n >\n <Textarea\n aria-label={labels.replyComposer}\n onChange={(event) => setBody(event.target.value)}\n placeholder={labels.replyComposer}\n value={body}\n />\n <div className=\"flex justify-between gap-2\">\n <Button\n onClick={() => actions.resolve(thread.id)}\n size=\"sm\"\n variant=\"outline\"\n >\n {labels.resolve}\n </Button>\n <Button disabled={!body.trim()} size=\"sm\" type=\"submit\">\n {labels.reply}\n </Button>\n </div>\n </form>\n )}\n </div>\n )\n}\n\nconst virtualAnchor = (getRect: () => DOMRect | undefined) => ({\n getBoundingClientRect: () => getRect() ?? new DOMRect(),\n})\n\nexport function CommentPopovers({\n actions,\n}: Readonly<{ actions: CommentsActions }>): ReactElement | null {\n const editor = useEditorRef()\n const { labels, popover, threads } = useComments()\n\n const composeRange = popover?.kind === 'compose' ? popover.ref.current : null\n const thread =\n popover?.kind === 'thread'\n ? threads.find((item) => item.id === popover.id)\n : undefined\n\n if (popover?.kind === 'compose' && composeRange) {\n return (\n <Popover\n onOpenChange={(open) => {\n if (!open) actions.closePopover()\n }}\n open\n >\n <PopoverPopup\n anchor={virtualAnchor(() =>\n editor.api.toDOMRange(composeRange)?.getBoundingClientRect(),\n )}\n aria-label={labels.newThread}\n data-slot=\"comment-compose\"\n >\n <ComposePanel\n actions={actions}\n labels={labels}\n quote={editor.api.string(composeRange)}\n />\n </PopoverPopup>\n </Popover>\n )\n }\n\n if (popover?.kind === 'thread' && thread) {\n return (\n <Popover\n onOpenChange={(open) => {\n if (!open) actions.closePopover()\n }}\n open\n >\n <PopoverPopup\n anchor={popover.anchor ?? undefined}\n aria-label={labels.thread}\n data-slot=\"comment-thread\"\n >\n <ThreadPanel actions={actions} labels={labels} thread={thread} />\n </PopoverPopup>\n </Popover>\n )\n }\n\n return null\n}\n\nexport function CommentsRail(): ReactElement {\n const { activeId, labels, openThread, threads } = useComments()\n const [showResolved, setShowResolved] = useState(false)\n const resolvedCount = threads.filter((thread) => thread.resolved).length\n const visible = threads.filter((thread) => showResolved || !thread.resolved)\n return (\n <div className=\"flex min-w-0 flex-col gap-3 p-4\" data-slot=\"comments-rail\">\n <div className=\"flex items-center justify-between gap-2\">\n <h3 className=\"font-medium text-sm\">{labels.list}</h3>\n {resolvedCount > 0 ? (\n <Label className=\"text-xs\">\n <Switch checked={showResolved} onCheckedChange={setShowResolved} />\n {labels.showResolved}\n </Label>\n ) : null}\n </div>\n {visible.length === 0 ? (\n <p className=\"text-muted-foreground text-sm\">{labels.empty}</p>\n ) : (\n <ul className=\"flex flex-col gap-2\">\n {visible.map((thread) => {\n const first = thread.messages[0]\n return (\n <li key={thread.id}>\n <button\n aria-label={labels.openThread(thread.quote)}\n aria-pressed={activeId === thread.id}\n className={cn(\n 'flex w-full flex-col gap-1.5 rounded-lg border bg-background p-3 text-start text-sm outline-none transition-colors hover:bg-accent/50 focus-visible:ring-2 focus-visible:ring-ring aria-pressed:bg-accent',\n thread.resolved && 'text-muted-foreground',\n )}\n data-resolved={thread.resolved}\n data-slot=\"comment-thread-item\"\n data-thread={thread.id}\n onClick={(event) =>\n openThread(\n thread.id,\n thread.anchored ? undefined : event.currentTarget,\n )\n }\n type=\"button\"\n >\n <span className=\"line-clamp-2 border-primary/60 border-s-2 ps-2 text-xs\">\n {thread.quote}\n </span>\n {first ? (\n <span className=\"line-clamp-2 text-foreground\">\n <span className=\"font-medium\">{first.author.name}: </span>\n {first.body}\n </span>\n ) : null}\n <span className=\"flex flex-wrap items-center gap-1.5 text-xs\">\n <Badge variant={thread.resolved ? 'success' : 'info'}>\n {thread.resolved ? labels.resolvedBadge : labels.open}\n </Badge>\n <span>{labels.replies(thread.messages.length)}</span>\n {thread.anchored ? null : <span>{labels.unanchored}</span>}\n </span>\n </button>\n </li>\n )\n })}\n </ul>\n )}\n </div>\n )\n}\n",
|
|
21
|
+
"target": "~/packages/ui/src/blocks/application/rich-text-editor/rich-text-editor-4/comments.tsx"
|
|
22
|
+
},
|
|
23
|
+
{
|
|
24
|
+
"path": "blocks/application/rich-text-editor/rich-text-editor-4/history-keys.ts",
|
|
25
|
+
"type": "registry:file",
|
|
26
|
+
"content": "import { createPlatePlugin } from 'platejs/react'\n\nexport const historyKeysPlugin = createPlatePlugin({\n handlers: {\n onKeyDown: ({ editor, event }) => {\n if (!(event.metaKey || event.ctrlKey) || event.altKey) return false\n const key = event.key.toLowerCase()\n const redo = (key === 'z' && event.shiftKey) || key === 'y'\n if (key !== 'z' && !redo) return false\n event.preventDefault()\n if (redo) editor.redo()\n else editor.undo()\n return true\n },\n },\n key: 'yjs_history_keys',\n})\n",
|
|
27
|
+
"target": "~/packages/ui/src/blocks/application/rich-text-editor/rich-text-editor-4/history-keys.ts"
|
|
28
|
+
},
|
|
29
|
+
{
|
|
30
|
+
"path": "blocks/application/rich-text-editor/rich-text-editor-4/index.ts",
|
|
31
|
+
"type": "registry:file",
|
|
32
|
+
"content": "export type {\n LocalRoom,\n LocalRoomClock,\n LocalRoomOptions,\n LocalRoomStep,\n LocalTeammate,\n} from './local-room'\nexport { createLocalRoom, useLocalRoom } from './local-room'\nexport { RichTextEditor4 } from './rich-text-editor-4'\nexport type {\n RichTextEditor4Color,\n RichTextEditor4Labels,\n RichTextEditor4LabelsInput,\n RichTextEditor4Message,\n RichTextEditor4NavbarContext,\n RichTextEditor4Props,\n RichTextEditor4Room,\n RichTextEditor4Status,\n RichTextEditor4Thread,\n RichTextEditor4User,\n} from './types'\n",
|
|
33
|
+
"target": "~/packages/ui/src/blocks/application/rich-text-editor/rich-text-editor-4/index.ts"
|
|
34
|
+
},
|
|
35
|
+
{
|
|
36
|
+
"path": "blocks/application/rich-text-editor/rich-text-editor-4/labels.ts",
|
|
37
|
+
"type": "registry:file",
|
|
38
|
+
"content": "import type { RichTextEditor4Labels } from './types'\n\nexport const defaultRichTextEditor4Labels: RichTextEditor4Labels = {\n blocks: {\n blockquote: 'Citação',\n h2: 'Título de seção',\n h3: 'Subtítulo',\n },\n comments: {\n cancel: 'Cancelar',\n composer: 'Escreva um comentário',\n empty: 'Selecione um trecho do texto para abrir uma conversa.',\n list: 'Conversas',\n new: 'Comentar',\n newThread: 'Nova conversa',\n open: 'Aberta',\n openThread: (quote) => `Abrir conversa sobre \"${quote}\"`,\n reopen: 'Reabrir',\n reopened: 'Conversa reaberta',\n replies: (count) => (count === 1 ? '1 mensagem' : `${count} mensagens`),\n reply: 'Responder',\n replyComposer: 'Escreva uma resposta',\n resolve: 'Resolver',\n resolved: 'Conversa resolvida',\n resolvedBadge: 'Resolvida',\n send: 'Enviar',\n showResolved: 'Mostrar resolvidas',\n thread: 'Conversa',\n unanchored: 'O trecho comentado foi removido',\n undo: 'Desfazer resolução',\n },\n editor: 'Especificação do produto',\n online: {\n label: 'Online',\n merged: (names) =>\n `As edições de ${names.join(', ')} foram mescladas ao documento.`,\n offline: (queued) =>\n queued === 0\n ? 'Você está offline. As suas edições ficam na fila até voltar.'\n : `Você está offline. ${queued} ${queued === 1 ? 'edição aguarda' : 'edições aguardam'} na fila.`,\n synced: 'Sincronizado. Nenhuma edição de outras pessoas chegou.',\n },\n presence: {\n follow: (name) => `Seguir o cursor de ${name}`,\n following: (name) => `Seguindo ${name}`,\n group: 'Pessoas neste documento',\n person: (name, status) => `${name}, ${status}`,\n status: {\n editing: 'Editando',\n idle: 'Ausente',\n viewing: 'Visualizando',\n },\n stopFollowing: 'Parar de seguir',\n summary: ({ editing, idle, viewing }) =>\n [\n editing > 0 ? `${editing} editando` : null,\n viewing > 0 ? `${viewing} visualizando` : null,\n idle > 0 ? `${idle} ausente${idle === 1 ? '' : 's'}` : null,\n ]\n .filter(Boolean)\n .join(', '),\n you: 'Você',\n },\n placeholder: \"Digite '/' para blocos\",\n replay: 'Reproduzir',\n slashMenu: 'Blocos',\n slashMenuEmpty: 'Nenhum bloco com esse nome',\n title: 'Especificação em tempo real',\n tools: {\n blockType: 'Tipo de bloco',\n bulletList: 'Lista com marcadores',\n comment: 'Comentar trecho',\n format: 'Formatação do documento',\n numberedList: 'Lista numerada',\n paragraph: 'Texto',\n },\n}\n",
|
|
39
|
+
"target": "~/packages/ui/src/blocks/application/rich-text-editor/rich-text-editor-4/labels.ts"
|
|
40
|
+
},
|
|
41
|
+
{
|
|
42
|
+
"path": "blocks/application/rich-text-editor/rich-text-editor-4/local-room.ts",
|
|
43
|
+
"type": "registry:file",
|
|
44
|
+
"content": "import { useEffect, useRef, useState } from 'react'\nimport {\n Awareness,\n applyAwarenessUpdate,\n encodeAwarenessUpdate,\n} from 'y-protocols/awareness'\nimport * as Y from 'yjs'\nimport {\n addReply,\n createThread,\n registerMember,\n setResolved,\n} from './comments-store'\nimport type {\n RichTextEditor4Room,\n RichTextEditor4Status,\n RichTextEditor4User,\n} from './types'\nimport {\n getSharedRoot,\n listTextBlocks,\n plainLength,\n plainText,\n} from './yjs-tree'\n\ninterface Peer {\n awareness: Awareness\n doc: Y.Doc\n}\n\ninterface AwarenessChange {\n added: number[]\n removed: number[]\n updated: number[]\n}\n\nfunction createLink(a: Peer, b: Peer) {\n const origin = Symbol('local-room-link')\n let connected = false\n\n const forwardDoc = (target: Y.Doc) => (update: Uint8Array, from: unknown) => {\n if (connected && from !== origin) Y.applyUpdate(target, update, origin)\n }\n const forwardAwareness =\n (source: Awareness, target: Awareness) =>\n ({ added, removed, updated }: AwarenessChange, from: unknown) => {\n if (!connected || from === origin) return\n applyAwarenessUpdate(\n target,\n encodeAwarenessUpdate(source, [...added, ...updated, ...removed]),\n origin,\n )\n }\n\n const docToB = forwardDoc(b.doc)\n const docToA = forwardDoc(a.doc)\n const awarenessToB = forwardAwareness(a.awareness, b.awareness)\n const awarenessToA = forwardAwareness(b.awareness, a.awareness)\n a.doc.on('update', docToB)\n b.doc.on('update', docToA)\n a.awareness.on('update', awarenessToB)\n b.awareness.on('update', awarenessToA)\n\n const exchange = (from: Peer, to: Peer) => {\n Y.applyUpdate(\n to.doc,\n Y.encodeStateAsUpdate(from.doc, Y.encodeStateVector(to.doc)),\n origin,\n )\n applyAwarenessUpdate(\n to.awareness,\n encodeAwarenessUpdate(from.awareness, [\n ...from.awareness.getStates().keys(),\n ]),\n origin,\n )\n }\n\n let saved: Record<string, unknown> | null = null\n\n return {\n connect() {\n if (connected) return\n connected = true\n exchange(a, b)\n exchange(b, a)\n if (saved) a.awareness.setLocalState(saved)\n saved = null\n },\n destroy() {\n connected = false\n a.doc.off('update', docToB)\n b.doc.off('update', docToA)\n a.awareness.off('update', awarenessToB)\n b.awareness.off('update', awarenessToA)\n },\n disconnect() {\n if (!connected) return\n saved = a.awareness.getLocalState()\n a.awareness.setLocalState(null)\n connected = false\n },\n get connected() {\n return connected\n },\n }\n}\n\nfunction refresh(awareness: Awareness) {\n const state = awareness.getLocalState()\n if (!state) return\n awareness.setLocalState(state)\n awareness.setLocalState(state)\n}\n\nexport type LocalRoomStep =\n | { at: number; block: number; offset: number; type: 'caret'; user: string }\n | {\n at: number\n block: number\n from: number\n to: number\n type: 'select'\n user: string\n }\n | {\n at: number\n block: number\n offset: number | 'end'\n text: string\n type: 'type'\n user: string\n }\n | {\n at: number\n status: RichTextEditor4Status\n type: 'status'\n user: string\n }\n | {\n at: number\n block: number\n body: string\n from: number\n id: string\n to: number\n type: 'comment'\n user: string\n }\n | { at: number; body: string; thread: string; type: 'reply'; user: string }\n | { at: number; thread: string; type: 'resolve'; user: string }\n\nexport interface LocalRoomClock {\n clearTimeout: (handle: unknown) => void\n now: () => number\n setTimeout: (callback: () => void, delay: number) => unknown\n}\n\nexport interface LocalRoomOptions {\n autoplay?: boolean\n clock?: LocalRoomClock\n script?: readonly LocalRoomStep[]\n teammates?: readonly RichTextEditor4User[]\n}\n\nexport interface LocalTeammate {\n caret: (block: number, offset: number) => void\n comment: (input: {\n block: number\n body: string\n from: number\n id: string\n to: number\n }) => void\n doc: Y.Doc\n reply: (thread: string, body: string) => void\n resolve: (thread: string) => void\n select: (block: number, from: number, to: number) => void\n setStatus: (status: RichTextEditor4Status) => void\n type: (block: number, text: string, offset?: number | 'end') => void\n user: RichTextEditor4User\n}\n\nexport interface LocalRoom extends RichTextEditor4Room {\n connect: () => void\n destroy: () => void\n disconnect: () => void\n join: () => RichTextEditor4Room\n readonly online: boolean\n replay: () => void\n step: () => LocalRoomStep | null\n stepAll: () => void\n teammates: readonly LocalTeammate[]\n}\n\nconst defaultClock: LocalRoomClock = {\n clearTimeout: (handle) =>\n globalThis.clearTimeout(handle as ReturnType<typeof setTimeout>),\n now: () => Date.now(),\n setTimeout: (callback, delay) => globalThis.setTimeout(callback, delay),\n}\n\nconst hasContent = (doc: Y.Doc) => getSharedRoot(doc).length > 0\n\nconst createPeer = (): Peer => {\n const doc = new Y.Doc()\n return { awareness: new Awareness(doc), doc }\n}\n\nfunction createTeammate(\n user: RichTextEditor4User,\n clock: LocalRoomClock,\n): LocalTeammate & Peer {\n const peer = createPeer()\n registerMember(peer.doc, user)\n peer.awareness.setLocalState({\n data: user,\n presence: { status: 'viewing' },\n selection: null,\n })\n\n const blockAt = (index: number) =>\n listTextBlocks(getSharedRoot(peer.doc))[index]\n const relative = (block: Y.XmlText, offset: number) =>\n Y.relativePositionToJSON(\n Y.createRelativePositionFromTypeIndex(block, offset),\n )\n const setSelection = (block: Y.XmlText, from: number, to: number) =>\n peer.awareness.setLocalStateField('selection', {\n anchor: relative(block, from),\n focus: relative(block, to),\n })\n const setStatus = (status: RichTextEditor4Status) =>\n peer.awareness.setLocalStateField('presence', { status })\n\n return {\n ...peer,\n caret(index, offset) {\n const block = blockAt(index)\n if (!block) return\n setSelection(block, offset, offset)\n },\n comment({ block: index, body, from, id, to }) {\n const block = blockAt(index)\n if (!block) return\n const quote = plainText(block).slice(from, to)\n peer.doc.transact(() => {\n block.format(from, to - from, {\n comment: true,\n [`comment_${id}`]: true,\n })\n createThread(peer.doc, {\n author: user,\n body,\n createdAt: clock.now(),\n id,\n quote,\n })\n })\n },\n reply(thread, body) {\n addReply(peer.doc, thread, { author: user, body, createdAt: clock.now() })\n },\n resolve(thread) {\n setResolved(peer.doc, thread, true, user)\n },\n select(index, from, to) {\n const block = blockAt(index)\n if (!block) return\n setSelection(block, from, to)\n },\n setStatus,\n type(index, text, offset = 'end') {\n const block = blockAt(index)\n if (!block) return\n const at = offset === 'end' ? plainLength(block) : offset\n peer.doc.transact(() => block.insert(at, text, {}), `teammate:${user.id}`)\n setSelection(block, at + text.length, at + text.length)\n setStatus('editing')\n },\n user,\n }\n}\n\nexport function createLocalRoom({\n autoplay = true,\n clock = defaultClock,\n script = [],\n teammates: users = [],\n}: Readonly<LocalRoomOptions> = {}): LocalRoom {\n const hub = createPeer()\n hub.awareness.setLocalState(null)\n const clients: { link: ReturnType<typeof createLink>; peer: Peer }[] = []\n const links: ReturnType<typeof createLink>[] = []\n\n const attach = (peer: Peer) => {\n const link = createLink(peer, hub)\n link.connect()\n links.push(link)\n return link\n }\n\n const members = users.map((user) => {\n const teammate = createTeammate(user, clock)\n attach(teammate)\n return teammate\n })\n\n const ordered = [...script].sort((a, b) => a.at - b.at)\n let cursor = 0\n let timers: unknown[] = []\n let started = false\n\n const run = (step: LocalRoomStep) => {\n const teammate = members.find((member) => member.user.id === step.user)\n if (!teammate) return\n switch (step.type) {\n case 'caret':\n teammate.caret(step.block, step.offset)\n break\n case 'comment':\n teammate.comment(step)\n break\n case 'reply':\n teammate.reply(step.thread, step.body)\n break\n case 'resolve':\n teammate.resolve(step.thread)\n break\n case 'select':\n teammate.select(step.block, step.from, step.to)\n break\n case 'status':\n teammate.setStatus(step.status)\n break\n case 'type':\n teammate.type(step.block, step.text, step.offset)\n break\n }\n }\n\n const stop = () => {\n for (const timer of timers) clock.clearTimeout(timer)\n timers = []\n }\n\n const start = () => {\n stop()\n started = true\n const base = cursor\n ordered.slice(base).forEach((step, index) => {\n const timer = clock.setTimeout(() => {\n if (cursor === base + index) {\n cursor += 1\n run(step)\n }\n }, step.at)\n timers.push(timer)\n })\n }\n\n const watch = () => {\n if (autoplay && !started && hasContent(hub.doc)) start()\n }\n hub.doc.on('update', watch)\n\n const makeClient = (): RichTextEditor4Room => {\n const peer = createPeer()\n const link = attach(peer)\n clients.push({ link, peer })\n return {\n awareness: peer.awareness,\n connect: () => {\n link.connect()\n for (const other of [...members, ...clients.map((c) => c.peer)]) {\n if (other !== peer) refresh(other.awareness)\n }\n },\n disconnect: () => link.disconnect(),\n doc: peer.doc,\n replay: () => room.replay(),\n }\n }\n\n const primary = makeClient()\n\n const room: LocalRoom = {\n awareness: primary.awareness,\n connect: () => primary.connect?.(),\n destroy() {\n stop()\n hub.doc.off('update', watch)\n for (const link of links) link.destroy()\n for (const peer of [hub, ...members, ...clients.map((c) => c.peer)]) {\n peer.awareness.destroy()\n peer.doc.destroy()\n }\n },\n disconnect: () => primary.disconnect?.(),\n doc: primary.doc,\n join: makeClient,\n get online() {\n return clients[0]?.link.connected ?? false\n },\n replay() {\n stop()\n cursor = 0\n started = false\n for (const teammate of members) {\n teammate.setStatus('viewing')\n teammate.awareness.setLocalStateField('selection', null)\n }\n if (autoplay) start()\n },\n step() {\n const next = ordered[cursor]\n if (!next) return null\n cursor += 1\n run(next)\n return next\n },\n stepAll() {\n while (room.step()) {}\n },\n teammates: members,\n }\n return room\n}\n\nexport function useLocalRoom(\n options?: Readonly<LocalRoomOptions>,\n): LocalRoom | null {\n const [room, setRoom] = useState<LocalRoom | null>(null)\n const optionsRef = useRef(options)\n useEffect(() => {\n const created = createLocalRoom(optionsRef.current)\n setRoom(created)\n return () => created.destroy()\n }, [])\n return room\n}\n",
|
|
45
|
+
"target": "~/packages/ui/src/blocks/application/rich-text-editor/rich-text-editor-4/local-room.ts"
|
|
46
|
+
},
|
|
47
|
+
{
|
|
48
|
+
"path": "blocks/application/rich-text-editor/rich-text-editor-4/presence-stack.tsx",
|
|
49
|
+
"type": "registry:file",
|
|
50
|
+
"content": "'use client'\n\nimport { Avatar, AvatarFallback } from '@tc96/ui/avatar'\nimport { Button } from '@tc96/ui/button'\nimport { getInitials } from '@tc96/ui/helpers/initials'\nimport { cn } from '@tc96/utils'\nimport type { ReactElement } from 'react'\nimport { richTextEditor4Colors } from './colors'\nimport type {\n RichTextEditor4Labels,\n RichTextEditor4Status,\n RichTextEditor4User,\n} from './types'\n\nexport interface PresenceEntry {\n id: string\n name: string\n status: RichTextEditor4Status\n user: RichTextEditor4User\n}\n\nconst statusDot = {\n editing: 'bg-success',\n idle: 'bg-muted-foreground',\n viewing: 'bg-info',\n} as const satisfies Record<RichTextEditor4Status, string>\n\nfunction Face({ entry }: Readonly<{ entry: PresenceEntry }>): ReactElement {\n const palette = richTextEditor4Colors[entry.user.color]\n return (\n <span\n className={cn(\n 'relative inline-flex rounded-full ring-2 ring-offset-2 ring-offset-background',\n palette.ring,\n )}\n >\n <Avatar className=\"[--avatar-size:--spacing(7)]\">\n <AvatarFallback>{getInitials(entry.name)}</AvatarFallback>\n </Avatar>\n <span\n className={cn(\n 'absolute -end-0.5 -bottom-0.5 size-2.5 rounded-full ring-2 ring-background',\n statusDot[entry.status],\n )}\n data-status={entry.status}\n data-slot=\"presence-status\"\n />\n </span>\n )\n}\n\nexport function PresenceStack({\n followId,\n labels,\n onFollow,\n others,\n self,\n}: Readonly<{\n followId: string | null\n labels: RichTextEditor4Labels['presence']\n onFollow: (id: string | null) => void\n others: PresenceEntry[]\n self: PresenceEntry\n}>): ReactElement {\n const everyone = [self, ...others]\n const counts: Record<RichTextEditor4Status, number> = {\n editing: 0,\n idle: 0,\n viewing: 0,\n }\n for (const entry of everyone) counts[entry.status] += 1\n const followed = others.find((entry) => entry.id === followId)\n return (\n <div\n className=\"flex flex-wrap items-center gap-3\"\n data-slot=\"presence-stack\"\n >\n <ul aria-label={labels.group} className=\"flex items-center gap-2.5\">\n <li data-person={self.id}>\n <span\n aria-label={labels.person(labels.you, labels.status[self.status])}\n role=\"img\"\n >\n <Face entry={self} />\n </span>\n </li>\n {others.map((entry) => (\n <li data-person={entry.id} key={entry.id}>\n <button\n aria-label={labels.person(\n entry.name,\n labels.status[entry.status],\n )}\n aria-pressed={followId === entry.id}\n className=\"inline-flex rounded-full outline-none focus-visible:ring-2 focus-visible:ring-ring\"\n onClick={() => onFollow(followId === entry.id ? null : entry.id)}\n title={labels.follow(entry.name)}\n type=\"button\"\n >\n <Face entry={entry} />\n </button>\n </li>\n ))}\n </ul>\n <output\n className=\"text-muted-foreground text-xs\"\n data-slot=\"presence-summary\"\n >\n {labels.summary(counts)}\n </output>\n {followed ? (\n <Button onClick={() => onFollow(null)} size=\"sm\" variant=\"outline\">\n {labels.following(followed.name)}\n <span className=\"sr-only\">. {labels.stopFollowing}</span>\n </Button>\n ) : null}\n </div>\n )\n}\n",
|
|
51
|
+
"target": "~/packages/ui/src/blocks/application/rich-text-editor/rich-text-editor-4/presence-stack.tsx"
|
|
52
|
+
},
|
|
53
|
+
{
|
|
54
|
+
"path": "blocks/application/rich-text-editor/rich-text-editor-4/remote-carets.tsx",
|
|
55
|
+
"type": "registry:file",
|
|
56
|
+
"content": "'use client'\n\nimport { cn } from '@tc96/utils'\nimport { NodeApi, type TRange } from 'platejs'\nimport type { PlateEditor } from 'platejs/react'\nimport {\n type ReactElement,\n type RefObject,\n useEffect,\n useRef,\n useState,\n} from 'react'\nimport type { Awareness } from 'y-protocols/awareness'\nimport type * as Y from 'yjs'\nimport { richTextEditor4Colors } from './colors'\nimport type { RichTextEditor4Status, RichTextEditor4User } from './types'\nimport {\n comparePoints,\n getSharedRoot,\n type PlainPoint,\n relativeToPlainPoint,\n} from './yjs-tree'\n\nexport interface RemotePerson {\n clientId: number\n color: RichTextEditor4User['color']\n id: string\n name: string\n selection: { anchor: unknown; focus: unknown } | null\n status: RichTextEditor4Status\n}\n\nconst noPeople: RemotePerson[] = []\n\nexport function useRemotePeople(\n awareness: Awareness,\n selfId: string,\n enabled: boolean,\n): RemotePerson[] {\n const [people, setPeople] = useState<RemotePerson[]>(noPeople)\n useEffect(() => {\n const read = () => {\n const next = new Map<string, RemotePerson>()\n awareness.getStates().forEach((state, clientId) => {\n const data = state.data as RichTextEditor4User | undefined\n if (clientId === awareness.clientID || !data || data.id === selfId)\n return\n const presence = state.presence as\n | { status?: RichTextEditor4Status }\n | undefined\n next.set(data.id, {\n clientId,\n color: data.color,\n id: data.id,\n name: data.name,\n selection: state.selection ?? null,\n status: presence?.status ?? 'viewing',\n })\n })\n setPeople([...next.values()])\n }\n read()\n awareness.on('change', read)\n return () => awareness.off('change', read)\n }, [awareness, selfId])\n return enabled ? people : noPeople\n}\n\ninterface Box {\n height: number\n left: number\n top: number\n width: number\n}\n\ninterface CaretLayout {\n caret: Box\n color: RichTextEditor4User['color']\n id: string\n name: string\n rects: Box[]\n}\n\ninterface DomPoint {\n node: Node\n offset: number\n}\n\nfunction locate(editor: PlateEditor, point: PlainPoint): DomPoint | null {\n const node = NodeApi.get(editor, point.path)\n const element = node && editor.api.toDOMNode(node)\n if (!element) return null\n const walker = element.ownerDocument.createTreeWalker(\n element,\n NodeFilter.SHOW_TEXT,\n {\n acceptNode: (text) =>\n text.parentElement?.closest('[data-slate-string]')\n ? NodeFilter.FILTER_ACCEPT\n : NodeFilter.FILTER_REJECT,\n },\n )\n let remaining = point.offset\n let last: Text | null = null\n while (walker.nextNode()) {\n const text = walker.currentNode as Text\n last = text\n if (remaining <= text.length) return { node: text, offset: remaining }\n remaining -= text.length\n }\n return last\n ? { node: last, offset: last.length }\n : { node: element, offset: 0 }\n}\n\nconst toBox = (rect: DOMRect, origin: DOMRect): Box => ({\n height: Math.round(rect.height),\n left: Math.round(rect.left - origin.left),\n top: Math.round(rect.top - origin.top),\n width: Math.round(rect.width),\n})\n\nfunction measureCaret(\n point: DomPoint,\n origin: DOMRect,\n editor: PlateEditor,\n path: number[],\n): Box {\n const range = document.createRange()\n range.setStart(point.node, point.offset)\n range.collapse(true)\n const rect = range.getClientRects()[0] ?? range.getBoundingClientRect()\n if (rect.height > 0) return { ...toBox(rect, origin), width: 0 }\n const block = NodeApi.get(editor, path)\n const element = block && editor.api.toDOMNode(block)\n const bounds = element?.getBoundingClientRect() ?? rect\n const lineHeight = element\n ? Number.parseFloat(getComputedStyle(element).lineHeight) || 24\n : 24\n return {\n height: Math.round(lineHeight),\n left: Math.round(bounds.left - origin.left),\n top: Math.round(bounds.top - origin.top),\n width: 0,\n }\n}\n\nfunction measureSelection(start: DomPoint, end: DomPoint, origin: DOMRect) {\n const range = document.createRange()\n range.setStart(start.node, start.offset)\n range.setEnd(end.node, end.offset)\n return Array.from(range.getClientRects())\n .filter((rect) => rect.width > 1 && rect.height > 1)\n .map((rect) => toBox(rect, origin))\n}\n\nconst boxStyle = (box: Box) => ({\n height: box.height,\n left: box.left,\n top: box.top,\n width: box.width,\n})\n\nexport function RemoteCarets({\n containerRef,\n doc,\n draft,\n editor,\n followId,\n people,\n}: Readonly<{\n containerRef: RefObject<HTMLElement | null>\n doc: Y.Doc\n draft: TRange | null\n editor: PlateEditor\n followId: string | null\n people: RemotePerson[]\n}>): ReactElement {\n const [layouts, setLayouts] = useState<CaretLayout[]>([])\n const [draftRects, setDraftRects] = useState<Box[]>([])\n const signature = useRef('')\n\n useEffect(() => {\n const container = containerRef.current\n if (!container) return\n let frame = 0\n const measure = () => {\n const origin = container.getBoundingClientRect()\n const root = getSharedRoot(doc)\n const next: CaretLayout[] = []\n for (const person of people) {\n if (!person.selection) continue\n const anchor = relativeToPlainPoint(doc, root, person.selection.anchor)\n const focus = relativeToPlainPoint(doc, root, person.selection.focus)\n if (!anchor || !focus) continue\n const [start, end] =\n comparePoints(anchor, focus) <= 0 ? [anchor, focus] : [focus, anchor]\n const from = locate(editor, start)\n const to = locate(editor, end)\n const at = locate(editor, focus)\n if (!from || !to || !at) continue\n next.push({\n caret: measureCaret(at, origin, editor, focus.path),\n color: person.color,\n id: person.id,\n name: person.name,\n rects:\n comparePoints(anchor, focus) === 0\n ? []\n : measureSelection(from, to, origin),\n })\n }\n const domRange = draft && editor.api.toDOMRange(draft)\n const nextDraft = domRange\n ? Array.from<DOMRect>(domRange.getClientRects())\n .filter((rect) => rect.width > 1 && rect.height > 1)\n .map((rect) => toBox(rect, origin))\n : []\n const key = JSON.stringify([next, nextDraft])\n if (key === signature.current) return\n signature.current = key\n setLayouts(next)\n setDraftRects(nextDraft)\n }\n const schedule = () => {\n cancelAnimationFrame(frame)\n frame = requestAnimationFrame(measure)\n }\n const editable = editor.api.toDOMNode(editor)\n const mutations = new MutationObserver(schedule)\n if (editable)\n mutations.observe(editable, {\n characterData: true,\n childList: true,\n subtree: true,\n })\n const resize = new ResizeObserver(schedule)\n resize.observe(container)\n doc.on('update', schedule)\n window.addEventListener('resize', schedule)\n schedule()\n return () => {\n cancelAnimationFrame(frame)\n mutations.disconnect()\n resize.disconnect()\n doc.off('update', schedule)\n window.removeEventListener('resize', schedule)\n }\n }, [containerRef, doc, editor, people, draft])\n\n const followed = layouts.find((layout) => layout.id === followId)\n const followedAt = followed\n ? `${followed.caret.left}:${followed.caret.top}`\n : ''\n useEffect(() => {\n if (!followId || !followedAt) return\n containerRef.current\n ?.querySelector(\n `[data-slot=\"remote-caret\"][data-user=\"${CSS.escape(followId)}\"]`,\n )\n ?.scrollIntoView({ block: 'nearest', inline: 'nearest' })\n }, [containerRef, followId, followedAt])\n\n return (\n <div\n aria-hidden=\"true\"\n className=\"pointer-events-none absolute inset-0 z-10\"\n data-slot=\"remote-carets\"\n >\n {draftRects.map((rect) => (\n <span\n className=\"absolute bg-primary/25\"\n data-slot=\"comment-draft\"\n key={`${rect.left}:${rect.top}:${rect.width}`}\n style={boxStyle(rect)}\n />\n ))}\n {layouts.map((layout) => {\n const palette = richTextEditor4Colors[layout.color]\n return (\n <div data-slot=\"remote-person\" data-user={layout.id} key={layout.id}>\n {layout.rects.map((rect) => (\n <span\n className={cn('absolute', palette.fill)}\n data-slot=\"remote-selection\"\n data-user={layout.id}\n key={`${rect.left}:${rect.top}:${rect.width}`}\n style={boxStyle(rect)}\n />\n ))}\n <span\n className={cn('absolute w-0.5 -translate-x-px', palette.bar)}\n data-slot=\"remote-caret\"\n data-user={layout.id}\n style={boxStyle({ ...layout.caret, width: 2 })}\n >\n <span\n className=\"absolute start-0 bottom-full flex -translate-y-px items-center gap-1 whitespace-nowrap rounded-sm rounded-bl-none border bg-popover px-1.5 py-0.5 text-popover-foreground text-xs shadow-sm\"\n data-slot=\"remote-caret-label\"\n >\n <span className={cn('size-1.5 rounded-full', palette.dot)} />\n {layout.name}\n </span>\n </span>\n </div>\n )\n })}\n </div>\n )\n}\n",
|
|
57
|
+
"target": "~/packages/ui/src/blocks/application/rich-text-editor/rich-text-editor-4/remote-carets.tsx"
|
|
58
|
+
},
|
|
59
|
+
{
|
|
60
|
+
"path": "blocks/application/rich-text-editor/rich-text-editor-4/rich-text-editor-4.tsx",
|
|
61
|
+
"type": "registry:file",
|
|
62
|
+
"content": "'use client'\n\nimport { ArrowCounterClockwiseIcon } from '@phosphor-icons/react'\nimport { HighlightPlugin } from '@platejs/basic-nodes/react'\nimport { YjsPlugin } from '@platejs/yjs/react'\nimport { Button } from '@tc96/ui/button'\nimport { Label } from '@tc96/ui/label'\nimport {\n RichTextEditor,\n type RichTextValue,\n useRichTextEditor,\n} from '@tc96/ui/patterns/rich-text-editor'\nimport { Switch } from '@tc96/ui/switch'\nimport { cn } from '@tc96/utils'\nimport { NodeIdPlugin } from 'platejs'\nimport {\n type ReactElement,\n useCallback,\n useEffect,\n useMemo,\n useRef,\n useState,\n} from 'react'\nimport * as Y from 'yjs'\nimport {\n CommentPopovers,\n CommentsProvider,\n CommentsRail,\n CommentToolbarButton,\n commentPlugins,\n useCommentsController,\n} from './comments'\nimport { clearThreads, getMembers, registerMember } from './comments-store'\nimport { historyKeysPlugin } from './history-keys'\nimport { defaultRichTextEditor4Labels } from './labels'\nimport { type PresenceEntry, PresenceStack } from './presence-stack'\nimport { RemoteCarets, useRemotePeople } from './remote-carets'\nimport { ROOM_PROVIDER_TYPE } from './room-provider'\nimport type {\n RichTextEditor4Labels,\n RichTextEditor4NavbarContext,\n RichTextEditor4Props,\n RichTextEditor4Status,\n} from './types'\n\nconst floatingMarks = [\n 'bold',\n 'italic',\n 'underline',\n 'strikethrough',\n 'code',\n] as const\n\nconst emptyValue: RichTextValue = [{ children: [{ text: '' }], type: 'p' }]\n\nconst EDITING_MS = 4000\n\nconst IDLE_MS = 60000\n\nconst roomKeys = new WeakMap<object, number>()\n\nlet nextRoomKey = 0\n\nfunction roomKey(room: object): number {\n const known = roomKeys.get(room)\n if (known !== undefined) return known\n nextRoomKey += 1\n roomKeys.set(room, nextRoomKey)\n return nextRoomKey\n}\n\nfunction mergeLabels(\n input: RichTextEditor4Props['labels'],\n): RichTextEditor4Labels {\n const base = defaultRichTextEditor4Labels\n return {\n ...base,\n ...input,\n blocks: { ...base.blocks, ...input?.blocks },\n comments: { ...base.comments, ...input?.comments },\n online: { ...base.online, ...input?.online },\n presence: {\n ...base.presence,\n ...input?.presence,\n status: { ...base.presence.status, ...input?.presence?.status },\n },\n tools: { ...base.tools, ...input?.tools },\n }\n}\n\ntype Note = { kind: 'merged'; names: string[] } | { kind: 'synced' }\n\nfunction CollaborativeEditor({\n className,\n defaultValue = emptyValue,\n labels: labelsInput,\n navbar,\n now = Date.now,\n onCommentsChange,\n room,\n user,\n}: Readonly<RichTextEditor4Props>): ReactElement {\n const labels = useMemo(() => mergeLabels(labelsInput), [labelsInput])\n const valueRef = useRef(defaultValue)\n const rootRef = useRef<HTMLElement>(null)\n const contentRef = useRef<HTMLDivElement>(null)\n const collecting = useRef<Set<number> | null>(null)\n const offline = useRef(false)\n const plugins = useMemo(\n () => [\n HighlightPlugin.configure({ enabled: false }),\n NodeIdPlugin.configure({ enabled: false }),\n ...commentPlugins(),\n historyKeysPlugin,\n YjsPlugin.configure({\n options: {\n awareness: room.awareness,\n cursors: { data: { ...user } },\n providers: [{ options: {}, type: ROOM_PROVIDER_TYPE } as never],\n ydoc: room.doc,\n },\n }),\n ],\n [room, user],\n )\n const editor = useRichTextEditor({\n features: { plugins, skipInitialization: true },\n })\n\n const [online, setOnline] = useState(true)\n const [queued, setQueued] = useState(0)\n const [note, setNote] = useState<Note | null>(null)\n const [followId, setFollowId] = useState<string | null>(null)\n const [selfStatus, setSelfStatus] = useState<RichTextEditor4Status>('viewing')\n\n useEffect(() => {\n void editor\n .getApi(YjsPlugin)\n .yjs.init({ id: 'tc96-room', value: valueRef.current })\n return () => editor.getApi(YjsPlugin).yjs.destroy()\n }, [editor])\n\n useEffect(() => {\n registerMember(room.doc, user)\n }, [room.doc, user])\n\n useEffect(() => {\n const onUpdate = (\n update: Uint8Array,\n _origin: unknown,\n _doc: Y.Doc,\n transaction: Y.Transaction,\n ) => {\n if (transaction.local) {\n if (offline.current) setQueued((count) => count + 1)\n return\n }\n const ids = collecting.current\n if (!ids) return\n const decoded = Y.decodeUpdate(update)\n for (const struct of decoded.structs) ids.add(struct.id.client)\n for (const client of decoded.ds.clients.keys()) ids.add(client)\n }\n room.doc.on('update', onUpdate)\n return () => room.doc.off('update', onUpdate)\n }, [room.doc])\n\n useEffect(() => {\n const { awareness, doc } = room\n let status: RichTextEditor4Status = 'viewing'\n let editingTimer: ReturnType<typeof setTimeout> | undefined\n let idleTimer: ReturnType<typeof setTimeout> | undefined\n const publish = (next: RichTextEditor4Status) => {\n status = next\n setSelfStatus(next)\n awareness.setLocalStateField('presence', { status: next })\n }\n const touch = () => {\n clearTimeout(idleTimer)\n if (status === 'idle') publish('viewing')\n idleTimer = setTimeout(() => publish('idle'), IDLE_MS)\n }\n const edited = (\n _update: Uint8Array,\n _origin: unknown,\n _doc: Y.Doc,\n transaction: Y.Transaction,\n ) => {\n if (!transaction.local) return\n publish('editing')\n clearTimeout(editingTimer)\n editingTimer = setTimeout(() => publish('viewing'), EDITING_MS)\n touch()\n }\n const element = rootRef.current\n publish('viewing')\n touch()\n doc.on('update', edited)\n for (const type of ['keydown', 'pointerdown', 'pointermove'])\n element?.addEventListener(type, touch)\n return () => {\n clearTimeout(editingTimer)\n clearTimeout(idleTimer)\n doc.off('update', edited)\n for (const type of ['keydown', 'pointerdown', 'pointermove'])\n element?.removeEventListener(type, touch)\n }\n }, [room])\n\n useEffect(() => {\n const element = rootRef.current\n const stop = (event: KeyboardEvent) => {\n if (!event.ctrlKey && !event.metaKey && event.key.length === 1)\n setFollowId(null)\n }\n element?.addEventListener('keydown', stop)\n return () => element?.removeEventListener('keydown', stop)\n }, [])\n\n const people = useRemotePeople(room.awareness, user.id, online)\n const others = useMemo<PresenceEntry[]>(\n () =>\n people.map((person) => ({\n id: person.id,\n name: person.name,\n status: person.status,\n user: { color: person.color, id: person.id, name: person.name },\n })),\n [people],\n )\n const self = useMemo<PresenceEntry>(\n () => ({ id: user.id, name: user.name, status: selfStatus, user }),\n [selfStatus, user],\n )\n\n const comments = useCommentsController({\n doc: room.doc,\n editor,\n labels: labels.comments,\n now,\n ...(onCommentsChange ? { onCommentsChange } : {}),\n user,\n })\n\n const changeOnline = useCallback(\n async (next: boolean) => {\n setOnline(next)\n if (!next) {\n offline.current = true\n setQueued(0)\n setNote(null)\n setFollowId(null)\n room.disconnect?.()\n return\n }\n collecting.current = new Set()\n offline.current = false\n await room.connect?.()\n await new Promise((resolve) => setTimeout(resolve, 0))\n const members = getMembers(room.doc)\n const names = [...(collecting.current ?? [])]\n .map((id) => members.get(String(id))?.name)\n .filter((name): name is string => !!name && name !== user.name)\n collecting.current = null\n setNote(\n names.length > 0\n ? { kind: 'merged', names: [...new Set(names)] }\n : { kind: 'synced' },\n )\n },\n [room, user.name],\n )\n\n const replay = useCallback(async () => {\n collecting.current = null\n offline.current = false\n setOnline(true)\n setQueued(0)\n setNote(null)\n setFollowId(null)\n await room.connect?.()\n clearThreads(room.doc)\n editor.tf.setValue(structuredClone(valueRef.current))\n room.replay?.()\n }, [editor, room])\n\n const context: RichTextEditor4NavbarContext = {\n online,\n status: (\n <>\n <PresenceStack\n followId={followId}\n labels={labels.presence}\n onFollow={setFollowId}\n others={others}\n self={self}\n />\n <Label>\n <Switch\n checked={online}\n onCheckedChange={(next) => void changeOnline(next)}\n />\n {labels.online.label}\n </Label>\n {room.replay ? (\n <Button onClick={() => void replay()} size=\"sm\" variant=\"outline\">\n <ArrowCounterClockwiseIcon aria-hidden=\"true\" />\n {labels.replay}\n </Button>\n ) : null}\n </>\n ),\n }\n const navbarNode = typeof navbar === 'function' ? navbar(context) : navbar\n\n const composeRange =\n comments.context.popover?.kind === 'compose'\n ? comments.context.popover.ref.current\n : null\n\n return (\n <CommentsProvider value={comments.context}>\n <section\n aria-label={labels.title}\n className={cn(\n 'flex min-w-0 flex-col bg-background text-foreground',\n className,\n )}\n data-online={online}\n data-slot=\"rich-text-editor-4\"\n ref={rootRef}\n >\n {navbarNode}\n {online && note ? (\n <output\n className=\"block border-b bg-info/8 px-4 py-2 text-info-foreground text-sm\"\n data-slot=\"online-note\"\n >\n {note.kind === 'merged'\n ? labels.online.merged(note.names)\n : labels.online.synced}\n </output>\n ) : null}\n {online ? null : (\n <output\n className=\"block border-b bg-warning/8 px-4 py-2 text-sm text-warning-foreground\"\n data-slot=\"offline-note\"\n >\n {labels.online.offline(queued)}\n </output>\n )}\n <div className=\"flex min-h-0 flex-1 flex-col md:flex-row\">\n <div\n className=\"min-h-80 min-w-0 flex-1 px-6 pt-10 pb-16 sm:px-12\"\n data-slot=\"rich-text-editor-4-body\"\n >\n <div className=\"relative mx-auto max-w-3xl\" ref={contentRef}>\n <RichTextEditor\n aria-label={labels.editor}\n blockLabels={{\n ...labels.blocks,\n ol: labels.tools.numberedList,\n ul: labels.tools.bulletList,\n }}\n blockTypeLabel={labels.tools.blockType}\n contentClassName=\"min-h-72\"\n editor={editor}\n floatingToolbarActions={\n <CommentToolbarButton label={labels.tools.comment} />\n }\n floatingToolbarMarks={floatingMarks}\n paragraphLabel={labels.tools.paragraph}\n placeholder={labels.placeholder}\n slashMenuEmptyLabel={labels.slashMenuEmpty}\n slashMenuLabel={labels.slashMenu}\n toolbarLabel={labels.tools.format}\n >\n <CommentPopovers actions={comments.actions} />\n </RichTextEditor>\n <RemoteCarets\n containerRef={contentRef}\n doc={room.doc}\n draft={composeRange}\n editor={editor}\n followId={followId}\n people={people}\n />\n </div>\n </div>\n <aside\n aria-label={labels.comments.list}\n className=\"border-t md:w-80 md:shrink-0 md:border-t-0 md:border-s\"\n >\n <CommentsRail />\n </aside>\n </div>\n </section>\n </CommentsProvider>\n )\n}\n\nexport function RichTextEditor4(\n props: Readonly<RichTextEditor4Props>,\n): ReactElement {\n return <CollaborativeEditor key={roomKey(props.room)} {...props} />\n}\n",
|
|
63
|
+
"target": "~/packages/ui/src/blocks/application/rich-text-editor/rich-text-editor-4/rich-text-editor-4.tsx"
|
|
64
|
+
},
|
|
65
|
+
{
|
|
66
|
+
"path": "blocks/application/rich-text-editor/rich-text-editor-4/room-provider.ts",
|
|
67
|
+
"type": "registry:file",
|
|
68
|
+
"content": "import {\n type ProviderConstructorProps,\n registerProviderType,\n type UnifiedProvider,\n} from '@platejs/yjs'\nimport type { Awareness } from 'y-protocols/awareness'\nimport type * as Y from 'yjs'\n\nexport const ROOM_PROVIDER_TYPE = 'tc96-room'\n\nclass RoomProvider implements UnifiedProvider {\n awareness: Awareness\n document: Y.Doc\n isConnected = false\n isSynced = false\n type = ROOM_PROVIDER_TYPE\n private readonly props: ProviderConstructorProps\n\n constructor(props: ProviderConstructorProps) {\n this.props = props\n this.awareness = props.awareness as Awareness\n this.document = props.doc as Y.Doc\n }\n\n connect() {\n this.isConnected = true\n this.isSynced = true\n this.props.onConnect?.()\n this.props.onSyncChange?.(true)\n }\n\n disconnect() {\n this.isConnected = false\n this.isSynced = false\n this.props.onDisconnect?.()\n }\n\n destroy() {\n this.disconnect()\n }\n}\n\nregisterProviderType(ROOM_PROVIDER_TYPE, RoomProvider)\n",
|
|
69
|
+
"target": "~/packages/ui/src/blocks/application/rich-text-editor/rich-text-editor-4/room-provider.ts"
|
|
70
|
+
},
|
|
71
|
+
{
|
|
72
|
+
"path": "blocks/application/rich-text-editor/rich-text-editor-4/types.ts",
|
|
73
|
+
"type": "registry:file",
|
|
74
|
+
"content": "import type { RichTextValue } from '@tc96/ui/patterns/rich-text-editor'\nimport type { ReactNode } from 'react'\nimport type { Awareness } from 'y-protocols/awareness'\nimport type * as Y from 'yjs'\n\nexport type RichTextEditor4Color =\n | 'chart-1'\n | 'chart-2'\n | 'chart-3'\n | 'chart-4'\n | 'chart-5'\n | 'primary'\n\nexport type RichTextEditor4Status = 'editing' | 'idle' | 'viewing'\n\nexport interface RichTextEditor4User {\n color: RichTextEditor4Color\n id: string\n name: string\n}\n\nexport interface RichTextEditor4Room {\n awareness: Awareness\n connect?: () => Promise<void> | void\n disconnect?: () => void\n doc: Y.Doc\n replay?: () => void\n}\n\nexport interface RichTextEditor4Message {\n author: RichTextEditor4User\n body: string\n createdAt: number\n id: string\n}\n\nexport interface RichTextEditor4Thread {\n anchored: boolean\n createdAt: number\n id: string\n messages: RichTextEditor4Message[]\n quote: string\n resolved: boolean\n resolvedBy?: RichTextEditor4User\n}\n\nexport interface RichTextEditor4Labels {\n blocks: { blockquote: string; h2: string; h3: string }\n comments: {\n cancel: string\n composer: string\n empty: string\n list: string\n new: string\n newThread: string\n open: string\n openThread: (quote: string) => string\n reopen: string\n reopened: string\n replies: (count: number) => string\n reply: string\n replyComposer: string\n resolve: string\n resolved: string\n resolvedBadge: string\n send: string\n showResolved: string\n thread: string\n undo: string\n unanchored: string\n }\n editor: string\n online: {\n label: string\n merged: (names: string[]) => string\n offline: (queued: number) => string\n synced: string\n }\n presence: {\n follow: (name: string) => string\n following: (name: string) => string\n group: string\n person: (name: string, status: string) => string\n status: Record<RichTextEditor4Status, string>\n stopFollowing: string\n summary: (counts: Record<RichTextEditor4Status, number>) => string\n you: string\n }\n placeholder: string\n replay: string\n slashMenu: string\n slashMenuEmpty: string\n title: string\n tools: {\n blockType: string\n bulletList: string\n comment: string\n format: string\n numberedList: string\n paragraph: string\n }\n}\n\nexport type RichTextEditor4LabelsInput = {\n [Key in keyof RichTextEditor4Labels]?: RichTextEditor4Labels[Key] extends string\n ? string\n : Partial<RichTextEditor4Labels[Key]>\n}\n\nexport interface RichTextEditor4NavbarContext {\n online: boolean\n status: ReactNode\n}\n\nexport interface RichTextEditor4Props {\n className?: string\n defaultValue?: RichTextValue\n labels?: RichTextEditor4LabelsInput\n navbar?: ReactNode | ((context: RichTextEditor4NavbarContext) => ReactNode)\n now?: () => number\n onCommentsChange?: (threads: RichTextEditor4Thread[]) => void\n room: RichTextEditor4Room\n user: RichTextEditor4User\n}\n",
|
|
75
|
+
"target": "~/packages/ui/src/blocks/application/rich-text-editor/rich-text-editor-4/types.ts"
|
|
76
|
+
},
|
|
77
|
+
{
|
|
78
|
+
"path": "blocks/application/rich-text-editor/rich-text-editor-4/yjs-tree.ts",
|
|
79
|
+
"type": "registry:file",
|
|
80
|
+
"content": "import * as Y from 'yjs'\n\nexport const SHARED_ROOT_KEY = 'content'\n\ninterface DeltaOp {\n insert: unknown\n}\n\nconst deltaOf = (text: Y.XmlText): DeltaOp[] => text.toDelta() as DeltaOp[]\n\nconst isElement = (value: unknown): value is Y.XmlText =>\n value instanceof Y.XmlText\n\nexport const getSharedRoot = (doc: Y.Doc): Y.XmlText =>\n doc.get(SHARED_ROOT_KEY, Y.XmlText)\n\nexport function plainLength(text: Y.XmlText): number {\n let total = 0\n for (const op of deltaOf(text)) {\n if (typeof op.insert === 'string') total += op.insert.length\n else if (isElement(op.insert)) total += plainLength(op.insert)\n }\n return total\n}\n\nexport function plainText(text: Y.XmlText): string {\n let value = ''\n for (const op of deltaOf(text)) {\n if (typeof op.insert === 'string') value += op.insert\n else if (isElement(op.insert)) value += plainText(op.insert)\n }\n return value\n}\n\nexport function isTextBlock(text: Y.XmlText): boolean {\n const ops = deltaOf(text)\n return (\n !ops.some((op) => isElement(op.insert)) ||\n ops.some((op) => typeof op.insert === 'string' && op.insert.length > 0)\n )\n}\n\nexport function listTextBlocks(root: Y.XmlText): Y.XmlText[] {\n const blocks: Y.XmlText[] = []\n const visit = (text: Y.XmlText) => {\n for (const op of deltaOf(text)) {\n if (!isElement(op.insert)) continue\n if (isTextBlock(op.insert)) blocks.push(op.insert)\n else visit(op.insert)\n }\n }\n visit(root)\n return blocks\n}\n\nfunction elementChildren(text: Y.XmlText): Y.XmlText[] {\n return deltaOf(text).flatMap((op) =>\n isElement(op.insert) ? [op.insert] : [],\n )\n}\n\nexport function pathOf(root: Y.XmlText, block: Y.XmlText): number[] | null {\n const path: number[] = []\n let current: Y.XmlText = block\n while (current !== root) {\n const parent = current.parent\n if (!isElement(parent)) return null\n path.unshift(elementChildren(parent).indexOf(current))\n current = parent\n }\n return path\n}\n\nfunction plainOffsetAt(text: Y.XmlText, index: number): number {\n let consumed = 0\n let plain = 0\n for (const op of deltaOf(text)) {\n if (consumed >= index) return plain\n if (typeof op.insert === 'string') {\n const length = op.insert.length\n if (consumed + length >= index) return plain + (index - consumed)\n consumed += length\n plain += length\n } else if (isElement(op.insert)) {\n consumed += 1\n plain += plainLength(op.insert)\n }\n }\n return plain\n}\n\nfunction plainOffsetBefore(parent: Y.XmlText, child: Y.XmlText): number {\n let plain = 0\n for (const op of deltaOf(parent)) {\n if (op.insert === child) return plain\n if (typeof op.insert === 'string') plain += op.insert.length\n else if (isElement(op.insert)) plain += plainLength(op.insert)\n }\n return plain\n}\n\nexport interface PlainPoint {\n offset: number\n path: number[]\n}\n\nexport function relativeToPlainPoint(\n doc: Y.Doc,\n root: Y.XmlText,\n json: unknown,\n): PlainPoint | null {\n if (!json || typeof json !== 'object') return null\n let absolute: ReturnType<typeof Y.createAbsolutePositionFromRelativePosition>\n try {\n absolute = Y.createAbsolutePositionFromRelativePosition(\n Y.createRelativePositionFromJSON(json),\n doc,\n )\n } catch {\n return null\n }\n if (!absolute || !isElement(absolute.type)) return null\n let type: Y.XmlText = absolute.type\n let offset = plainOffsetAt(type, absolute.index)\n while (type !== root) {\n const parent = type.parent\n if (!isElement(parent) || parent === root || !isTextBlock(parent)) break\n offset += plainOffsetBefore(parent, type)\n type = parent\n }\n const path = pathOf(root, type)\n return path ? { offset, path } : null\n}\n\nexport function comparePoints(a: PlainPoint, b: PlainPoint): number {\n const length = Math.min(a.path.length, b.path.length)\n for (let index = 0; index < length; index += 1) {\n const difference = (a.path[index] ?? 0) - (b.path[index] ?? 0)\n if (difference !== 0) return difference\n }\n return a.path.length === b.path.length\n ? a.offset - b.offset\n : a.path.length - b.path.length\n}\n",
|
|
81
|
+
"target": "~/packages/ui/src/blocks/application/rich-text-editor/rich-text-editor-4/yjs-tree.ts"
|
|
82
|
+
},
|
|
83
|
+
{
|
|
84
|
+
"path": "helpers/initials.ts",
|
|
85
|
+
"type": "registry:file",
|
|
86
|
+
"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",
|
|
87
|
+
"target": "~/packages/ui/src/helpers/initials.ts"
|
|
88
|
+
},
|
|
89
|
+
{
|
|
90
|
+
"path": "helpers/rich-text.ts",
|
|
91
|
+
"type": "registry:file",
|
|
92
|
+
"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",
|
|
93
|
+
"target": "~/packages/ui/src/helpers/rich-text.ts"
|
|
94
|
+
},
|
|
95
|
+
{
|
|
96
|
+
"path": "patterns/rich-text-editor/block-draggable.tsx",
|
|
97
|
+
"type": "registry:file",
|
|
98
|
+
"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",
|
|
99
|
+
"target": "~/packages/ui/src/patterns/rich-text-editor/block-draggable.tsx"
|
|
100
|
+
},
|
|
101
|
+
{
|
|
102
|
+
"path": "patterns/rich-text-editor/editor-title.tsx",
|
|
103
|
+
"type": "registry:file",
|
|
104
|
+
"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",
|
|
105
|
+
"target": "~/packages/ui/src/patterns/rich-text-editor/editor-title.tsx"
|
|
106
|
+
},
|
|
107
|
+
{
|
|
108
|
+
"path": "patterns/rich-text-editor/extra-blocks.tsx",
|
|
109
|
+
"type": "registry:file",
|
|
110
|
+
"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",
|
|
111
|
+
"target": "~/packages/ui/src/patterns/rich-text-editor/extra-blocks.tsx"
|
|
112
|
+
},
|
|
113
|
+
{
|
|
114
|
+
"path": "patterns/rich-text-editor/floating-toolbar.tsx",
|
|
115
|
+
"type": "registry:file",
|
|
116
|
+
"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",
|
|
117
|
+
"target": "~/packages/ui/src/patterns/rich-text-editor/floating-toolbar.tsx"
|
|
118
|
+
},
|
|
119
|
+
{
|
|
120
|
+
"path": "patterns/rich-text-editor/index.ts",
|
|
121
|
+
"type": "registry:file",
|
|
122
|
+
"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",
|
|
123
|
+
"target": "~/packages/ui/src/patterns/rich-text-editor/index.ts"
|
|
124
|
+
},
|
|
125
|
+
{
|
|
126
|
+
"path": "patterns/rich-text-editor/link-button.tsx",
|
|
127
|
+
"type": "registry:file",
|
|
128
|
+
"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",
|
|
129
|
+
"target": "~/packages/ui/src/patterns/rich-text-editor/link-button.tsx"
|
|
130
|
+
},
|
|
131
|
+
{
|
|
132
|
+
"path": "patterns/rich-text-editor/plugins.tsx",
|
|
133
|
+
"type": "registry:file",
|
|
134
|
+
"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",
|
|
135
|
+
"target": "~/packages/ui/src/patterns/rich-text-editor/plugins.tsx"
|
|
136
|
+
},
|
|
137
|
+
{
|
|
138
|
+
"path": "patterns/rich-text-editor/rich-text-editor.tsx",
|
|
139
|
+
"type": "registry:file",
|
|
140
|
+
"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",
|
|
141
|
+
"target": "~/packages/ui/src/patterns/rich-text-editor/rich-text-editor.tsx"
|
|
142
|
+
},
|
|
143
|
+
{
|
|
144
|
+
"path": "patterns/rich-text-editor/slash-menu.tsx",
|
|
145
|
+
"type": "registry:file",
|
|
146
|
+
"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",
|
|
147
|
+
"target": "~/packages/ui/src/patterns/rich-text-editor/slash-menu.tsx"
|
|
148
|
+
},
|
|
149
|
+
{
|
|
150
|
+
"path": "patterns/rich-text-editor/table-actions.ts",
|
|
151
|
+
"type": "registry:file",
|
|
152
|
+
"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",
|
|
153
|
+
"target": "~/packages/ui/src/patterns/rich-text-editor/table-actions.ts"
|
|
154
|
+
},
|
|
155
|
+
{
|
|
156
|
+
"path": "patterns/rich-text-editor/toolbar-parts.tsx",
|
|
157
|
+
"type": "registry:file",
|
|
158
|
+
"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",
|
|
159
|
+
"target": "~/packages/ui/src/patterns/rich-text-editor/toolbar-parts.tsx"
|
|
160
|
+
}
|
|
161
|
+
],
|
|
162
|
+
"dependencies": [
|
|
163
|
+
"@phosphor-icons/react@2.1.10",
|
|
164
|
+
"@platejs/basic-nodes@53.0.0",
|
|
165
|
+
"@platejs/basic-styles@53.0.0",
|
|
166
|
+
"@platejs/combobox@53.0.0",
|
|
167
|
+
"@platejs/comment@53.0.0",
|
|
168
|
+
"@platejs/date@53.0.0",
|
|
169
|
+
"@platejs/dnd@53.3.8",
|
|
170
|
+
"@platejs/link@53.3.5",
|
|
171
|
+
"@platejs/list-classic@53.0.0",
|
|
172
|
+
"@platejs/mention@53.0.0",
|
|
173
|
+
"@platejs/selection@53.1.6",
|
|
174
|
+
"@platejs/slash-command@53.0.0",
|
|
175
|
+
"@platejs/table@53.0.9",
|
|
176
|
+
"@platejs/yjs@53.5.6",
|
|
177
|
+
"platejs@53.3.14",
|
|
178
|
+
"react@19.1.1",
|
|
179
|
+
"react-dnd@^16.0.1",
|
|
180
|
+
"react-dnd-html5-backend@^16.0.1",
|
|
181
|
+
"y-protocols@1.0.7",
|
|
182
|
+
"yjs@13.6.33"
|
|
183
|
+
],
|
|
184
|
+
"registryDependencies": [
|
|
185
|
+
"@ui/avatar",
|
|
186
|
+
"@ui/badge",
|
|
187
|
+
"@ui/button",
|
|
188
|
+
"@ui/checkbox",
|
|
189
|
+
"@ui/input",
|
|
190
|
+
"@ui/label",
|
|
191
|
+
"@ui/popover",
|
|
192
|
+
"@ui/select",
|
|
193
|
+
"@ui/switch",
|
|
194
|
+
"@ui/textarea",
|
|
195
|
+
"@ui/toast",
|
|
196
|
+
"@ui/toggle",
|
|
197
|
+
"@ui/toolbar"
|
|
198
|
+
],
|
|
199
|
+
"$schema": "https://ui.shadcn.com/schema/registry-item.json"
|
|
200
|
+
}
|