@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,158 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "rich-text-editor-2",
|
|
3
|
+
"type": "registry:block",
|
|
4
|
+
"files": [
|
|
5
|
+
{
|
|
6
|
+
"path": "blocks/application/rich-text-editor/rich-text-editor-2/index.ts",
|
|
7
|
+
"type": "registry:file",
|
|
8
|
+
"content": "export { RichTextEditor2 } from './rich-text-editor-2'\nexport type {\n RichTextEditor2BlockKind,\n RichTextEditor2Labels,\n RichTextEditor2NavbarContext,\n RichTextEditor2Person,\n RichTextEditor2Props,\n RichTextEditor2Settings,\n} from './types'\n",
|
|
9
|
+
"target": "~/packages/ui/src/blocks/application/rich-text-editor/rich-text-editor-2/index.ts"
|
|
10
|
+
},
|
|
11
|
+
{
|
|
12
|
+
"path": "blocks/application/rich-text-editor/rich-text-editor-2/labels.ts",
|
|
13
|
+
"type": "registry:file",
|
|
14
|
+
"content": "import type { RichTextEditor2Labels } from './types'\n\nexport const defaultRichTextEditor2Labels: RichTextEditor2Labels = {\n blockKinds: {\n blockquote: 'Citação',\n callout: 'Destaque',\n code: 'Bloco de código',\n h2: 'Título de seção',\n h3: 'Subtítulo',\n ol: 'Lista numerada',\n p: 'Texto',\n todo: 'Lista de tarefas',\n ul: 'Lista com marcadores',\n },\n editor: 'Conteúdo da página',\n fullWidth: 'Largura total',\n locked: 'Página bloqueada',\n lockPage: 'Bloquear página',\n mention: 'Pessoas',\n mentionEmpty: 'Ninguém com esse nome',\n outline: 'Índice da página',\n outlineEmpty: 'Adicione títulos para montar o índice.',\n outlineTrigger: 'Abrir índice da página',\n placeholder: \"Digite '/' para blocos ou '@' para mencionar alguém\",\n saved: 'Salvo',\n saving: 'Salvando...',\n slashMenu: 'Blocos',\n slashMenuEmpty: 'Nenhum bloco com esse nome',\n smallText: 'Texto pequeno',\n tableAddColumn: 'Adicionar coluna',\n tableAddRow: 'Adicionar linha',\n tableBar: 'Ações da tabela',\n tableHeader: 'Linha de cabeçalho',\n tableRemove: 'Excluir tabela',\n tableRemoveCancel: 'Cancelar',\n tableRemoveColumn: 'Excluir coluna',\n tableRemoveConfirm: 'Excluir tabela',\n tableRemoveDescription: 'Todo o conteúdo da tabela será removido da página.',\n tableRemoveRow: 'Excluir linha',\n tableRemoveTitle: 'Excluir esta tabela?',\n}\n",
|
|
15
|
+
"target": "~/packages/ui/src/blocks/application/rich-text-editor/rich-text-editor-2/labels.ts"
|
|
16
|
+
},
|
|
17
|
+
{
|
|
18
|
+
"path": "blocks/application/rich-text-editor/rich-text-editor-2/rich-text-editor-2.tsx",
|
|
19
|
+
"type": "registry:file",
|
|
20
|
+
"content": "import { getInitials } from '@tc96/ui/helpers/initials'\nimport {\n RichTextEditor,\n type RichTextMention,\n type RichTextValue,\n useRichTextEditor,\n} from '@tc96/ui/patterns/rich-text-editor'\nimport { cn } from '@tc96/utils'\nimport { useEffect, useMemo, useRef, useState } from 'react'\nimport { defaultRichTextEditor2Labels } from './labels'\nimport type {\n RichTextEditor2NavbarContext,\n RichTextEditor2Props,\n RichTextEditor2Settings,\n} from './types'\nimport { WikiOutlinePopover, WikiOutlineRail } from './wiki-outline'\nimport {\n WikiLockBadge,\n WikiPageMenuItems,\n WikiPageStatus,\n WikiPageStrip,\n} from './wiki-page-menu'\nimport { WikiTableBar } from './wiki-table-bar'\n\nconst defaultSettings: RichTextEditor2Settings = {\n fullWidth: false,\n locked: false,\n smallText: false,\n}\n\nexport function RichTextEditor2({\n className,\n defaultSettings: settingsProp,\n defaultValue,\n labels: labelsProp,\n navbar,\n onSave,\n onSettingsChange,\n people = [],\n saveDelay = 800,\n}: Readonly<RichTextEditor2Props>) {\n const labels = {\n ...defaultRichTextEditor2Labels,\n ...labelsProp,\n blockKinds: {\n ...defaultRichTextEditor2Labels.blockKinds,\n ...labelsProp?.blockKinds,\n },\n }\n const [settings, setSettings] = useState<RichTextEditor2Settings>({\n ...defaultSettings,\n ...settingsProp,\n })\n const [saveStatus, setSaveStatus] = useState<'saved' | 'saving'>('saved')\n const timer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined)\n\n const mentions = useMemo<RichTextMention[]>(\n () =>\n people.map((person) => ({\n avatar: {\n fallback: getInitials(person.name),\n ...(person.image ? { url: person.image } : {}),\n },\n id: person.id,\n label: person.name,\n })),\n [people],\n )\n\n const editor = useRichTextEditor({\n ...(defaultValue ? { defaultValue } : {}),\n features: { h1: true },\n mentions,\n })\n\n useEffect(() => () => clearTimeout(timer.current), [])\n\n const handleValueChange = (value: RichTextValue) => {\n if (!onSave) return\n setSaveStatus('saving')\n clearTimeout(timer.current)\n timer.current = setTimeout(() => {\n onSave(value)\n setSaveStatus('saved')\n }, saveDelay)\n }\n\n const handleSettingChange = (\n key: keyof RichTextEditor2Settings,\n value: boolean,\n ) => {\n const next = { ...settings, [key]: value }\n setSettings(next)\n onSettingsChange?.(next)\n }\n\n const status = onSave ? saveStatus : null\n const outline = <WikiOutlinePopover labels={labels} />\n const lockBadge = settings.locked ? <WikiLockBadge labels={labels} /> : null\n const context: RichTextEditor2NavbarContext = {\n lockBadge,\n onSettingChange: handleSettingChange,\n pageMenuItems: (\n <WikiPageMenuItems\n labels={labels}\n onSettingChange={handleSettingChange}\n settings={settings}\n />\n ),\n saveStatus: status,\n settings,\n status:\n status || lockBadge ? (\n <WikiPageStatus\n labels={labels}\n lockBadge={lockBadge}\n saveStatus={status}\n />\n ) : null,\n }\n const navbarNode = typeof navbar === 'function' ? navbar(context) : navbar\n\n return (\n <div\n className={cn('w-full', className)}\n data-slot=\"rich-text-editor-2\"\n data-width={settings.fullWidth ? 'full' : 'page'}\n >\n <div\n className={cn(\n 'relative mx-auto w-full',\n settings.fullWidth ? 'max-w-none' : 'max-w-4xl',\n )}\n >\n <RichTextEditor\n aria-label={labels.editor}\n blockLabels={{\n blockquote: labels.blockKinds.blockquote,\n h2: labels.blockKinds.h2,\n h3: labels.blockKinds.h3,\n ol: labels.blockKinds.ol,\n ul: labels.blockKinds.ul,\n }}\n contentClassName={cn(\n 'min-h-96 px-6 pt-10 pb-24 sm:px-12 lg:pe-16',\n settings.smallText ? 'text-sm' : 'text-base',\n )}\n editor={editor}\n mentionEmptyLabel={labels.mentionEmpty}\n mentionLabel={labels.mention}\n mentions={mentions}\n onValueChange={handleValueChange}\n paragraphLabel={labels.blockKinds.p}\n placeholder={labels.placeholder}\n readOnly={settings.locked}\n slashMenuEmptyLabel={labels.slashMenuEmpty}\n slashMenuLabel={labels.slashMenu}\n toolbar={\n <>\n {navbarNode}\n <WikiPageStrip outline={outline} />\n <WikiTableBar labels={labels} />\n </>\n }\n >\n <WikiOutlineRail labels={labels} />\n </RichTextEditor>\n </div>\n </div>\n )\n}\n",
|
|
21
|
+
"target": "~/packages/ui/src/blocks/application/rich-text-editor/rich-text-editor-2/rich-text-editor-2.tsx"
|
|
22
|
+
},
|
|
23
|
+
{
|
|
24
|
+
"path": "blocks/application/rich-text-editor/rich-text-editor-2/types.ts",
|
|
25
|
+
"type": "registry:file",
|
|
26
|
+
"content": "import type { RichTextValue } from '@tc96/ui/patterns/rich-text-editor'\nimport type { ReactNode } from 'react'\n\nexport type RichTextEditor2BlockKind =\n | 'blockquote'\n | 'callout'\n | 'code'\n | 'h2'\n | 'h3'\n | 'ol'\n | 'p'\n | 'todo'\n | 'ul'\n\nexport interface RichTextEditor2Person {\n id: string\n image?: string\n name: string\n role: string\n}\n\nexport interface RichTextEditor2Settings {\n fullWidth: boolean\n locked: boolean\n smallText: boolean\n}\n\nexport interface RichTextEditor2Labels {\n blockKinds: Record<RichTextEditor2BlockKind, string>\n editor: string\n fullWidth: string\n locked: string\n lockPage: string\n mention: string\n mentionEmpty: string\n outline: string\n outlineEmpty: string\n outlineTrigger: string\n placeholder: string\n saved: string\n saving: string\n slashMenu: string\n slashMenuEmpty: string\n smallText: string\n tableAddColumn: string\n tableAddRow: string\n tableBar: string\n tableHeader: string\n tableRemove: string\n tableRemoveCancel: string\n tableRemoveColumn: string\n tableRemoveConfirm: string\n tableRemoveDescription: string\n tableRemoveRow: string\n tableRemoveTitle: string\n}\n\nexport interface RichTextEditor2NavbarContext {\n lockBadge: ReactNode\n onSettingChange: (key: keyof RichTextEditor2Settings, value: boolean) => void\n pageMenuItems: ReactNode\n saveStatus: 'saved' | 'saving' | null\n settings: RichTextEditor2Settings\n status: ReactNode\n}\n\nexport interface RichTextEditor2Props {\n className?: string\n defaultSettings?: Partial<RichTextEditor2Settings>\n defaultValue?: RichTextValue\n navbar?: ReactNode | ((context: RichTextEditor2NavbarContext) => ReactNode)\n labels?: Partial<Omit<RichTextEditor2Labels, 'blockKinds'>> & {\n blockKinds?: Partial<RichTextEditor2Labels['blockKinds']>\n }\n onSave?: (value: RichTextValue) => void\n onSettingsChange?: (settings: RichTextEditor2Settings) => void\n people?: RichTextEditor2Person[]\n saveDelay?: number\n}\n",
|
|
27
|
+
"target": "~/packages/ui/src/blocks/application/rich-text-editor/rich-text-editor-2/types.ts"
|
|
28
|
+
},
|
|
29
|
+
{
|
|
30
|
+
"path": "blocks/application/rich-text-editor/rich-text-editor-2/wiki-outline.tsx",
|
|
31
|
+
"type": "registry:file",
|
|
32
|
+
"content": "import { ListBulletsIcon } from '@phosphor-icons/react'\nimport { Button } from '@tc96/ui/button'\nimport { Popover, PopoverPopup, PopoverTrigger } from '@tc96/ui/popover'\nimport { cn } from '@tc96/utils'\nimport { NodeApi } from 'platejs'\nimport {\n type PlateEditor,\n useEditorRef,\n useEditorSelector,\n} from 'platejs/react'\nimport { useMemo, useState } from 'react'\nimport type { RichTextEditor2Labels } from './types'\n\ninterface OutlineItem {\n index: number\n level: 2 | 3\n text: string\n}\n\nfunction headingsOf(editor: PlateEditor): string {\n const items: OutlineItem[] = []\n editor.children.forEach((node, index) => {\n if (node.type !== 'h2' && node.type !== 'h3') return\n const text = NodeApi.string(node).trim()\n if (text) items.push({ index, level: node.type === 'h2' ? 2 : 3, text })\n })\n return JSON.stringify(items)\n}\n\nfunction useOutline(): { items: OutlineItem[]; jump: (index: number) => void } {\n const editor = useEditorRef()\n const serialized = useEditorSelector(headingsOf, [])\n const items = useMemo(\n () => JSON.parse(serialized) as OutlineItem[],\n [serialized],\n )\n const jump = (index: number) => {\n const node = editor.children[index]\n if (!node) return\n editor.api\n .toDOMNode(node)\n ?.scrollIntoView({ behavior: 'smooth', block: 'start' })\n }\n return { items, jump }\n}\n\nexport function WikiOutlineRail({\n labels,\n}: Readonly<{ labels: RichTextEditor2Labels }>) {\n const { items, jump } = useOutline()\n if (items.length === 0) return null\n\n return (\n <div\n className=\"pointer-events-none absolute inset-y-0 inset-e-0 hidden lg:block\"\n data-slot=\"wiki-outline-rail\"\n >\n <nav\n aria-label={labels.outline}\n className=\"group/outline pointer-events-auto sticky top-24 ms-auto w-8 rounded-xl border border-transparent p-1 transition-[width] focus-within:w-60 focus-within:border-border focus-within:bg-popover focus-within:shadow-lg/5 hover:w-60 hover:border-border hover:bg-popover hover:shadow-lg/5\"\n >\n <ul className=\"flex flex-col gap-0.5\">\n {items.map((item) => (\n <li key={`${item.index}-${item.text}`}>\n <button\n className=\"flex w-full cursor-pointer items-center gap-2 rounded-md px-1.5 py-1 text-start text-muted-foreground text-sm outline-none hover:bg-accent hover:text-accent-foreground focus-visible:ring-2 focus-visible:ring-ring\"\n data-level={item.level}\n onClick={() => jump(item.index)}\n type=\"button\"\n >\n <span\n className={cn(\n 'sr-only min-w-0 flex-1 truncate group-focus-within/outline:not-sr-only group-hover/outline:not-sr-only',\n item.level === 3 && 'ps-3',\n )}\n >\n {item.text}\n </span>\n <span\n aria-hidden=\"true\"\n className={cn(\n 'ms-auto h-0.5 shrink-0 rounded-full bg-current opacity-60',\n item.level === 2 ? 'w-4' : 'w-2',\n )}\n />\n </button>\n </li>\n ))}\n </ul>\n </nav>\n </div>\n )\n}\n\nexport function WikiOutlinePopover({\n labels,\n}: Readonly<{ labels: RichTextEditor2Labels }>) {\n const { items, jump } = useOutline()\n const [open, setOpen] = useState(false)\n\n return (\n <Popover onOpenChange={setOpen} open={open}>\n <PopoverTrigger\n aria-label={labels.outlineTrigger}\n render={<Button className=\"lg:hidden\" size=\"icon-sm\" variant=\"ghost\" />}\n >\n <ListBulletsIcon aria-hidden=\"true\" />\n </PopoverTrigger>\n <PopoverPopup align=\"start\" className=\"w-64\">\n {items.length === 0 ? (\n <p className=\"text-muted-foreground text-sm\">{labels.outlineEmpty}</p>\n ) : (\n <ul\n aria-label={labels.outline}\n className=\"flex flex-col gap-0.5\"\n data-slot=\"wiki-outline-list\"\n >\n {items.map((item) => (\n <li key={`${item.index}-${item.text}`}>\n <button\n className={cn(\n 'flex w-full cursor-pointer items-center truncate rounded-md px-2 py-1 text-start text-sm outline-none hover:bg-accent hover:text-accent-foreground focus-visible:ring-2 focus-visible:ring-ring',\n item.level === 3 && 'ps-5 text-muted-foreground',\n )}\n onClick={() => {\n setOpen(false)\n jump(item.index)\n }}\n type=\"button\"\n >\n {item.text}\n </button>\n </li>\n ))}\n </ul>\n )}\n </PopoverPopup>\n </Popover>\n )\n}\n",
|
|
33
|
+
"target": "~/packages/ui/src/blocks/application/rich-text-editor/rich-text-editor-2/wiki-outline.tsx"
|
|
34
|
+
},
|
|
35
|
+
{
|
|
36
|
+
"path": "blocks/application/rich-text-editor/rich-text-editor-2/wiki-page-menu.tsx",
|
|
37
|
+
"type": "registry:file",
|
|
38
|
+
"content": "import { LockSimpleIcon } from '@phosphor-icons/react'\nimport { Badge } from '@tc96/ui/badge'\nimport { MenuCheckboxItem } from '@tc96/ui/menu'\nimport type { ReactNode } from 'react'\nimport type { RichTextEditor2Labels, RichTextEditor2Settings } from './types'\n\nexport function WikiPageMenuItems({\n labels,\n onSettingChange,\n settings,\n}: Readonly<{\n labels: RichTextEditor2Labels\n onSettingChange: (key: keyof RichTextEditor2Settings, value: boolean) => void\n settings: RichTextEditor2Settings\n}>) {\n return (\n <>\n <MenuCheckboxItem\n checked={settings.fullWidth}\n onCheckedChange={(next) => onSettingChange('fullWidth', next)}\n >\n {labels.fullWidth}\n </MenuCheckboxItem>\n <MenuCheckboxItem\n checked={settings.smallText}\n onCheckedChange={(next) => onSettingChange('smallText', next)}\n >\n {labels.smallText}\n </MenuCheckboxItem>\n <MenuCheckboxItem\n checked={settings.locked}\n onCheckedChange={(next) => onSettingChange('locked', next)}\n >\n {labels.lockPage}\n </MenuCheckboxItem>\n </>\n )\n}\n\nexport function WikiLockBadge({\n labels,\n}: Readonly<{ labels: RichTextEditor2Labels }>) {\n return (\n <Badge variant=\"secondary\">\n <LockSimpleIcon aria-hidden=\"true\" />\n {labels.locked}\n </Badge>\n )\n}\n\nexport function WikiPageStatus({\n labels,\n lockBadge,\n saveStatus,\n}: Readonly<{\n labels: RichTextEditor2Labels\n lockBadge: ReactNode\n saveStatus: 'saved' | 'saving' | null\n}>) {\n return (\n <>\n {saveStatus ? (\n <output\n className=\"text-muted-foreground text-sm\"\n data-slot=\"wiki-save-status\"\n >\n {labels[saveStatus]}\n </output>\n ) : null}\n {lockBadge}\n </>\n )\n}\n\nexport function WikiPageStrip({ outline }: Readonly<{ outline: ReactNode }>) {\n return (\n <div\n className=\"flex min-h-10 items-center gap-2 px-4 py-1 lg:hidden\"\n data-slot=\"wiki-page-strip\"\n >\n {outline}\n </div>\n )\n}\n",
|
|
39
|
+
"target": "~/packages/ui/src/blocks/application/rich-text-editor/rich-text-editor-2/wiki-page-menu.tsx"
|
|
40
|
+
},
|
|
41
|
+
{
|
|
42
|
+
"path": "blocks/application/rich-text-editor/rich-text-editor-2/wiki-table-bar.tsx",
|
|
43
|
+
"type": "registry:file",
|
|
44
|
+
"content": "import {\n ColumnsPlusRightIcon,\n RowsPlusBottomIcon,\n TableIcon,\n TrashIcon,\n} from '@phosphor-icons/react'\nimport {\n AlertDialog,\n AlertDialogClose,\n AlertDialogDescription,\n AlertDialogFooter,\n AlertDialogHeader,\n AlertDialogPopup,\n AlertDialogTitle,\n} from '@tc96/ui/alert-dialog'\nimport { Button } from '@tc96/ui/button'\nimport {\n addTableColumn,\n addTableRow,\n hasTableHeaderRow,\n isInTable,\n removeTable,\n removeTableColumn,\n removeTableRow,\n toggleTableHeaderRow,\n} from '@tc96/ui/patterns/rich-text-editor'\nimport {\n Toolbar,\n ToolbarButton,\n ToolbarGroup,\n ToolbarSeparator,\n} from '@tc96/ui/toolbar'\nimport {\n useEditorReadOnly,\n useEditorRef,\n useEditorSelector,\n} from 'platejs/react'\nimport { useState } from 'react'\nimport type { RichTextEditor2Labels } from './types'\n\nexport function WikiTableBar({\n labels,\n}: Readonly<{ labels: RichTextEditor2Labels }>) {\n const editor = useEditorRef()\n const readOnly = useEditorReadOnly()\n const inTable = useEditorSelector((current) => isInTable(current), [])\n const header = useEditorSelector((current) => hasTableHeaderRow(current), [])\n const [confirming, setConfirming] = useState(false)\n\n const run = (action: () => void) => () => {\n action()\n editor.tf.focus()\n }\n const keepFocus = (event: { preventDefault: () => void }) =>\n event.preventDefault()\n\n if (readOnly || (!inTable && !confirming)) return null\n\n return (\n <>\n <Toolbar\n aria-label={labels.tableBar}\n className=\"my-2 flex-wrap\"\n data-slot=\"wiki-table-bar\"\n >\n <ToolbarGroup>\n <TableIcon aria-hidden=\"true\" className=\"mx-1.5 size-4 opacity-60\" />\n <ToolbarButton\n onClick={run(() => addTableRow(editor, 'after'))}\n onMouseDown={keepFocus}\n render={<Button size=\"sm\" variant=\"ghost\" />}\n >\n <RowsPlusBottomIcon aria-hidden=\"true\" />\n {labels.tableAddRow}\n </ToolbarButton>\n <ToolbarButton\n onClick={run(() => addTableColumn(editor, 'after'))}\n onMouseDown={keepFocus}\n render={<Button size=\"sm\" variant=\"ghost\" />}\n >\n <ColumnsPlusRightIcon aria-hidden=\"true\" />\n {labels.tableAddColumn}\n </ToolbarButton>\n <ToolbarButton\n aria-pressed={header}\n onClick={run(() => toggleTableHeaderRow(editor))}\n onMouseDown={keepFocus}\n render={<Button size=\"sm\" variant=\"ghost\" />}\n >\n {labels.tableHeader}\n </ToolbarButton>\n </ToolbarGroup>\n <ToolbarSeparator />\n <ToolbarGroup>\n <ToolbarButton\n onClick={run(() => removeTableRow(editor))}\n onMouseDown={keepFocus}\n render={<Button size=\"sm\" variant=\"ghost\" />}\n >\n {labels.tableRemoveRow}\n </ToolbarButton>\n <ToolbarButton\n onClick={run(() => removeTableColumn(editor))}\n onMouseDown={keepFocus}\n render={<Button size=\"sm\" variant=\"ghost\" />}\n >\n {labels.tableRemoveColumn}\n </ToolbarButton>\n <ToolbarButton\n onClick={() => setConfirming(true)}\n onMouseDown={keepFocus}\n render={<Button size=\"sm\" variant=\"ghost\" />}\n >\n <TrashIcon aria-hidden=\"true\" />\n {labels.tableRemove}\n </ToolbarButton>\n </ToolbarGroup>\n </Toolbar>\n <AlertDialog onOpenChange={setConfirming} open={confirming}>\n <AlertDialogPopup>\n <AlertDialogHeader>\n <AlertDialogTitle>{labels.tableRemoveTitle}</AlertDialogTitle>\n <AlertDialogDescription>\n {labels.tableRemoveDescription}\n </AlertDialogDescription>\n </AlertDialogHeader>\n <AlertDialogFooter>\n <AlertDialogClose render={<Button size=\"sm\" variant=\"outline\" />}>\n {labels.tableRemoveCancel}\n </AlertDialogClose>\n <AlertDialogClose\n onClick={run(() => removeTable(editor))}\n render={<Button size=\"sm\" variant=\"destructive\" />}\n >\n {labels.tableRemoveConfirm}\n </AlertDialogClose>\n </AlertDialogFooter>\n </AlertDialogPopup>\n </AlertDialog>\n </>\n )\n}\n",
|
|
45
|
+
"target": "~/packages/ui/src/blocks/application/rich-text-editor/rich-text-editor-2/wiki-table-bar.tsx"
|
|
46
|
+
},
|
|
47
|
+
{
|
|
48
|
+
"path": "helpers/initials.ts",
|
|
49
|
+
"type": "registry:file",
|
|
50
|
+
"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",
|
|
51
|
+
"target": "~/packages/ui/src/helpers/initials.ts"
|
|
52
|
+
},
|
|
53
|
+
{
|
|
54
|
+
"path": "helpers/rich-text.ts",
|
|
55
|
+
"type": "registry:file",
|
|
56
|
+
"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",
|
|
57
|
+
"target": "~/packages/ui/src/helpers/rich-text.ts"
|
|
58
|
+
},
|
|
59
|
+
{
|
|
60
|
+
"path": "patterns/rich-text-editor/block-draggable.tsx",
|
|
61
|
+
"type": "registry:file",
|
|
62
|
+
"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",
|
|
63
|
+
"target": "~/packages/ui/src/patterns/rich-text-editor/block-draggable.tsx"
|
|
64
|
+
},
|
|
65
|
+
{
|
|
66
|
+
"path": "patterns/rich-text-editor/editor-title.tsx",
|
|
67
|
+
"type": "registry:file",
|
|
68
|
+
"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",
|
|
69
|
+
"target": "~/packages/ui/src/patterns/rich-text-editor/editor-title.tsx"
|
|
70
|
+
},
|
|
71
|
+
{
|
|
72
|
+
"path": "patterns/rich-text-editor/extra-blocks.tsx",
|
|
73
|
+
"type": "registry:file",
|
|
74
|
+
"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",
|
|
75
|
+
"target": "~/packages/ui/src/patterns/rich-text-editor/extra-blocks.tsx"
|
|
76
|
+
},
|
|
77
|
+
{
|
|
78
|
+
"path": "patterns/rich-text-editor/floating-toolbar.tsx",
|
|
79
|
+
"type": "registry:file",
|
|
80
|
+
"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",
|
|
81
|
+
"target": "~/packages/ui/src/patterns/rich-text-editor/floating-toolbar.tsx"
|
|
82
|
+
},
|
|
83
|
+
{
|
|
84
|
+
"path": "patterns/rich-text-editor/index.ts",
|
|
85
|
+
"type": "registry:file",
|
|
86
|
+
"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",
|
|
87
|
+
"target": "~/packages/ui/src/patterns/rich-text-editor/index.ts"
|
|
88
|
+
},
|
|
89
|
+
{
|
|
90
|
+
"path": "patterns/rich-text-editor/link-button.tsx",
|
|
91
|
+
"type": "registry:file",
|
|
92
|
+
"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",
|
|
93
|
+
"target": "~/packages/ui/src/patterns/rich-text-editor/link-button.tsx"
|
|
94
|
+
},
|
|
95
|
+
{
|
|
96
|
+
"path": "patterns/rich-text-editor/plugins.tsx",
|
|
97
|
+
"type": "registry:file",
|
|
98
|
+
"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",
|
|
99
|
+
"target": "~/packages/ui/src/patterns/rich-text-editor/plugins.tsx"
|
|
100
|
+
},
|
|
101
|
+
{
|
|
102
|
+
"path": "patterns/rich-text-editor/rich-text-editor.tsx",
|
|
103
|
+
"type": "registry:file",
|
|
104
|
+
"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",
|
|
105
|
+
"target": "~/packages/ui/src/patterns/rich-text-editor/rich-text-editor.tsx"
|
|
106
|
+
},
|
|
107
|
+
{
|
|
108
|
+
"path": "patterns/rich-text-editor/slash-menu.tsx",
|
|
109
|
+
"type": "registry:file",
|
|
110
|
+
"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",
|
|
111
|
+
"target": "~/packages/ui/src/patterns/rich-text-editor/slash-menu.tsx"
|
|
112
|
+
},
|
|
113
|
+
{
|
|
114
|
+
"path": "patterns/rich-text-editor/table-actions.ts",
|
|
115
|
+
"type": "registry:file",
|
|
116
|
+
"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",
|
|
117
|
+
"target": "~/packages/ui/src/patterns/rich-text-editor/table-actions.ts"
|
|
118
|
+
},
|
|
119
|
+
{
|
|
120
|
+
"path": "patterns/rich-text-editor/toolbar-parts.tsx",
|
|
121
|
+
"type": "registry:file",
|
|
122
|
+
"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",
|
|
123
|
+
"target": "~/packages/ui/src/patterns/rich-text-editor/toolbar-parts.tsx"
|
|
124
|
+
}
|
|
125
|
+
],
|
|
126
|
+
"dependencies": [
|
|
127
|
+
"@phosphor-icons/react@2.1.10",
|
|
128
|
+
"@platejs/basic-nodes@53.0.0",
|
|
129
|
+
"@platejs/basic-styles@53.0.0",
|
|
130
|
+
"@platejs/combobox@53.0.0",
|
|
131
|
+
"@platejs/date@53.0.0",
|
|
132
|
+
"@platejs/dnd@53.3.8",
|
|
133
|
+
"@platejs/link@53.3.5",
|
|
134
|
+
"@platejs/list-classic@53.0.0",
|
|
135
|
+
"@platejs/mention@53.0.0",
|
|
136
|
+
"@platejs/selection@53.1.6",
|
|
137
|
+
"@platejs/slash-command@53.0.0",
|
|
138
|
+
"@platejs/table@53.0.9",
|
|
139
|
+
"platejs@53.3.14",
|
|
140
|
+
"react@19.1.1",
|
|
141
|
+
"react-dnd@^16.0.1",
|
|
142
|
+
"react-dnd-html5-backend@^16.0.1"
|
|
143
|
+
],
|
|
144
|
+
"registryDependencies": [
|
|
145
|
+
"@ui/alert-dialog",
|
|
146
|
+
"@ui/avatar",
|
|
147
|
+
"@ui/badge",
|
|
148
|
+
"@ui/button",
|
|
149
|
+
"@ui/checkbox",
|
|
150
|
+
"@ui/input",
|
|
151
|
+
"@ui/menu",
|
|
152
|
+
"@ui/popover",
|
|
153
|
+
"@ui/select",
|
|
154
|
+
"@ui/toggle",
|
|
155
|
+
"@ui/toolbar"
|
|
156
|
+
],
|
|
157
|
+
"$schema": "https://ui.shadcn.com/schema/registry-item.json"
|
|
158
|
+
}
|