@vibe-tiptap/editor-ui 0.0.0-stage → 1.1.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 ADDED
@@ -0,0 +1,15 @@
1
+ ISC License
2
+
3
+ Copyright (c) 2026 vibe-tiptap contributors
4
+
5
+ Permission to use, copy, modify, and/or distribute this software for any
6
+ purpose with or without fee is hereby granted, provided that the above
7
+ copyright notice and this permission notice appear in all copies.
8
+
9
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
10
+ WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
11
+ MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
12
+ ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
13
+ WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
14
+ ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
15
+ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,10 @@
1
- # Temporary Holding Version
1
+ # @vibe-tiptap/editor-ui
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Vibe Tiptap 的内部 UI 共享层,为 React 和 Vue UI 包提供工具栏配置、主题、Markdown 文件处理、打印和白板辅助模块。
4
+
5
+ 通常无需在应用中直接安装此包,请使用 `@vibe-tiptap/shadcn-ui` 或 `@vibe-tiptap/naive-ui`。需要开发自定义 UI 时,可按公开子路径导入:
6
+
7
+ ```ts
8
+ import { resolveEditorPalette } from '@vibe-tiptap/editor-ui/editor-theme'
9
+ import { normalizeToolbarConfig } from '@vibe-tiptap/editor-ui/toolbar-config'
10
+ ```
@@ -0,0 +1,15 @@
1
+ export declare const TOOLBAR_ICON_VIEW_BOX = "0 0 24 24";
2
+ export declare const FIRST_LINE_INDENT_ICON: {
3
+ strokeWidth: number;
4
+ paths: string[];
5
+ };
6
+ export declare const MARKDOWN_ICON: {
7
+ strokeWidth: number;
8
+ paths: string[];
9
+ };
10
+ export declare const MARKDOWN_ACTION_ICON_TRANSFORM = "translate(0 -3.5)";
11
+ export declare const MARKDOWN_ACTION_ICON_PATHS: {
12
+ import: string[];
13
+ export: string[];
14
+ copy: string[];
15
+ };
@@ -0,0 +1,22 @@
1
+ export const TOOLBAR_ICON_VIEW_BOX = '0 0 24 24';
2
+ export const FIRST_LINE_INDENT_ICON = {
3
+ strokeWidth: 2,
4
+ paths: ['m4 3 3 3-3 3', 'M11 6h9', 'M4 12h16', 'M4 18h16'],
5
+ };
6
+ export const MARKDOWN_ICON = {
7
+ strokeWidth: 1.75,
8
+ paths: [
9
+ 'M4 5h16a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V7a2 2 0 0 1 2-2Z',
10
+ 'M5.5 15v-6l2.5 3 2.5-3v6',
11
+ 'M16.5 9v6m-2.5-2.5 2.5 2.5 2.5-2.5',
12
+ ],
13
+ };
14
+ export const MARKDOWN_ACTION_ICON_TRANSFORM = 'translate(0 -3.5)';
15
+ export const MARKDOWN_ACTION_ICON_PATHS = {
16
+ import: ['M12 18v4.5m-3-3 3 3 3-3'],
17
+ export: ['M12 22.5V18m-3 3 3-3 3 3'],
18
+ copy: [
19
+ 'M11.75 18.5h3.5a.75.75 0 0 1 .75.75v2.5a.75.75 0 0 1-.75.75h-3.5a.75.75 0 0 1-.75-.75v-2.5a.75.75 0 0 1 .75-.75Z',
20
+ 'M8.5 21v-3.5h5',
21
+ ],
22
+ };
@@ -0,0 +1,12 @@
1
+ import type { ToolbarHeadingLevel } from './toolbar-config.js';
2
+ export declare const TOOLBAR_HEADING_PREVIEW_STYLES: Record<ToolbarHeadingLevel, {
3
+ fontSize: string;
4
+ fontWeight: number;
5
+ }>;
6
+ export declare const PRESET_TEXT_COLORS: string[];
7
+ export declare const PRESET_HIGHLIGHT_COLORS: string[];
8
+ export declare function resolveEditorPalette(colors?: readonly string[], highlights?: readonly string[]): {
9
+ colors: string[];
10
+ highlights: string[];
11
+ };
12
+ export declare function toColorHex(value: string | undefined, ownerDocument?: Document): string | undefined;
@@ -0,0 +1,129 @@
1
+ export const TOOLBAR_HEADING_PREVIEW_STYLES = {
2
+ 0: { fontSize: '13px', fontWeight: 400 },
3
+ 1: { fontSize: '15px', fontWeight: 700 },
4
+ 2: { fontSize: '14px', fontWeight: 700 },
5
+ 3: { fontSize: '13px', fontWeight: 600 },
6
+ 4: { fontSize: '13px', fontWeight: 600 },
7
+ 5: { fontSize: '12px', fontWeight: 600 },
8
+ 6: { fontSize: '12px', fontWeight: 500 },
9
+ };
10
+ export const PRESET_TEXT_COLORS = [
11
+ '#000000',
12
+ '#434343',
13
+ '#666666',
14
+ '#999999',
15
+ '#b7b7b7',
16
+ '#cccccc',
17
+ '#d9d9d9',
18
+ '#efefef',
19
+ '#e03131',
20
+ '#e8590c',
21
+ '#f08c00',
22
+ '#fcc419',
23
+ '#d9480f',
24
+ '#f76707',
25
+ '#fa5252',
26
+ '#ff6b6b',
27
+ '#2f9e44',
28
+ '#40c057',
29
+ '#82c91e',
30
+ '#a9e34b',
31
+ '#0c8599',
32
+ '#1098ad',
33
+ '#15aabf',
34
+ '#22b8cf',
35
+ '#1864ab',
36
+ '#1971c2',
37
+ '#228be6',
38
+ '#4dabf7',
39
+ '#5f3dc4',
40
+ '#6741d9',
41
+ '#7048e8',
42
+ '#9775fa',
43
+ '#a61e4d',
44
+ '#c2255c',
45
+ '#d6336c',
46
+ '#f06595',
47
+ '#5c2f14',
48
+ '#7b4019',
49
+ '#a0522d',
50
+ '#c08456',
51
+ ];
52
+ export const PRESET_HIGHLIGHT_COLORS = [
53
+ '#fff3bf',
54
+ '#ffe8cc',
55
+ '#ffe066',
56
+ '#fab005',
57
+ '#ffc9c9',
58
+ '#ffa8a8',
59
+ '#ff8787',
60
+ '#fa5252',
61
+ '#d3f9d8',
62
+ '#b2f2bb',
63
+ '#8ce99a',
64
+ '#40c057',
65
+ '#c3fae8',
66
+ '#96f2d7',
67
+ '#63e6be',
68
+ '#0ca678',
69
+ '#d0ebff',
70
+ '#a5d8ff',
71
+ '#74c0fc',
72
+ '#1c7ed6',
73
+ '#e5dbff',
74
+ '#d0bfff',
75
+ '#b197fc',
76
+ '#7048e8',
77
+ '#fcc2d7',
78
+ '#faa2c1',
79
+ '#f783ac',
80
+ '#d6336c',
81
+ '#fff0f6',
82
+ '#ffdeeb',
83
+ '#f8b4cd',
84
+ '#e64980',
85
+ ];
86
+ export function resolveEditorPalette(colors, highlights) {
87
+ return {
88
+ colors: [...(colors ?? PRESET_TEXT_COLORS)],
89
+ highlights: [...(highlights ?? PRESET_HIGHLIGHT_COLORS)],
90
+ };
91
+ }
92
+ export function toColorHex(value, ownerDocument) {
93
+ const color = value?.trim().toLowerCase();
94
+ if (!color)
95
+ return;
96
+ if (/^#(?:[\da-f]{6}|[\da-f]{8})$/.test(color))
97
+ return color;
98
+ if (/^#(?:[\da-f]{3}|[\da-f]{4})$/.test(color))
99
+ return color.replace(/[\da-f]/g, '$&$&');
100
+ if (!ownerDocument)
101
+ return;
102
+ const canvas = ownerDocument.createElement('canvas');
103
+ canvas.width = canvas.height = 1;
104
+ const context = canvas.getContext('2d');
105
+ if (!context)
106
+ return;
107
+ context.fillStyle = color;
108
+ const resolved = context.fillStyle;
109
+ // Canvas 遇到无效色值会保留原色,换一个初始值可区分无效输入与纯黑。
110
+ context.fillStyle = resolved === '#000000' ? '#ffffff' : '#000000';
111
+ context.fillStyle = color;
112
+ if (context.fillStyle !== resolved || typeof resolved !== 'string')
113
+ return;
114
+ if (resolved.startsWith('#'))
115
+ return resolved;
116
+ let channels;
117
+ const rgba = /^rgba\((\d+), (\d+), (\d+), ([\d.]+)\)$/.exec(resolved);
118
+ if (rgba) {
119
+ channels = rgba.slice(1, 4).map(Number);
120
+ channels.push(Math.round(Number(rgba[4]) * 255));
121
+ }
122
+ else {
123
+ context.fillRect(0, 0, 1, 1);
124
+ channels = Array.from(context.getImageData(0, 0, 1, 1).data);
125
+ }
126
+ if (channels[3] === 255)
127
+ channels.pop();
128
+ return `#${channels.map((channel) => channel.toString(16).padStart(2, '0')).join('')}`;
129
+ }
@@ -0,0 +1,41 @@
1
+ import type { CoreEditorContext, LocaleProp, LocaleTranslate, MarkdownImportOptions, NotifyFn } from '@vibe-tiptap/core';
2
+ export interface MarkdownActionContext {
3
+ getMarkdown: () => string;
4
+ importMarkdown: CoreEditorContext['importMarkdown'] | ((markdown: string, options?: MarkdownImportOptions) => void);
5
+ notify: NotifyFn;
6
+ }
7
+ export interface ExportMarkdownOptions {
8
+ filename?: string | (() => string);
9
+ locale?: LocaleProp;
10
+ t?: LocaleTranslate;
11
+ }
12
+ export interface CopyMarkdownOptions {
13
+ locale?: LocaleProp;
14
+ t?: LocaleTranslate;
15
+ clipboard?: Pick<Clipboard, 'writeText'>;
16
+ }
17
+ export type ToolbarMarkdownAction = 'import' | 'export' | 'copy';
18
+ export interface ToolbarMarkdownOption {
19
+ label: string;
20
+ value: ToolbarMarkdownAction;
21
+ }
22
+ export interface MarkdownFileOptions {
23
+ importAccept?: string;
24
+ importStrict?: boolean;
25
+ exportFilename?: string | (() => string);
26
+ }
27
+ export interface ResolvedMarkdownFileOptions {
28
+ importAccept: string;
29
+ importStrict?: boolean;
30
+ exportFilename?: string | (() => string);
31
+ }
32
+ export declare const TOOLBAR_MARKDOWN_IMPORT_ACCEPT = ".md,.markdown,text/markdown,text/plain";
33
+ export declare const TOOLBAR_MARKDOWN_OPTIONS: ToolbarMarkdownOption[];
34
+ export declare function resolveMarkdownFileOptions(options?: MarkdownFileOptions): ResolvedMarkdownFileOptions;
35
+ export declare function importMarkdownFile(ctx: Pick<MarkdownActionContext, 'importMarkdown' | 'notify'>, file: File, options?: MarkdownImportOptions & {
36
+ locale?: LocaleProp;
37
+ t?: LocaleTranslate;
38
+ canImport?: () => boolean;
39
+ }): Promise<void | import("@vibe-tiptap/core").MarkdownImportResult>;
40
+ export declare function exportMarkdownFile(ctx: Pick<MarkdownActionContext, 'getMarkdown' | 'notify'>, options?: ExportMarkdownOptions): boolean;
41
+ export declare function copyMarkdown(ctx: Pick<MarkdownActionContext, 'getMarkdown' | 'notify'>, options?: CopyMarkdownOptions): Promise<boolean>;
@@ -0,0 +1,91 @@
1
+ import { resolveLocale } from '@vibe-tiptap/core';
2
+ export const TOOLBAR_MARKDOWN_IMPORT_ACCEPT = '.md,.markdown,text/markdown,text/plain';
3
+ export const TOOLBAR_MARKDOWN_OPTIONS = [
4
+ { label: '导入', value: 'import' },
5
+ { label: '导出', value: 'export' },
6
+ { label: '复制', value: 'copy' },
7
+ ];
8
+ export function resolveMarkdownFileOptions(options = {}) {
9
+ return {
10
+ importAccept: options.importAccept ?? TOOLBAR_MARKDOWN_IMPORT_ACCEPT,
11
+ importStrict: options.importStrict,
12
+ exportFilename: options.exportFilename,
13
+ };
14
+ }
15
+ function resolveExportMarkdownFilename(filename) {
16
+ const resolved = typeof filename === 'function' ? filename() : filename;
17
+ const trimmed = resolved?.trim();
18
+ return trimmed || `content-${Date.now()}.md`;
19
+ }
20
+ export async function importMarkdownFile(ctx, file, options = {}) {
21
+ const { t: fallbackT } = resolveLocale(options.locale);
22
+ const t = options.t ?? fallbackT;
23
+ let text;
24
+ try {
25
+ text = await file.text();
26
+ }
27
+ catch {
28
+ ctx.notify(t('notify.markdownImportReadFailed'), 'error');
29
+ return;
30
+ }
31
+ if (options.canImport?.() === false)
32
+ return;
33
+ try {
34
+ const result = options.strict
35
+ ? ctx.importMarkdown(text, { strict: true })
36
+ : ctx.importMarkdown(text);
37
+ if (result?.status === 'failed') {
38
+ ctx.notify(t('notify.markdownImportFailed'), 'error');
39
+ }
40
+ else if (result?.status === 'fallback') {
41
+ ctx.notify(t('notify.markdownImportFallback'), 'warning');
42
+ }
43
+ else {
44
+ ctx.notify(t('notify.markdownImportSuccess'), 'success');
45
+ }
46
+ return result;
47
+ }
48
+ catch {
49
+ ctx.notify(t('notify.markdownImportFailed'), 'error');
50
+ }
51
+ }
52
+ export function exportMarkdownFile(ctx, options = {}) {
53
+ const { t: fallbackT } = resolveLocale(options.locale);
54
+ const t = options.t ?? fallbackT;
55
+ const md = ctx.getMarkdown();
56
+ if (!md) {
57
+ ctx.notify(t('notify.markdownExportUnavailable'), 'warning');
58
+ return false;
59
+ }
60
+ const blob = new Blob([md], { type: 'text/markdown;charset=utf-8' });
61
+ const url = URL.createObjectURL(blob);
62
+ const a = document.createElement('a');
63
+ a.href = url;
64
+ a.download = resolveExportMarkdownFilename(options.filename);
65
+ a.click();
66
+ URL.revokeObjectURL(url);
67
+ return true;
68
+ }
69
+ export async function copyMarkdown(ctx, options = {}) {
70
+ const { t: fallbackT } = resolveLocale(options.locale);
71
+ const t = options.t ?? fallbackT;
72
+ const markdown = ctx.getMarkdown();
73
+ if (!markdown) {
74
+ ctx.notify(t('notify.markdownCopyUnavailable'), 'warning');
75
+ return false;
76
+ }
77
+ const clipboard = options.clipboard ?? globalThis.navigator?.clipboard;
78
+ if (!clipboard?.writeText) {
79
+ ctx.notify(t('notify.clipboardUnavailable'), 'warning');
80
+ return false;
81
+ }
82
+ try {
83
+ await clipboard.writeText(markdown);
84
+ ctx.notify(t('notify.markdownCopied'), 'success');
85
+ return true;
86
+ }
87
+ catch {
88
+ ctx.notify(t('notify.clipboardUnavailable'), 'warning');
89
+ return false;
90
+ }
91
+ }
@@ -0,0 +1,7 @@
1
+ import type { MentionTarget } from '@vibe-tiptap/core';
2
+ export declare function bindMentionHover(editor: HTMLElement, onChange: (target: MentionTarget | undefined) => void, hoverDelay?: number): {
3
+ close: () => void;
4
+ keepOpen: () => void;
5
+ leave: () => void;
6
+ destroy(): void;
7
+ };
@@ -0,0 +1,84 @@
1
+ import { getMentionTarget } from '@vibe-tiptap/core';
2
+ const DEFAULT_MENTION_HOVER_DELAY = 500;
3
+ const MENTION_LEAVE_DELAY = 150;
4
+ export function bindMentionHover(editor, onChange, hoverDelay = DEFAULT_MENTION_HOVER_DELAY) {
5
+ let target;
6
+ let pendingTarget;
7
+ let openTimer;
8
+ let closeTimer;
9
+ const keepOpen = () => clearTimeout(closeTimer);
10
+ function cancelOpen() {
11
+ clearTimeout(openTimer);
12
+ openTimer = undefined;
13
+ pendingTarget = undefined;
14
+ }
15
+ function close() {
16
+ keepOpen();
17
+ cancelOpen();
18
+ if (!target)
19
+ return;
20
+ target = undefined;
21
+ onChange(undefined);
22
+ }
23
+ function leave() {
24
+ keepOpen();
25
+ closeTimer = setTimeout(close, MENTION_LEAVE_DELAY);
26
+ }
27
+ function onOver(event) {
28
+ const next = getMentionTarget(editor, event.target);
29
+ if (!next)
30
+ return;
31
+ if (next.element === pendingTarget?.element)
32
+ return;
33
+ if (next.element === target?.element) {
34
+ cancelOpen();
35
+ keepOpen();
36
+ return;
37
+ }
38
+ close();
39
+ pendingTarget = next;
40
+ openTimer = setTimeout(() => {
41
+ cancelOpen();
42
+ if (!editor.contains(next.element))
43
+ return;
44
+ target = next;
45
+ onChange(next);
46
+ }, Math.max(0, hoverDelay));
47
+ }
48
+ function onOut(event) {
49
+ const mention = getMentionTarget(editor, event.target);
50
+ if (!mention)
51
+ return;
52
+ if (event.relatedTarget instanceof Node && mention.element.contains(event.relatedTarget))
53
+ return;
54
+ if (mention.element === pendingTarget?.element)
55
+ cancelOpen();
56
+ if (mention.element === target?.element)
57
+ leave();
58
+ }
59
+ function onKeyDown(event) {
60
+ if (event.key === 'Escape')
61
+ close();
62
+ }
63
+ const observer = new MutationObserver(() => {
64
+ if (target && !editor.contains(target.element))
65
+ close();
66
+ });
67
+ observer.observe(editor, { childList: true, subtree: true });
68
+ editor.addEventListener('mouseover', onOver);
69
+ editor.addEventListener('mouseout', onOut);
70
+ editor.ownerDocument.addEventListener('keydown', onKeyDown);
71
+ return {
72
+ close,
73
+ keepOpen,
74
+ leave,
75
+ destroy() {
76
+ keepOpen();
77
+ cancelOpen();
78
+ observer.disconnect();
79
+ editor.removeEventListener('mouseover', onOver);
80
+ editor.removeEventListener('mouseout', onOut);
81
+ editor.ownerDocument.removeEventListener('keydown', onKeyDown);
82
+ },
83
+ };
84
+ }
@@ -0,0 +1,10 @@
1
+ import type { LocaleProp, LocaleTranslate } from '@vibe-tiptap/core';
2
+ export interface PrintOptions {
3
+ title?: string;
4
+ cleanupDelay?: number;
5
+ }
6
+ export interface PrintActionOptions extends PrintOptions {
7
+ locale?: LocaleProp;
8
+ t?: LocaleTranslate;
9
+ }
10
+ export declare function printEditorContent(html: string, options?: PrintActionOptions): HTMLIFrameElement;
@@ -0,0 +1,34 @@
1
+ import { resolveLocale } from '@vibe-tiptap/core';
2
+ const DEFAULT_PRINT_CLEANUP_DELAY = 500;
3
+ const PRINT_STYLES = 'body{font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,"Helvetica Neue",Arial,sans-serif;padding:24px;line-height:1.6}img{max-width:100%}table{border-collapse:collapse;width:100%}th,td{border:1px solid #ddd;padding:6px 10px}pre{background:#f5f7fa;padding:12px;border-radius:4px;overflow-x:auto}code{background:#f5f7fa;padding:1px 4px;border-radius:3px}blockquote{border-left:3px solid #ddd;padding-left:1em;color:#666}';
4
+ export function printEditorContent(html, options = {}) {
5
+ const { t: fallbackT } = resolveLocale(options.locale);
6
+ const t = options.t ?? fallbackT;
7
+ const iframe = document.createElement('iframe');
8
+ iframe.style.position = 'fixed';
9
+ iframe.style.right = '0';
10
+ iframe.style.bottom = '0';
11
+ iframe.style.width = '0';
12
+ iframe.style.height = '0';
13
+ iframe.style.border = '0';
14
+ document.body.appendChild(iframe);
15
+ const doc = iframe.contentWindow?.document;
16
+ if (!doc) {
17
+ iframe.remove();
18
+ throw new Error('Unable to access print iframe document');
19
+ }
20
+ doc.open();
21
+ doc.write(`<!DOCTYPE html><html><head><meta charset="utf-8"><title></title>
22
+ <style>${PRINT_STYLES}</style>
23
+ </head><body>${html}</body></html>`);
24
+ doc.title = options.title ?? t('print.defaultTitle');
25
+ const cleanup = () => iframe.remove();
26
+ iframe.onload = () => {
27
+ iframe.onload = null;
28
+ iframe.contentWindow?.focus();
29
+ iframe.contentWindow?.print();
30
+ setTimeout(cleanup, options.cleanupDelay ?? DEFAULT_PRINT_CLEANUP_DELAY);
31
+ };
32
+ doc.close();
33
+ return iframe;
34
+ }
@@ -0,0 +1,7 @@
1
+ import type { Editor } from '@vibe-tiptap/core';
2
+ export declare function trackTextBubbleAnchor(editor: Editor): {
3
+ getReference(): {
4
+ getBoundingClientRect: () => DOMRect;
5
+ } | null;
6
+ destroy(): void;
7
+ };
@@ -0,0 +1,60 @@
1
+ const DRAG_THRESHOLD = 4;
2
+ export function trackTextBubbleAnchor(editor) {
3
+ const { view } = editor;
4
+ const { dom } = view;
5
+ let anchor;
6
+ function onMouseDown(event) {
7
+ anchor = undefined;
8
+ if (event.button !== 0 ||
9
+ event.shiftKey ||
10
+ event.ctrlKey ||
11
+ event.metaKey ||
12
+ event.altKey) {
13
+ return;
14
+ }
15
+ const { clientX: x, clientY: y } = event;
16
+ const hit = view.posAtCoords({ left: x, top: y });
17
+ if (hit)
18
+ anchor = { pos: hit.pos, x, y };
19
+ }
20
+ function onMouseMove(event) {
21
+ if (anchor &&
22
+ (event.buttons & 1) &&
23
+ Math.hypot(event.clientX - anchor.x, event.clientY - anchor.y) > DRAG_THRESHOLD) {
24
+ anchor = undefined;
25
+ }
26
+ }
27
+ const onBeforeTransaction = ({ transaction, nextState, }) => {
28
+ if (!anchor)
29
+ return;
30
+ if (!transaction.getMeta('pointer') &&
31
+ (transaction.selectionSet || !nextState.selection.eq(editor.state.selection))) {
32
+ anchor = undefined;
33
+ }
34
+ else if (transaction.docChanged) {
35
+ const mapped = transaction.mapping.mapResult(anchor.pos);
36
+ anchor = mapped.deleted ? undefined : { ...anchor, pos: mapped.pos };
37
+ }
38
+ };
39
+ dom.addEventListener('mousedown', onMouseDown, true);
40
+ dom.ownerDocument.addEventListener('mousemove', onMouseMove, true);
41
+ editor.on('beforeTransaction', onBeforeTransaction);
42
+ return {
43
+ getReference() {
44
+ const { selection } = editor.state;
45
+ if (!anchor || selection.empty || anchor.pos < selection.from || anchor.pos > selection.to) {
46
+ return null;
47
+ }
48
+ const { left, top, bottom } = view.coordsAtPos(anchor.pos);
49
+ const rect = new DOMRect(left, top, 0, bottom - top);
50
+ return {
51
+ getBoundingClientRect: () => rect,
52
+ };
53
+ },
54
+ destroy() {
55
+ dom.removeEventListener('mousedown', onMouseDown, true);
56
+ dom.ownerDocument.removeEventListener('mousemove', onMouseMove, true);
57
+ editor.off('beforeTransaction', onBeforeTransaction);
58
+ },
59
+ };
60
+ }
@@ -0,0 +1,39 @@
1
+ import type { CodeBlockLanguageOption, HorizontalRuleOption, ToolbarBuiltinKey } from '@vibe-tiptap/core';
2
+ export type { CodeBlockLanguageOption, HorizontalRuleOption } from '@vibe-tiptap/core';
3
+ export type NaiveToolbarBuiltinKey = ToolbarBuiltinKey | 'whiteboard' | 'markdown' | 'print' | 'fullscreen' | 'preview';
4
+ export type NaiveToolbarConfig = NaiveToolbarBuiltinKey[][];
5
+ export type NaiveToolbarProp = NaiveToolbarConfig | false;
6
+ export declare const NAIVE_UI_DEFAULT_TOOLBAR: NaiveToolbarConfig;
7
+ export declare function normalizeToolbarConfig(toolbar?: NaiveToolbarProp): NaiveToolbarConfig;
8
+ export type ToolbarHeadingLevel = 0 | 1 | 2 | 3 | 4 | 5 | 6;
9
+ export type ToolbarTextAlign = 'left' | 'center' | 'right' | 'justify';
10
+ export interface ToolbarHeadingOption {
11
+ label: string;
12
+ level: ToolbarHeadingLevel;
13
+ }
14
+ export interface ToolbarAlignOption {
15
+ label: string;
16
+ value: ToolbarTextAlign;
17
+ }
18
+ export interface ToolbarTableGridOptions {
19
+ maxRows?: number;
20
+ maxCols?: number;
21
+ }
22
+ export interface ResolvedToolbarTableGridOptions {
23
+ maxRows: number;
24
+ maxCols: number;
25
+ }
26
+ export interface ToolbarOptions {
27
+ tableGrid?: ToolbarTableGridOptions;
28
+ }
29
+ export interface ResolvedToolbarMenuOptions {
30
+ codeBlockLanguages: CodeBlockLanguageOption[];
31
+ horizontalRules: HorizontalRuleOption[];
32
+ tableGrid: ResolvedToolbarTableGridOptions;
33
+ }
34
+ export declare const TOOLBAR_HEADING_OPTIONS: ToolbarHeadingOption[];
35
+ export declare const DEFAULT_CODE_BLOCK_LANGUAGES: CodeBlockLanguageOption[];
36
+ export declare const DEFAULT_HORIZONTAL_RULES: HorizontalRuleOption[];
37
+ export declare const TOOLBAR_TABLE_GRID: ResolvedToolbarTableGridOptions;
38
+ export declare const TOOLBAR_ALIGN_OPTIONS: ToolbarAlignOption[];
39
+ export declare function resolveToolbarMenuOptions(options?: ToolbarOptions, codeBlockLanguages?: CodeBlockLanguageOption[], horizontalRules?: HorizontalRuleOption[]): ResolvedToolbarMenuOptions;
@@ -0,0 +1,60 @@
1
+ import { CODE_BLOCK_LANGUAGES } from '@vibe-tiptap/core';
2
+ export const NAIVE_UI_DEFAULT_TOOLBAR = [
3
+ ['undo', 'redo'],
4
+ ['heading'],
5
+ ['bold', 'italic', 'underline', 'strike', 'code', 'superscript', 'subscript'],
6
+ ['color', 'highlight', 'clearFormat'],
7
+ ['align', 'decreaseIndent', 'increaseIndent', 'firstLineIndent'],
8
+ ['bulletList', 'orderedList', 'taskList', 'blockquote', 'codeBlock'],
9
+ ['link', 'image', 'video', 'audio', 'attachment', 'table', 'whiteboard', 'hr'],
10
+ ['findReplace', 'markdown', 'print'],
11
+ ['preview', 'fullscreen'],
12
+ ];
13
+ export function normalizeToolbarConfig(toolbar) {
14
+ if (toolbar === false)
15
+ return [];
16
+ const source = toolbar ?? NAIVE_UI_DEFAULT_TOOLBAR;
17
+ return source.filter((group) => group.length > 0).map((group) => [...group]);
18
+ }
19
+ export const TOOLBAR_HEADING_OPTIONS = [
20
+ { label: '正文', level: 0 },
21
+ { label: '标题 1', level: 1 },
22
+ { label: '标题 2', level: 2 },
23
+ { label: '标题 3', level: 3 },
24
+ { label: '标题 4', level: 4 },
25
+ { label: '标题 5', level: 5 },
26
+ { label: '标题 6', level: 6 },
27
+ ];
28
+ export const DEFAULT_CODE_BLOCK_LANGUAGES = CODE_BLOCK_LANGUAGES.map((language) => ({ ...language }));
29
+ export const DEFAULT_HORIZONTAL_RULES = [
30
+ { label: '实线', value: 'solid' },
31
+ { label: '粗线', value: 'thick' },
32
+ { label: '虚线', value: 'dashed' },
33
+ { label: '点线', value: 'dotted' },
34
+ ];
35
+ export const TOOLBAR_TABLE_GRID = {
36
+ maxRows: 8,
37
+ maxCols: 10,
38
+ };
39
+ export const TOOLBAR_ALIGN_OPTIONS = [
40
+ { label: '左对齐', value: 'left' },
41
+ { label: '居中', value: 'center' },
42
+ { label: '右对齐', value: 'right' },
43
+ { label: '两端对齐', value: 'justify' },
44
+ ];
45
+ function resolvePositiveInteger(value, fallback) {
46
+ if (typeof value !== 'number' || !Number.isFinite(value))
47
+ return fallback;
48
+ const normalized = Math.floor(value);
49
+ return normalized > 0 ? normalized : fallback;
50
+ }
51
+ export function resolveToolbarMenuOptions(options = {}, codeBlockLanguages = DEFAULT_CODE_BLOCK_LANGUAGES, horizontalRules = DEFAULT_HORIZONTAL_RULES) {
52
+ return {
53
+ codeBlockLanguages: [...codeBlockLanguages],
54
+ horizontalRules: [...horizontalRules],
55
+ tableGrid: {
56
+ maxRows: resolvePositiveInteger(options.tableGrid?.maxRows, TOOLBAR_TABLE_GRID.maxRows),
57
+ maxCols: resolvePositiveInteger(options.tableGrid?.maxCols, TOOLBAR_TABLE_GRID.maxCols),
58
+ },
59
+ };
60
+ }
@@ -0,0 +1,12 @@
1
+ import '@excalidraw/excalidraw/index.css';
2
+ import type { ExcalidrawImperativeAPI } from '@excalidraw/excalidraw/types';
3
+ import type { UploadAsset } from '@vibe-tiptap/core';
4
+ export type WhiteboardImageUrls = Map<string, {
5
+ dataURL: string;
6
+ url: string;
7
+ }>;
8
+ export declare function mountWhiteboard(host: HTMLElement, scene: string | undefined, imageUrls: WhiteboardImageUrls, signal: AbortSignal, onReady: (api: ExcalidrawImperativeAPI) => void): Promise<(() => void) | undefined>;
9
+ export declare function exportWhiteboard(api: ExcalidrawImperativeAPI, imageUrls: WhiteboardImageUrls, uploadAsset: UploadAsset, baseURI: string, signal: AbortSignal): Promise<{
10
+ sceneData: string;
11
+ file: File;
12
+ }>;
@@ -0,0 +1,104 @@
1
+ import { Excalidraw, exportScene, loadFromBlob, serializeAsJSON } from '@excalidraw/excalidraw';
2
+ import '@excalidraw/excalidraw/index.css';
3
+ import { createElement } from 'react';
4
+ import { createRoot } from 'react-dom/client';
5
+ const WHITEBOARD_EXPORT_PADDING = 32;
6
+ function isRecord(value) {
7
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
8
+ }
9
+ function resolveImageUrl(url, baseURI) {
10
+ const resolved = new URL(url, baseURI);
11
+ if (!['http:', 'https:', 'blob:'].includes(resolved.protocol)) {
12
+ throw new Error('Invalid whiteboard image URL');
13
+ }
14
+ return resolved;
15
+ }
16
+ async function restoreWhiteboard(scene, baseURI, imageUrls, signal) {
17
+ const data = JSON.parse(scene);
18
+ if (isRecord(data) && isRecord(data.files)) {
19
+ await Promise.all(Object.entries(data.files).map(async ([id, file]) => {
20
+ if (!isRecord(file) || typeof file.url !== 'string')
21
+ return;
22
+ const response = await fetch(resolveImageUrl(file.url, baseURI), { signal });
23
+ if (!response.ok)
24
+ throw new Error('Unable to download whiteboard image');
25
+ const blob = await response.blob();
26
+ const type = typeof file.mimeType === 'string' ? file.mimeType : blob.type;
27
+ const dataURL = await new Promise((resolve, reject) => {
28
+ const reader = new FileReader();
29
+ reader.onload = () => typeof reader.result === 'string'
30
+ ? resolve(reader.result)
31
+ : reject(new Error('Unable to read whiteboard image'));
32
+ reader.onerror = () => reject(reader.error);
33
+ reader.readAsDataURL(new Blob([blob], { type }));
34
+ });
35
+ imageUrls.set(id, { dataURL, url: file.url });
36
+ file.dataURL = dataURL;
37
+ delete file.url;
38
+ }));
39
+ }
40
+ return loadFromBlob(new Blob([JSON.stringify(data)], { type: 'application/json' }), null, null);
41
+ }
42
+ export async function mountWhiteboard(host, scene, imageUrls, signal, onReady) {
43
+ const initialData = scene
44
+ ? await restoreWhiteboard(scene, host.ownerDocument.baseURI, imageUrls, signal)
45
+ : undefined;
46
+ if (signal.aborted)
47
+ return;
48
+ const root = createRoot(host);
49
+ root.render(createElement(Excalidraw, {
50
+ initialData,
51
+ onExcalidrawAPI: (api) => {
52
+ if (api)
53
+ onReady(api);
54
+ },
55
+ langCode: host.ownerDocument.documentElement.lang.startsWith('en') ? 'en' : 'zh-CN',
56
+ handleKeyboardGlobally: false,
57
+ validateEmbeddable: false,
58
+ }));
59
+ return () => root.unmount();
60
+ }
61
+ export async function exportWhiteboard(api, imageUrls, uploadAsset, baseURI, signal) {
62
+ const elements = api.getSceneElements();
63
+ const appState = api.getAppState();
64
+ const files = api.getFiles();
65
+ const blob = await exportScene({
66
+ type: 'png',
67
+ data: { elements, appState, files },
68
+ config: {
69
+ padding: WHITEBOARD_EXPORT_PADDING,
70
+ theme: appState.exportWithDarkMode ? 'dark' : 'light',
71
+ canvasBackgroundColor: appState.exportBackground ? appState.viewBackgroundColor : false,
72
+ scale: appState.exportScale,
73
+ embedScene: appState.exportEmbedScene,
74
+ },
75
+ });
76
+ const fileIds = new Set(elements.flatMap((element) => element.type === 'image' && element.fileId ? [element.fileId] : []));
77
+ const uploadedFiles = new Map();
78
+ for (const id of fileIds) {
79
+ const file = files[id];
80
+ if (!file)
81
+ continue;
82
+ const { dataURL, ...metadata } = file;
83
+ const previous = imageUrls.get(id);
84
+ let url = previous?.dataURL === dataURL ? previous.url : undefined;
85
+ if (!url) {
86
+ const response = await fetch(dataURL, { signal });
87
+ const image = await response.blob();
88
+ const extension = file.mimeType.split('/')[1]?.split('+')[0] ?? 'bin';
89
+ signal.throwIfAborted();
90
+ const asset = await uploadAsset(new File([image], `whiteboard-image.${extension}`, { type: file.mimeType }), 'image');
91
+ url = (typeof asset === 'string' ? asset : asset?.url)?.trim();
92
+ if (!url)
93
+ throw new Error('Whiteboard image upload returned no URL');
94
+ resolveImageUrl(url, baseURI);
95
+ imageUrls.set(id, { dataURL, url });
96
+ }
97
+ uploadedFiles.set(id, { ...metadata, url });
98
+ }
99
+ const scene = JSON.parse(serializeAsJSON(elements, appState, {}, 'local'));
100
+ if (!isRecord(scene))
101
+ throw new Error('Invalid whiteboard scene');
102
+ const sceneData = JSON.stringify({ ...scene, files: Object.fromEntries(uploadedFiles) });
103
+ return { sceneData, file: new File([blob], 'whiteboard.png', { type: 'image/png' }) };
104
+ }
package/package.json CHANGED
@@ -1,6 +1,37 @@
1
1
  {
2
2
  "name": "@vibe-tiptap/editor-ui",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "1.1.0",
4
+ "description": "Vibe Tiptap UI 实现共享的工具栏、主题和文件辅助模块",
5
+ "license": "ISC",
6
+ "type": "module",
7
+ "exports": {
8
+ "./*": {
9
+ "types": "./dist/*.d.ts",
10
+ "import": "./dist/*.js"
11
+ }
12
+ },
13
+ "files": [
14
+ "dist"
15
+ ],
16
+ "publishConfig": {
17
+ "access": "public"
18
+ },
19
+ "dependencies": {
20
+ "@excalidraw/excalidraw": "0.18.0-dabd83c",
21
+ "@vibe-tiptap/core": "1.1.0"
22
+ },
23
+ "peerDependencies": {
24
+ "react": "^18.0.0 || ^19.0.0",
25
+ "react-dom": "^18.0.0 || ^19.0.0"
26
+ },
27
+ "devDependencies": {
28
+ "@types/react": "^19.3.0",
29
+ "@types/react-dom": "^19.3.0",
30
+ "react": "^19.3.0",
31
+ "react-dom": "^19.3.0"
32
+ },
33
+ "scripts": {
34
+ "build": "tsc -p tsconfig.json",
35
+ "typecheck": "tsc -p tsconfig.json --noEmit"
36
+ }
6
37
  }