mirror of
https://gitee.com/qqtt-ah/ecom-dmb.git
synced 2026-11-24 03:19:18 +08:00
update: 升级vben5.5.9到5.7.0
This commit is contained in:
@@ -0,0 +1,450 @@
|
||||
import type { Editor as CoreEditor } from '@tiptap/core';
|
||||
import type { Node as ProseMirrorNode } from '@tiptap/pm/model';
|
||||
import type { EditorView } from '@tiptap/pm/view';
|
||||
import type { Extensions } from '@tiptap/vue-3';
|
||||
|
||||
import type { ImageUploadOptions, VbenTiptapExtensionOptions } from './types';
|
||||
|
||||
import { $t } from '@vben/locales';
|
||||
|
||||
import { alert } from '@vben-core/popup-ui';
|
||||
|
||||
import Highlight from '@tiptap/extension-highlight';
|
||||
import Image from '@tiptap/extension-image';
|
||||
import Link from '@tiptap/extension-link';
|
||||
import Placeholder from '@tiptap/extension-placeholder';
|
||||
import TextAlign from '@tiptap/extension-text-align';
|
||||
import { Color, TextStyle } from '@tiptap/extension-text-style';
|
||||
import { Plugin, PluginKey } from '@tiptap/pm/state';
|
||||
import StarterKit from '@tiptap/starter-kit';
|
||||
|
||||
const DEFAULT_ACCEPT = 'image/*';
|
||||
|
||||
function validateFile(
|
||||
file: File,
|
||||
options: ImageUploadOptions,
|
||||
): string | undefined {
|
||||
if (options.maxSize !== undefined && file.size > options.maxSize) {
|
||||
return $t('ui.tiptap.upload.fileTooLarge');
|
||||
}
|
||||
|
||||
const accept = options.accept ?? DEFAULT_ACCEPT;
|
||||
if (accept && accept !== '*/*' && accept !== 'image/*') {
|
||||
const acceptedTypes = accept.split(',').map((t) => t.trim());
|
||||
const isAccepted = acceptedTypes.some((type) => {
|
||||
if (type.endsWith('/*')) {
|
||||
return file.type.startsWith(type.slice(0, -1));
|
||||
}
|
||||
return file.type === type;
|
||||
});
|
||||
if (!isAccepted) {
|
||||
return $t('ui.tiptap.upload.fileTypeNotAllowed');
|
||||
}
|
||||
}
|
||||
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function handleUploadError(error: unknown, options: ImageUploadOptions): void {
|
||||
if (options.onUploadError) {
|
||||
options.onUploadError(error);
|
||||
} else {
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
alert(message, $t('ui.tiptap.upload.uploadFailed')).catch(() => {});
|
||||
}
|
||||
}
|
||||
|
||||
function findPlaceholderPos(doc: ProseMirrorNode, blobUrl: string): number {
|
||||
let found = -1;
|
||||
doc.descendants((node: ProseMirrorNode, offset: number) => {
|
||||
if (found !== -1) return false;
|
||||
if (
|
||||
node.type.name === 'image' &&
|
||||
node.attrs.src === blobUrl &&
|
||||
node.attrs['data-uploading'] === 'true'
|
||||
) {
|
||||
found = offset;
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
});
|
||||
return found;
|
||||
}
|
||||
|
||||
interface UploadContext {
|
||||
blobUrl: string;
|
||||
pos: number;
|
||||
}
|
||||
|
||||
function createUploadProcess(
|
||||
editor: CoreEditor,
|
||||
file: File,
|
||||
options: ImageUploadOptions,
|
||||
blobUrlTracker?: Set<string>,
|
||||
pos?: number,
|
||||
): UploadContext {
|
||||
const blobUrl = URL.createObjectURL(file);
|
||||
blobUrlTracker?.add(blobUrl);
|
||||
const insertPos = pos ?? editor.state.selection.from;
|
||||
|
||||
// Insert placeholder image with blob URL
|
||||
editor
|
||||
.chain()
|
||||
.insertContentAt(insertPos, {
|
||||
attrs: {
|
||||
'data-upload-progress': 0,
|
||||
'data-uploading': 'true',
|
||||
src: blobUrl,
|
||||
},
|
||||
type: 'image',
|
||||
})
|
||||
.run();
|
||||
|
||||
const nodePos = findPlaceholderPos(editor.state.doc, blobUrl);
|
||||
|
||||
const uploadContext: UploadContext = { blobUrl, pos: nodePos };
|
||||
|
||||
options
|
||||
.upload(file, (percent: number) => {
|
||||
if (editor.isDestroyed) return;
|
||||
|
||||
const currentPos = findPlaceholderPos(editor.state.doc, blobUrl);
|
||||
if (currentPos === -1) return;
|
||||
|
||||
const node = editor.state.doc.nodeAt(currentPos);
|
||||
if (!node) return;
|
||||
|
||||
const transaction = editor.state.tr.setNodeMarkup(currentPos, undefined, {
|
||||
...node.attrs,
|
||||
'data-upload-progress': percent,
|
||||
});
|
||||
editor.view.dispatch(transaction);
|
||||
})
|
||||
.then((url: string) => {
|
||||
if (editor.isDestroyed) {
|
||||
URL.revokeObjectURL(blobUrl);
|
||||
return;
|
||||
}
|
||||
|
||||
const currentPos = findPlaceholderPos(editor.state.doc, blobUrl);
|
||||
|
||||
if (currentPos === -1) {
|
||||
blobUrlTracker?.delete(blobUrl);
|
||||
URL.revokeObjectURL(blobUrl);
|
||||
return;
|
||||
}
|
||||
|
||||
const node = editor.state.doc.nodeAt(currentPos);
|
||||
if (!node) {
|
||||
blobUrlTracker?.delete(blobUrl);
|
||||
URL.revokeObjectURL(blobUrl);
|
||||
return;
|
||||
}
|
||||
|
||||
const transaction = editor.state.tr.setNodeMarkup(currentPos, undefined, {
|
||||
...node.attrs,
|
||||
'data-upload-progress': null,
|
||||
'data-uploading': null,
|
||||
src: url,
|
||||
});
|
||||
editor.view.dispatch(transaction);
|
||||
blobUrlTracker?.delete(blobUrl);
|
||||
URL.revokeObjectURL(blobUrl);
|
||||
})
|
||||
.catch((error: unknown) => {
|
||||
if (editor.isDestroyed) {
|
||||
URL.revokeObjectURL(blobUrl);
|
||||
return;
|
||||
}
|
||||
|
||||
const currentPos = findPlaceholderPos(editor.state.doc, blobUrl);
|
||||
|
||||
if (currentPos !== -1) {
|
||||
const transaction = editor.state.tr.delete(
|
||||
currentPos,
|
||||
currentPos + (editor.state.doc.nodeAt(currentPos)?.nodeSize ?? 1),
|
||||
);
|
||||
editor.view.dispatch(transaction);
|
||||
}
|
||||
|
||||
URL.revokeObjectURL(blobUrl);
|
||||
blobUrlTracker?.delete(blobUrl);
|
||||
handleUploadError(error, options);
|
||||
});
|
||||
|
||||
return uploadContext;
|
||||
}
|
||||
|
||||
function createCustomImage(
|
||||
imageUpload: ImageUploadOptions,
|
||||
blobUrlTracker?: Set<string>,
|
||||
) {
|
||||
return Image.extend({
|
||||
addAttributes() {
|
||||
return {
|
||||
...this.parent?.(),
|
||||
'data-upload-progress': {
|
||||
default: null,
|
||||
parseHTML: (element) => element.dataset.uploadProgress,
|
||||
renderHTML: () => {
|
||||
return {};
|
||||
},
|
||||
},
|
||||
'data-uploading': {
|
||||
default: null,
|
||||
parseHTML: (element) => element.dataset.uploading,
|
||||
renderHTML: () => {
|
||||
return {};
|
||||
},
|
||||
},
|
||||
};
|
||||
},
|
||||
|
||||
addNodeView() {
|
||||
return ({ node }) => {
|
||||
const isUploading = node.attrs['data-uploading'] === 'true';
|
||||
|
||||
if (!isUploading) {
|
||||
return null as any;
|
||||
}
|
||||
|
||||
const wrapper = document.createElement('div');
|
||||
wrapper.className = 'vben-tiptap-upload-wrapper';
|
||||
|
||||
const img = document.createElement('img');
|
||||
img.src = node.attrs.src;
|
||||
img.className = 'vben-tiptap__image';
|
||||
wrapper.append(img);
|
||||
|
||||
const spinner = document.createElement('div');
|
||||
spinner.className = 'vben-tiptap-upload-spinner';
|
||||
wrapper.append(spinner);
|
||||
|
||||
const progressBar = document.createElement('div');
|
||||
progressBar.className = 'vben-tiptap-upload-progress';
|
||||
const progressFill = document.createElement('div');
|
||||
progressFill.className = 'vben-tiptap-upload-progress-fill';
|
||||
progressBar.append(progressFill);
|
||||
wrapper.append(progressBar);
|
||||
|
||||
const progress = node.attrs['data-upload-progress'];
|
||||
if (progress !== null && progress !== undefined && progress > 0) {
|
||||
spinner.style.display = 'none';
|
||||
progressBar.style.display = '';
|
||||
progressFill.style.width = `${progress}%`;
|
||||
} else {
|
||||
spinner.style.display = '';
|
||||
progressBar.style.display = 'none';
|
||||
}
|
||||
|
||||
return {
|
||||
dom: wrapper,
|
||||
update(updatedNode: ProseMirrorNode) {
|
||||
if (updatedNode.attrs['data-uploading'] !== 'true') {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (updatedNode.attrs.src !== img.src) {
|
||||
img.src = updatedNode.attrs.src;
|
||||
}
|
||||
|
||||
const newProgress = updatedNode.attrs['data-upload-progress'];
|
||||
if (
|
||||
newProgress !== null &&
|
||||
newProgress !== undefined &&
|
||||
newProgress > 0
|
||||
) {
|
||||
spinner.style.display = 'none';
|
||||
progressBar.style.display = '';
|
||||
progressFill.style.width = `${newProgress}%`;
|
||||
} else {
|
||||
spinner.style.display = '';
|
||||
progressBar.style.display = 'none';
|
||||
}
|
||||
|
||||
return true;
|
||||
},
|
||||
} as any;
|
||||
};
|
||||
},
|
||||
|
||||
addCommands() {
|
||||
return {
|
||||
...this.parent?.(),
|
||||
uploadImage:
|
||||
() =>
|
||||
({ editor: cmdEditor }: { editor: CoreEditor }) => {
|
||||
const input = document.createElement('input');
|
||||
input.type = 'file';
|
||||
input.accept = imageUpload.accept ?? DEFAULT_ACCEPT;
|
||||
input.style.display = 'none';
|
||||
|
||||
input.addEventListener('change', () => {
|
||||
const file = input.files?.[0];
|
||||
if (!file) return;
|
||||
|
||||
const error = validateFile(file, imageUpload);
|
||||
if (error) {
|
||||
handleUploadError(new Error(error), imageUpload);
|
||||
return;
|
||||
}
|
||||
|
||||
createUploadProcess(cmdEditor, file, imageUpload, blobUrlTracker);
|
||||
input.remove();
|
||||
});
|
||||
|
||||
document.body.append(input);
|
||||
input.click();
|
||||
return true;
|
||||
},
|
||||
};
|
||||
},
|
||||
|
||||
addProseMirrorPlugins() {
|
||||
const editor = this.editor;
|
||||
|
||||
return [
|
||||
new Plugin({
|
||||
key: new PluginKey('imageUploadDrop'),
|
||||
props: {
|
||||
handleDrop: (view: EditorView, event: DragEvent) => {
|
||||
if (!event.dataTransfer?.files.length) return false;
|
||||
|
||||
const imageFiles = [...event.dataTransfer.files].filter((f) =>
|
||||
f.type.startsWith('image/'),
|
||||
);
|
||||
if (imageFiles.length === 0) return false;
|
||||
|
||||
event.preventDefault();
|
||||
|
||||
// Only support single image upload
|
||||
const file = imageFiles[0];
|
||||
if (!file) return false;
|
||||
if (imageFiles.length > 1) {
|
||||
handleUploadError(
|
||||
new Error($t('ui.tiptap.upload.onlySingleImage')),
|
||||
imageUpload,
|
||||
);
|
||||
}
|
||||
|
||||
const error = validateFile(file, imageUpload);
|
||||
if (error) {
|
||||
handleUploadError(new Error(error), imageUpload);
|
||||
return true;
|
||||
}
|
||||
|
||||
const coordinates = view.posAtCoords({
|
||||
left: event.clientX,
|
||||
top: event.clientY,
|
||||
});
|
||||
|
||||
const pos = coordinates?.pos ?? view.state.selection.from;
|
||||
|
||||
createUploadProcess(
|
||||
editor,
|
||||
file,
|
||||
imageUpload,
|
||||
blobUrlTracker,
|
||||
pos,
|
||||
);
|
||||
return true;
|
||||
},
|
||||
},
|
||||
}),
|
||||
new Plugin({
|
||||
key: new PluginKey('imageUploadPaste'),
|
||||
props: {
|
||||
handlePaste: (_view: EditorView, event: ClipboardEvent) => {
|
||||
const items = event.clipboardData?.items;
|
||||
if (!items) return false;
|
||||
|
||||
const imageFiles: File[] = [];
|
||||
for (const item of items) {
|
||||
if (item.type.startsWith('image/')) {
|
||||
const file = item.getAsFile();
|
||||
if (file) imageFiles.push(file);
|
||||
}
|
||||
}
|
||||
|
||||
if (imageFiles.length === 0) return false;
|
||||
|
||||
event.preventDefault();
|
||||
|
||||
const imageFile = imageFiles[0];
|
||||
if (!imageFile) return false;
|
||||
if (imageFiles.length > 1) {
|
||||
handleUploadError(
|
||||
new Error($t('ui.tiptap.upload.onlySingleImage')),
|
||||
imageUpload,
|
||||
);
|
||||
}
|
||||
|
||||
const error = validateFile(imageFile, imageUpload);
|
||||
if (error) {
|
||||
handleUploadError(new Error(error), imageUpload);
|
||||
return true;
|
||||
}
|
||||
|
||||
createUploadProcess(
|
||||
editor,
|
||||
imageFile,
|
||||
imageUpload,
|
||||
blobUrlTracker,
|
||||
);
|
||||
return true;
|
||||
},
|
||||
},
|
||||
}),
|
||||
];
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function createDefaultTiptapExtensions(
|
||||
options: VbenTiptapExtensionOptions = {},
|
||||
): Extensions {
|
||||
return [
|
||||
StarterKit.configure({
|
||||
heading: {
|
||||
levels: [1, 2, 3, 4],
|
||||
},
|
||||
link: false,
|
||||
}),
|
||||
TextAlign.configure({
|
||||
types: ['heading', 'paragraph'],
|
||||
}),
|
||||
TextStyle,
|
||||
Color.configure({
|
||||
types: ['textStyle'],
|
||||
}),
|
||||
Highlight.configure({
|
||||
multicolor: true,
|
||||
}),
|
||||
Link.configure({
|
||||
autolink: true,
|
||||
defaultProtocol: 'https',
|
||||
enableClickSelection: true,
|
||||
openOnClick: false,
|
||||
protocols: ['mailto', { optionalSlashes: true, scheme: 'tel' }],
|
||||
}),
|
||||
options.imageUpload
|
||||
? createCustomImage(
|
||||
options.imageUpload,
|
||||
options._blobUrlTracker,
|
||||
).configure({
|
||||
allowBase64: true,
|
||||
HTMLAttributes: {
|
||||
class: 'vben-tiptap__image',
|
||||
},
|
||||
})
|
||||
: Image.configure({
|
||||
allowBase64: true,
|
||||
HTMLAttributes: {
|
||||
class: 'vben-tiptap__image',
|
||||
},
|
||||
}),
|
||||
Placeholder.configure({
|
||||
placeholder: options.placeholder ?? $t('ui.tiptap.placeholder'),
|
||||
}),
|
||||
];
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
export { default as VbenTiptapPreview } from './preview.vue';
|
||||
export { default as VbenTiptap } from './tiptap.vue';
|
||||
|
||||
export * from './types';
|
||||
@@ -0,0 +1,34 @@
|
||||
<script setup lang="ts">
|
||||
import type { TipTapPreviewProps } from './types';
|
||||
|
||||
import { computed } from 'vue';
|
||||
|
||||
import { cn } from '@vben-core/shared/utils';
|
||||
|
||||
import './style.css';
|
||||
const props = withDefaults(defineProps<TipTapPreviewProps>(), {
|
||||
content: '',
|
||||
minHeight: 160,
|
||||
});
|
||||
const contentMinHeight = computed(() =>
|
||||
typeof props.minHeight === 'number'
|
||||
? `${props.minHeight}px`
|
||||
: props.minHeight,
|
||||
);
|
||||
const previewClass = computed(() =>
|
||||
cn(
|
||||
'vben-tiptap-content',
|
||||
'text-foreground bg-transparent p-0 leading-7',
|
||||
props.class,
|
||||
),
|
||||
);
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<!-- eslint-disable vue/no-v-html -->
|
||||
<div
|
||||
:class="previewClass"
|
||||
:style="{ minHeight: contentMinHeight }"
|
||||
v-html="content"
|
||||
></div>
|
||||
</template>
|
||||
@@ -0,0 +1,112 @@
|
||||
@reference "@vben/tailwind-config/theme";
|
||||
|
||||
.vben-tiptap-content h1 {
|
||||
@apply text-2xl font-bold leading-[1.4];
|
||||
}
|
||||
|
||||
.vben-tiptap-content h2 {
|
||||
@apply text-xl font-bold leading-[1.45];
|
||||
}
|
||||
|
||||
.vben-tiptap-content h3 {
|
||||
@apply text-lg font-semibold leading-[1.5];
|
||||
}
|
||||
|
||||
.vben-tiptap-content h4 {
|
||||
@apply text-base font-semibold leading-[1.55];
|
||||
}
|
||||
|
||||
.vben-tiptap-content ul {
|
||||
@apply list-disc pl-6;
|
||||
}
|
||||
|
||||
.vben-tiptap-content ol {
|
||||
@apply list-decimal pl-6;
|
||||
}
|
||||
|
||||
.vben-tiptap-content blockquote {
|
||||
@apply border-l-4 border-primary pl-4 text-muted-foreground;
|
||||
}
|
||||
|
||||
.vben-tiptap-content a {
|
||||
@apply text-primary underline decoration-1 underline-offset-[3px];
|
||||
}
|
||||
|
||||
.vben-tiptap-content code {
|
||||
@apply rounded-[0.45rem] border border-border bg-secondary px-[0.35rem] py-[0.15rem] text-[0.9em] text-primary;
|
||||
}
|
||||
|
||||
.vben-tiptap-content pre {
|
||||
@apply overflow-x-auto rounded-[0.9rem] border border-border bg-popover p-4 text-popover-foreground;
|
||||
}
|
||||
|
||||
.vben-tiptap-content pre code {
|
||||
@apply border-none bg-transparent p-0 text-inherit;
|
||||
}
|
||||
|
||||
.vben-tiptap-content img,
|
||||
.vben-tiptap-content .vben-tiptap__image {
|
||||
max-width: min(100%, 640px);
|
||||
}
|
||||
|
||||
/* Image upload states */
|
||||
.vben-tiptap-upload-wrapper {
|
||||
position: relative;
|
||||
display: inline-block;
|
||||
max-width: min(100%, 640px);
|
||||
margin: 1rem 0;
|
||||
}
|
||||
|
||||
.vben-tiptap-upload-wrapper img {
|
||||
display: block;
|
||||
margin: 0;
|
||||
opacity: 0.6;
|
||||
}
|
||||
|
||||
.vben-tiptap-upload-spinner {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
background-color: hsl(var(--card) / 30%);
|
||||
border-radius: 1rem;
|
||||
}
|
||||
|
||||
.vben-tiptap-upload-spinner::after {
|
||||
display: block;
|
||||
width: 24px;
|
||||
height: 24px;
|
||||
content: '';
|
||||
border: 2px solid hsl(var(--foreground) / 30%);
|
||||
border-top-color: hsl(var(--foreground));
|
||||
border-radius: 50%;
|
||||
animation: vben-tiptap-spin 0.8s linear infinite;
|
||||
}
|
||||
|
||||
.vben-tiptap-upload-progress {
|
||||
position: absolute;
|
||||
bottom: 0;
|
||||
left: 0;
|
||||
width: 100%;
|
||||
height: 4px;
|
||||
overflow: hidden;
|
||||
background-color: hsl(var(--muted));
|
||||
border-radius: 0 0 1rem 1rem;
|
||||
}
|
||||
|
||||
.vben-tiptap-upload-progress-fill {
|
||||
height: 100%;
|
||||
background-color: hsl(var(--primary));
|
||||
transition: width 0.2s ease;
|
||||
}
|
||||
|
||||
@keyframes vben-tiptap-spin {
|
||||
from {
|
||||
transform: rotate(0deg);
|
||||
}
|
||||
|
||||
to {
|
||||
transform: rotate(360deg);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,324 @@
|
||||
<script setup lang="ts">
|
||||
import type {
|
||||
TipTapProps,
|
||||
ToolbarAction,
|
||||
ToolbarMenuItem,
|
||||
VbenTiptapChangeEvent,
|
||||
} from './types';
|
||||
|
||||
import { computed, onBeforeUnmount, reactive, watch } from 'vue';
|
||||
|
||||
import { Check, ChevronDown, Eye } from '@vben/icons';
|
||||
import { $t } from '@vben/locales';
|
||||
|
||||
import { useVbenModal } from '@vben-core/popup-ui';
|
||||
import { VbenIconButton, VbenPopover } from '@vben-core/shadcn-ui';
|
||||
import { cn } from '@vben-core/shared/utils';
|
||||
|
||||
import { EditorContent, useEditor } from '@tiptap/vue-3';
|
||||
|
||||
import { createDefaultTiptapExtensions } from './extensions';
|
||||
import Preview from './preview.vue';
|
||||
import { createToolbarGroups } from './toolbar';
|
||||
import { useTiptapToolbar } from './use-tiptap-toolbar';
|
||||
|
||||
import './style.css';
|
||||
const props = withDefaults(defineProps<TipTapProps>(), {
|
||||
editable: true,
|
||||
extensions: undefined,
|
||||
imageUpload: undefined,
|
||||
minHeight: 240,
|
||||
maxHeight: 400,
|
||||
placeholder: $t('ui.tiptap.placeholder'),
|
||||
previewable: true,
|
||||
toolbar: true,
|
||||
});
|
||||
const emit = defineEmits<{
|
||||
change: [payload: VbenTiptapChangeEvent];
|
||||
}>();
|
||||
const modelValue = defineModel<string>({ default: '' });
|
||||
const contentMinHeight = computed(() =>
|
||||
typeof props.minHeight === 'number'
|
||||
? `${props.minHeight}px`
|
||||
: props.minHeight,
|
||||
);
|
||||
const contentMaxHeight = computed(() =>
|
||||
typeof props.maxHeight === 'number'
|
||||
? `${props.maxHeight}px`
|
||||
: props.maxHeight,
|
||||
);
|
||||
const tiptapContentClass = cn(
|
||||
'vben-tiptap-content vben-tiptap__content',
|
||||
'text-foreground max-h-(--vben-tiptap-max-height) min-h-(--vben-tiptap-min-height) overflow-auto leading-7 outline-none',
|
||||
);
|
||||
const blobUrlTracker = new Set<string>();
|
||||
const editor = useEditor({
|
||||
content: modelValue.value,
|
||||
editable: props.editable,
|
||||
editorProps: {
|
||||
attributes: {
|
||||
class: tiptapContentClass,
|
||||
},
|
||||
},
|
||||
extensions:
|
||||
props.extensions ??
|
||||
createDefaultTiptapExtensions({
|
||||
_blobUrlTracker: blobUrlTracker,
|
||||
imageUpload: props.imageUpload,
|
||||
placeholder: props.placeholder,
|
||||
}),
|
||||
onUpdate: ({ editor }) => {
|
||||
const html = editor.getHTML();
|
||||
if (html !== modelValue.value) {
|
||||
modelValue.value = html;
|
||||
}
|
||||
emit('change', {
|
||||
html,
|
||||
json: editor.getJSON(),
|
||||
text: editor.getText(),
|
||||
});
|
||||
},
|
||||
});
|
||||
const toolbarGroups = computed<ToolbarAction[][]>(() => {
|
||||
// Only show upload toolbar option when using default extensions
|
||||
// (custom extensions may not include the uploadImage command)
|
||||
const effectiveImageUpload = props.extensions ? undefined : props.imageUpload;
|
||||
return createToolbarGroups(effectiveImageUpload);
|
||||
});
|
||||
const previewContent = computed(
|
||||
() => editor.value?.getHTML() ?? modelValue.value,
|
||||
);
|
||||
const [PreviewModal, previewModalApi] = useVbenModal({
|
||||
footer: false,
|
||||
fullscreenButton: false,
|
||||
});
|
||||
const {
|
||||
applyPaletteColor,
|
||||
canRunAction,
|
||||
canRunMenuItem,
|
||||
clearPaletteColor,
|
||||
getActionIndicatorColor,
|
||||
getMenuItemClass,
|
||||
getPaletteCurrentColor,
|
||||
getPaletteSwatchClass,
|
||||
getToolbarButtonClass,
|
||||
isMenuItemActive,
|
||||
runAction,
|
||||
runMenuItem,
|
||||
} = useTiptapToolbar({
|
||||
editable: () => props.editable,
|
||||
editor,
|
||||
});
|
||||
|
||||
const menuOpenState = reactive<Record<string, boolean>>({});
|
||||
|
||||
function getMenuOpen(action: ToolbarAction): boolean {
|
||||
return menuOpenState[action.label] ?? false;
|
||||
}
|
||||
|
||||
function setMenuOpen(action: ToolbarAction, open: boolean) {
|
||||
menuOpenState[action.label] = open;
|
||||
}
|
||||
|
||||
function handleMenuItemClick(action: ToolbarAction, item: ToolbarMenuItem) {
|
||||
runMenuItem(item);
|
||||
setMenuOpen(action, false);
|
||||
}
|
||||
|
||||
function openPreviewModal() {
|
||||
previewModalApi.open();
|
||||
}
|
||||
watch(
|
||||
() => props.editable,
|
||||
(editable) => {
|
||||
editor.value?.setEditable(editable);
|
||||
},
|
||||
);
|
||||
watch(
|
||||
() => modelValue.value,
|
||||
(nextValue = '') => {
|
||||
if (!editor.value) {
|
||||
return;
|
||||
}
|
||||
const currentValue = editor.value.getHTML();
|
||||
if (nextValue === currentValue) {
|
||||
return;
|
||||
}
|
||||
editor.value.commands.setContent(nextValue, {
|
||||
emitUpdate: false,
|
||||
});
|
||||
},
|
||||
);
|
||||
onBeforeUnmount(() => {
|
||||
for (const url of blobUrlTracker) {
|
||||
URL.revokeObjectURL(url);
|
||||
}
|
||||
blobUrlTracker.clear();
|
||||
editor.value?.destroy();
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div
|
||||
:style="{
|
||||
'--vben-tiptap-min-height': contentMinHeight,
|
||||
'--vben-tiptap-max-height': contentMaxHeight,
|
||||
}"
|
||||
class="vben-tiptap overflow-hidden rounded-xl border border-border bg-card"
|
||||
>
|
||||
<div
|
||||
v-if="toolbar"
|
||||
class="sticky top-0 z-10 flex flex-wrap items-center gap-2 border-b border-border p-2 backdrop-blur-[14px]"
|
||||
>
|
||||
<div
|
||||
v-for="(group, groupIndex) in toolbarGroups"
|
||||
:key="groupIndex"
|
||||
class="flex items-center gap-1"
|
||||
>
|
||||
<template v-for="action in group" :key="action.label">
|
||||
<VbenPopover
|
||||
v-if="action.menu || action.palette"
|
||||
:open="action.menu ? getMenuOpen(action) : undefined"
|
||||
:content-props="{ align: 'start', side: 'bottom', sideOffset: 8 }"
|
||||
content-class="w-auto p-2"
|
||||
@update:open="action.menu ? setMenuOpen(action, $event) : undefined"
|
||||
>
|
||||
<template #trigger>
|
||||
<VbenIconButton
|
||||
:aria-label="action.label"
|
||||
:class="getToolbarButtonClass(action)"
|
||||
:disabled="!canRunAction(action)"
|
||||
:tooltip="action.label"
|
||||
tooltip-side="top"
|
||||
variant="ghost"
|
||||
>
|
||||
<template v-if="action.triggerText">
|
||||
<span class="text-xs font-semibold tracking-wide">
|
||||
{{
|
||||
typeof action.triggerText === 'function'
|
||||
? action.triggerText(editor)
|
||||
: action.triggerText
|
||||
}}
|
||||
</span>
|
||||
<ChevronDown class="size-4 opacity-70" />
|
||||
</template>
|
||||
<component
|
||||
v-else-if="action.icon"
|
||||
:is="action.icon"
|
||||
class="size-4"
|
||||
/>
|
||||
<span
|
||||
v-if="getActionIndicatorColor(action)"
|
||||
:style="{ backgroundColor: getActionIndicatorColor(action) }"
|
||||
class="absolute bottom-1 left-1/2 h-1 w-4 -translate-x-1/2 rounded-full shadow-[0_0_0_1px_hsl(var(--card)/0.7)]"
|
||||
></span>
|
||||
</VbenIconButton>
|
||||
</template>
|
||||
<div
|
||||
v-if="action.palette"
|
||||
class="flex max-w-52 flex-wrap items-center gap-2"
|
||||
>
|
||||
<button
|
||||
v-for="color in action.palette.colors"
|
||||
:key="color"
|
||||
:aria-label="`${action.label}-${color}`"
|
||||
:class="getPaletteSwatchClass(action, color)"
|
||||
:style="{ backgroundColor: color }"
|
||||
type="button"
|
||||
@click="applyPaletteColor(action, color)"
|
||||
>
|
||||
<Check
|
||||
v-if="getPaletteCurrentColor(action) === color"
|
||||
class="size-4 text-white drop-shadow-sm"
|
||||
/>
|
||||
</button>
|
||||
<button
|
||||
v-if="action.palette.clear"
|
||||
class="h-8 w-full rounded-xl border border-border bg-secondary text-muted-foreground transition-colors hover:bg-accent hover:text-foreground"
|
||||
type="button"
|
||||
@click="clearPaletteColor(action)"
|
||||
>
|
||||
{{ $t('ui.tiptap.toolbar.clear') }}
|
||||
</button>
|
||||
</div>
|
||||
<div v-else-if="action.menu" class="flex min-w-32 flex-col gap-1">
|
||||
<button
|
||||
v-for="item in action.menu.items"
|
||||
:key="item.shortLabel"
|
||||
:class="getMenuItemClass(item)"
|
||||
:disabled="!canRunMenuItem(item)"
|
||||
type="button"
|
||||
@click="handleMenuItemClick(action, item)"
|
||||
>
|
||||
<span class="w-7 text-xs font-semibold tracking-wide">
|
||||
{{ item.shortLabel }}
|
||||
</span>
|
||||
<span class="flex-1">{{ item.label }}</span>
|
||||
<Check
|
||||
v-if="isMenuItemActive(item)"
|
||||
class="size-4 text-primary"
|
||||
/>
|
||||
</button>
|
||||
</div>
|
||||
</VbenPopover>
|
||||
<VbenIconButton
|
||||
v-else
|
||||
:aria-label="action.label"
|
||||
:class="getToolbarButtonClass(action)"
|
||||
:disabled="!canRunAction(action)"
|
||||
:tooltip="action.label"
|
||||
tooltip-side="top"
|
||||
@click="runAction(action)"
|
||||
>
|
||||
<component :is="action.icon" class="size-4" />
|
||||
<span
|
||||
v-if="getActionIndicatorColor(action)"
|
||||
:style="{ backgroundColor: getActionIndicatorColor(action) }"
|
||||
class="absolute bottom-1 left-1/2 h-1 w-4 -translate-x-1/2 rounded-full shadow-[0_0_0_1px_hsl(var(--card)/0.7)]"
|
||||
></span>
|
||||
</VbenIconButton>
|
||||
</template>
|
||||
<div
|
||||
v-if="groupIndex < toolbarGroups.length - 1"
|
||||
class="ml-1 h-5 w-px bg-border"
|
||||
></div>
|
||||
</div>
|
||||
<div v-if="previewable" class="ml-auto flex items-center">
|
||||
<VbenIconButton
|
||||
:aria-label="$t('ui.tiptap.toolbar.preview')"
|
||||
:class="
|
||||
getToolbarButtonClass({
|
||||
action: () => {},
|
||||
label: $t('ui.tiptap.toolbar.preview'),
|
||||
})
|
||||
"
|
||||
:tooltip="$t('ui.tiptap.toolbar.preview')"
|
||||
tooltip-side="top"
|
||||
variant="ghost"
|
||||
@click="openPreviewModal"
|
||||
>
|
||||
<Eye class="size-4" />
|
||||
</VbenIconButton>
|
||||
</div>
|
||||
</div>
|
||||
<EditorContent v-if="editor" :editor="editor" class="p-4" />
|
||||
<PreviewModal
|
||||
v-if="previewable"
|
||||
:title="$t('ui.tiptap.toolbar.preview')"
|
||||
class="w-4/5"
|
||||
>
|
||||
<Preview :content="previewContent" :min-height="320" />
|
||||
</PreviewModal>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.vben-tiptap
|
||||
:deep(.vben-tiptap__content p.is-editor-empty:first-child::before) {
|
||||
float: left;
|
||||
height: 0;
|
||||
color: hsl(var(--input-placeholder));
|
||||
pointer-events: none;
|
||||
content: attr(data-placeholder);
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,374 @@
|
||||
import type { Editor } from '@tiptap/vue-3';
|
||||
|
||||
import type {
|
||||
ImageUploadOptions,
|
||||
ToolbarAction,
|
||||
ToolbarMenuItem,
|
||||
} from './types';
|
||||
|
||||
import {
|
||||
AlignCenter,
|
||||
AlignLeft,
|
||||
AlignRight,
|
||||
Bold,
|
||||
Highlighter,
|
||||
ImagePlus,
|
||||
Italic,
|
||||
Link2,
|
||||
List,
|
||||
ListOrdered,
|
||||
MessageSquareCode,
|
||||
Paintbrush,
|
||||
Redo2,
|
||||
RemoveFormatting,
|
||||
SquareCode,
|
||||
Strikethrough,
|
||||
TextQuote,
|
||||
Underline,
|
||||
Undo2,
|
||||
Unlink2,
|
||||
} from '@vben/icons';
|
||||
import { $t } from '@vben/locales';
|
||||
import { COLOR_PRESETS } from '@vben/preferences';
|
||||
|
||||
import { prompt } from '@vben-core/popup-ui';
|
||||
|
||||
const headingLevels = [1, 2, 3, 4] as const;
|
||||
const editorColorPresets = [
|
||||
'hsl(var(--foreground))',
|
||||
'hsl(var(--warning))',
|
||||
'hsl(var(--success))',
|
||||
'hsl(var(--destructive))',
|
||||
...COLOR_PRESETS.map((item) => item.color),
|
||||
];
|
||||
const editorHighlightPresets = [
|
||||
withAlpha('hsl(var(--warning))', 0.45),
|
||||
withAlpha('hsl(var(--success))', 0.35),
|
||||
withAlpha('hsl(var(--primary))', 0.3),
|
||||
withAlpha('hsl(var(--destructive))', 0.3),
|
||||
...COLOR_PRESETS.map((item) => withAlpha(item.color, 0.4)),
|
||||
];
|
||||
|
||||
function createHeadingMenuItems(): ToolbarMenuItem[] {
|
||||
return [
|
||||
{
|
||||
action: (editor) => editor.chain().focus().setParagraph().run(),
|
||||
can: (editor) => editor.can().chain().focus().setParagraph().run(),
|
||||
isActive: (editor) => editor.isActive('paragraph'),
|
||||
label: $t('ui.tiptap.toolbar.paragraph'),
|
||||
shortLabel: 'P',
|
||||
},
|
||||
...headingLevels.map((level) => ({
|
||||
action: (editor: Editor) =>
|
||||
editor.chain().focus().toggleHeading({ level }).run(),
|
||||
can: (editor: Editor) =>
|
||||
editor.can().chain().focus().toggleHeading({ level }).run(),
|
||||
isActive: (editor: Editor) => editor.isActive('heading', { level }),
|
||||
label: $t(`ui.tiptap.toolbar.heading${level}`),
|
||||
shortLabel: `H${level}`,
|
||||
})),
|
||||
];
|
||||
}
|
||||
|
||||
function getHeadingTriggerText(editor?: Editor) {
|
||||
if (editor?.isActive('paragraph')) {
|
||||
return 'P';
|
||||
}
|
||||
|
||||
const level = headingLevels.find((headingLevel) =>
|
||||
editor?.isActive('heading', { level: headingLevel }),
|
||||
);
|
||||
|
||||
return level ? `H${level}` : 'H';
|
||||
}
|
||||
|
||||
function normalizeLinkUrl(url: string) {
|
||||
if (/^(https?:|mailto:|tel:)/i.test(url)) {
|
||||
return url;
|
||||
}
|
||||
|
||||
return `https://${url}`;
|
||||
}
|
||||
|
||||
function withAlpha(color: string, alpha: number) {
|
||||
const normalizedAlpha = Math.min(Math.max(alpha, 0), 1);
|
||||
const hslMatch = color.match(/^hsl\((.+)\)$/);
|
||||
|
||||
if (!hslMatch) {
|
||||
return color;
|
||||
}
|
||||
|
||||
return `hsl(${hslMatch[1]} / ${normalizedAlpha})`;
|
||||
}
|
||||
|
||||
async function handleLinkAction(editor: Editor) {
|
||||
const currentHref = editor.getAttributes('link').href as string | undefined;
|
||||
|
||||
let url: string | undefined;
|
||||
|
||||
try {
|
||||
url = await prompt<string>({
|
||||
componentProps: {
|
||||
placeholder: 'https://example.com',
|
||||
},
|
||||
content: $t('ui.tiptap.prompts.link'),
|
||||
defaultValue: currentHref ?? '',
|
||||
});
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
|
||||
const nextUrl = (url ?? '').trim();
|
||||
|
||||
if (!nextUrl) {
|
||||
editor.chain().focus().extendMarkRange('link').unsetLink().run();
|
||||
return;
|
||||
}
|
||||
|
||||
editor
|
||||
.chain()
|
||||
.focus()
|
||||
.extendMarkRange('link')
|
||||
.setLink({
|
||||
href: normalizeLinkUrl(nextUrl),
|
||||
})
|
||||
.run();
|
||||
}
|
||||
|
||||
async function handleImageAction(editor: Editor) {
|
||||
let url: string | undefined;
|
||||
|
||||
try {
|
||||
url = await prompt<string>({
|
||||
componentProps: {
|
||||
placeholder: 'https://example.com/image.png',
|
||||
},
|
||||
content: $t('ui.tiptap.prompts.image'),
|
||||
defaultValue: '',
|
||||
});
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
|
||||
const nextUrl = (url ?? '').trim();
|
||||
|
||||
if (!nextUrl) {
|
||||
return;
|
||||
}
|
||||
|
||||
editor.chain().focus().setImage({ src: nextUrl }).run();
|
||||
}
|
||||
|
||||
export function createToolbarGroups(
|
||||
imageUpload?: ImageUploadOptions,
|
||||
): ToolbarAction[][] {
|
||||
const headingMenuItems = createHeadingMenuItems();
|
||||
|
||||
return [
|
||||
[
|
||||
{
|
||||
action: (editor) => editor.chain().focus().undo().run(),
|
||||
can: (editor) => editor.can().chain().focus().undo().run(),
|
||||
icon: Undo2,
|
||||
label: $t('ui.tiptap.toolbar.undo'),
|
||||
},
|
||||
{
|
||||
action: (editor) => editor.chain().focus().redo().run(),
|
||||
can: (editor) => editor.can().chain().focus().redo().run(),
|
||||
icon: Redo2,
|
||||
label: $t('ui.tiptap.toolbar.redo'),
|
||||
},
|
||||
{
|
||||
action: (editor) =>
|
||||
editor.chain().focus().clearNodes().unsetAllMarks().run(),
|
||||
icon: RemoveFormatting,
|
||||
label: $t('ui.tiptap.toolbar.clear'),
|
||||
},
|
||||
],
|
||||
[
|
||||
{
|
||||
action: (editor) => editor.chain().focus().toggleBold().run(),
|
||||
active: { name: 'bold' },
|
||||
can: (editor) => editor.can().chain().focus().toggleBold().run(),
|
||||
icon: Bold,
|
||||
label: $t('ui.tiptap.toolbar.bold'),
|
||||
},
|
||||
{
|
||||
action: (editor) => editor.chain().focus().toggleItalic().run(),
|
||||
active: { name: 'italic' },
|
||||
can: (editor) => editor.can().chain().focus().toggleItalic().run(),
|
||||
icon: Italic,
|
||||
label: $t('ui.tiptap.toolbar.italic'),
|
||||
},
|
||||
{
|
||||
action: (editor) => editor.chain().focus().toggleUnderline().run(),
|
||||
active: { name: 'underline' },
|
||||
can: (editor) => editor.can().chain().focus().toggleUnderline().run(),
|
||||
icon: Underline,
|
||||
label: $t('ui.tiptap.toolbar.underline'),
|
||||
},
|
||||
{
|
||||
action: (editor) => editor.chain().focus().toggleStrike().run(),
|
||||
active: { name: 'strike' },
|
||||
can: (editor) => editor.can().chain().focus().toggleStrike().run(),
|
||||
icon: Strikethrough,
|
||||
label: $t('ui.tiptap.toolbar.strike'),
|
||||
},
|
||||
{
|
||||
action: (editor) => editor.chain().focus().toggleCode().run(),
|
||||
active: { name: 'code' },
|
||||
can: (editor) => editor.can().chain().focus().toggleCode().run(),
|
||||
icon: SquareCode,
|
||||
label: $t('ui.tiptap.toolbar.code'),
|
||||
},
|
||||
],
|
||||
[
|
||||
{
|
||||
action: () => {},
|
||||
can: (editor) =>
|
||||
headingMenuItems.some((item) => (item.can ? item.can(editor) : true)),
|
||||
isActive: (editor) =>
|
||||
headingMenuItems.some((item) => item.isActive?.(editor)),
|
||||
label: $t('ui.tiptap.toolbar.heading'),
|
||||
menu: {
|
||||
items: headingMenuItems,
|
||||
},
|
||||
triggerText: (editor) => getHeadingTriggerText(editor),
|
||||
},
|
||||
{
|
||||
action: (editor) => editor.chain().focus().toggleBulletList().run(),
|
||||
active: { name: 'bulletList' },
|
||||
can: (editor) => editor.can().chain().focus().toggleBulletList().run(),
|
||||
icon: List,
|
||||
label: $t('ui.tiptap.toolbar.bulletList'),
|
||||
},
|
||||
{
|
||||
action: (editor) => editor.chain().focus().toggleOrderedList().run(),
|
||||
active: { name: 'orderedList' },
|
||||
can: (editor) => editor.can().chain().focus().toggleOrderedList().run(),
|
||||
icon: ListOrdered,
|
||||
label: $t('ui.tiptap.toolbar.orderedList'),
|
||||
},
|
||||
{
|
||||
action: (editor) => editor.chain().focus().toggleBlockquote().run(),
|
||||
active: { name: 'blockquote' },
|
||||
can: (editor) => editor.can().chain().focus().toggleBlockquote().run(),
|
||||
icon: TextQuote,
|
||||
label: $t('ui.tiptap.toolbar.blockquote'),
|
||||
},
|
||||
{
|
||||
action: (editor) => editor.chain().focus().toggleCodeBlock().run(),
|
||||
active: { name: 'codeBlock' },
|
||||
can: (editor) => editor.can().chain().focus().toggleCodeBlock().run(),
|
||||
icon: MessageSquareCode,
|
||||
label: $t('ui.tiptap.toolbar.codeBlock'),
|
||||
},
|
||||
],
|
||||
[
|
||||
{
|
||||
action: (editor) => handleLinkAction(editor),
|
||||
active: { name: 'link' },
|
||||
can: (editor) =>
|
||||
editor.can().chain().focus().extendMarkRange('link').run(),
|
||||
icon: Link2,
|
||||
label: $t('ui.tiptap.toolbar.link'),
|
||||
},
|
||||
{
|
||||
action: (editor) => editor.chain().focus().unsetLink().run(),
|
||||
can: (editor) => editor.can().chain().focus().unsetLink().run(),
|
||||
icon: Unlink2,
|
||||
isActive: (editor) => editor.isActive('link'),
|
||||
label: $t('ui.tiptap.toolbar.unlink'),
|
||||
},
|
||||
{
|
||||
action: (editor) => handleImageAction(editor),
|
||||
icon: ImagePlus,
|
||||
label: $t('ui.tiptap.toolbar.image'),
|
||||
...(imageUpload
|
||||
? {
|
||||
action: () => {},
|
||||
menu: {
|
||||
items: [
|
||||
{
|
||||
action: (editor) => {
|
||||
if (typeof editor.commands.uploadImage === 'function') {
|
||||
editor.commands.uploadImage();
|
||||
}
|
||||
},
|
||||
label: $t('ui.tiptap.toolbar.imageUpload'),
|
||||
shortLabel: 'UPL',
|
||||
},
|
||||
{
|
||||
action: (editor) => handleImageAction(editor),
|
||||
label: $t('ui.tiptap.toolbar.imageUrl'),
|
||||
shortLabel: 'URL',
|
||||
},
|
||||
],
|
||||
},
|
||||
}
|
||||
: {}),
|
||||
},
|
||||
],
|
||||
[
|
||||
{
|
||||
action: () => {},
|
||||
icon: Paintbrush,
|
||||
indicatorColor: (editor) =>
|
||||
editor.getAttributes('textStyle').color as string | undefined,
|
||||
isActive: (editor) => Boolean(editor.getAttributes('textStyle').color),
|
||||
label: $t('ui.tiptap.toolbar.textColor'),
|
||||
palette: {
|
||||
apply: (editor, color) =>
|
||||
editor.chain().focus().setColor(color).run(),
|
||||
clear: (editor) => editor.chain().focus().unsetColor().run(),
|
||||
colors: editorColorPresets,
|
||||
currentColor: (editor) =>
|
||||
editor.getAttributes('textStyle').color as string | undefined,
|
||||
},
|
||||
},
|
||||
{
|
||||
action: () => {},
|
||||
icon: Highlighter,
|
||||
indicatorColor: (editor) =>
|
||||
(editor.getAttributes('highlight').color as string | undefined) ??
|
||||
'#fef08a',
|
||||
isActive: (editor) => editor.isActive('highlight'),
|
||||
label: $t('ui.tiptap.toolbar.highlightColor'),
|
||||
palette: {
|
||||
apply: (editor, color) =>
|
||||
editor.chain().focus().setHighlight({ color }).run(),
|
||||
clear: (editor) => editor.chain().focus().unsetHighlight().run(),
|
||||
colors: editorHighlightPresets,
|
||||
currentColor: (editor) =>
|
||||
editor.getAttributes('highlight').color as string | undefined,
|
||||
},
|
||||
},
|
||||
],
|
||||
[
|
||||
{
|
||||
action: (editor) => editor.chain().focus().setTextAlign('left').run(),
|
||||
can: (editor) =>
|
||||
editor.can().chain().focus().setTextAlign('left').run(),
|
||||
icon: AlignLeft,
|
||||
isActive: (editor) => editor.isActive({ textAlign: 'left' }),
|
||||
label: $t('ui.tiptap.toolbar.alignLeft'),
|
||||
},
|
||||
{
|
||||
action: (editor) => editor.chain().focus().setTextAlign('center').run(),
|
||||
can: (editor) =>
|
||||
editor.can().chain().focus().setTextAlign('center').run(),
|
||||
icon: AlignCenter,
|
||||
isActive: (editor) => editor.isActive({ textAlign: 'center' }),
|
||||
label: $t('ui.tiptap.toolbar.alignCenter'),
|
||||
},
|
||||
{
|
||||
action: (editor) => editor.chain().focus().setTextAlign('right').run(),
|
||||
can: (editor) =>
|
||||
editor.can().chain().focus().setTextAlign('right').run(),
|
||||
icon: AlignRight,
|
||||
isActive: (editor) => editor.isActive({ textAlign: 'right' }),
|
||||
label: $t('ui.tiptap.toolbar.alignRight'),
|
||||
},
|
||||
],
|
||||
];
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
import type { Extensions, JSONContent } from '@tiptap/core';
|
||||
import type { Editor } from '@tiptap/vue-3';
|
||||
|
||||
import type { Component } from 'vue';
|
||||
|
||||
declare module '@tiptap/core' {
|
||||
interface Commands<ReturnType> {
|
||||
imageUpload: {
|
||||
uploadImage: () => ReturnType;
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
export interface ImageUploadOptions {
|
||||
/** 允许的文件类型,默认 'image/*' */
|
||||
accept?: string;
|
||||
/** 最大文件大小(字节),默认 5MB */
|
||||
maxSize?: number;
|
||||
/** 上传失败回调,未提供时使用 alert 弹窗提示 */
|
||||
onUploadError?: (error: unknown) => void;
|
||||
/** 上传函数,返回图片 URL,可选 onProgress 回调报告上传进度 */
|
||||
upload: (
|
||||
file: File,
|
||||
onProgress?: (percent: number) => void,
|
||||
) => Promise<string>;
|
||||
}
|
||||
|
||||
export interface TipTapProps {
|
||||
editable?: boolean;
|
||||
extensions?: Extensions;
|
||||
imageUpload?: ImageUploadOptions;
|
||||
minHeight?: number | string;
|
||||
maxHeight?: number | string;
|
||||
placeholder?: string;
|
||||
previewable?: boolean;
|
||||
toolbar?: boolean;
|
||||
}
|
||||
|
||||
export interface TipTapPreviewProps {
|
||||
class?: any;
|
||||
content?: string;
|
||||
minHeight?: number | string;
|
||||
}
|
||||
|
||||
export interface VbenTiptapChangeEvent {
|
||||
html: string;
|
||||
json: JSONContent;
|
||||
text: string;
|
||||
}
|
||||
|
||||
export interface VbenTiptapExtensionOptions {
|
||||
imageUpload?: ImageUploadOptions;
|
||||
/** 内部使用:追踪 blob URL 以便组件销毁时清理 */
|
||||
_blobUrlTracker?: Set<string>;
|
||||
placeholder?: string;
|
||||
}
|
||||
|
||||
export interface ToolbarAction {
|
||||
action: (editor: Editor) => void;
|
||||
active?: {
|
||||
attrs?: Record<string, unknown>;
|
||||
name: string;
|
||||
};
|
||||
can?: (editor: Editor) => boolean;
|
||||
icon?: Component;
|
||||
indicatorColor?: (editor: Editor) => string | undefined;
|
||||
isActive?: (editor: Editor) => boolean;
|
||||
label: string;
|
||||
menu?: {
|
||||
items: ToolbarMenuItem[];
|
||||
};
|
||||
palette?: {
|
||||
apply: (editor: Editor, color: string) => void;
|
||||
clear?: (editor: Editor) => void;
|
||||
colors: string[];
|
||||
currentColor?: (editor: Editor) => string | undefined;
|
||||
};
|
||||
triggerText?: ((editor?: Editor) => string) | string;
|
||||
}
|
||||
|
||||
export interface ToolbarMenuItem {
|
||||
action: (editor: Editor) => void;
|
||||
can?: (editor: Editor) => boolean;
|
||||
isActive?: (editor: Editor) => boolean;
|
||||
label: string;
|
||||
shortLabel: string;
|
||||
}
|
||||
@@ -0,0 +1,176 @@
|
||||
import type { Editor } from '@tiptap/vue-3';
|
||||
|
||||
import type { ShallowRef } from 'vue';
|
||||
|
||||
import type { ToolbarAction, ToolbarMenuItem } from './types';
|
||||
|
||||
import { cn } from '@vben-core/shared/utils';
|
||||
|
||||
interface UseTiptapToolbarOptions {
|
||||
editable: () => boolean;
|
||||
editor: Readonly<ShallowRef<Editor | undefined>>;
|
||||
}
|
||||
|
||||
export function useTiptapToolbar(options: UseTiptapToolbarOptions) {
|
||||
const getEditor = () => options.editor.value;
|
||||
|
||||
function getActionIndicatorColor(action: ToolbarAction) {
|
||||
const currentEditor = getEditor();
|
||||
|
||||
if (!currentEditor || !action.indicatorColor) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
return action.indicatorColor(currentEditor);
|
||||
}
|
||||
|
||||
function getPaletteCurrentColor(action: ToolbarAction) {
|
||||
const currentEditor = getEditor();
|
||||
|
||||
if (!currentEditor || !action.palette?.currentColor) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
return action.palette.currentColor(currentEditor);
|
||||
}
|
||||
|
||||
function canRunAction(action: ToolbarAction) {
|
||||
const currentEditor = getEditor();
|
||||
|
||||
if (!currentEditor || !options.editable()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return action.can ? action.can(currentEditor) : true;
|
||||
}
|
||||
|
||||
function canRunMenuItem(item: ToolbarMenuItem) {
|
||||
const currentEditor = getEditor();
|
||||
|
||||
if (!currentEditor || !options.editable()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return item.can ? item.can(currentEditor) : true;
|
||||
}
|
||||
|
||||
function isActionActive(action: ToolbarAction) {
|
||||
const currentEditor = getEditor();
|
||||
|
||||
if (!currentEditor) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (action.isActive) {
|
||||
return action.isActive(currentEditor);
|
||||
}
|
||||
|
||||
if (!action.active) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return currentEditor.isActive(action.active.name, action.active.attrs);
|
||||
}
|
||||
|
||||
function isMenuItemActive(item: ToolbarMenuItem, currentEditor?: Editor) {
|
||||
const targetEditor = currentEditor ?? getEditor();
|
||||
|
||||
if (!targetEditor || !item.isActive) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return item.isActive(targetEditor);
|
||||
}
|
||||
|
||||
function runAction(action: ToolbarAction) {
|
||||
const currentEditor = getEditor();
|
||||
|
||||
if (!currentEditor || !options.editable()) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (action.menu || action.palette) {
|
||||
return;
|
||||
}
|
||||
|
||||
action.action(currentEditor);
|
||||
}
|
||||
|
||||
function runMenuItem(item: ToolbarMenuItem) {
|
||||
const currentEditor = getEditor();
|
||||
|
||||
if (!currentEditor || !options.editable()) {
|
||||
return;
|
||||
}
|
||||
|
||||
item.action(currentEditor);
|
||||
}
|
||||
|
||||
function applyPaletteColor(action: ToolbarAction, color: string) {
|
||||
const currentEditor = getEditor();
|
||||
|
||||
if (!currentEditor || !action.palette) {
|
||||
return;
|
||||
}
|
||||
|
||||
action.palette.apply(currentEditor, color);
|
||||
}
|
||||
|
||||
function clearPaletteColor(action: ToolbarAction) {
|
||||
const currentEditor = getEditor();
|
||||
|
||||
if (!currentEditor || !action.palette?.clear) {
|
||||
return;
|
||||
}
|
||||
|
||||
action.palette.clear(currentEditor);
|
||||
}
|
||||
|
||||
function getToolbarButtonClass(action: ToolbarAction) {
|
||||
return cn(
|
||||
'text-muted-foreground relative rounded-[10px] border border-transparent bg-transparent shadow-none',
|
||||
'transition-[transform,color,background-color,border-color,box-shadow] duration-200 ease-out',
|
||||
'enabled:hover:border-border enabled:hover:-translate-y-px disabled:opacity-45',
|
||||
'enabled:hover:bg-accent enabled:hover:text-foreground',
|
||||
isActionActive(action) &&
|
||||
'bg-accent border-primary/30 shadow-primary text-primary',
|
||||
);
|
||||
}
|
||||
|
||||
function getPaletteSwatchClass(action: ToolbarAction, color: string) {
|
||||
return cn(
|
||||
'border-border inline-flex size-8 items-center justify-center rounded-full border',
|
||||
'shadow-accent',
|
||||
'transition-[transform,box-shadow,border-color] duration-200 ease-out',
|
||||
'hover:-translate-y-px hover:scale-[1.04]',
|
||||
getPaletteCurrentColor(action) === color &&
|
||||
'border-primary shadow-primary',
|
||||
);
|
||||
}
|
||||
|
||||
function getMenuItemClass(item: ToolbarMenuItem) {
|
||||
return cn(
|
||||
'flex items-center gap-2 rounded-lg p-2 text-left text-sm transition-colors',
|
||||
'disabled:cursor-not-allowed disabled:opacity-45',
|
||||
isMenuItemActive(item)
|
||||
? 'bg-accent text-foreground'
|
||||
: 'hover:bg-accent hover:text-foreground text-muted-foreground',
|
||||
);
|
||||
}
|
||||
|
||||
return {
|
||||
applyPaletteColor,
|
||||
canRunAction,
|
||||
canRunMenuItem,
|
||||
clearPaletteColor,
|
||||
getActionIndicatorColor,
|
||||
getMenuItemClass,
|
||||
getPaletteCurrentColor,
|
||||
getPaletteSwatchClass,
|
||||
getToolbarButtonClass,
|
||||
isActionActive,
|
||||
isMenuItemActive,
|
||||
runAction,
|
||||
runMenuItem,
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user