diff --git a/apps/client/src/features/editor/components/slash-menu/menu-items.ts b/apps/client/src/features/editor/components/slash-menu/menu-items.ts index 0327acdde..389ec96f8 100644 --- a/apps/client/src/features/editor/components/slash-menu/menu-items.ts +++ b/apps/client/src/features/editor/components/slash-menu/menu-items.ts @@ -389,6 +389,14 @@ const CommandGroups: SlashMenuGroupedItemsType = { command: ({ editor, range }: CommandProps) => editor.chain().focus().deleteRange(range).setDetails().run(), }, + { + title: "Tabs", + description: "Insert a multi-tab content block.", + searchTerms: ["tabs", "tabbed", "multi", "panel"], + icon: IconSitemap, + command: ({ editor, range }: CommandProps) => + editor.chain().focus().deleteRange(range).insertTabs().run(), + }, { title: "Callout", description: "Insert callout notice.", diff --git a/apps/client/src/features/editor/components/tabs/tabs-view.tsx b/apps/client/src/features/editor/components/tabs/tabs-view.tsx new file mode 100644 index 000000000..6b193521d --- /dev/null +++ b/apps/client/src/features/editor/components/tabs/tabs-view.tsx @@ -0,0 +1,140 @@ +import React, { + ChangeEvent, + useCallback, + useEffect, + useMemo, + useRef, + useState, + type KeyboardEvent, +} from 'react'; +import { NodeViewContent, NodeViewWrapper, type NodeViewProps } from '@tiptap/react'; +import { Tabs, TextInput } from '@mantine/core'; + +export default function TabsView(props: NodeViewProps) { + const { node, editor, getPos } = props; + const isEditable = editor.isEditable; + const allowFocusRef = useRef(false); + + const tabs = useMemo(() => { + return Array.from({ length: node.childCount }, (_, index) => { + const labelNode = node.child(index)?.child(0); + const labelText = labelNode?.textContent; + const labelId = node.child(index)?.attrs?.id; + + return { + label: labelText ?? '', + id: labelId ?? index, + }; + }); + }, [node]); + + const activeTab = clampIndex(node.attrs.activeTab); + const [activeLabel, setActiveLabel] = useState(tabs[activeTab].label ?? ''); + + useEffect(() => { + setActiveLabel(tabs[activeTab].label); + }, [activeTab, tabs]); + + const handleMouseDown = useCallback((event: React.MouseEvent) => { + const previous = document.activeElement as HTMLElement | null; + const input = event.currentTarget; + + if (!previous.contains(input)) { + allowFocusRef.current = true; + return; + } + + allowFocusRef.current = true; + }, []); + + const handleFocus = useCallback( + (event: React.FocusEvent) => { + if (!allowFocusRef.current || !isEditable) { + event.preventDefault(); + event.target.blur(); + } + }, + [isEditable] + ); + + const handleBlur = useCallback(() => { + allowFocusRef.current = false; + }, []); + + const commitLabel = useCallback( + (event: ChangeEvent) => { + const label = event.currentTarget.value; + setActiveLabel(label); + + if (label === tabs[activeTab].label) return; + if (typeof getPos === 'function') { + editor.commands.updateTabLabel?.(activeTab, label, getPos()); + } + }, + [activeTab, editor, getPos, tabs] + ); + + const handleLabelKeyDown = useCallback( + (event: KeyboardEvent) => { + event.stopPropagation(); + if (event.key === 'Escape') { + event.preventDefault(); + event.currentTarget.blur(); + } + }, + [] + ); + + return ( + + + + {tabs.map(({ label, id }, index) => ( + event.currentTarget.blur()} + onClick={(e) => { + e.preventDefault(); + if (typeof getPos === 'function') { + editor.commands.setActiveTab?.(index, getPos()); + } + }} + > + + + ))} + + + +
+ +
+
+ ); +} + +const clampIndex = (value: unknown, length = Number.MAX_SAFE_INTEGER) => { + const parsed = typeof value === 'number' ? value : Number(value ?? 0); + if (!Number.isFinite(parsed) || length <= 0) return 0; + return Math.max(0, Math.min(Math.trunc(parsed), length - 1)); +}; diff --git a/apps/client/src/features/editor/extensions/extensions.ts b/apps/client/src/features/editor/extensions/extensions.ts index 672c669da..f31316534 100644 --- a/apps/client/src/features/editor/extensions/extensions.ts +++ b/apps/client/src/features/editor/extensions/extensions.ts @@ -62,6 +62,10 @@ import { TransclusionReference, TableView, BaseEmbed as BaseEmbedNode, + Tabs, + Tab, + TabLabel, + TabPanel, } from "@docmost/editor-ext"; import { randomElement, @@ -90,6 +94,7 @@ import ExcalidrawView from "@/features/editor/components/excalidraw/excalidraw-v import EmbedView from "@/features/editor/components/embed/embed-view.tsx"; import PdfView from "@/features/editor/components/pdf/pdf-view.tsx"; import SubpagesView from "@/features/editor/components/subpages/subpages-view.tsx"; +import TabsView from "@/features/editor/components/tabs/tabs-view.tsx"; import TransclusionView from "@/features/editor/components/transclusion/transclusion-view.tsx"; import TransclusionReferenceView from "@/features/editor/components/transclusion/transclusion-reference-view.tsx"; import { BaseEmbedView } from "@/features/editor/components/base-embed/base-embed-view.tsx"; @@ -289,6 +294,12 @@ export const mainExtensions = [ Details, DetailsSummary, DetailsContent, + Tabs.configure({ + view: TabsView, + }), + Tab, + TabLabel, + TabPanel, Youtube.configure({ addPasteHandler: false, controls: true, diff --git a/apps/client/src/features/editor/styles/index.css b/apps/client/src/features/editor/styles/index.css index 7b1ce93e8..e7d8ee0a5 100644 --- a/apps/client/src/features/editor/styles/index.css +++ b/apps/client/src/features/editor/styles/index.css @@ -17,4 +17,5 @@ @import "./indent.css"; @import "./columns.css"; @import "./status.css"; +@import "./tabs.css"; @import "./base-embed.css"; diff --git a/apps/client/src/features/editor/styles/tabs.css b/apps/client/src/features/editor/styles/tabs.css new file mode 100644 index 000000000..4fe4d8ba5 --- /dev/null +++ b/apps/client/src/features/editor/styles/tabs.css @@ -0,0 +1,7 @@ +.ProseMirror { + [data-type="tabs"] { + button { + outline: none; + } + } +} diff --git a/apps/server/src/collaboration/collaboration.util.ts b/apps/server/src/collaboration/collaboration.util.ts index e8e8d4273..508005eb1 100644 --- a/apps/server/src/collaboration/collaboration.util.ts +++ b/apps/server/src/collaboration/collaboration.util.ts @@ -45,6 +45,10 @@ import { TransclusionSource, TransclusionReference, BaseEmbed, + Tabs, + Tab, + TabLabel, + TabPanel, } from '@docmost/editor-ext'; import { generateText, getSchema, JSONContent } from '@tiptap/core'; import { generateHTML, generateJSON } from '../common/helpers/prosemirror/html'; @@ -87,6 +91,10 @@ export const tiptapExtensions = [ Details, DetailsContent, DetailsSummary, + Tabs, + Tab, + TabLabel, + TabPanel, CustomTable, TableCell, TableRow, diff --git a/packages/editor-ext/src/index.ts b/packages/editor-ext/src/index.ts index d8ed68f2f..fee26dd7e 100644 --- a/packages/editor-ext/src/index.ts +++ b/packages/editor-ext/src/index.ts @@ -30,6 +30,7 @@ export * from "./lib/shared-storage"; export * from "./lib/recreate-transform"; export * from "./lib/columns"; export * from "./lib/status"; +export * from "./lib/tabs"; export * from "./lib/pdf"; export * from "./lib/page-break"; export * from "./lib/resizable-nodeview"; diff --git a/packages/editor-ext/src/lib/tabs/index.ts b/packages/editor-ext/src/lib/tabs/index.ts new file mode 100644 index 000000000..109932cab --- /dev/null +++ b/packages/editor-ext/src/lib/tabs/index.ts @@ -0,0 +1,8 @@ +export { Tabs } from "./tabs"; +export { Tab } from "./tab"; +export { TabLabel } from "./tab-label"; +export { TabPanel } from "./tab-panel"; +export type { TabsOptions } from "./tabs"; +export type { TabOptions } from "./tab"; +export type { TabLabelOptions } from "./tab-label"; +export type { TabPanelOptions } from "./tab-panel"; diff --git a/packages/editor-ext/src/lib/tabs/tab-label.ts b/packages/editor-ext/src/lib/tabs/tab-label.ts new file mode 100644 index 000000000..a5cc240c3 --- /dev/null +++ b/packages/editor-ext/src/lib/tabs/tab-label.ts @@ -0,0 +1,42 @@ +import { mergeAttributes, Node } from "@tiptap/core"; + +export interface TabLabelOptions { + HTMLAttributes: Record; +} + +export const TabLabel = Node.create({ + name: "tabLabel", + content: "inline*", + defining: true, + selectable: false, + + addOptions() { + return { + HTMLAttributes: {}, + }; + }, + + parseHTML() { + return [ + { + tag: `div[data-type="${this.name}"]`, + }, + ]; + }, + + renderHTML({ HTMLAttributes }) { + return [ + "div", + mergeAttributes( + { + "data-type": this.name, + hidden: "hidden", + "aria-hidden": "true", + }, + this.options.HTMLAttributes, + HTMLAttributes, + ), + 0, + ]; + }, +}); diff --git a/packages/editor-ext/src/lib/tabs/tab-panel.ts b/packages/editor-ext/src/lib/tabs/tab-panel.ts new file mode 100644 index 000000000..acd082beb --- /dev/null +++ b/packages/editor-ext/src/lib/tabs/tab-panel.ts @@ -0,0 +1,37 @@ +import { mergeAttributes, Node } from "@tiptap/core"; + +export interface TabPanelOptions { + HTMLAttributes: Record; +} + +export const TabPanel = Node.create({ + name: "tabPanel", + content: "block+", + defining: true, + + addOptions() { + return { + HTMLAttributes: {}, + }; + }, + + parseHTML() { + return [ + { + tag: `div[data-type="${this.name}"]`, + }, + ]; + }, + + renderHTML({ HTMLAttributes }) { + return [ + "div", + mergeAttributes( + { "data-type": this.name, role: "tabpanel" }, + this.options.HTMLAttributes, + HTMLAttributes, + ), + 0, + ]; + }, +}); diff --git a/packages/editor-ext/src/lib/tabs/tab.ts b/packages/editor-ext/src/lib/tabs/tab.ts new file mode 100644 index 000000000..ed2c79cfa --- /dev/null +++ b/packages/editor-ext/src/lib/tabs/tab.ts @@ -0,0 +1,71 @@ +import { mergeAttributes, Node } from '@tiptap/core'; + +export interface TabOptions { + HTMLAttributes: Record; +} + +export const Tab = Node.create({ + name: 'tab', + content: 'tabLabel tabPanel', + defining: true, + isolating: true, + + addOptions() { + return { + HTMLAttributes: {}, + }; + }, + + addAttributes() { + return { + id: { + default: '', + parseHTML: (element: HTMLElement) => + element.getAttribute('data-tab-id') ?? '', + renderHTML: (attributes: { id?: string }) => ({ + 'data-tab-id': attributes.id ?? '', + }), + }, + active: { + default: true, + parseHTML: (element: HTMLElement) => { + const rawValue = element.getAttribute('data-tab-active'); + if (rawValue === null) { + return !element.hasAttribute('hidden'); + } + + return rawValue === 'true'; + }, + renderHTML: (attributes: { active?: boolean }) => { + const isActive = attributes.active !== false; + + return { + 'data-tab-active': isActive ? 'true' : 'false', + 'aria-hidden': isActive ? 'false' : 'true', + ...(isActive ? {} : { hidden: 'hidden' }), + }; + }, + }, + }; + }, + + parseHTML() { + return [ + { + tag: `div[data-type="${this.name}"]`, + }, + ]; + }, + + renderHTML({ HTMLAttributes }) { + return [ + 'div', + mergeAttributes( + { 'data-type': this.name }, + this.options.HTMLAttributes, + HTMLAttributes, + ), + 0, + ]; + }, +}); diff --git a/packages/editor-ext/src/lib/tabs/tabs.ts b/packages/editor-ext/src/lib/tabs/tabs.ts new file mode 100644 index 000000000..79c7e3c64 --- /dev/null +++ b/packages/editor-ext/src/lib/tabs/tabs.ts @@ -0,0 +1,203 @@ +import { Node, mergeAttributes } from '@tiptap/core'; +import { Fragment, type Node as PMNode } from '@tiptap/pm/model'; +import { TextSelection, type EditorState } from '@tiptap/pm/state'; +import { ReactNodeViewRenderer, type ReactNodeViewProps } from '@tiptap/react'; +import type { ComponentType } from 'react'; +import { generateNodeId } from '../utils'; + +export interface TabsOptions { + HTMLAttributes: Record; + view: ComponentType> | null; +} + +declare module '@tiptap/core' { + interface Commands { + tabs: { + insertTabs: () => ReturnType; + setActiveTab: (index: number, tabsPos?: number) => ReturnType; + updateTabLabel: ( + index: number, + label: string, + tabsPos?: number, + ) => ReturnType; + }; + } +} + +export const Tabs = Node.create({ + name: 'tabs', + group: 'block', + content: 'tab+', + defining: true, + isolating: true, + + addOptions() { + return { HTMLAttributes: {}, view: null }; + }, + + addAttributes() { + return { + activeTab: { + default: 0, + parseHTML: (element) => + Number(element.getAttribute('data-active-tab')) || 0, + renderHTML: (attributes) => ({ + 'data-active-tab': clampIndex(attributes.activeTab), + }), + }, + }; + }, + + parseHTML() { + return [{ tag: `div[data-type="${this.name}"]` }]; + }, + + renderHTML({ HTMLAttributes }) { + return [ + 'div', + mergeAttributes( + { 'data-type': this.name }, + this.options.HTMLAttributes, + HTMLAttributes, + ), + 0, + ]; + }, + + addNodeView() { + if (!this.options.view) return undefined; + this.editor.isInitialized = true; + return ReactNodeViewRenderer(this.options.view); + }, + + addCommands() { + const createTab = ( + schema: EditorState['schema'], + label: string, + active: boolean, + ) => { + const { tab, tabLabel, tabPanel, paragraph } = schema.nodes; + if (!tab || !tabLabel || !tabPanel || !paragraph) return null; + + return tab.create({ id: generateNodeId(), active }, [ + tabLabel.create(null, schema.text(label || ' ')), + tabPanel.create(null, paragraph.create()), + ]); + }; + + const resolveTarget = (state: EditorState, pos: number) => { + const node = state.doc.nodeAt(pos); + return { node, pos: pos }; + }; + + const getTabPos = (doc: PMNode, tabsPos: number, tabIndex: number) => { + const pos = doc.resolve(tabsPos + 1); + return pos.posAtIndex(tabIndex, pos.depth); + }; + + return { + insertTabs: + () => + ({ tr, state, dispatch }) => { + const firstTab = createTab(state.schema, 'Tab 1', true); + const secondTab = createTab(state.schema, 'Tab 2', false); + if (!firstTab || !secondTab) return false; + + const tabsNode = this.type.create( + { + activeTab: 0, + }, + Fragment.fromArray([firstTab, secondTab]), + ); + + const insertionPos = tr.selection.from; + tr.replaceSelectionWith(tabsNode).scrollIntoView(); + + const firstTabPos = getTabPos(tr.doc, insertionPos, 0); + const firstTabNode = tr.doc.nodeAt(firstTabPos); + if (!firstTabNode) return false; + + const labelSize = firstTabNode.child(0)?.nodeSize ?? 0; + const panelContentPos = firstTabPos + 2 + labelSize + 2; + + tr.setSelection( + TextSelection.near(tr.doc.resolve(panelContentPos), 1), + ); + + if (dispatch) dispatch(tr); + return true; + }, + + setActiveTab: + (index, tabsPos) => + ({ state, tr, dispatch }) => { + const target = resolveTarget(state, tabsPos); + if (!target || target.node.childCount <= 0) return false; + + const nextIndex = clampIndex(index, target.node.childCount); + const prevIndex = clampIndex( + target.node.attrs.activeTab, + target.node.childCount, + ); + + const nextTab = getTabPos(state.doc, target.pos, nextIndex); + if (prevIndex !== nextIndex) { + const prevTab = getTabPos(state.doc, target.pos, prevIndex); + + tr.setNodeMarkup(target.pos, undefined, { + ...target.node.attrs, + activeTab: nextIndex, + }); + tr.setNodeMarkup(prevTab, undefined, { + ...target.node.child(prevIndex).attrs, + active: false, + }); + tr.setNodeMarkup(nextTab, undefined, { + ...target.node.child(nextIndex).attrs, + active: true, + }); + } + + const tabNode = state.doc.nodeAt(nextTab); + const labelSize = tabNode?.child(0).nodeSize ?? 0; + const panelContentPos = nextTab + 1 + labelSize + 1; + + tr.setSelection( + TextSelection.near(tr.doc.resolve(panelContentPos), 1), + ); + + if (dispatch) dispatch(tr.scrollIntoView()); + return true; + }, + + updateTabLabel: + (index, label, tabsPos) => + ({ state, tr, dispatch }) => { + const target = resolveTarget(state, tabsPos); + if (!target) return false; + + const labelIndex = clampIndex(index, target.node.childCount); + const $tabs = state.doc.resolve(target.pos + 1); + const tabPos = $tabs.posAtIndex(labelIndex, $tabs.depth); + + const labelNode = state.doc.nodeAt(tabPos + 1); + const labelContentPos = tabPos + 2; + + tr.replaceWith( + labelContentPos, + labelContentPos + labelNode.content.size, + state.schema.text(label || ' '), + ); + + if (dispatch) dispatch(tr); + return true; + }, + }; + }, +}); + +const clampIndex = (value: unknown, length = Number.MAX_SAFE_INTEGER) => { + const parsed = typeof value === 'number' ? value : Number(value ?? 0); + if (!Number.isFinite(parsed) || length <= 0) return 0; + return Math.max(0, Math.min(Math.trunc(parsed), length - 1)); +};