first commit

This commit is contained in:
zhuzhengjian
2025-11-21 10:05:54 +08:00
commit a46a07cb54
21 changed files with 2989 additions and 0 deletions

24
.gitignore vendored Normal file
View File

@@ -0,0 +1,24 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*
node_modules
dist
dist-ssr
*.local
# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?

3
.vscode/extensions.json vendored Normal file
View File

@@ -0,0 +1,3 @@
{
"recommendations": ["Vue.volar"]
}

5
README.md Normal file
View File

@@ -0,0 +1,5 @@
# Vue 3 + TypeScript + Vite
This template should help get you started developing with Vue 3 and TypeScript in Vite. The template uses Vue 3 `<script setup>` SFCs, check out the [script setup docs](https://v3.vuejs.org/api/sfc-script-setup.html#sfc-script-setup) to learn more.
Learn more about the recommended Project Setup and IDE Support in the [Vue Docs TypeScript Guide](https://vuejs.org/guide/typescript/overview.html#project-setup).

2
check_exports.ts Normal file
View File

@@ -0,0 +1,2 @@
import * as TiptapVue from '@tiptap/vue-3';
console.log(Object.keys(TiptapVue));

13
index.html Normal file
View File

@@ -0,0 +1,13 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>notion-editor</title>
</head>
<body>
<div id="app"></div>
<script type="module" src="/src/main.ts"></script>
</body>
</html>

42
package.json Normal file
View File

@@ -0,0 +1,42 @@
{
"name": "notion-editor",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "vue-tsc -b && vite build",
"preview": "vite preview"
},
"dependencies": {
"@floating-ui/dom": "^1.7.4",
"@shikijs/monaco": "^3.15.0",
"@tiptap/core": "^3.11.0",
"@tiptap/extension-bubble-menu": "^3.11.0",
"@tiptap/extension-code-block-lowlight": "^3.11.0",
"@tiptap/extension-floating-menu": "^3.11.0",
"@tiptap/extension-placeholder": "^3.11.0",
"@tiptap/pm": "^3.11.0",
"@tiptap/starter-kit": "^3.11.0",
"@tiptap/suggestion": "^3.11.0",
"@tiptap/vue-3": "^3.11.0",
"lowlight": "^3.3.0",
"lucide-vue-next": "^0.554.0",
"monaco-editor": "^0.55.1",
"shiki": "^3.15.0",
"vue": "^3.5.24"
},
"devDependencies": {
"@types/node": "^24.10.1",
"@vitejs/plugin-vue": "^6.0.1",
"@vue/tsconfig": "^0.8.1",
"typescript": "~5.9.3",
"vite": "npm:rolldown-vite@7.2.5",
"vue-tsc": "^3.1.4"
},
"pnpm": {
"overrides": {
"vite": "npm:rolldown-vite@7.2.5"
}
}
}

1828
pnpm-lock.yaml generated Normal file

File diff suppressed because it is too large Load Diff

1
public/vite.svg Normal file
View File

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="31.88" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 257"><defs><linearGradient id="IconifyId1813088fe1fbc01fb466" x1="-.828%" x2="57.636%" y1="7.652%" y2="78.411%"><stop offset="0%" stop-color="#41D1FF"></stop><stop offset="100%" stop-color="#BD34FE"></stop></linearGradient><linearGradient id="IconifyId1813088fe1fbc01fb467" x1="43.376%" x2="50.316%" y1="2.242%" y2="89.03%"><stop offset="0%" stop-color="#FFEA83"></stop><stop offset="8.333%" stop-color="#FFDD35"></stop><stop offset="100%" stop-color="#FFA800"></stop></linearGradient></defs><path fill="url(#IconifyId1813088fe1fbc01fb466)" d="M255.153 37.938L134.897 252.976c-2.483 4.44-8.862 4.466-11.382.048L.875 37.958c-2.746-4.814 1.371-10.646 6.827-9.67l120.385 21.517a6.537 6.537 0 0 0 2.322-.004l117.867-21.483c5.438-.991 9.574 4.796 6.877 9.62Z"></path><path fill="url(#IconifyId1813088fe1fbc01fb467)" d="M185.432.063L96.44 17.501a3.268 3.268 0 0 0-2.634 3.014l-5.474 92.456a3.268 3.268 0 0 0 3.997 3.378l24.777-5.718c2.318-.535 4.413 1.507 3.936 3.838l-7.361 36.047c-.495 2.426 1.782 4.5 4.151 3.78l15.304-4.649c2.372-.72 4.652 1.36 4.15 3.788l-11.698 56.621c-.732 3.542 3.979 5.473 5.943 2.437l1.313-2.028l72.516-144.72c1.215-2.423-.88-5.186-3.54-4.672l-25.505 4.922c-2.396.462-4.435-1.77-3.759-4.114l16.646-57.705c.677-2.35-1.37-4.583-3.769-4.113Z"></path></svg>

After

Width:  |  Height:  |  Size: 1.5 KiB

16
src/App.vue Normal file
View File

@@ -0,0 +1,16 @@
<script setup lang="ts">
import Editor from './components/Editor.vue'
</script>
<template>
<Editor />
</template>
<style>
body {
margin: 0;
font-family: 'Inter', sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
</style>

1
src/assets/vue.svg Normal file
View File

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="37.07" height="36" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 198"><path fill="#41B883" d="M204.8 0H256L128 220.8L0 0h97.92L128 51.2L157.44 0h47.36Z"></path><path fill="#41B883" d="m0 0l128 220.8L256 0h-51.2L128 132.48L50.56 0H0Z"></path><path fill="#35495E" d="M50.56 0L128 133.12L204.8 0h-47.36L128 51.2L97.92 0H50.56Z"></path></svg>

After

Width:  |  Height:  |  Size: 496 B

View File

@@ -0,0 +1,306 @@
<template>
<node-view-wrapper class="code-block-wrapper" @dblclick="onContainerClick">
<div class="code-block-header">
<select v-model="selectedLanguage" class="language-select" contenteditable="false">
<option value="null">auto</option>
<option disabled></option>
<option v-for="(language, index) in languages" :key="index" :value="language">
{{ language }}
</option>
</select>
<div class="actions">
<button @click="copyCode" class="action-btn" title="Copy code">
<CopyIcon class="icon" />
</button>
</div>
</div>
<div class="code-block-content" v-if="!isEditable">
<div v-html="highlightedCode" class="shiki-container"></div>
</div>
<div class="monaco-container" ref="monacoContainer" v-show="isEditable"></div>
</node-view-wrapper>
</template>
<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount, watch, computed } from 'vue'
import { NodeViewWrapper, nodeViewProps } from '@tiptap/vue-3'
import * as monaco from 'monaco-editor'
import { createHighlighter } from 'shiki'
import { Copy as CopyIcon } from 'lucide-vue-next'
import { shikiToMonaco } from '@shikijs/monaco'
const props = defineProps(nodeViewProps)
const languages = [
'javascript',
'typescript',
'html',
'css',
'python',
'json',
'markdown',
'vue',
'java',
'c',
'cpp',
'go',
'rust',
'sql',
'shell',
]
const selectedLanguage = computed({
get: () => props.node.attrs.language,
set: (language: string) => props.updateAttributes({ language }),
})
const monacoContainer = ref<HTMLElement | null>(null)
let editor: monaco.editor.IStandaloneCodeEditor | null = null
const isEditable = ref(false)
const highlightedCode = ref('')
// Shiki highlighter instance
let highlighter: any = null
const initShiki = async () => {
highlighter = await createHighlighter({
themes: ['vitesse-dark'],
langs: languages,
})
updateHighlightedCode()
}
const updateHighlightedCode = async () => {
if (!highlighter) return
const code = props.node.content.firstChild?.text || ''
const lang = selectedLanguage.value || 'text'
try {
highlightedCode.value = highlighter.codeToHtml(code, {
lang,
theme: 'vitesse-dark'
})
} catch (e) {
// Fallback if language not found
highlightedCode.value = highlighter.codeToHtml(code, {
lang: 'text',
theme: 'vitesse-dark'
})
}
}
const initMonaco = async () => {
if (!monacoContainer.value) return
// Create the highlighter, it can be reused
const highlighter = await createHighlighter({
themes: [
'vitesse-dark',
'vitesse-light',
],
langs: [
'javascript',
'typescript',
'vue'
],
})
// Register the languageIds first. Only registered languages will be highlighted.
monaco.languages.register({ id: 'vue' })
monaco.languages.register({ id: 'typescript' })
monaco.languages.register({ id: 'javascript' })
// Register the themes from Shiki, and provide syntax highlighting for Monaco.
shikiToMonaco(highlighter, monaco)
editor = monaco.editor.create(monacoContainer.value, {
value: props.node.content.firstChild?.text || '',
language: selectedLanguage.value || 'plaintext',
theme: 'vitesse-dark',
minimap: { enabled: false },
scrollBeyondLastLine: false,
automaticLayout: true,
fontSize: 14,
fontFamily: 'JetBrains Mono, monospace',
lineNumbers: 'off',
padding: { top: 16, bottom: 16 },
})
editor.onDidChangeModelContent(() => {
const value = editor?.getValue()
if (value !== undefined) {
// Update Tiptap node content
// We need to be careful not to trigger a re-render loop
// This is a simplified approach; for robust sync, might need more logic
// But since we switch modes, it might be okay.
// Actually, Tiptap expects us to update the node.
// But since we are in a NodeView, we can't easily update the content directly without replacing the node?
// Wait, for code blocks, usually we update the text content.
// Let's try to update the node content using a transaction if possible, or just emit an update.
// For now, let's just keep local state and update on blur or mode switch?
// Better: Update on change.
// NOTE: Updating the node content from within the node view can be tricky.
// A common pattern is to use `props.updateAttributes` for attributes,
// but for content, we might need to use `props.editor.commands.command(...)`.
// However, since we are "taking over" the rendering, we can just update the node when we are done?
// Or we can try to keep them in sync.
// Let's try to just update the node content when we exit edit mode.
}
})
// Sync content changes from Tiptap to Monaco (if changed externally)
// watch(() => props.node.content, ...)
}
// Toggle edit mode
// We can toggle edit mode on click
const toggleEditMode = () => {
isEditable.value = !isEditable.value
if (isEditable.value) {
setTimeout(() => {
if (!editor) {
initMonaco()
} else {
editor.setValue(props.node.content.firstChild?.text || '')
editor.layout()
}
editor?.focus()
}, 0)
} else {
// Save content back to Tiptap
if (editor) {
const content = editor.getValue()
const pos = props.getPos()
if (typeof pos === 'number') {
props.editor.view.dispatch(
props.editor.view.state.tr.insertText(content, pos + 1, pos + 1 + props.node.content.size)
)
}
}
updateHighlightedCode()
}
}
const onContainerClick = () => {
if (!isEditable.value) {
toggleEditMode()
}
}
// Handle click outside to exit edit mode
// This is a bit complex inside a NodeView.
// A simpler way is to use the `blur` event of Monaco editor.
// But Monaco's blur might trigger when clicking the language select.
// Let's try to use a "Done" button or just blur.
onMounted(() => {
initShiki()
// Watch for language changes to update syntax highlighting and Monaco model language
watch(selectedLanguage, (newLang) => {
if (editor) {
monaco.editor.setModelLanguage(editor.getModel()!, newLang || 'plaintext')
}
updateHighlightedCode()
})
})
onBeforeUnmount(() => {
if (editor) {
editor.dispose()
}
})
const copyCode = () => {
const code = props.node.content.firstChild?.text || ''
navigator.clipboard.writeText(code)
}
// Expose methods if needed
defineExpose({
toggleEditMode
})
</script>
<style scoped>
.code-block-wrapper {
background-color: #0d1117;
border-radius: 0.5rem;
margin: 1rem 0;
overflow: hidden;
position: relative;
}
.code-block-header {
display: flex;
justify-content: space-between;
align-items: center;
padding: 0.5rem 1rem;
background-color: #161b22;
border-bottom: 1px solid #30363d;
}
.language-select {
background: transparent;
color: #c9d1d9;
border: none;
font-size: 0.875rem;
cursor: pointer;
outline: none;
}
.actions {
display: flex;
gap: 0.5rem;
}
.action-btn {
background: transparent;
border: none;
color: #8b949e;
cursor: pointer;
padding: 0.25rem;
border-radius: 0.25rem;
display: flex;
align-items: center;
justify-content: center;
}
.action-btn:hover {
background-color: #30363d;
color: #c9d1d9;
}
.icon {
width: 1rem;
height: 1rem;
}
.code-block-content {
padding: 1rem;
overflow-x: auto;
font-family: 'JetBrains Mono', monospace;
font-size: 0.875rem;
line-height: 1.5;
cursor: text;
}
.monaco-container {
height: 200px; /* Or auto-grow? Monaco needs explicit height usually. */
/* Let's start with fixed height or resizeable */
min-height: 100px;
}
/* Shiki styles */
.shiki-container {
margin: 0;
}
:deep(.shiki) {
background-color: transparent !important;
margin: 0;
}
</style>

391
src/components/Editor.vue Normal file
View File

@@ -0,0 +1,391 @@
<template>
<div class="editor-container" v-if="editor">
<bubble-menu
class="bubble-menu"
:tippy-options="{ duration: 100 }"
:editor="editor"
>
<button @click="editor.chain().focus().toggleBold().run()" :class="{ 'is-active': editor.isActive('bold') }">
<BoldIcon class="icon" />
</button>
<button @click="editor.chain().focus().toggleItalic().run()" :class="{ 'is-active': editor.isActive('italic') }">
<ItalicIcon class="icon" />
</button>
<button @click="editor.chain().focus().toggleStrike().run()" :class="{ 'is-active': editor.isActive('strike') }">
<StrikethroughIcon class="icon" />
</button>
<button @click="editor.chain().focus().toggleCode().run()" :class="{ 'is-active': editor.isActive('code') }">
<CodeIcon class="icon" />
</button>
</bubble-menu>
<floating-menu
class="floating-menu"
:tippy-options="{ duration: 100 }"
:editor="editor"
>
<button @click="editor.chain().focus().toggleHeading({ level: 1 }).run()" :class="{ 'is-active': editor.isActive('heading', { level: 1 }) }">
H1
</button>
<button @click="editor.chain().focus().toggleHeading({ level: 2 }).run()" :class="{ 'is-active': editor.isActive('heading', { level: 2 }) }">
H2
</button>
<button @click="editor.chain().focus().toggleBulletList().run()" :class="{ 'is-active': editor.isActive('bulletList') }">
List
</button>
</floating-menu>
<editor-content :editor="editor" class="editor-content" />
</div>
</template>
<script setup lang="ts">
import { useEditor, EditorContent, VueRenderer, VueNodeViewRenderer } from '@tiptap/vue-3'
import { BubbleMenu, FloatingMenu } from '@tiptap/vue-3/menus'
import StarterKit from '@tiptap/starter-kit'
import Placeholder from '@tiptap/extension-placeholder'
import CodeBlockLowlight from '@tiptap/extension-code-block-lowlight'
import SlashCommand from '../extensions/SlashCommand'
import { computePosition, flip, shift, offset, autoUpdate } from '@floating-ui/dom'
import {
Bold as BoldIcon,
Italic as ItalicIcon,
Strikethrough as StrikethroughIcon,
Code as CodeIcon,
Type as TextIcon,
Heading1,
Heading2,
Heading3,
List,
ListOrdered,
Code2,
Quote
} from 'lucide-vue-next'
import SlashCommandList from './SlashCommandList.vue'
import CodeBlockComponent from './CodeBlockComponent.vue'
import { all, createLowlight } from 'lowlight'
const lowlight = createLowlight(all)
const getSuggestionItems = ({ query }: { query: string }) => {
return [
{
title: 'Text',
description: 'Just start writing with plain text.',
icon: TextIcon,
command: ({ editor, range }: any) => {
editor.chain().focus().deleteRange(range).setParagraph().run()
},
},
{
title: 'Heading 1',
description: 'Big section heading.',
icon: Heading1,
command: ({ editor, range }: any) => {
editor.chain().focus().deleteRange(range).setNode('heading', { level: 1 }).run()
},
},
{
title: 'Heading 2',
description: 'Medium section heading.',
icon: Heading2,
command: ({ editor, range }: any) => {
editor.chain().focus().deleteRange(range).setNode('heading', { level: 2 }).run()
},
},
{
title: 'Heading 3',
description: 'Small section heading.',
icon: Heading3,
command: ({ editor, range }: any) => {
editor.chain().focus().deleteRange(range).setNode('heading', { level: 3 }).run()
},
},
{
title: 'Bullet List',
description: 'Create a simple bullet list.',
icon: List,
command: ({ editor, range }: any) => {
editor.chain().focus().deleteRange(range).toggleBulletList().run()
},
},
{
title: 'Ordered List',
description: 'Create a list with numbering.',
icon: ListOrdered,
command: ({ editor, range }: any) => {
editor.chain().focus().deleteRange(range).toggleOrderedList().run()
},
},
{
title: 'Code Block',
description: 'Capture a code snippet.',
icon: Code2,
command: ({ editor, range }: any) => {
editor.chain().focus().deleteRange(range).toggleCodeBlock().run()
},
},
{
title: 'Blockquote',
description: 'Capture a quote.',
icon: Quote,
command: ({ editor, range }: any) => {
editor.chain().focus().deleteRange(range).toggleBlockquote().run()
},
},
].filter(item => item.title.toLowerCase().startsWith(query.toLowerCase()))
}
const renderSuggestion = () => {
let component: any
let popup: HTMLElement | null = null
let cleanup: (() => void) | null = null
return {
onStart: (props: any) => {
component = new VueRenderer(SlashCommandList, {
props,
editor: props.editor,
})
if (!props.clientRect) {
return
}
popup = component.element as HTMLElement
document.body.appendChild(popup)
if (!popup) {
return
}
// Initial positioning
const virtualEl = {
getBoundingClientRect: props.clientRect,
}
cleanup = autoUpdate(virtualEl, popup, () => {
computePosition(virtualEl, popup!, {
placement: 'bottom-start',
middleware: [offset(10), flip(), shift()],
}).then(({ x, y }) => {
Object.assign(popup!.style, {
left: `${x}px`,
top: `${y}px`,
position: 'absolute',
zIndex: '9999',
})
})
})
},
onUpdate(props: any) {
component.updateProps(props)
if (!props.clientRect) {
return
}
// Re-run positioning if needed (autoUpdate handles most cases)
},
onKeyDown(props: any) {
if (props.event.key === 'Escape') {
if (cleanup) cleanup()
if (popup && popup.parentNode) popup.parentNode.removeChild(popup)
return true
}
return component.ref?.onKeyDown(props)
},
onExit() {
if (cleanup) cleanup()
if (popup && popup.parentNode) popup.parentNode.removeChild(popup)
component.destroy()
},
}
}
const editor = useEditor({
extensions: [
StarterKit.configure({
codeBlock: false, // Disable default code block to use custom one
}),
CodeBlockLowlight.extend({
addNodeView() {
return VueNodeViewRenderer(CodeBlockComponent)
},
}).configure({ lowlight }),
Placeholder.configure({
placeholder: 'Type / for commands...',
}),
SlashCommand.configure({
suggestion: {
items: getSuggestionItems,
render: renderSuggestion,
},
}),
],
content: `
<h2>
Hi there,
</h2>
<p>
this is a <em>basic</em> example of <strong>tiptap</strong>. Sure, there are all kind of basic text styles youd probably expect from a text editor. But wait until you see the lists:
</p>
<ul>
<li>
Thats a bullet list with one …
</li>
<li>
… or two list items.
</li>
</ul>
<p>
Isnt that great? And all of that is editable. But wait, theres more. Lets try a code block:
</p>
<pre><code class="language-css">body {
display: none;
}</code></pre>
<p>
I know, I know, this is impressive. Its only the tip of the iceberg though. Give it a try and click a little bit around. Dont forget to check the other examples too.
</p>
<blockquote>
Wow, that's amazing. Good work, boy! 👏
<br />
— Mom
</blockquote>
`,
})
</script>
<style>
/* Basic Editor Styles */
.editor-container {
max-width: 800px;
margin: 4rem auto;
padding: 0 1rem;
}
.ProseMirror {
outline: none;
}
.ProseMirror p.is-editor-empty:first-child::before {
color: #adb5bd;
content: attr(data-placeholder);
float: left;
height: 0;
pointer-events: none;
}
/* Typography */
h1 {
font-size: 2.5rem;
font-weight: 700;
margin-top: 2.5rem;
margin-bottom: 1rem;
line-height: 1.2;
}
h2 {
font-size: 1.75rem;
font-weight: 600;
margin-top: 2rem;
margin-bottom: 0.75rem;
line-height: 1.3;
}
h3 {
font-size: 1.25rem;
font-weight: 600;
margin-top: 1.5rem;
margin-bottom: 0.5rem;
line-height: 1.4;
}
p {
margin-bottom: 1rem;
line-height: 1.6;
color: #334155;
}
ul, ol {
padding-left: 1.5rem;
margin-bottom: 1rem;
}
li {
margin-bottom: 0.25rem;
}
blockquote {
border-left: 3px solid #e2e8f0;
padding-left: 1rem;
margin-left: 0;
margin-bottom: 1rem;
font-style: italic;
color: #64748b;
}
pre {
background: #0d0d0d;
color: #fff;
font-family: 'JetBrainsMono', monospace;
padding: 0.75rem 1rem;
border-radius: 0.5rem;
margin-bottom: 1rem;
}
code {
color: #616161;
background: none;
font-size: 0.8em;
}
pre code {
color: inherit;
padding: 0;
background: none;
font-size: 0.8rem;
}
/* Bubble Menu & Floating Menu */
.bubble-menu,
.floating-menu {
display: flex;
background-color: #fff;
padding: 0.2rem;
border-radius: 0.5rem;
box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
border: 1px solid #e2e8f0;
}
.bubble-menu button,
.floating-menu button {
border: none;
background: none;
color: #64748b;
font-size: 0.875rem;
font-weight: 500;
padding: 0.25rem 0.5rem;
cursor: pointer;
border-radius: 0.25rem;
display: flex;
align-items: center;
}
.bubble-menu button:hover,
.floating-menu button:hover,
.bubble-menu button.is-active,
.floating-menu button.is-active {
color: #000;
background-color: #f1f5f9;
}
.bubble-menu .icon {
width: 1rem;
height: 1rem;
}
</style>

View File

@@ -0,0 +1,41 @@
<script setup lang="ts">
import { ref } from 'vue'
defineProps<{ msg: string }>()
const count = ref(0)
</script>
<template>
<h1>{{ msg }}</h1>
<div class="card">
<button type="button" @click="count++">count is {{ count }}</button>
<p>
Edit
<code>components/HelloWorld.vue</code> to test HMR
</p>
</div>
<p>
Check out
<a href="https://vuejs.org/guide/quick-start.html#local" target="_blank"
>create-vue</a
>, the official Vue + Vite starter
</p>
<p>
Learn more about IDE Support for Vue in the
<a
href="https://vuejs.org/guide/scaling-up/tooling.html#ide-support"
target="_blank"
>Vue Docs Scaling up Guide</a
>.
</p>
<p class="read-the-docs">Click on the Vite and Vue logos to learn more</p>
</template>
<style scoped>
.read-the-docs {
color: #888;
}
</style>

View File

@@ -0,0 +1,151 @@
<template>
<div class="slash-command-list">
<template v-if="items.length">
<button
v-for="(item, index) in items"
:key="index"
class="slash-command-item"
:class="{ 'is-selected': index === selectedIndex }"
@click="selectItem(index)"
@mouseenter="selectedIndex = index"
>
<component :is="item.icon" class="icon" />
<div class="label">
<div class="title">{{ item.title }}</div>
<div class="description" v-if="item.description">{{ item.description }}</div>
</div>
</button>
</template>
<div v-else class="slash-command-empty">
No result
</div>
</div>
</template>
<script setup lang="ts">
import { ref, watch } from 'vue'
import type { Component } from 'vue'
interface CommandItem {
title: string
description?: string
icon: Component
command: (editor: any) => void
}
const props = defineProps<{
items: CommandItem[]
command: (item: CommandItem) => void
}>()
const selectedIndex = ref(0)
watch(
() => props.items,
() => {
selectedIndex.value = 0
},
)
const onKeyDown = ({ event }: { event: KeyboardEvent }) => {
if (event.key === 'ArrowUp') {
upHandler()
return true
}
if (event.key === 'ArrowDown') {
downHandler()
return true
}
if (event.key === 'Enter') {
enterHandler()
return true
}
return false
}
const upHandler = () => {
selectedIndex.value = (selectedIndex.value + props.items.length - 1) % props.items.length
}
const downHandler = () => {
selectedIndex.value = (selectedIndex.value + 1) % props.items.length
}
const enterHandler = () => {
selectItem(selectedIndex.value)
}
const selectItem = (index: number) => {
const item = props.items[index]
if (item) {
props.command(item)
}
}
defineExpose({
onKeyDown,
})
</script>
<style scoped>
.slash-command-list {
background: #fff;
border: 1px solid #e2e8f0;
border-radius: 0.5rem;
box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
padding: 0.25rem;
width: 300px;
max-height: 300px;
overflow-y: auto;
}
.slash-command-item {
display: flex;
align-items: center;
width: 100%;
padding: 0.5rem;
border: none;
background: transparent;
border-radius: 0.25rem;
cursor: pointer;
text-align: left;
color: #1e293b;
}
.slash-command-item:hover,
.slash-command-item.is-selected {
background-color: #f1f5f9;
}
.icon {
width: 1.25rem;
height: 1.25rem;
margin-right: 0.75rem;
color: #64748b;
}
.label {
flex: 1;
}
.title {
font-size: 0.875rem;
font-weight: 500;
}
.description {
font-size: 0.75rem;
color: #64748b;
}
.slash-command-empty {
padding: 0.5rem;
font-size: 0.875rem;
color: #64748b;
text-align: center;
}
</style>

View File

@@ -0,0 +1,26 @@
import { Extension } from '@tiptap/core'
import Suggestion from '@tiptap/suggestion'
export default Extension.create({
name: 'slash-command',
addOptions() {
return {
suggestion: {
char: '/',
command: ({ editor, range, props }: any) => {
props.command({ editor, range })
},
},
}
},
addProseMirrorPlugins() {
return [
Suggestion({
editor: this.editor,
...this.options.suggestion,
}),
]
},
})

4
src/main.ts Normal file
View File

@@ -0,0 +1,4 @@
import { createApp } from 'vue'
import App from './App.vue'
createApp(App).mount('#app')

79
src/style.css Normal file
View File

@@ -0,0 +1,79 @@
:root {
font-family: system-ui, Avenir, Helvetica, Arial, sans-serif;
line-height: 1.5;
font-weight: 400;
color-scheme: light dark;
color: rgba(255, 255, 255, 0.87);
background-color: #242424;
font-synthesis: none;
text-rendering: optimizeLegibility;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
a {
font-weight: 500;
color: #646cff;
text-decoration: inherit;
}
a:hover {
color: #535bf2;
}
body {
margin: 0;
display: flex;
place-items: center;
min-width: 320px;
min-height: 100vh;
}
h1 {
font-size: 3.2em;
line-height: 1.1;
}
button {
border-radius: 8px;
border: 1px solid transparent;
padding: 0.6em 1.2em;
font-size: 1em;
font-weight: 500;
font-family: inherit;
background-color: #1a1a1a;
cursor: pointer;
transition: border-color 0.25s;
}
button:hover {
border-color: #646cff;
}
button:focus,
button:focus-visible {
outline: 4px auto -webkit-focus-ring-color;
}
.card {
padding: 2em;
}
#app {
max-width: 1280px;
margin: 0 auto;
padding: 2rem;
text-align: center;
}
@media (prefers-color-scheme: light) {
:root {
color: #213547;
background-color: #ffffff;
}
a:hover {
color: #747bff;
}
button {
background-color: #f9f9f9;
}
}

16
tsconfig.app.json Normal file
View File

@@ -0,0 +1,16 @@
{
"extends": "@vue/tsconfig/tsconfig.dom.json",
"compilerOptions": {
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo",
"types": ["vite/client"],
/* Linting */
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"erasableSyntaxOnly": true,
"noFallthroughCasesInSwitch": true,
"noUncheckedSideEffectImports": true
},
"include": ["src/**/*.ts", "src/**/*.tsx", "src/**/*.vue"]
}

7
tsconfig.json Normal file
View File

@@ -0,0 +1,7 @@
{
"files": [],
"references": [
{ "path": "./tsconfig.app.json" },
{ "path": "./tsconfig.node.json" }
]
}

26
tsconfig.node.json Normal file
View File

@@ -0,0 +1,26 @@
{
"compilerOptions": {
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo",
"target": "ES2023",
"lib": ["ES2023"],
"module": "ESNext",
"types": ["node"],
"skipLibCheck": true,
/* Bundler mode */
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"verbatimModuleSyntax": true,
"moduleDetection": "force",
"noEmit": true,
/* Linting */
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"erasableSyntaxOnly": true,
"noFallthroughCasesInSwitch": true,
"noUncheckedSideEffectImports": true
},
"include": ["vite.config.ts"]
}

7
vite.config.ts Normal file
View File

@@ -0,0 +1,7 @@
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
// https://vite.dev/config/
export default defineConfig({
plugins: [vue()],
})