feat!: v0.2 overhaul — reactive toolbar, AI document agent, 94% smaller bundle

编辑器交互(丝滑)
- 工具栏状态跟随光标:useReactiveEditor 组合式函数(shallowRef + triggerRef,
  绕过 Vue computed 值相等截断),16 个工具栏组件接入
- 输入防抖:分页计算 rAF 合帧 + 200ms 防抖,@update 事件防抖派发,
  卸载/重建前 flush 不丢最后输入;共享 debounce 工具(src/utils/debounce.ts)
- v-model 支持(HTML/JSON 双模式):监听器检测(ref<string>() 初值安全)、
  回环短路缓存、协作模式守卫
- 修复:标题下拉失焦、字数统计光标移动重算、LinkBubbleMenu 深度遍历、
  事件监听器泄漏、页数按内容/字体/容器尺寸自动重算

暗色模式与样式
- 修复 9 个组件暗色选择器(.dark 类 → data-theme 属性,44 处);
  setTheme 同步挂 .dark 类兜底
- 补齐 ::selection/caret-color、:focus-visible、prefers-reduced-motion、
  color-scheme、暗色滚动条、下拉/浮层过渡动画
- 落地页 blur 滤镜动画改为 transform-only(原会卡死合成器)

包体积(gzip 1.4MB → ~88KB,-94%)
- 修复 Vite 6 lib+ES 跳过 terser(自定义 libTerser 插件)
- KaTeX/mammoth/docx/file-saver 改为 external + 动态导入
- version 档位(minimal/basic/advanced/premium)真正裁剪扩展;
  组件默认 premium 保持 0.1.x 行为兼容
- 依赖重分类:antd 系转 peer、协作库转可选 peer;删除死依赖与
  278 个误提交的 .d.ts 构建产物;demo 构建目录分离

AI 文档助手(用文字描述编写和修改文档)
- documentTools:7 个结构化编辑工具(块索引 + 文本查找寻址、
  结构边界哨兵防跨单元格假匹配、多匹配消歧、replaceAll 单事务)
- runDocumentAgent:OpenAI function-calling 循环,6 家 provider 通用,
  超时兜底、abort、编辑器销毁保护、历史概要去重
- AiChatPanel:右下角聊天面板,步骤实时展示、IME 安全回车、
  features.aiChat 可关;工具集与循环公开导出供自定义集成
- 修复 anthropic/ollama 默认端点(原 anthropic key 会被发往 openai.com)

DX 与文档
- README 重写对齐真实 API;AGENTS.md 更新;locale 浏览器语言自动检测;
  字体列表跨平台化;5 套主题 CSS 随包发布;demo 刷新保持状态;
  API key 安全警示;测试 2 → 57 个

BREAKING CHANGE: ant-design-vue/@ant-design/icons-vue 转为 peer 依赖;
协作功能需自装 yjs/y-websocket/@tiptap/extension-collaboration*;
数学公式需自行 import 'katex/dist/katex.min.css';@update 事件防抖 200ms;
version="basic"/"minimal" 现在真正裁剪扩展(表格/公式/AI 不加载)。
迁移指南见 README「Migrating to 0.2」。

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
benngaihkandClaude Fable 5 committed 2026-07-14 00:05:07 +08:00
1 parent 7c6f5be3eb
commit c915f0d506
357 files changed
+3347 -5784

No files matched your search

+11
View File
@@ -0,0 +1,11 @@
{
"version": "0.0.1",
"configurations": [
{
"name": "dev",
"runtimeExecutable": "pnpm",
"runtimeArgs": ["dev"],
"port": 5173
}
]
}
+13 -6
View File
@@ -1,7 +1,12 @@
# Tiptap AI Configuration
# Copy this file to .env and fill in your values
#
# SECURITY NOTE: VITE_* variables are inlined into the client bundle at build
# time — any key you put here ships to every browser. Only use keys you own
# with a spending limit, or point VITE_AI_BASE_URL at your own backend proxy
# that holds the real key server-side.
# AI Provider: openai | aliyun | ollama | deepseek | anthropic | custom
# AI Provider: openai | deepseek | anthropic | aliyun | ollama | custom
VITE_AI_PROVIDER=openai
# API Key (required for most providers)
@@ -13,16 +18,18 @@ VITE_AI_API_KEY=your-api-key-here
# Base URL (optional, uses default for each provider)
# OpenAI: https://api.openai.com/v1
# DeepSeek: https://api.deepseek.com
# Anthropic: https://api.anthropic.com/v1
# Aliyun: https://dashscope.aliyuncs.com/compatible-mode/v1
# Ollama: http://localhost:11434/api
# DeepSeek: https://api.deepseek.com/v1
# Ollama: http://localhost:11434/v1
# VITE_AI_BASE_URL=
# Model (optional, uses default for each provider)
# OpenAI: gpt-4o, gpt-3.5-turbo
# Aliyun: qwen-turbo, qwen-plus, qwen-max
# Ollama: llama3, mistral, codellama
# OpenAI: gpt-4o, gpt-4o-mini
# DeepSeek: deepseek-chat, deepseek-coder
# Anthropic: claude-3-5-sonnet-20241022
# Aliyun: qwen-turbo, qwen-plus, qwen-max
# Ollama: llama3.2, mistral, codellama
# VITE_AI_MODEL=
# Temperature (optional, default: 0.7)
+5
View File
@@ -5,9 +5,14 @@ node_modules/
# Build output
dist/
dist-demo/
dist-ssr/
*.local
# Generated type declarations (stale vue-tsc output; published types come from vite-plugin-dts)
src/**/*.d.ts
src/**/*.d.ts.map
# Environment variables
.env
.env.local
+284 -66
View File
@@ -31,6 +31,16 @@ Built on [Tiptap 3](https://tiptap.dev/) + [Vue 3](https://vuejs.org/) + [TypeSc
Tiptap UI Kit is a **fully open-source**, production-ready rich text editor UI kit that brings together the best of modern web technologies. It is the most feature-complete Tiptap + Vue 3 editor template available.
### ⚡ v0.2: 94% smaller bundle
The v0.2 release cut the shipped library from **2.4 MB JS + 1.5 MB CSS** down to **249 KB JS (63 KB gzip) + 96 KB CSS (15 KB gzip)** — roughly **78 KB total gzipped, a 94% reduction**. How:
- **Lazy loading** — KaTeX (math), mammoth / docx / file-saver (Word import/export) are only downloaded when the feature is first used
- **Tiered extension loading** — the default `version="basic"` loads only lightweight extensions; heavy ones (tables, math, AI) load with `version="premium"`
- **Externalized peers** — Ant Design Vue and the collaboration stack (Yjs) are peer dependencies instead of being bundled
See [Migrating to 0.2](#-migrating-to-02) if you are upgrading.
### Compared to alternatives
| Feature | Tiptap UI Kit | Raw Tiptap | Other Vue Editors |
@@ -47,9 +57,10 @@ Tiptap UI Kit is a **fully open-source**, production-ready rich text editor UI k
### Key highlights
- 🎨 **5 Beautiful Theme Presets** — Notion-like, Word-like (A4 pagination), GitHub, Typora, and Default
- ⚡ **Tiny Footprint** — ~78 KB gzipped total, heavy features lazy-loaded on demand
- 🤖 **AI-Powered Features** — Continue writing, polish text, translate, summarize, custom AI commands (OpenAI-compatible)
- 🌓 **Perfect Dark Mode** — Seamless light/dark theme switching across all themes
- 🛠️ **Modular Architecture** — Use only what you need, tree-shakeable
- 🛠️ **Modular Architecture** — Tiered versions and per-feature flags, load only what you need
- 🌍 **i18n Ready** — Chinese (Simplified/Traditional) and English support
- 💯 **100% Free & Open Source** — MIT licensed, free for commercial use
@@ -72,14 +83,14 @@ Perfect for building modern document editors, content management systems, note-t
- **Word Mode** - Professional A4 paper layout with automatic pagination
- **Modular Architecture** - Enable only the features you need, keep bundle size small
- **Modular Architecture** - Tiered editor versions (`minimal` / `basic` / `premium`) plus per-feature flags keep the bundle small
- **Internationalization** - Built-in support for:
- 简体中文 (Simplified Chinese)
- 繁體中文 (Traditional Chinese)
- English
- **Accessible** - WCAG compliant with full keyboard navigation
- **Keyboard Navigation** - Productivity-focused shortcuts for power users
### ✏️ Rich Text Editing
@@ -94,12 +105,13 @@ Perfect for building modern document editors, content management systems, note-t
- **Code Blocks** - Syntax highlighting powered by Lowlight
- **Typography** - Font family, size, line height control
- **Special Formats** - Subscript, superscript, format painter
- **Math Formulas** - KaTeX-powered inline and block math equations
- **Math Formulas** - KaTeX-powered inline and block math equations (KaTeX is lazy-loaded on first use)
### 🤖 AI-Powered Features
**Note:** AI features work with any OpenAI-compatible API. Configure your own API key in the AI Settings.
**Note:** AI features work with any OpenAI-compatible API. Users configure their own API key via the built-in AI Settings modal, or the host app supplies `VITE_AI_*` environment variables. See [AI Configuration](#ai-configuration).
- **⚡ AI Assistant (agent)** - Describe any edit in plain words — "add a 3x3 table at the end", "rewrite the second paragraph" — and the AI edits the document for you via tool calls
- **✨ Continue Writing** - AI completes your sentences and paragraphs intelligently
- **📝 Polish Text** - Improve grammar, clarity, and style automatically
- **🌐 Translation** - Translate to 14+ languages with one click
@@ -107,22 +119,22 @@ Perfect for building modern document editors, content management systems, note-t
- **🤖 Custom AI Commands** - Define your own AI transformations
**Supported AI Providers:**
- OpenAI (GPT-4, GPT-3.5)
- 阿里云通义千问 (Aliyun Qianwen)
- DeepSeek
- OpenAI (GPT-4o, GPT-4o-mini)
- DeepSeek (DeepSeek-V3, DeepSeek-R1)
- Anthropic (Claude, via OpenAI-compatible endpoint)
- 阿里云通义千问 (Aliyun Qwen)
- Ollama (local deployment)
- Any OpenAI-compatible API
- Custom — any OpenAI-compatible API
### 🚀 Advanced Features
- **Real-time Collaboration** - Multi-user editing powered by Yjs
- **Real-time Collaboration** - Multi-user editing powered by Yjs (optional peer dependencies)
- **Drag & Drop** - Intuitive content reordering with visual feedback
- **Search & Replace** - Find and replace text across the document
- **Keyboard Shortcuts** - Productivity-focused shortcuts for power users
- **Slash Commands** - Type `/` to insert blocks, Notion-style
- **Word Import/Export** - Import `.docx` via mammoth, export via docx (both lazy-loaded on click)
- **Responsive Design** - Optimized for mobile, tablet, and desktop
- **Preview Mode** - Read-only rendering for content review
- **Zoom Control** - Scale from 50% to 200%
- **Version History** - Track and restore previous versions
- **Format Painter** - Copy formatting across content
- **Paste Support** - Smart paste from Word, Excel, and web pages
@@ -130,8 +142,6 @@ Perfect for building modern document editors, content management systems, note-t
## 📦 Installation
### From npm
```bash
# Using npm
npm install tiptap-ui-kit
@@ -145,10 +155,22 @@ yarn add tiptap-ui-kit
### Peer Dependencies
Tiptap UI Kit requires the following peer dependencies:
Tiptap UI Kit requires the following peer dependencies (npm 7+ and pnpm install them automatically; otherwise install them yourself):
```bash
pnpm add @tiptap/core @tiptap/pm @tiptap/starter-kit @tiptap/vue-3 vue
pnpm add vue @tiptap/core @tiptap/pm @tiptap/starter-kit @tiptap/vue-3 ant-design-vue @ant-design/icons-vue
```
**Optional peers — only needed for real-time collaboration:**
```bash
pnpm add yjs y-websocket @tiptap/extension-collaboration @tiptap/extension-collaboration-cursor
```
**Optional CSS — only needed for math formulas:**
```ts
import 'katex/dist/katex.min.css'
```
---
@@ -161,8 +183,9 @@ pnpm add @tiptap/core @tiptap/pm @tiptap/starter-kit @tiptap/vue-3 vue
<template>
<TiptapProEditor
v-model="content"
:theme="theme"
:locale="locale"
version="premium"
locale="en-US"
:features="{ headerNav: true, footerNav: true }"
/>
</template>
@@ -171,44 +194,112 @@ import { ref } from 'vue'
import { TiptapProEditor } from 'tiptap-ui-kit'
import 'tiptap-ui-kit/style.css'
// v-model with a string -> the editor emits HTML strings
const content = ref('<p>Hello Tiptap UI Kit!</p>')
const theme = ref('notion') // default | word | notion | github | typora
const locale = ref('en-US') // en-US | zh-CN | zh-TW
</script>
```
### With AI Features
Notes:
- `import 'tiptap-ui-kit/style.css'` is required — it contains the editor styles **and all 5 theme presets**.
- `:features="{ headerNav: true, footerNav: true }"` enables the toolbar and the footer (zoom / word count). They are **off by default**.
- If you omit `locale`, the editor auto-detects the browser language (`zh` → `zh-CN`/`zh-TW`, otherwise `en-US`).
### v-model: HTML or JSON
The type of the value you bind decides the output format:
```vue
<script setup>
// HTML mode: bind a string, receive HTML strings
const html = ref('<p>Hello</p>')
// JSON mode: bind an object, receive ProseMirror JSON
const json = ref({ type: 'doc', content: [{ type: 'paragraph' }] })
</script>
<template>
<TiptapProEditor v-model="html" />
<!-- or -->
<TiptapProEditor v-model="json" />
</template>
```
Alternatively, use `initialContent` (HTML string or ProseMirror JSON) with the `@update` event if you don't need two-way binding:
```vue
<template>
<TiptapProEditor
:initial-content="'<p>Hello</p>'"
version="premium"
:features="{ headerNav: true }"
@update="handleUpdate"
/>
</template>
<script setup>
// @update emits ProseMirror JSON, debounced by 200ms
const handleUpdate = (json) => {
console.log('Document JSON:', json)
}
</script>
```
### Editor Versions
The `version` prop controls which Tiptap extensions are loaded — smaller versions download less code:
| `version` | What's included |
|-----------|-----------------|
| `minimal` | Basic text formatting, lists, undo/redo |
| `basic` (default) | `minimal` + colors, alignment, images, links, task lists — **no** tables, math, format painter, or AI |
| `advanced` / `premium` | Everything: tables, math formulas (KaTeX), code blocks, fonts, format painter, AI features |
```vue
<!-- Lightweight comment box -->
<TiptapProEditor v-model="content" version="minimal" />
<!-- Full-featured document editor -->
<TiptapProEditor v-model="content" version="premium" />
```
### Feature Flags
Fine-tune UI modules with the `features` prop (all off by default):
```vue
<template>
<TiptapProEditor
v-model="content"
:ai-config="{
provider: 'openai',
apiKey: 'your-api-key',
model: 'gpt-4o-mini'
version="premium"
:features="{
headerNav: true, // toolbar
footerNav: true, // footer with zoom & word count
slashCommand: true, // type / to insert blocks
dragHandleMenu: true, // drag handle with block menu
tableToolbar: true, // floating table toolbar
image: true, // floating image toolbar
linkBubbleMenu: true, // link preview bubble
floatingMenu: true, // selection floating menu
collaboration: false, // Yjs collaboration (see Collaboration docs)
}"
/>
</template>
```
**🔒 Security Note:** Never hardcode API keys in production. Use environment variables or let users configure their own keys via the AI Settings modal.
### Advanced Configuration
### Full Props, Events & Methods
```vue
<template>
<TiptapProEditor
ref="editorRef"
v-model="content"
:theme="theme"
:locale="locale"
version="premium"
locale="zh-CN"
:readonly="false"
:word-mode="true"
:dark-mode="isDark"
:show-toolbar="true"
:show-footer="true"
:placeholder="'Start writing...'"
@update:modelValue="handleUpdate"
:preview-mode="false"
:features="{ headerNav: true, footerNav: true }"
@update="onUpdate"
/>
</template>
@@ -218,13 +309,15 @@ import { TiptapProEditor } from 'tiptap-ui-kit'
import 'tiptap-ui-kit/style.css'
const content = ref('')
const theme = ref('word')
const locale = ref('zh-CN')
const isDark = ref(false)
const editorRef = ref(null)
const handleUpdate = (newContent) => {
console.log('Content updated:', newContent)
}
const onUpdate = (json) => { /* ProseMirror JSON, debounced 200ms */ }
// Exposed methods via template ref:
// editorRef.value.getEditor() - the raw Tiptap Editor instance
// editorRef.value.getJSON() - ProseMirror JSON
// editorRef.value.getHTML() - HTML string
// editorRef.value.getText() - plain text
</script>
```
@@ -232,49 +325,172 @@ const handleUpdate = (newContent) => {
## 📚 Documentation
### Props
| Prop | Type | Default | Description |
|------|------|---------|-------------|
| `modelValue` | `string \| object` | — | `v-model` binding. String → HTML in/out; object → ProseMirror JSON in/out |
| `initialContent` | `string \| object` | `''` | Initial content (HTML or ProseMirror JSON). Ignored if `modelValue` is set |
| `version` | `'minimal' \| 'basic' \| 'advanced' \| 'premium'` | `'basic'` | Extension tier — see [Editor Versions](#editor-versions) |
| `features` | `FeatureConfig` | — | Per-feature UI flags — see [Feature Flags](#feature-flags) |
| `locale` | `'en-US' \| 'zh-CN' \| 'zh-TW'` | auto-detected | UI language; falls back to browser language detection |
| `readonly` | `boolean` | `false` | Read-only mode |
| `previewMode` | `boolean` | `false` | Preview rendering: no toolbar/footer, not editable |
| `documentId` | `string` | — | Document ID, used as the collaboration room name |
| `zoomBarPlacement` | `'bottom' \| 'belowToolbar'` | `'bottom'` | Zoom bar position |
| `tableMenuShowMode` | `1 \| 2` | `2` | Table toolbar trigger: 1 = on focus, 2 = on cell selection |
### Events
| Event | Payload | Description |
|-------|---------|-------------|
| `update` | ProseMirror JSON | Content changed — **debounced 200ms** |
| `update:modelValue` | `string \| object` | v-model sync (HTML or JSON, matching what you bound) — not debounced |
| `collaboratorsChange` | `number` | Number of online collaborators changed |
| `collaboratorsListChange` | `Array<{ id, name, color }>` | Online collaborator list changed |
### Exposed Methods
Available on the component via template ref: `getEditor()`, `getJSON()`, `getHTML()`, `getText()`.
### Themes
Tiptap UI Kit comes with 5 professionally designed themes:
All 5 theme presets ship inside `tiptap-ui-kit/style.css` — no extra CSS imports. Switch themes with the `setTheme` function (it applies a `theme-*` class and `data-theme` attribute on `<html>`):
```ts
import { setTheme, toggleThemeMode, getTheme } from 'tiptap-ui-kit'
// setTheme(preset, mode) — mode defaults to 'light'
setTheme('notion', 'dark') // Notion theme, dark mode
setTheme('word') // Word theme, light mode
setTheme('github', 'auto') // follow system preference
toggleThemeMode() // toggle light <-> dark
getTheme() // { preset: 'github', mode: 'auto' }
```
| Theme | Description | Best For |
|-------|-------------|----------|
| **default** | Clean and minimal design | General purpose editing |
| **word** | Microsoft Word-like with A4 pages | Formal documents, reports |
| **notion** | Modern, distraction-free | Note-taking, knowledge base |
| **github** | Developer-friendly markdown | Technical documentation |
| **typora** | Elegant reading/writing | Long-form content, blogs |
| `default` | Clean and minimal design | General purpose editing |
| `word` | Microsoft Word-like with A4 pages | Formal documents, reports |
| `notion` | Modern, distraction-free | Note-taking, knowledge base |
| `github` | Developer-friendly markdown | Technical documentation |
| `typora` | Elegant reading/writing | Long-form content, blogs |
```vue
<TiptapProEditor theme="notion" />
```
Dark mode is driven by `data-theme="dark"` on the document element. You can also register your own theme variables with `registerTheme('custom', { '--your-css-var': 'value' })` and apply them via `setTheme('custom')`.
### Localization
Supported languages: `en-US`, `zh-CN`, `zh-TW`
Supported languages: `en-US`, `zh-CN`, `zh-TW`.
```vue
<TiptapProEditor locale="zh-CN" />
<TiptapProEditor v-model="content" locale="zh-CN" />
```
If `locale` is not provided, the browser language is detected automatically: `zh-TW`/`zh-HK`/`zh-MO` → Traditional Chinese, other `zh` → Simplified Chinese, everything else → English.
### Math Formulas
Math rendering uses KaTeX, which is **lazy-loaded** the first time a formula is rendered — it costs nothing if you don't use it. You must import the KaTeX stylesheet yourself:
```ts
import 'katex/dist/katex.min.css'
```
### AI Assistant — edit documents with plain words
Once AI is configured (see [AI Configuration](#ai-configuration) below), a floating **⚡ AI** button appears at the bottom-right of the editor. Open it and describe what you want:
> 「在文档末尾加一个 3x3 的表格」 · "Rewrite the second paragraph to be more concise" · 「把所有出现的产品名加粗」
The AI reads the document and edits it directly through a set of structured tools (insert/replace/delete blocks, edit/format text). Every step is shown in the chat, edits apply live, and **Cmd/Ctrl+Z undoes them** like any other edit. Works with all supported providers via OpenAI-style function calling.
Disable the panel with `:features="{ aiChat: false }"`.
**Build your own integration** — the tool layer and agent loop are exported, so you can drive the same document tools from your own UI, backend, or agent framework:
```ts
import { documentTools, toOpenAiTools, runDocumentAgent } from 'tiptap-ui-kit'
// One-shot: run the built-in agent loop against the current editor
await runDocumentAgent({
editor,
instruction: 'Add a summary section at the end',
callbacks: { onToolResult: (name) => console.log('step:', name) },
})
// Or take the raw tools (name/description/JSON-schema/execute) and wire them
// into any tool-calling loop — e.g. an Anthropic Messages API client or the
// Claude Agent SDK on your backend, proxying tool calls to the browser editor.
const tools = toOpenAiTools(documentTools)
```
### AI Configuration
Configure AI features via props or the built-in settings modal:
There is **no AI prop on the component**. AI is configured in one of two ways:
```typescript
interface AiConfig {
provider: 'openai' | 'aliyun' | 'deepseek' | 'ollama'
apiKey: string
baseUrl?: string // Optional custom endpoint
model?: string // Optional model name
}
**1. Built-in AI Settings modal (end-user configuration)**
Users open AI Settings from the editor toolbar, pick a provider, and paste their own API key. The configuration is persisted in the browser's `localStorage`.
**2. Environment variables (host-app configuration)**
Set `VITE_AI_*` variables in your app's `.env` (see [.env.example](.env.example)):
```bash
# openai | deepseek | anthropic | aliyun | ollama | custom
VITE_AI_PROVIDER=openai
VITE_AI_API_KEY=sk-...
VITE_AI_BASE_URL=https://api.openai.com/v1 # optional
VITE_AI_MODEL=gpt-4o-mini # optional
```
> **🔒 Security warning:** API keys entered in the AI Settings modal are stored in browser `localStorage` with **reversible obfuscation, not encryption**. Any script running on the page — an XSS payload, a malicious browser extension — can read them. Only use keys you own with a spending limit configured, and never embed organization-wide keys this way. For production apps, the recommended setup is a backend proxy that holds the real key server-side (point the editor at it with provider `custom` / `VITE_AI_BASE_URL`).
### Real-time Collaboration
Collaboration is opt-in and requires the optional peer dependencies plus a [y-websocket](https://github.com/yjs/y-websocket) server:
```bash
pnpm add yjs y-websocket @tiptap/extension-collaboration @tiptap/extension-collaboration-cursor
```
```bash
# .env
VITE_COLLABORATION_WS_URL=wss://your-server.com/ws
```
```vue
<TiptapProEditor
v-model="content"
version="premium"
document-id="doc-42"
:features="{ headerNav: true, collaboration: true }"
@collaborators-change="(n) => console.log(n, 'online')"
/>
```
`documentId` is used as the collaboration room name. If `collaboration` is enabled without `VITE_COLLABORATION_WS_URL`, a console warning is printed and collaboration stays off.
### API Reference
Full API documentation is available in the [API.md](API.md) file.
The [Props](#props), [Events](#events) and [Exposed Methods](#exposed-methods) tables above are the full public API of `TiptapProEditor`. Everything importable from `'tiptap-ui-kit'` is typed — check your editor's autocomplete for theme utilities (`setTheme`, `toggleThemeMode`, `registerTheme`, …) and locale utilities (`createI18n`, `detectDefaultLocale`, …).
---
## 🔄 Migrating to 0.2
v0.2 focuses on bundle size. Upgrading from 0.1 requires a few adjustments:
1. **New peer dependencies** — `ant-design-vue` and `@ant-design/icons-vue` are no longer bundled. npm 7+ / pnpm install peers automatically; with older tooling, install them manually.
2. **Collaboration peers are optional** — `yjs`, `y-websocket`, `@tiptap/extension-collaboration`, `@tiptap/extension-collaboration-cursor` are only needed if you enable collaboration.
3. **KaTeX CSS** — math styles are no longer bundled. If you use math formulas, add `import 'katex/dist/katex.min.css'` to your app. KaTeX itself lazy-loads on first formula render.
4. **`version` semantics changed** — `version="basic"` (the default) now loads only lightweight extensions (no tables, math, format painter, or AI). If you relied on the old everything-included behavior, pass `version="premium"`. A new `minimal` tier is available for the smallest builds.
5. **`@update` is debounced by 200ms** — it emits ProseMirror JSON at most once per 200ms pause. For synchronous updates use `v-model` / `@update:modelValue`.
6. **`v-model` is now supported** — bind a string for HTML or an object for ProseMirror JSON.
7. **Theme CSS is bundled** — all 5 theme presets are inside `tiptap-ui-kit/style.css`; remove any per-theme CSS imports.
---
## 💡 Use Cases
@@ -343,12 +559,14 @@ pnpm test
```
src/
├── ai/ # AI features (continue writing, polish, etc.)
├── core/ # Core editor components
├── api/ # AI & WebSocket API clients
├── core/ # Core editor component (TiptapProEditor)
├── extensions/ # Tiptap extensions
├── features/ # Toolbar features (basic & advanced)
├── locales/ # Internationalization
├── themes/ # Theme presets
├── tools/ # Optional tools (collaboration, etc.)
├── styles/ # Base styles
├── themes/ # Theme presets & theme manager
├── tools/ # UI modules (toolbar, collaboration, menus, etc.)
└── ui/ # Reusable UI components
```
+13 -5
View File
@@ -116,6 +116,7 @@ import LandingPage from './LandingPage.vue'
import EditorAutoDemo from './EditorAutoDemo.vue'
import InlinePluginDemo from './InlinePluginDemo.vue'
import { createI18n, type LocaleCode } from '../src/locales'
import { detectDefaultLocale } from '../src/locales/manager'
import { PRESET_CONFIGS } from '../src/core/editorConfig'
import type { FeatureFlags, ThemePreset } from '../src/core/editorConfig'
import { setTheme, setDeviceView, setOrientation, type DeviceView, THEME_PRESETS } from '../src/themes'
@@ -128,16 +129,23 @@ import '../src/themes/presets/github.css'
import '../src/themes/presets/typora.css'
import '../src/styles/device-responsive.css'
// Landing page state
const showLanding = ref(true)
// Landing page state(用 hash 记住状态,刷新不回落地页)
const showLanding = ref(!location.hash.startsWith('#demo'))
// Demo mode: 'full' = full editor, 'inline' = inline + plugins
const demoMode = ref<'full' | 'inline'>('full')
const demoMode = ref<'full' | 'inline'>(location.hash === '#demo-inline' ? 'inline' : 'full')
const handleStartDemo = () => {
showLanding.value = false
history.replaceState(null, '', '#demo')
}
watch(demoMode, (mode) => {
if (!showLanding.value) {
history.replaceState(null, '', mode === 'inline' ? '#demo-inline' : '#demo')
}
})
// Theme mode (light/dark)
const theme = ref<'light' | 'dark'>('light')
const toggleTheme = () => {
@@ -175,8 +183,8 @@ const antdTheme = computed(() => ({
algorithm: theme.value === 'dark' ? antTheme.darkAlgorithm : antTheme.defaultAlgorithm,
}))
// Locale
const locale = ref<LocaleCode>('en-US')
// Locale(初始值跟随浏览器语言自动检测,与 i18n manager 保持一致)
const locale = ref<LocaleCode>(detectDefaultLocale())
watch(locale, (newLocale) => {
createI18n({ locale: newLocale })
})
+19 -18
View File
@@ -198,7 +198,7 @@ const demoScript: DemoStep[] = [
// Code block
{ action: 'format', format: 'code' },
{ action: 'addLine', line: { html: '', class: 'line-code', tag: 'pre' } },
{ action: 'type', text: '<span class="code-kw">import</span> { TiptapEditor } <span class="code-kw">from</span> <span class="code-str">\'tiptap-ui-kit\'</span>', lineIndex: 7, duration: 25 },
{ action: 'type', text: '<span class="code-kw">import</span> { TiptapProEditor } <span class="code-kw">from</span> <span class="code-str">\'tiptap-ui-kit\'</span>', lineIndex: 7, duration: 25 },
{ action: 'format', format: '' },
{ action: 'pause', duration: 300 },
@@ -337,21 +337,24 @@ onBeforeUnmount(() => {
.editor-preview__glow {
position: absolute;
inset: -20px;
background: conic-gradient(
from 0deg,
#667eea33, #764ba233, #f093fb33, #f5576c33,
#43e97b33, #38f9d733, #4facfe33, #667eea33
);
/* 预模糊的多层径向渐变代替 conic-gradient + filter: blur():
blur 滤镜叠加旋转动画会逐帧重栅格化、严重拖垮合成器;
渐变自带柔边,动画只走 transform,全程留在合成线程 */
background:
radial-gradient(45% 45% at 25% 25%, rgba(102, 126, 234, 0.4), transparent 70%),
radial-gradient(50% 50% at 75% 20%, rgba(240, 147, 251, 0.35), transparent 70%),
radial-gradient(45% 50% at 80% 75%, rgba(67, 233, 123, 0.3), transparent 70%),
radial-gradient(50% 45% at 25% 80%, rgba(79, 172, 254, 0.38), transparent 70%),
radial-gradient(60% 60% at 50% 50%, rgba(118, 75, 162, 0.25), transparent 75%);
border-radius: 24px;
filter: blur(40px);
opacity: 0.6;
animation: glow-rotate 8s linear infinite;
will-change: transform;
z-index: 0;
}
.editor-preview[data-theme="dark"] .editor-preview__glow {
opacity: 0.4;
filter: blur(50px);
opacity: 0.45;
}
@keyframes glow-rotate {
@@ -705,8 +708,8 @@ onBeforeUnmount(() => {
border-radius: 12px;
font-size: 13px;
font-weight: 600;
backdrop-filter: blur(12px);
-webkit-backdrop-filter: blur(12px);
/* 不用 backdrop-filter(配合无限浮动动画时逐帧重采样背景,代价极高),
改用高不透明度实底色,见 .label--* 与暗色覆盖 */
opacity: 0;
transform: translateY(10px) scale(0.9);
transition: none;
@@ -747,7 +750,7 @@ onBeforeUnmount(() => {
.label--themes {
top: 15%;
right: -75px;
background: rgba(255, 255, 255, 0.85);
background: rgba(255, 255, 255, 0.94);
color: #333;
box-shadow: 0 4px 20px rgba(102, 126, 234, 0.15), 0 0 0 1px rgba(102, 126, 234, 0.1);
}
@@ -759,7 +762,7 @@ onBeforeUnmount(() => {
.label--ai {
bottom: 35%;
left: -70px;
background: rgba(255, 255, 255, 0.85);
background: rgba(255, 255, 255, 0.94);
color: #333;
box-shadow: 0 4px 20px rgba(240, 147, 251, 0.15), 0 0 0 1px rgba(240, 147, 251, 0.1);
}
@@ -771,7 +774,7 @@ onBeforeUnmount(() => {
.label--collab {
top: 55%;
right: -85px;
background: rgba(255, 255, 255, 0.85);
background: rgba(255, 255, 255, 0.94);
color: #333;
box-shadow: 0 4px 20px rgba(67, 233, 123, 0.15), 0 0 0 1px rgba(67, 233, 123, 0.1);
}
@@ -783,7 +786,7 @@ onBeforeUnmount(() => {
.label--word {
bottom: 10%;
left: -65px;
background: rgba(255, 255, 255, 0.85);
background: rgba(255, 255, 255, 0.94);
color: #333;
box-shadow: 0 4px 20px rgba(79, 172, 254, 0.15), 0 0 0 1px rgba(79, 172, 254, 0.1);
}
@@ -793,7 +796,7 @@ onBeforeUnmount(() => {
}
.editor-preview[data-theme="dark"] .floating-label {
background: rgba(26, 27, 38, 0.85);
background: rgba(26, 27, 38, 0.94);
color: #c0caf5;
}
@@ -892,7 +895,6 @@ onBeforeUnmount(() => {
}
.editor-preview__glow {
inset: -15px;
filter: blur(30px);
}
}
@@ -932,7 +934,6 @@ onBeforeUnmount(() => {
.editor-preview__glow {
inset: -10px;
filter: blur(25px);
}
.mobile-label {
+2
View File
@@ -1,6 +1,8 @@
import { createApp } from 'vue'
import Antd from 'ant-design-vue'
import 'ant-design-vue/dist/reset.css'
// KaTeX 样式:库不再内置,使用数学公式时需自行引入
import 'katex/dist/katex.min.css'
import App from './App.vue'
const app = createApp(App)
+31 -23
View File
@@ -1,6 +1,6 @@
{
"name": "tiptap-ui-kit",
"version": "0.1.1",
"version": "0.2.0",
"description": "Beautiful Tiptap 3 + Vue 3 rich-text editor theme with AI support",
"type": "module",
"packageManager": "pnpm@9.15.9",
@@ -27,7 +27,6 @@
"dev": "vite",
"build": "vite build",
"build:demo": "vite build --config vite.config.demo.ts",
"build:types": "vue-tsc --emitDeclarationOnly",
"preview": "vite preview",
"typecheck": "vue-tsc --noEmit",
"test": "vitest",
@@ -37,28 +36,42 @@
"prepare": "npm run build",
"prepublishOnly": "pnpm build",
"pack:check": "pnpm build && npm pack --dry-run",
"release": "pnpm build && pnpm publish --access public",
"moltbook": "node scripts/moltbook-bot.cjs",
"moltbook:post": "node scripts/moltbook-bot.cjs post",
"moltbook:status": "node scripts/moltbook-bot.cjs status",
"moltbook:auto": "node scripts/moltbook-bot.cjs auto",
"moltbook:smart": "node scripts/moltbook-smart-bot.cjs run",
"moltbook:smart:auto": "node scripts/moltbook-smart-bot.cjs auto",
"moltbook:feedback": "node scripts/moltbook-smart-bot.cjs feedback",
"moltbook:monitor": "node scripts/moltbook-monitor.cjs",
"moltbook:watch": "node scripts/moltbook-monitor.cjs watch"
"release": "pnpm build && pnpm publish --access public"
},
"peerDependencies": {
"@ant-design/icons-vue": "^7.0.1",
"@tiptap/core": "^3.0.0",
"@tiptap/extension-collaboration": "^3.0.0",
"@tiptap/extension-collaboration-cursor": "^2.26.2",
"@tiptap/pm": "^3.0.0",
"@tiptap/starter-kit": "^3.0.0",
"@tiptap/vue-3": "^3.0.0",
"vue": "^3.4.0"
"ant-design-vue": "^4.0.0",
"vue": "^3.4.0",
"y-websocket": "^3.0.0",
"yjs": "^13.6.0"
},
"peerDependenciesMeta": {
"@tiptap/extension-collaboration": {
"optional": true
},
"@tiptap/extension-collaboration-cursor": {
"optional": true
},
"y-websocket": {
"optional": true
},
"yjs": {
"optional": true
}
},
"devDependencies": {
"@ant-design/icons-vue": "^7.0.1",
"@tiptap/core": "^3.7.2",
"@tiptap/extension-bubble-menu": "^3.7.2",
"@tiptap/extension-code-block-lowlight": "^3.7.1",
"@tiptap/extension-collaboration": "^3.13.0",
"@tiptap/extension-collaboration-cursor": "^2.26.2",
"@tiptap/extension-typography": "^3.7.2",
"@tiptap/extensions": "^3.11.1",
"@tiptap/pm": "^3.7.2",
@@ -70,10 +83,9 @@
"@vitejs/plugin-vue": "^5.2.1",
"@vitest/ui": "^4.0.18",
"@vue/test-utils": "^2.4.6",
"ant-design-vue": "^4.2.6",
"happy-dom": "^20.4.0",
"lowlight": "^3.3.0",
"lucide-vue-next": "^0.507.0",
"rollup-plugin-obfuscator": "^1.1.0",
"sass-embedded": "^1.96.0",
"terser": "^5.44.1",
"typescript": "^5.7.2",
@@ -82,7 +94,9 @@
"vitest": "^4.0.18",
"vue": "^3.5.13",
"vue-tsc": "^2.1.10",
"vue-types": "^3.0.2"
"vue-types": "^3.0.2",
"y-websocket": "^3.0.0",
"yjs": "^13.6.27"
},
"keywords": [
"tiptap",
@@ -137,10 +151,7 @@
"pnpm": ">=8.0.0"
},
"dependencies": {
"@ant-design/icons-vue": "^7.0.1",
"@tiptap/extension-character-count": "^3.0.0",
"@tiptap/extension-collaboration": "^3.13.0",
"@tiptap/extension-collaboration-cursor": "^2.26.2",
"@tiptap/extension-color": "^3.0.0",
"@tiptap/extension-font-family": "^3.7.2",
"@tiptap/extension-highlight": "^3.0.0",
@@ -158,12 +169,9 @@
"@tiptap/extension-text-align": "^3.0.0",
"@tiptap/extension-text-style": "^3.0.0",
"@tiptap/extension-underline": "^3.0.0",
"ant-design-vue": "^4.2.6",
"docx": "^9.5.1",
"file-saver": "^2.0.5",
"katex": "^0.16.28",
"mammoth": "^1.11.0",
"y-websocket": "^3.0.0",
"yjs": "^13.6.27"
"mammoth": "^1.11.0"
}
}
+18 -819
View File
File diff suppressed because it is too large. Load diff
File renamed without changes.
-11
View File
@@ -1,11 +0,0 @@
import { describe, it, expect } from 'vitest'
describe('Example Test Suite', () => {
it('should pass basic assertion', () => {
expect(true).toBe(true)
})
it('should perform basic math', () => {
expect(1 + 1).toBe(2)
})
})
-16
View File
@@ -1,16 +0,0 @@
/**
* Icons Adapter
* Allows users to provide their own icon components
*/
import type { Component } from 'vue';
export type IconName = 'bold' | 'italic' | 'underline' | 'strikethrough' | 'heading1' | 'heading2' | 'heading3' | 'alignLeft' | 'alignCenter' | 'alignRight' | 'alignJustify' | 'listBullet' | 'listOrdered' | 'listCheck' | 'link' | 'image' | 'table' | 'code' | 'codeBlock' | 'undo' | 'redo' | 'formatClear' | 'formatPainter' | 'subscript' | 'superscript' | 'quote' | 'horizontalRule' | 'plus' | 'minus' | 'close' | 'check' | 'chevronDown' | 'chevronUp' | 'chevronLeft' | 'chevronRight' | 'drag' | 'copy' | 'cut' | 'delete' | 'duplicate' | 'ai' | 'sparkles' | 'wand' | 'sun' | 'moon';
export type IconAdapter = Partial<Record<IconName, Component | string>>;
/**
* Default icons using Unicode/Emoji
* Users can replace with Lucide, Ant Design Icons, etc.
*/
export declare const defaultIconAdapter: IconAdapter;
export declare function setIconAdapter(adapter: IconAdapter): void;
export declare function getIconAdapter(): IconAdapter;
export declare function getIcon(name: IconName): Component | string;
//# sourceMappingURL=icons.d.ts.map
-1
View File
@@ -1 +0,0 @@
{"version":3,"file":"icons.d.ts","sourceRoot":"","sources":["icons.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,KAAK,CAAA;AAEpC,MAAM,MAAM,QAAQ,GAChB,MAAM,GAAG,QAAQ,GAAG,WAAW,GAAG,eAAe,GACjD,UAAU,GAAG,UAAU,GAAG,UAAU,GACpC,WAAW,GAAG,aAAa,GAAG,YAAY,GAAG,cAAc,GAC3D,YAAY,GAAG,aAAa,GAAG,WAAW,GAC1C,MAAM,GAAG,OAAO,GAAG,OAAO,GAAG,MAAM,GAAG,WAAW,GACjD,MAAM,GAAG,MAAM,GACf,aAAa,GAAG,eAAe,GAC/B,WAAW,GAAG,aAAa,GAC3B,OAAO,GAAG,gBAAgB,GAC1B,MAAM,GAAG,OAAO,GAAG,OAAO,GAAG,OAAO,GACpC,aAAa,GAAG,WAAW,GAAG,aAAa,GAAG,cAAc,GAC5D,MAAM,GAAG,MAAM,GAAG,KAAK,GAAG,QAAQ,GAAG,WAAW,GAChD,IAAI,GAAG,UAAU,GAAG,MAAM,GAC1B,KAAK,GAAG,MAAM,CAAA;AAElB,MAAM,MAAM,WAAW,GAAG,OAAO,CAAC,MAAM,CAAC,QAAQ,EAAE,SAAS,GAAG,MAAM,CAAC,CAAC,CAAA;AAEvE;;;GAGG;AACH,eAAO,MAAM,kBAAkB,EAAE,WAwBhC,CAAA;AAKD,wBAAgB,cAAc,CAAC,OAAO,EAAE,WAAW,GAAG,IAAI,CAEzD;AAED,wBAAgB,cAAc,IAAI,WAAW,CAE5C;AAED,wBAAgB,OAAO,CAAC,IAAI,EAAE,QAAQ,GAAG,SAAS,GAAG,MAAM,CAE1D"}
-8
View File
@@ -1,8 +0,0 @@
/**
* Adapters Entry
* Provides compatibility layer for @vben/* packages
*/
export { useUserStore, setUserInfo } from './user';
export type { UserInfo } from './user';
export { usePreferences, initTheme } from './preferences';
//# sourceMappingURL=index.d.ts.map
-1
View File
@@ -1 +0,0 @@
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAGH,OAAO,EAAE,YAAY,EAAE,WAAW,EAAE,MAAM,QAAQ,CAAA;AAClD,YAAY,EAAE,QAAQ,EAAE,MAAM,QAAQ,CAAA;AAGtC,OAAO,EAAE,cAAc,EAAE,SAAS,EAAE,MAAM,eAAe,CAAA"}
-36
View File
@@ -1,36 +0,0 @@
/**
* Notification Adapter
* Allows users to plug in their own notification system (e.g., ant-design-vue, element-plus)
*/
export interface NotificationOptions {
message: string;
description?: string;
duration?: number;
}
export interface NotificationAdapter {
success(options: NotificationOptions): void;
error(options: NotificationOptions): void;
warning(options: NotificationOptions): void;
info(options: NotificationOptions): void;
}
/**
* Default notification adapter using console
*/
export declare const defaultNotificationAdapter: NotificationAdapter;
/**
* Create an Ant Design Vue notification adapter
* @example
* import { notification } from 'ant-design-vue'
* const adapter = createAntdNotificationAdapter(notification)
*/
export declare function createAntdNotificationAdapter(notification: any): NotificationAdapter;
export declare function setNotificationAdapter(adapter: NotificationAdapter): void;
export declare function getNotificationAdapter(): NotificationAdapter;
/** Shorthand for showing notifications */
export declare const notify: {
success: (opts: NotificationOptions) => void;
error: (opts: NotificationOptions) => void;
warning: (opts: NotificationOptions) => void;
info: (opts: NotificationOptions) => void;
};
//# sourceMappingURL=notification.d.ts.map
-1
View File
@@ -1 +0,0 @@
{"version":3,"file":"notification.d.ts","sourceRoot":"","sources":["notification.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,MAAM,WAAW,mBAAmB;IAClC,OAAO,EAAE,MAAM,CAAA;IACf,WAAW,CAAC,EAAE,MAAM,CAAA;IACpB,QAAQ,CAAC,EAAE,MAAM,CAAA;CAClB;AAED,MAAM,WAAW,mBAAmB;IAClC,OAAO,CAAC,OAAO,EAAE,mBAAmB,GAAG,IAAI,CAAA;IAC3C,KAAK,CAAC,OAAO,EAAE,mBAAmB,GAAG,IAAI,CAAA;IACzC,OAAO,CAAC,OAAO,EAAE,mBAAmB,GAAG,IAAI,CAAA;IAC3C,IAAI,CAAC,OAAO,EAAE,mBAAmB,GAAG,IAAI,CAAA;CACzC;AAED;;GAEG;AACH,eAAO,MAAM,0BAA0B,EAAE,mBAKxC,CAAA;AAED;;;;;GAKG;AACH,wBAAgB,6BAA6B,CAAC,YAAY,EAAE,GAAG,GAAG,mBAAmB,CAOpF;AAKD,wBAAgB,sBAAsB,CAAC,OAAO,EAAE,mBAAmB,GAAG,IAAI,CAEzE;AAED,wBAAgB,sBAAsB,IAAI,mBAAmB,CAE5D;AAED,0CAA0C;AAC1C,eAAO,MAAM,MAAM;oBACD,mBAAmB;kBACrB,mBAAmB;oBACjB,mBAAmB;iBACtB,mBAAmB;CACjC,CAAA"}
-20
View File
@@ -1,20 +0,0 @@
/**
* Preferences Adapter
* Replaces @vben/preferences
*/
type Theme = 'light' | 'dark';
/**
* Use preferences (compatible with @vben/preferences)
*/
export declare function usePreferences(): {
theme: Readonly<import("vue").Ref<Theme, Theme>>;
isDark: Readonly<import("vue").Ref<boolean, boolean>>;
setTheme: (t: Theme) => void;
toggleTheme: () => void;
};
/**
* Initialize theme from system preferences
*/
export declare function initTheme(): void;
export {};
//# sourceMappingURL=preferences.d.ts.map
-1
View File
@@ -1 +0,0 @@
{"version":3,"file":"preferences.d.ts","sourceRoot":"","sources":["preferences.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAIH,KAAK,KAAK,GAAG,OAAO,GAAG,MAAM,CAAA;AAI7B;;GAEG;AACH,wBAAgB,cAAc;;;kBAIP,KAAK;;EAkB3B;AAED;;GAEG;AACH,wBAAgB,SAAS,IAAI,IAAI,CAKhC"}
-33
View File
@@ -1,33 +0,0 @@
/**
* User Adapter
* Replaces @vben/stores useUserStore
*/
export interface UserInfo {
userId: string | number;
realName: string;
userName: string;
avatar?: string;
}
/**
* Set user info (call this on app init)
*/
export declare function setUserInfo(info: UserInfo): void;
/**
* Get user store (compatible with @vben/stores)
*/
export declare function useUserStore(): {
userInfo: {
readonly userId: string | number;
readonly realName: string;
readonly userName: string;
readonly avatar?: string | undefined;
} | null;
setUserInfo: typeof setUserInfo;
getUserInfo: () => {
userId: string | number;
realName: string;
userName: string;
avatar?: string | undefined;
} | null;
};
//# sourceMappingURL=user.d.ts.map
-1
View File
@@ -1 +0,0 @@
{"version":3,"file":"user.d.ts","sourceRoot":"","sources":["user.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAIH,MAAM,WAAW,QAAQ;IACvB,MAAM,EAAE,MAAM,GAAG,MAAM,CAAA;IACvB,QAAQ,EAAE,MAAM,CAAA;IAChB,QAAQ,EAAE,MAAM,CAAA;IAChB,MAAM,CAAC,EAAE,MAAM,CAAA;CAChB;AAUD;;GAEG;AACH,wBAAgB,WAAW,CAAC,IAAI,EAAE,QAAQ,GAAG,IAAI,CAEhD;AAED;;GAEG;AACH,wBAAgB,YAAY;;yBAxBlB,MAAM,GAAG,MAAM;2BACb,MAAM;2BACN,MAAM;0BACP,MAAM;;;;gBAHP,MAAM,GAAG,MAAM;kBACb,MAAM;kBACN,MAAM;iBACP,MAAM;;EA2BhB"}
-16
View File
@@ -1,16 +0,0 @@
import type { Component } from 'vue';
import type { Editor } from '@tiptap/core';
interface Props {
editor: Editor;
icon?: Component;
label?: string;
title?: string;
active?: boolean;
placement?: 'top' | 'bottom' | 'bottomLeft' | 'bottomRight' | 'topLeft' | 'topRight';
}
declare const _default: import("vue").DefineComponent<Props, {}, {}, {}, {}, import("vue").ComponentOptionsMixin, import("vue").ComponentOptionsMixin, {}, string, import("vue").PublicProps, Readonly<Props> & Readonly<{}>, {
active: boolean;
placement: "top" | "bottom" | "bottomLeft" | "bottomRight" | "topLeft" | "topRight";
}, {}, {}, {}, string, import("vue").ComponentProvideOptions, false, {}, any>;
export default _default;
//# sourceMappingURL=AiMenuButton.vue.d.ts.map
-1
View File
@@ -1 +0,0 @@
{"version":3,"file":"AiMenuButton.vue.d.ts","sourceRoot":"","sources":["AiMenuButton.vue"],"names":[],"mappings":"AAsrBA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,KAAK,CAAC;AACrC,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,cAAc,CAAC;AAU3C,UAAU,KAAK;IACb,MAAM,EAAE,MAAM,CAAC;IACf,IAAI,CAAC,EAAE,SAAS,CAAC;IACjB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,MAAM,CAAC,EAAE,OAAO,CAAC;IACjB,SAAS,CAAC,EAAE,KAAK,GAAG,QAAQ,GAAG,YAAY,GAAG,aAAa,GAAG,SAAS,GAAG,UAAU,CAAC;CACtF;;YAFU,OAAO;eACJ,KAAK,GAAG,QAAQ,GAAG,YAAY,GAAG,aAAa,GAAG,SAAS,GAAG,UAAU;;AA+wBtF,wBAOG"}
-14
View File
@@ -1,14 +0,0 @@
/**
* Aliyun (Alibaba Cloud) Adapter
* For Qwen/Tongyi Qianwen models via DashScope API
*/
import type { AiAdapter, AiConfig, AiMessage, AiResponse, AiStreamCallbacks } from '../types';
export declare class AliyunAdapter implements AiAdapter {
provider: "aliyun";
private config;
constructor(config: AiConfig);
chat(messages: AiMessage[], options?: Partial<AiConfig>): Promise<AiResponse>;
chatStream(messages: AiMessage[], callbacks: AiStreamCallbacks, options?: Partial<AiConfig>): Promise<void>;
}
export declare function createAliyunAdapter(config: AiConfig): AiAdapter;
//# sourceMappingURL=aliyun.d.ts.map
-1
View File
@@ -1 +0,0 @@
{"version":3,"file":"aliyun.d.ts","sourceRoot":"","sources":["aliyun.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,KAAK,EAAE,SAAS,EAAE,QAAQ,EAAE,SAAS,EAAE,UAAU,EAAE,iBAAiB,EAAE,MAAM,UAAU,CAAA;AAE7F,qBAAa,aAAc,YAAW,SAAS;IAC7C,QAAQ,EAAG,QAAQ,CAAS;IAC5B,OAAO,CAAC,MAAM,CAAU;gBAEZ,MAAM,EAAE,QAAQ;IAItB,IAAI,CAAC,QAAQ,EAAE,SAAS,EAAE,EAAE,OAAO,CAAC,EAAE,OAAO,CAAC,QAAQ,CAAC,GAAG,OAAO,CAAC,UAAU,CAAC;IA4C7E,UAAU,CAAC,QAAQ,EAAE,SAAS,EAAE,EAAE,SAAS,EAAE,iBAAiB,EAAE,OAAO,CAAC,EAAE,OAAO,CAAC,QAAQ,CAAC,GAAG,OAAO,CAAC,IAAI,CAAC;CAqElH;AAED,wBAAgB,mBAAmB,CAAC,MAAM,EAAE,QAAQ,GAAG,SAAS,CAE/D"}
-7
View File
@@ -1,7 +0,0 @@
/**
* AI Adapters Entry
*/
export { OpenAiAdapter, createOpenAiAdapter } from './openai';
export { AliyunAdapter, createAliyunAdapter } from './aliyun';
export { OllamaAdapter, createOllamaAdapter } from './ollama';
//# sourceMappingURL=index.d.ts.map
-1
View File
@@ -1 +0,0 @@
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,EAAE,aAAa,EAAE,mBAAmB,EAAE,MAAM,UAAU,CAAA;AAC7D,OAAO,EAAE,aAAa,EAAE,mBAAmB,EAAE,MAAM,UAAU,CAAA;AAC7D,OAAO,EAAE,aAAa,EAAE,mBAAmB,EAAE,MAAM,UAAU,CAAA"}
-14
View File
@@ -1,14 +0,0 @@
/**
* Ollama Adapter
* For local Ollama models
*/
import type { AiAdapter, AiConfig, AiMessage, AiResponse, AiStreamCallbacks } from '../types';
export declare class OllamaAdapter implements AiAdapter {
provider: "ollama";
private config;
constructor(config: AiConfig);
chat(messages: AiMessage[], options?: Partial<AiConfig>): Promise<AiResponse>;
chatStream(messages: AiMessage[], callbacks: AiStreamCallbacks, options?: Partial<AiConfig>): Promise<void>;
}
export declare function createOllamaAdapter(config: AiConfig): AiAdapter;
//# sourceMappingURL=ollama.d.ts.map
-1
View File
@@ -1 +0,0 @@
{"version":3,"file":"ollama.d.ts","sourceRoot":"","sources":["ollama.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,KAAK,EAAE,SAAS,EAAE,QAAQ,EAAE,SAAS,EAAE,UAAU,EAAE,iBAAiB,EAAE,MAAM,UAAU,CAAA;AAE7F,qBAAa,aAAc,YAAW,SAAS;IAC7C,QAAQ,EAAG,QAAQ,CAAS;IAC5B,OAAO,CAAC,MAAM,CAAU;gBAEZ,MAAM,EAAE,QAAQ;IAItB,IAAI,CAAC,QAAQ,EAAE,SAAS,EAAE,EAAE,OAAO,CAAC,EAAE,OAAO,CAAC,QAAQ,CAAC,GAAG,OAAO,CAAC,UAAU,CAAC;IAqC7E,UAAU,CAAC,QAAQ,EAAE,SAAS,EAAE,EAAE,SAAS,EAAE,iBAAiB,EAAE,OAAO,CAAC,EAAE,OAAO,CAAC,QAAQ,CAAC,GAAG,OAAO,CAAC,IAAI,CAAC;CA6DlH;AAED,wBAAgB,mBAAmB,CAAC,MAAM,EAAE,QAAQ,GAAG,SAAS,CAE/D"}
-14
View File
@@ -1,14 +0,0 @@
/**
* OpenAI Adapter
* Compatible with OpenAI API standard (also works with DeepSeek, etc.)
*/
import type { AiAdapter, AiConfig, AiMessage, AiResponse, AiStreamCallbacks } from '../types';
export declare class OpenAiAdapter implements AiAdapter {
provider: "openai";
private config;
constructor(config: AiConfig);
chat(messages: AiMessage[], options?: Partial<AiConfig>): Promise<AiResponse>;
chatStream(messages: AiMessage[], callbacks: AiStreamCallbacks, options?: Partial<AiConfig>): Promise<void>;
}
export declare function createOpenAiAdapter(config: AiConfig): AiAdapter;
//# sourceMappingURL=openai.d.ts.map
-1
View File
@@ -1 +0,0 @@
{"version":3,"file":"openai.d.ts","sourceRoot":"","sources":["openai.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,KAAK,EAAE,SAAS,EAAE,QAAQ,EAAE,SAAS,EAAE,UAAU,EAAE,iBAAiB,EAAE,MAAM,UAAU,CAAA;AAE7F,qBAAa,aAAc,YAAW,SAAS;IAC7C,QAAQ,EAAG,QAAQ,CAAS;IAC5B,OAAO,CAAC,MAAM,CAAU;gBAEZ,MAAM,EAAE,QAAQ;IAItB,IAAI,CAAC,QAAQ,EAAE,SAAS,EAAE,EAAE,OAAO,CAAC,EAAE,OAAO,CAAC,QAAQ,CAAC,GAAG,OAAO,CAAC,UAAU,CAAC;IAqC7E,UAAU,CAAC,QAAQ,EAAE,SAAS,EAAE,EAAE,SAAS,EAAE,iBAAiB,EAAE,OAAO,CAAC,EAAE,OAAO,CAAC,QAAQ,CAAC,GAAG,OAAO,CAAC,IAAI,CAAC;CA+DlH;AAED,wBAAgB,mBAAmB,CAAC,MAAM,EAAE,QAAQ,GAAG,SAAS,CAE/D"}
+489
View File
@@ -0,0 +1,489 @@
<template>
<Teleport to="body">
<!-- 悬浮启动按钮 -->
<button
v-if="!open"
class="ai-chat-launcher"
type="button"
:title="t('aiChat.title')"
:aria-label="t('aiChat.title')"
@click="open = true"
>
<ThunderboltOutlined />
<span class="ai-chat-launcher__label">AI</span>
</button>
<!-- 聊天面板 -->
<Transition name="ai-chat-slide">
<div v-if="open" class="ai-chat-panel" role="dialog" :aria-label="t('aiChat.title')">
<div class="ai-chat-panel__header">
<span class="ai-chat-panel__title">
<ThunderboltOutlined />
{{ t('aiChat.title') }}
</span>
<div class="ai-chat-panel__actions">
<button
class="ai-chat-panel__icon-btn"
type="button"
:title="t('aiChat.settings')"
@click="showSettings = true"
>
<SettingOutlined />
</button>
<button
class="ai-chat-panel__icon-btn"
type="button"
:title="t('aiChat.close')"
@click="open = false"
>
<CloseOutlined />
</button>
</div>
</div>
<div ref="messagesRef" class="ai-chat-panel__messages">
<div v-if="messages.length === 0" class="ai-chat-panel__welcome">
{{ t('aiChat.welcome') }}
</div>
<template v-for="(msg, i) in messages" :key="i">
<div v-if="msg.type === 'user'" class="ai-chat-msg ai-chat-msg--user">
{{ msg.text }}
</div>
<div v-else-if="msg.type === 'assistant'" class="ai-chat-msg ai-chat-msg--assistant">
{{ msg.text }}
</div>
<div
v-else-if="msg.type === 'tool'"
class="ai-chat-step"
:class="{ 'ai-chat-step--error': msg.isError }"
>
<component :is="msg.isError ? CloseCircleOutlined : CheckCircleOutlined" />
{{ msg.text }}
</div>
<div v-else class="ai-chat-msg ai-chat-msg--error">
{{ msg.text }}
<button
v-if="msg.showConfigure"
class="ai-chat-panel__configure-btn"
type="button"
@click="showSettings = true"
>
{{ t('aiChat.configure') }}
</button>
</div>
</template>
<div v-if="running" class="ai-chat-step ai-chat-step--running">
<LoadingOutlined spin />
{{ t('aiChat.running') }}
</div>
</div>
<div class="ai-chat-panel__input-area">
<textarea
ref="inputRef"
v-model="input"
class="ai-chat-panel__input"
:placeholder="t('aiChat.placeholder')"
:disabled="running"
rows="2"
@keydown.enter.exact="onEnterKey"
/>
<button
v-if="running"
class="ai-chat-panel__send ai-chat-panel__send--stop"
type="button"
@click="stop"
>
{{ t('aiChat.stop') }}
</button>
<button
v-else
class="ai-chat-panel__send"
type="button"
:disabled="!input.trim() || !editor"
@click="send"
>
{{ t('aiChat.send') }}
</button>
</div>
</div>
</Transition>
<!-- AI 设置弹窗(复用现有组件) -->
<AiSettingsModal v-model:open="showSettings" />
</Teleport>
</template>
<script setup lang="ts">
/**
* AiChatPanel - AI 文档助手聊天面板
* @description 用户以自然语言描述需求(「帮我在末尾加一个 3x3 表格」「把第二段润色一下」),
* AI 通过 tool-use 循环直接编辑当前文档。悬浮于编辑器右下角,自带启动按钮。
*/
import { computed, nextTick, onBeforeUnmount, ref, watch } from 'vue'
import type { Editor } from '@tiptap/core'
import {
CheckCircleOutlined,
CloseCircleOutlined,
CloseOutlined,
LoadingOutlined,
SettingOutlined,
ThunderboltOutlined,
} from '@ant-design/icons-vue'
import { t, useI18n } from '@/locales'
import AiSettingsModal from '../components/AiSettingsModal.vue'
import { runDocumentAgent, AgentNotConfiguredError } from './agentLoop'
interface Props {
editor: Editor | null | undefined
}
const props = defineProps<Props>()
const editor = computed(() => props.editor ?? null)
const { locale } = useI18n()
// ===== 面板状态 =====
const open = ref(false)
const showSettings = ref(false)
const running = ref(false)
const input = ref('')
const messagesRef = ref<HTMLElement | null>(null)
const inputRef = ref<HTMLTextAreaElement | null>(null)
interface ChatItem {
type: 'user' | 'assistant' | 'tool' | 'error'
text: string
isError?: boolean
showConfigure?: boolean
}
const messages = ref<ChatItem[]>([])
let abortController: AbortController | null = null
// ===== 工具名 → 本地化步骤文案 =====
function toolLabel(name: string): string {
const key = `aiChat.tools.${name}`
const label = t(key)
return label === key ? name : label
}
// ===== 自动滚动到底部 =====
async function scrollToBottom() {
await nextTick()
const el = messagesRef.value
if (el) el.scrollTop = el.scrollHeight
}
watch(open, async (isOpen) => {
if (isOpen) {
await scrollToBottom()
inputRef.value?.focus()
}
})
// ===== 发送 =====
async function send() {
const instruction = input.value.trim()
if (!instruction || running.value || !editor.value) return
// 多轮上下文:只带 user/assistant 文本轮次,最近 8 条(在 push 本次指令前构造,不含本条)
const history = messages.value
.filter((m) => m.type === 'user' || m.type === 'assistant')
.slice(-8)
.map((m) => ({ role: m.type as 'user' | 'assistant', content: m.text }))
input.value = ''
messages.value.push({ type: 'user', text: instruction })
running.value = true
abortController = new AbortController()
await scrollToBottom()
try {
const result = await runDocumentAgent({
editor: editor.value,
instruction,
history,
signal: abortController.signal,
locale: locale.value,
callbacks: {
onToolResult: (name, _result, isError) => {
messages.value.push({ type: 'tool', text: toolLabel(name), isError })
scrollToBottom()
},
},
})
if (result.finalText) {
messages.value.push({ type: 'assistant', text: result.finalText })
} else if (result.toolCallCount > 0) {
messages.value.push({ type: 'assistant', text: t('aiChat.doneNoSummary') })
} else {
messages.value.push({ type: 'error', text: t('aiChat.emptyResponse') })
}
} catch (error) {
if (error instanceof AgentNotConfiguredError) {
messages.value.push({ type: 'error', text: t('aiChat.notConfigured'), showConfigure: true })
} else if (error instanceof DOMException && error.name === 'AbortError') {
messages.value.push({ type: 'error', text: t('aiChat.stopped') })
} else {
const detail = error instanceof Error ? error.message : String(error)
messages.value.push({ type: 'error', text: `${t('aiChat.error')}: ${detail}` })
}
} finally {
running.value = false
abortController = null
await scrollToBottom()
inputRef.value?.focus()
}
}
function stop() {
abortController?.abort()
}
// 面板卸载(编辑器销毁/路由切换)时中止仍在运行的 agent,避免后台继续消耗 API
onBeforeUnmount(() => {
abortController?.abort()
})
/** Enter 发送;中文/日文输入法组合期间的回车(选词确认)不触发 */
function onEnterKey(e: KeyboardEvent) {
if (e.isComposing || e.keyCode === 229) return
e.preventDefault()
send()
}
</script>
<style scoped>
/* ===== 启动按钮 ===== */
.ai-chat-launcher {
position: fixed;
right: 20px;
bottom: 72px;
z-index: 900;
display: flex;
align-items: center;
gap: 6px;
padding: 10px 16px;
border: none;
border-radius: 999px;
background: var(--tiptap-primary, #3b82f6);
color: #fff;
font-size: 14px;
font-weight: 600;
cursor: pointer;
box-shadow: 0 4px 16px rgba(0, 0, 0, 0.18);
transition: transform 0.15s ease, box-shadow 0.15s ease;
}
.ai-chat-launcher:hover {
transform: translateY(-2px);
box-shadow: 0 6px 20px rgba(0, 0, 0, 0.24);
}
/* ===== 面板 ===== */
.ai-chat-panel {
position: fixed;
right: 20px;
bottom: 72px;
z-index: 950;
display: flex;
flex-direction: column;
width: 360px;
max-width: calc(100vw - 40px);
height: 480px;
max-height: calc(100vh - 120px);
border: 1px solid var(--tiptap-border, #e5e7eb);
border-radius: 12px;
background: var(--tiptap-bg, #ffffff);
color: var(--tiptap-text, #1f2937);
box-shadow: 0 12px 40px rgba(0, 0, 0, 0.16);
overflow: hidden;
}
.ai-chat-panel__header {
display: flex;
align-items: center;
justify-content: space-between;
padding: 10px 14px;
border-bottom: 1px solid var(--tiptap-border, #e5e7eb);
background: var(--tiptap-bg-secondary, #f9fafb);
}
.ai-chat-panel__title {
display: flex;
align-items: center;
gap: 6px;
font-size: 14px;
font-weight: 600;
}
.ai-chat-panel__actions {
display: flex;
gap: 4px;
}
.ai-chat-panel__icon-btn {
display: flex;
align-items: center;
justify-content: center;
width: 26px;
height: 26px;
border: none;
border-radius: 6px;
background: transparent;
color: var(--tiptap-text-secondary, #6b7280);
cursor: pointer;
transition: background-color 0.15s ease, color 0.15s ease;
}
.ai-chat-panel__icon-btn:hover {
background: var(--tiptap-toolbar-btn-hover, #e8e8e8);
color: var(--tiptap-text, #1f2937);
}
/* ===== 消息区 ===== */
.ai-chat-panel__messages {
flex: 1;
overflow-y: auto;
padding: 12px;
display: flex;
flex-direction: column;
gap: 8px;
scrollbar-width: thin;
}
.ai-chat-panel__welcome {
padding: 12px;
font-size: 13px;
line-height: 1.6;
color: var(--tiptap-text-secondary, #6b7280);
white-space: pre-line;
}
.ai-chat-msg {
max-width: 90%;
padding: 8px 12px;
border-radius: 10px;
font-size: 13px;
line-height: 1.6;
white-space: pre-wrap;
word-break: break-word;
}
.ai-chat-msg--user {
align-self: flex-end;
background: var(--tiptap-primary, #3b82f6);
color: #fff;
}
.ai-chat-msg--assistant {
align-self: flex-start;
background: var(--tiptap-bg-secondary, #f3f4f6);
}
.ai-chat-msg--error {
align-self: flex-start;
background: rgba(239, 68, 68, 0.1);
color: #dc2626;
}
.ai-chat-step {
display: flex;
align-items: center;
gap: 6px;
align-self: flex-start;
padding: 2px 8px;
font-size: 12px;
color: var(--tiptap-text-secondary, #6b7280);
}
.ai-chat-step--error {
color: #dc2626;
}
.ai-chat-step--running {
color: var(--tiptap-primary, #3b82f6);
}
.ai-chat-panel__configure-btn {
display: block;
margin-top: 6px;
padding: 4px 10px;
border: none;
border-radius: 6px;
background: var(--tiptap-primary, #3b82f6);
color: #fff;
font-size: 12px;
cursor: pointer;
}
/* ===== 输入区 ===== */
.ai-chat-panel__input-area {
display: flex;
align-items: flex-end;
gap: 8px;
padding: 10px 12px;
border-top: 1px solid var(--tiptap-border, #e5e7eb);
}
.ai-chat-panel__input {
flex: 1;
resize: none;
border: 1px solid var(--tiptap-border, #e5e7eb);
border-radius: 8px;
padding: 8px 10px;
font-size: 13px;
font-family: inherit;
line-height: 1.5;
background: var(--tiptap-bg, #fff);
color: var(--tiptap-text, #1f2937);
outline: none;
transition: border-color 0.15s ease;
}
.ai-chat-panel__input:focus {
border-color: var(--tiptap-primary, #3b82f6);
}
.ai-chat-panel__send {
flex-shrink: 0;
padding: 8px 14px;
border: none;
border-radius: 8px;
background: var(--tiptap-primary, #3b82f6);
color: #fff;
font-size: 13px;
font-weight: 500;
cursor: pointer;
transition: opacity 0.15s ease;
}
.ai-chat-panel__send:disabled {
opacity: 0.4;
cursor: not-allowed;
}
.ai-chat-panel__send--stop {
background: #dc2626;
}
/* ===== 出入场动画 ===== */
.ai-chat-slide-enter-active,
.ai-chat-slide-leave-active {
transition: opacity 0.18s ease, transform 0.18s ease;
}
.ai-chat-slide-enter-from,
.ai-chat-slide-leave-to {
opacity: 0;
transform: translateY(12px);
}
/* 暗色模式无需单独覆盖:面板全部取 --tiptap-* 变量,
变量在 :root[data-theme="dark"] 上已翻转,Teleport 到 body 后仍继承生效 */
</style>
@@ -0,0 +1,254 @@
/**
* documentTools 单元测试(无头 Editor)
*/
import { describe, it, expect, beforeEach, afterEach } from 'vitest'
import { Editor } from '@tiptap/core'
import StarterKit from '@tiptap/starter-kit'
import Underline from '@tiptap/extension-underline'
import Highlight from '@tiptap/extension-highlight'
import { TextStyle } from '@tiptap/extension-text-style'
import { Color } from '@tiptap/extension-color'
import { Table } from '@tiptap/extension-table'
import { TableRow } from '@tiptap/extension-table-row'
import { TableHeader } from '@tiptap/extension-table-header'
import { TableCell } from '@tiptap/extension-table-cell'
import { documentTools, getDocumentTool, getDocumentOutline, toOpenAiTools } from '../documentTools'
let editor: Editor
function run(name: string, args: Record<string, unknown> = {}): string {
const tool = getDocumentTool(name)
if (!tool) throw new Error(`tool not found: ${name}`)
return tool.execute(editor, args)
}
beforeEach(() => {
editor = new Editor({
extensions: [
StarterKit,
Underline,
Highlight.configure({ multicolor: true }),
TextStyle,
Color,
Table,
TableRow,
TableHeader,
TableCell,
],
content: '<h1>标题一</h1><p>这是<strong>第一段</strong>正文。</p><p>第二段正文。</p>',
})
})
afterEach(() => {
editor.destroy()
})
describe('read_document / outline', () => {
it('lists blocks with indexes and types', () => {
const result = run('read_document')
expect(result).toContain('3 block(s)')
expect(result).toContain('[0] h1: 标题一')
expect(result).toContain('[1] p: 这是第一段正文。')
expect(result).toContain('[2] p: 第二段正文。')
})
it('outline truncates long blocks', () => {
editor.commands.setContent(`<p>${'长'.repeat(300)}</p>`)
const outline = getDocumentOutline(editor, 100)
expect(outline).toContain('…')
expect(outline.length).toBeLessThan(200)
})
})
describe('get_selection', () => {
it('reports no selection', () => {
expect(run('get_selection')).toContain('No text is selected')
})
it('returns selected text', () => {
editor.commands.setTextSelection({ from: 1, to: 4 })
expect(run('get_selection')).toContain('标题一')
})
})
describe('insert_blocks', () => {
it('inserts at document end', () => {
run('insert_blocks', { html: '<p>新段落</p>', position: 'documentEnd' })
expect(editor.getHTML()).toContain('新段落')
expect(run('read_document')).toContain('[3] p: 新段落')
})
it('inserts before a block', () => {
run('insert_blocks', { html: '<h2>插入的标题</h2>', position: 'beforeBlock', blockIndex: 1 })
expect(run('read_document')).toContain('[1] h2: 插入的标题')
})
it('inserts after a block', () => {
run('insert_blocks', { html: '<p>插在标题后</p>', position: 'afterBlock', blockIndex: 0 })
expect(run('read_document')).toContain('[1] p: 插在标题后')
})
it('inserts a table', () => {
run('insert_blocks', {
html: '<table><tr><th>A</th><th>B</th></tr><tr><td>1</td><td>2</td></tr></table>',
position: 'documentEnd',
})
expect(run('read_document')).toMatch(/table 2x2/)
})
it('rejects empty html', () => {
expect(() => run('insert_blocks', { html: ' ', position: 'documentEnd' })).toThrow()
})
})
describe('replace_blocks', () => {
it('replaces a single block', () => {
run('replace_blocks', { fromBlock: 2, html: '<h2>替换后的标题</h2>' })
const outline = run('read_document')
expect(outline).toContain('[2] h2: 替换后的标题')
expect(outline).not.toContain('第二段正文')
})
it('replaces a range of blocks', () => {
run('replace_blocks', { fromBlock: 1, toBlock: 2, html: '<p>合并成一段</p>' })
const outline = run('read_document')
expect(outline).toContain('2 block(s)')
expect(outline).toContain('[1] p: 合并成一段')
})
it('rejects out-of-range indexes with helpful error', () => {
expect(() => run('replace_blocks', { fromBlock: 99, html: '<p>x</p>' })).toThrow(/0-2/)
})
})
describe('delete_blocks', () => {
it('deletes one block', () => {
run('delete_blocks', { fromBlock: 0 })
const outline = run('read_document')
expect(outline).toContain('2 block(s)')
expect(outline).not.toContain('标题一')
})
it('deletes a range (trailing empty paragraph is kept by the editor)', () => {
run('delete_blocks', { fromBlock: 1, toBlock: 2 })
const outline = run('read_document')
// StarterKit 的 TrailingNode 会在文档尾部保留一个空段落,属编辑器交互设计
expect(outline).toContain('标题一')
expect(outline).not.toContain('第二段')
expect(outline).not.toContain('第一段')
})
})
describe('edit_text', () => {
it('replaces first occurrence and keeps formatting around', () => {
run('edit_text', { find: '第一段', replace: '首段' })
const html = editor.getHTML()
expect(html).toContain('首段')
expect(html).not.toContain('第一段')
// 加粗标记仍存在
expect(html).toContain('<strong>')
})
it('matches text spanning mark boundaries', () => {
// "这是第一段" 跨越 普通文本("这是") 和 strong("第一段")
run('edit_text', { find: '这是第一段', replace: '本段' })
expect(editor.state.doc.textContent).toContain('本段正文')
})
it('replaces the nth occurrence', () => {
editor.commands.setContent('<p>苹果一</p><p>苹果二</p>')
run('edit_text', { find: '苹果', replace: '香蕉', occurrence: 2 })
const text = editor.state.doc.textContent
expect(text).toContain('苹果一')
expect(text).toContain('香蕉二')
})
it('replaceAll replaces every occurrence', () => {
editor.commands.setContent('<p>猫和猫与猫</p>')
const result = run('edit_text', { find: '猫', replace: '狗', replaceAll: true })
expect(result).toContain('3 occurrence(s)')
expect(editor.state.doc.textContent).toBe('狗和狗与狗')
})
it('replaceAll where replacement contains the find replaces each original match exactly once', () => {
// 'a' → 'aa':不能指数膨胀,每个原始匹配只替换一次
editor.commands.setContent('<p>a和a与a</p>')
const result = run('edit_text', { find: 'a', replace: 'aa', replaceAll: true })
expect(result).toContain('3 occurrence(s)')
expect(editor.state.doc.textContent).toBe('aa和aa与aa')
})
it('does not match text spanning table cells', () => {
editor.commands.setContent('<table><tr><td>价格</td><td>100</td></tr></table>')
// '格100' 跨两个单元格,不应视为匹配
expect(() => run('edit_text', { find: '格100', replace: 'x' })).toThrow(/not found/i)
// 单元格内部的文本仍可正常匹配
run('edit_text', { find: '100', replace: '200' })
expect(editor.state.doc.textContent).toContain('200')
})
it('throws when multiple matches and no occurrence is given', () => {
editor.commands.setContent('<p>苹果一</p><p>苹果二</p>')
expect(() => run('edit_text', { find: '苹果', replace: '香蕉' })).toThrow(/occurrence \(1-2\)/i)
// 文档未被修改
expect(editor.state.doc.textContent).toContain('苹果一')
expect(editor.state.doc.textContent).toContain('苹果二')
})
it('throws helpful error when text not found', () => {
expect(() => run('edit_text', { find: '不存在的文字', replace: 'x' })).toThrow(/not found/i)
})
})
describe('format_text', () => {
it('applies bold and italic', () => {
run('format_text', { find: '第二段', formats: ['bold', 'italic'] })
expect(editor.getHTML()).toMatch(/<(strong|em)>.*<(strong|em)>?/)
const html = editor.getHTML()
expect(html).toContain('strong')
expect(html).toContain('em')
})
it('removes bold', () => {
run('format_text', { find: '第一段', formats: ['bold'], action: 'remove' })
expect(editor.getHTML()).not.toContain('<strong>')
})
it('applies text color', () => {
run('format_text', { find: '标题一', formats: ['textColor'], color: '#ff0000' })
expect(editor.getHTML()).toContain('#ff0000')
})
it('applies highlight with color', () => {
run('format_text', { find: '第二段', formats: ['highlight'], color: '#ffff00' })
expect(editor.getHTML()).toContain('mark')
})
it('throws when multiple matches and no occurrence is given', () => {
editor.commands.setContent('<p>重点</p><p>重点</p>')
expect(() => run('format_text', { find: '重点', formats: ['bold'] })).toThrow(/occurrence \(1-2\)/i)
})
it('removes textColor by clearing only the color attribute (no throw, color gone)', () => {
run('format_text', { find: '标题一', formats: ['textColor'], color: '#ff0000' })
expect(editor.getHTML()).toContain('#ff0000')
// remove 走 setMark('textStyle', { color: null }),不 unsetMark 整个 textStyle,
// 以免连带清掉 fontSize/fontFamily 等其它 textStyle 属性(本测试环境无 fontSize 扩展,
// 仅验证不抛错且颜色被移除)
run('format_text', { find: '标题一', formats: ['textColor'], action: 'remove' })
expect(editor.getHTML()).not.toContain('#ff0000')
})
})
describe('OpenAI tools export', () => {
it('produces valid function definitions', () => {
const tools = toOpenAiTools()
expect(tools).toHaveLength(documentTools.length)
for (const t of tools) {
expect(t.type).toBe('function')
expect(t.function.name).toBeTruthy()
expect(t.function.description).toBeTruthy()
expect(t.function.parameters).toHaveProperty('type', 'object')
}
})
})
+260
View File
@@ -0,0 +1,260 @@
/**
* Document Agent Loop - 文档编辑 AI Agent 循环
* @description 基于 OpenAI function-calling 格式的 tool-use 循环:
* 模型收到用户的自然语言指令 → 调用 documentTools 修改文档 → 直到给出最终答复。
* 所有已支持的 provider(OpenAI/Anthropic/DeepSeek/阿里云/Ollama/自定义)都走
* OpenAI 兼容的 /chat/completions(Anthropic 官方提供 OpenAI 兼容层)。
*/
import type { Editor } from '@tiptap/core'
import { getAiConfig, getBaseUrl } from '@/api/ai'
import { getProviderInfo, type AiProvider } from '@/ai/config/types'
import { documentTools, toOpenAiTools, type DocumentTool } from './documentTools'
// ============================================================================
// 类型
// ============================================================================
/** 对话消息(OpenAI chat 格式的子集) */
export interface AgentChatMessage {
role: 'system' | 'user' | 'assistant' | 'tool'
content: string | null
tool_calls?: Array<{
id: string
type: 'function'
function: { name: string; arguments: string }
}>
tool_call_id?: string
}
/** agent 过程事件回调(驱动 UI 展示步骤) */
export interface AgentCallbacks {
/** 模型请求执行某个工具(执行前触发) */
onToolCall?: (name: string, args: Record<string, unknown>) => void
/** 工具执行完成(成功或失败) */
onToolResult?: (name: string, result: string, isError: boolean) => void
/** 模型输出了最终文本答复 */
onAssistantMessage?: (text: string) => void
}
export interface RunDocumentAgentOptions {
editor: Editor
/** 用户的自然语言指令 */
instruction: string
/** 既往对话(仅 user/assistant 文本轮次,用于多轮上下文) */
history?: Array<{ role: 'user' | 'assistant'; content: string }>
/** 中断信号(停止按钮) */
signal?: AbortSignal
/** 最大工具调用轮数,默认 12 */
maxTurns?: number
/** 界面语言,用于提示模型用同语言答复 */
locale?: string
/** 自定义工具集(默认 documentTools 全集) */
tools?: DocumentTool[]
callbacks?: AgentCallbacks
}
export interface DocumentAgentResult {
/** 模型的最终文字答复 */
finalText: string
/** 执行过的工具调用数 */
toolCallCount: number
}
/** AI 未配置(无 API Key)时抛出,UI 捕获后引导用户去配置 */
export class AgentNotConfiguredError extends Error {
constructor() {
super('AI is not configured: missing API key.')
this.name = 'AgentNotConfiguredError'
}
}
// ============================================================================
// 系统提示词
// ============================================================================
function buildSystemPrompt(locale?: string): string {
return [
'You are a document editing assistant embedded in a rich-text editor.',
'The user gives natural-language instructions; you edit the document by calling tools.',
'',
'Workflow:',
'1. Call read_document first to see the document structure and block indexes.',
'2. Make edits with the editing tools. Block indexes change after every edit — rely on the "Document now" outline returned by each tool, or call read_document again.',
'3. When done, reply with a brief summary of what you changed (no raw HTML in the reply).',
'',
'Rules:',
'- Keep HTML simple: p, h1-h6, ul/ol/li, table/tr/th/td, blockquote, pre/code, strong, em, u, s, a, hr.',
'- Prefer edit_text/format_text for small inline changes; replace_blocks for structural rewrites.',
'- Never fabricate document content you have not read.',
'- If the instruction is ambiguous, make a reasonable choice and mention it in your summary.',
`- Reply to the user in ${locale === 'zh-CN' ? 'Simplified Chinese' : locale === 'zh-TW' ? 'Traditional Chinese' : 'the same language as their instruction'}.`,
].join('\n')
}
// ============================================================================
// 主循环
// ============================================================================
const DEFAULT_MAX_TURNS = 12
/** 工具结果里文档概要的起始标记(与 documentTools 的 okWithOutline 对齐) */
const OUTLINE_MARKER = '\nDocument now:\n'
/** 把历史 tool 消息中已过期的文档概要截断,避免每轮重复携带旧概要导致上下文膨胀 */
function supersedeOldOutlines(messages: AgentChatMessage[]): void {
for (const m of messages) {
if (m.role !== 'tool' || typeof m.content !== 'string') continue
const idx = m.content.indexOf(OUTLINE_MARKER)
if (idx === -1) continue
m.content = `${m.content.slice(0, idx)}\n(outline superseded by a later edit)`
}
}
/**
* 运行文档编辑 agent
* @description 阻塞直到模型给出最终答复、达到轮数上限或被 signal 中断。
* 编辑通过 editor 事务实时生效(用户可随时 Cmd+Z 撤销)。
*/
export async function runDocumentAgent(options: RunDocumentAgentOptions): Promise<DocumentAgentResult> {
const {
editor,
instruction,
history = [],
signal,
maxTurns = DEFAULT_MAX_TURNS,
locale,
tools = documentTools,
callbacks = {},
} = options
const config = getAiConfig()
// 仅当 provider 必需 API Key 而用户未配置时才算「未配置」(如 Ollama 本地无需 key)
const providerInfo = getProviderInfo(config.provider as AiProvider)
if ((providerInfo?.requiresApiKey ?? true) && !config.apiKey) {
throw new AgentNotConfiguredError()
}
const baseUrl = getBaseUrl(config.provider, config.baseUrl)
const timeout = config.timeout || 60000
const openAiTools = toOpenAiTools(tools)
// apiKey 为空(如 Ollama)时省略 Authorization header
const headers: Record<string, string> = { 'Content-Type': 'application/json' }
if (config.apiKey) headers.Authorization = `Bearer ${config.apiKey}`
const messages: AgentChatMessage[] = [
{ role: 'system', content: buildSystemPrompt(locale) },
...history.map((m) => ({ role: m.role, content: m.content }) as AgentChatMessage),
{ role: 'user', content: instruction },
]
let toolCallCount = 0
for (let turn = 0; turn < maxTurns; turn++) {
if (editor.isDestroyed) throw new Error('Editor was destroyed while the agent was running.')
// 超时兜底:手动组合外部 signal 与超时信号(AbortSignal.any 的兼容写法)
const timeoutController = new AbortController()
const timer = setTimeout(() => timeoutController.abort(), timeout)
const onExternalAbort = () => timeoutController.abort()
if (signal?.aborted) timeoutController.abort()
else signal?.addEventListener('abort', onExternalAbort)
let data: { choices?: Array<{ message?: Record<string, unknown> }> }
try {
const response = await fetch(`${baseUrl}/chat/completions`, {
method: 'POST',
headers,
body: JSON.stringify({
model: config.model,
messages,
tools: openAiTools,
tool_choice: 'auto',
}),
signal: timeoutController.signal,
})
if (!response.ok) {
const body = await response.text().catch(() => '')
throw new Error(`AI API error ${response.status}: ${body.slice(0, 300) || response.statusText}`)
}
data = await response.json()
} catch (error) {
// 用户主动停止:让 AbortError 冒泡;否则 abort 只可能来自超时
if ((error as Error | null)?.name === 'AbortError' && !signal?.aborted) {
throw new Error('AI request timeout')
}
throw error
} finally {
clearTimeout(timer)
signal?.removeEventListener('abort', onExternalAbort)
}
const message = data.choices?.[0]?.message as
| { content?: unknown; tool_calls?: AgentChatMessage['tool_calls'] }
| undefined
if (!message) throw new Error('AI API returned no message.')
const toolCalls = message.tool_calls
if (!toolCalls || toolCalls.length === 0) {
// 最终答复
const finalText = typeof message.content === 'string' ? message.content : ''
if (finalText) callbacks.onAssistantMessage?.(finalText)
return { finalText, toolCallCount }
}
// 记录 assistant 的工具调用消息
messages.push({
role: 'assistant',
content: typeof message.content === 'string' ? message.content : null,
tool_calls: toolCalls,
})
// 逐个执行工具
for (const call of toolCalls) {
if (signal?.aborted) throw new DOMException('Aborted', 'AbortError')
if (editor.isDestroyed) throw new Error('Editor was destroyed while the agent was running.')
const name = call.function?.name || ''
let args: Record<string, unknown> = {}
try {
args = call.function?.arguments ? JSON.parse(call.function.arguments) : {}
} catch {
// 参数解析失败也要回传给模型让它重试
}
callbacks.onToolCall?.(name, args)
toolCallCount++
let result: string
let isError = false
const tool = tools.find((t) => t.name === name)
if (!tool) {
result = `Error: unknown tool "${name}". Available: ${tools.map((t) => t.name).join(', ')}`
isError = true
} else {
try {
result = tool.execute(editor, args)
} catch (error) {
result = `Error: ${error instanceof Error ? error.message : String(error)}`
isError = true
}
}
callbacks.onToolResult?.(name, result, isError)
// 控制历史膨胀:旧工具结果里的文档概要已过期,截断为占位说明,
// 每轮请求只携带最新一份概要
supersedeOldOutlines(messages)
messages.push({ role: 'tool', tool_call_id: call.id, content: result })
}
}
// 达到轮数上限:让模型知道并收尾会更好,但为控制成本直接返回
return {
finalText: '',
toolCallCount,
}
}
+467
View File
@@ -0,0 +1,467 @@
/**
* Document Tools - AI 文档编辑工具集
* @description 把编辑器的基本操作封装成结构化「工具」(OpenAI function-calling 格式),
* 供 AI agent 通过 tool-use 循环调用,实现「用文字描述来编写和修改文档」。
*
* 寻址设计:
* - 块级操作用「块索引」(文档顶层节点的序号,read_document 返回)
* - 行内操作用「文本查找」(find + occurrence),不暴露脆弱的 ProseMirror 位置
* - 每次修改后返回最新文档概要,模型无需再调 read_document 对齐索引
*/
import type { Editor } from '@tiptap/core'
// ============================================================================
// 类型
// ============================================================================
/** 工具定义(parameters 为 JSON Schema,与 OpenAI function calling 对齐) */
export interface DocumentTool {
name: string
description: string
parameters: Record<string, unknown>
/** 执行工具,返回给模型看的结果文本;抛错时错误信息也会回传给模型 */
execute: (editor: Editor, args: Record<string, unknown>) => string
}
interface BlockInfo {
index: number
/** 节点起点前的位置(block 边界) */
from: number
/** 节点终点后的位置 */
to: number
node: import('@tiptap/pm/model').Node
}
// ============================================================================
// 内部工具函数
// ============================================================================
/** 收集文档顶层块 */
function getBlocks(editor: Editor): BlockInfo[] {
const blocks: BlockInfo[] = []
editor.state.doc.forEach((node, offset, index) => {
blocks.push({ index, from: offset, to: offset + node.nodeSize, node })
})
return blocks
}
/** 单个块的简短描述(类型 + 截断文本) */
function describeBlock(node: import('@tiptap/pm/model').Node, maxLen: number): string {
let type = node.type.name
if (type === 'heading') type = `h${node.attrs.level}`
else if (type === 'paragraph') type = 'p'
else if (type === 'bulletList') type = 'ul'
else if (type === 'orderedList') type = 'ol'
else if (type === 'codeBlock') type = `code(${node.attrs.language || 'text'})`
else if (type === 'table') {
const rows = node.childCount
const cols = rows > 0 ? node.firstChild!.childCount : 0
return `table ${rows}x${cols}: ${truncate(node.textContent, maxLen)}`
}
const text = node.textContent.trim()
return text ? `${type}: ${truncate(text, maxLen)}` : `${type}: (empty)`
}
function truncate(text: string, maxLen: number): string {
const t = text.replace(/\s+/g, ' ').trim()
return t.length > maxLen ? `${t.slice(0, maxLen)}…` : t
}
/** 文档概要:[i] type: text(模型用它获得块索引) */
export function getDocumentOutline(editor: Editor, maxLenPerBlock = 150, maxBlocks = 300): string {
const blocks = getBlocks(editor)
if (blocks.length === 0) return '(document is empty)'
const lines = blocks
.slice(0, maxBlocks)
.map((b) => `[${b.index}] ${describeBlock(b.node, maxLenPerBlock)}`)
if (blocks.length > maxBlocks) {
lines.push(`… (${blocks.length - maxBlocks} more blocks omitted)`)
}
return lines.join('\n')
}
/** 修改成功后返回给模型的统一结果(附最新概要,避免索引漂移) */
function okWithOutline(editor: Editor, message: string): string {
return `${message}\nDocument now:\n${getDocumentOutline(editor, 80)}`
}
/** 校验并解析块索引范围 */
function resolveBlockRange(
editor: Editor,
fromBlock: number,
toBlock?: number
): { from: number; to: number; count: number } {
const blocks = getBlocks(editor)
const last = typeof toBlock === 'number' ? toBlock : fromBlock
if (
!Number.isInteger(fromBlock) ||
!Number.isInteger(last) ||
fromBlock < 0 ||
last >= blocks.length ||
fromBlock > last
) {
throw new Error(
`Invalid block range [${fromBlock}, ${last}]. Document has ${blocks.length} blocks (0-${blocks.length - 1}). Call read_document to get fresh indexes.`
)
}
return { from: blocks[fromBlock].from, to: blocks[last].to, count: last - fromBlock + 1 }
}
interface TextMatch {
from: number
to: number
/** 匹配所在顶层块索引(用于多匹配歧义提示) */
blockIndex: number
}
/**
* 扫描全文,返回 find 文本的所有匹配区间(绝对位置)。
* 支持跨行内节点边界(如一半加粗一半普通)的匹配;
* 在块级结构边界(嵌套段落/表格单元格)和硬换行处插入不可匹配的哨兵字符,
* 避免「相邻单元格文本拼起来恰好等于 find」这类跨结构假匹配。
*/
function findAllTextRanges(editor: Editor, find: string): TextMatch[] {
if (!find) throw new Error('`find` must be a non-empty string.')
const doc = editor.state.doc
// 逐块拼接文本并记录每个字符的绝对位置,避免跨块误匹配
const matches: TextMatch[] = []
doc.forEach((block, blockOffset, blockIndex) => {
let text = ''
const positions: number[] = []
block.descendants((node, pos) => {
if (node.isText && node.text) {
for (let i = 0; i < node.text.length; i++) {
text += node.text[i]
// +1 跳过块的开始 token
positions.push(blockOffset + 1 + pos + i)
}
} else if (node.isBlock || node.type.name === 'hardBreak') {
// 结构边界:用户的 find 不会包含 \u0000,跨边界的假匹配自然失配
if (text) {
text += '\u0000'
positions.push(-1)
}
}
return true
})
let idx = text.indexOf(find)
while (idx !== -1) {
matches.push({
from: positions[idx],
to: positions[idx + find.length - 1] + 1,
blockIndex,
})
idx = text.indexOf(find, idx + 1)
}
})
return matches
}
/**
* 解析出唯一目标匹配。
* occurrence 未显式传入且存在多个匹配时抛错要求消歧,避免默默改错位置。
*/
function resolveSingleMatch(
editor: Editor,
find: string,
occurrence: number | undefined
): { from: number; to: number } {
const matches = findAllTextRanges(editor, find)
if (matches.length === 0) {
throw new Error(`Text not found: "${truncate(find, 60)}". Check exact wording with read_document.`)
}
if (occurrence === undefined) {
if (matches.length > 1) {
const blocks = [...new Set(matches.map((m) => m.blockIndex))].join(', ')
throw new Error(
`Found ${matches.length} matches for "${truncate(find, 60)}" (in block(s) ${blocks}). Pass occurrence (1-${matches.length}) to disambiguate.`
)
}
return matches[0]
}
if (!Number.isInteger(occurrence) || occurrence < 1 || occurrence > matches.length) {
throw new Error(`Occurrence ${occurrence} out of range: only ${matches.length} match(es) found.`)
}
return matches[occurrence - 1]
}
// ============================================================================
// 工具定义
// ============================================================================
const readDocument: DocumentTool = {
name: 'read_document',
description:
'Read the current document as an outline of top-level blocks with their indexes. Always call this first to understand the document and get fresh block indexes.',
parameters: { type: 'object', properties: {}, additionalProperties: false },
execute: (editor) => {
const blocks = getBlocks(editor)
return `Document has ${blocks.length} block(s):\n${getDocumentOutline(editor)}`
},
}
const getSelection: DocumentTool = {
name: 'get_selection',
description:
"Get the user's currently selected text, if any. Useful when the user refers to “the selected text” / “选中的文字”.",
parameters: { type: 'object', properties: {}, additionalProperties: false },
execute: (editor) => {
const { from, to, empty } = editor.state.selection
if (empty) return 'No text is selected.'
const text = editor.state.doc.textBetween(from, to, '\n')
return `Selected text (${text.length} chars): "${truncate(text, 2000)}"`
},
}
const insertBlocks: DocumentTool = {
name: 'insert_blocks',
description:
'Insert new content into the document as HTML. Supported tags: p, h1-h6, ul/ol/li, table/tr/th/td, blockquote, pre/code, strong, em, u, s, a, img, hr. Keep HTML simple and valid.',
parameters: {
type: 'object',
properties: {
html: { type: 'string', description: 'HTML content to insert' },
position: {
type: 'string',
enum: ['documentStart', 'documentEnd', 'beforeBlock', 'afterBlock'],
description: 'Where to insert',
},
blockIndex: {
type: 'number',
description: 'Required when position is beforeBlock/afterBlock: the anchor block index',
},
},
required: ['html', 'position'],
additionalProperties: false,
},
execute: (editor, args) => {
const html = String(args.html || '')
if (!html.trim()) throw new Error('`html` must not be empty.')
const position = String(args.position)
let pos: number
if (position === 'documentStart') {
pos = 0
} else if (position === 'documentEnd') {
pos = editor.state.doc.content.size
} else if (position === 'beforeBlock' || position === 'afterBlock') {
const blockIndex = Number(args.blockIndex)
const range = resolveBlockRange(editor, blockIndex)
pos = position === 'beforeBlock' ? range.from : range.to
} else {
throw new Error(`Unknown position: ${position}`)
}
const ok = editor.chain().insertContentAt(pos, html).run()
if (!ok) throw new Error('Insert failed: the HTML may be invalid for this position.')
return okWithOutline(editor, 'Inserted.')
},
}
const replaceBlocks: DocumentTool = {
name: 'replace_blocks',
description:
'Replace a range of top-level blocks (inclusive) with new HTML content. Use read_document indexes.',
parameters: {
type: 'object',
properties: {
fromBlock: { type: 'number', description: 'First block index to replace' },
toBlock: { type: 'number', description: 'Last block index (defaults to fromBlock)' },
html: { type: 'string', description: 'Replacement HTML content' },
},
required: ['fromBlock', 'html'],
additionalProperties: false,
},
execute: (editor, args) => {
const html = String(args.html || '')
if (!html.trim()) throw new Error('`html` must not be empty. To remove blocks use delete_blocks.')
const { from, to, count } = resolveBlockRange(
editor,
Number(args.fromBlock),
args.toBlock === undefined ? undefined : Number(args.toBlock)
)
const ok = editor.chain().insertContentAt({ from, to }, html).run()
if (!ok) throw new Error('Replace failed: the HTML may be invalid.')
return okWithOutline(editor, `Replaced ${count} block(s).`)
},
}
const deleteBlocks: DocumentTool = {
name: 'delete_blocks',
description: 'Delete a range of top-level blocks (inclusive). Use read_document indexes.',
parameters: {
type: 'object',
properties: {
fromBlock: { type: 'number', description: 'First block index to delete' },
toBlock: { type: 'number', description: 'Last block index (defaults to fromBlock)' },
},
required: ['fromBlock'],
additionalProperties: false,
},
execute: (editor, args) => {
const { from, to, count } = resolveBlockRange(
editor,
Number(args.fromBlock),
args.toBlock === undefined ? undefined : Number(args.toBlock)
)
const ok = editor.chain().deleteRange({ from, to }).run()
if (!ok) throw new Error('Delete failed.')
return okWithOutline(editor, `Deleted ${count} block(s).`)
},
}
const editText: DocumentTool = {
name: 'edit_text',
description:
'Replace an exact text snippet with new plain text (keeps surrounding formatting). For structural changes use replace_blocks instead.',
parameters: {
type: 'object',
properties: {
find: { type: 'string', description: 'Exact text to find (case-sensitive)' },
replace: { type: 'string', description: 'Replacement plain text (may be empty to delete)' },
occurrence: {
type: 'number',
description:
'Which match to replace, 1-based. Required when there are multiple matches (unless replaceAll).',
},
replaceAll: { type: 'boolean', description: 'Replace every match. Default false.' },
},
required: ['find', 'replace'],
additionalProperties: false,
},
execute: (editor, args) => {
const find = String(args.find ?? '')
const replace = String(args.replace ?? '')
if (args.replaceAll) {
// 一次性收集全部区间,单条事务里从后往前替换:
// 前面的位置不受影响、每个原始匹配恰好替换一次、一次 Cmd+Z 可全部撤销
const matches = findAllTextRanges(editor, find)
if (matches.length === 0) throw new Error(`Text not found: "${truncate(find, 60)}"`)
editor
.chain()
.command(({ tr }) => {
for (let i = matches.length - 1; i >= 0; i--) {
tr.insertText(replace, matches[i].from, matches[i].to)
}
return true
})
.run()
return okWithOutline(editor, `Replaced ${matches.length} occurrence(s).`)
}
const occurrence = args.occurrence === undefined ? undefined : Number(args.occurrence)
const { from, to } = resolveSingleMatch(editor, find, occurrence)
editor
.chain()
.command(({ tr }) => {
tr.insertText(replace, from, to)
return true
})
.run()
return okWithOutline(editor, 'Text replaced.')
},
}
/** 行内格式 → mark 名与属性 */
const FORMAT_MARKS: Record<string, { mark: string; attrs?: (args: Record<string, unknown>) => Record<string, unknown> }> = {
bold: { mark: 'bold' },
italic: { mark: 'italic' },
underline: { mark: 'underline' },
strike: { mark: 'strike' },
code: { mark: 'code' },
highlight: {
mark: 'highlight',
attrs: (args) => (args.color ? { color: String(args.color) } : {}),
},
textColor: {
mark: 'textStyle',
attrs: (args) => ({ color: String(args.color || '#000000') }),
},
}
const formatText: DocumentTool = {
name: 'format_text',
description:
'Add or remove inline formatting on an exact text snippet. Formats: bold, italic, underline, strike, code, highlight, textColor. For highlight/textColor pass `color` (hex).',
parameters: {
type: 'object',
properties: {
find: { type: 'string', description: 'Exact text to format (case-sensitive)' },
occurrence: {
type: 'number',
description: 'Which match, 1-based. Required when there are multiple matches.',
},
formats: {
type: 'array',
items: {
type: 'string',
enum: ['bold', 'italic', 'underline', 'strike', 'code', 'highlight', 'textColor'],
},
description: 'Formats to apply or remove',
},
action: { type: 'string', enum: ['add', 'remove'], description: 'Default add' },
color: { type: 'string', description: 'Hex color for highlight/textColor' },
},
required: ['find', 'formats'],
additionalProperties: false,
},
execute: (editor, args) => {
const find = String(args.find ?? '')
const occurrence = args.occurrence === undefined ? undefined : Number(args.occurrence)
const formats = Array.isArray(args.formats) ? args.formats.map(String) : []
if (formats.length === 0) throw new Error('`formats` must not be empty.')
const action = args.action === 'remove' ? 'remove' : 'add'
const { from, to } = resolveSingleMatch(editor, find, occurrence)
let chain = editor.chain().setTextSelection({ from, to })
for (const format of formats) {
const def = FORMAT_MARKS[format]
if (!def) throw new Error(`Unknown format: ${format}`)
if (action === 'add') {
chain = chain.setMark(def.mark, def.attrs ? def.attrs(args) : undefined)
} else if (format === 'textColor') {
// 不能 unsetMark('textStyle'):会连带清掉 fontSize/fontFamily 等其它 textStyle 属性
chain = chain.setMark('textStyle', { color: null })
} else {
chain = chain.unsetMark(def.mark)
}
}
const ok = chain.setTextSelection(to).run()
if (!ok) {
throw new Error(
`Formatting failed. The "${formats.join(', ')}" mark(s) may not be enabled in this editor.`
)
}
return okWithOutline(editor, `Formatting ${action === 'add' ? 'applied' : 'removed'}.`)
},
}
// ============================================================================
// 导出
// ============================================================================
/** 所有文档编辑工具(顺序即推荐调用优先级) */
export const documentTools: DocumentTool[] = [
readDocument,
getSelection,
insertBlocks,
replaceBlocks,
deleteBlocks,
editText,
formatText,
]
/** 按名称查找工具 */
export function getDocumentTool(name: string): DocumentTool | undefined {
return documentTools.find((t) => t.name === name)
}
/** 转成 OpenAI function-calling 的 tools 数组 */
export function toOpenAiTools(tools: DocumentTool[] = documentTools) {
return tools.map((t) => ({
type: 'function' as const,
function: { name: t.name, description: t.description, parameters: t.parameters },
}))
}
+23
View File
@@ -0,0 +1,23 @@
/**
* AI Document Agent - 文字指令编辑文档
* @description 把编辑器基本操作封装为结构化工具集,AI 通过 tool-use 循环
* 按用户的自然语言指令编写和修改文档。
*/
export {
documentTools,
getDocumentTool,
getDocumentOutline,
toOpenAiTools,
} from './documentTools'
export type { DocumentTool } from './documentTools'
export { runDocumentAgent, AgentNotConfiguredError } from './agentLoop'
export type {
AgentCallbacks,
AgentChatMessage,
DocumentAgentResult,
RunDocumentAgentOptions,
} from './agentLoop'
export { default as AiChatPanel } from './AiChatPanel.vue'
+5
View File
@@ -33,6 +33,7 @@
class="ai-settings__input"
/>
<p class="ai-settings__hint">{{ t('aiSettings.apiKeyHint') }}</p>
<p class="ai-settings__hint ai-settings__hint--warning">{{ t('aiSettings.securityNote') }}</p>
</div>
<!-- 自定义端点 -->
@@ -301,6 +302,10 @@ function handleClose() {
color: var(--primary-color, #1890ff);
}
.ai-settings__hint--warning {
color: var(--warning-color, #d48806);
}
.ai-settings__error {
margin: 0;
font-size: 12px;
-9
View File
@@ -1,9 +0,0 @@
import type { Editor } from '@tiptap/vue-3';
import type { AiAdapter } from '@/ai';
interface Props {
editor: Editor | null;
adapter: AiAdapter;
}
declare const _default: import("vue").DefineComponent<Props, {}, {}, {}, {}, import("vue").ComponentOptionsMixin, import("vue").ComponentOptionsMixin, {}, string, import("vue").PublicProps, Readonly<Props> & Readonly<{}>, {}, {}, {}, {}, string, import("vue").ComponentProvideOptions, false, {}, any>;
export default _default;
//# sourceMappingURL=AiToolbarMenu.vue.d.ts.map
@@ -1 +0,0 @@
{"version":3,"file":"AiToolbarMenu.vue.d.ts","sourceRoot":"","sources":["AiToolbarMenu.vue"],"names":[],"mappings":"AA6VA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,eAAe,CAAA;AAI3C,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,MAAM,CAAA;AAErC,UAAU,KAAK;IACb,MAAM,EAAE,MAAM,GAAG,IAAI,CAAA;IACrB,OAAO,EAAE,SAAS,CAAA;CACnB;;AAgSD,wBAMG"}
-5
View File
@@ -1,5 +0,0 @@
/**
* AI Components Entry
*/
export { default as AiToolbarMenu } from './AiToolbarMenu.vue';
//# sourceMappingURL=index.d.ts.map
-1
View File
@@ -1 +0,0 @@
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,EAAE,OAAO,IAAI,aAAa,EAAE,MAAM,qBAAqB,CAAA"}
-14
View File
@@ -1,14 +0,0 @@
/**
* AI Config Loader
* Load AI configuration from environment variables
*/
import type { AiConfig } from './types';
/**
* Load AI configuration from environment variables
*/
export declare function loadAiConfig(): AiConfig;
/**
* Create AI config manually
*/
export declare function createAiConfig(config: Partial<AiConfig>): AiConfig;
//# sourceMappingURL=config.d.ts.map
-1
View File
@@ -1 +0,0 @@
{"version":3,"file":"config.d.ts","sourceRoot":"","sources":["config.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,KAAK,EAAE,QAAQ,EAAc,MAAM,SAAS,CAAA;AAiDnD;;GAEG;AACH,wBAAgB,YAAY,IAAI,QAAQ,CAYvC;AAED;;GAEG;AACH,wBAAgB,cAAc,CAAC,MAAM,EAAE,OAAO,CAAC,QAAQ,CAAC,GAAG,QAAQ,CAYlE"}
+93
View File
@@ -0,0 +1,93 @@
/**
* AI 配置存储单元测试
*/
import { describe, it, expect, beforeEach } from 'vitest'
import { createAiConfigStore } from '../store'
import type { AiUserConfig } from '../types'
function makeConfig(overrides: Partial<AiUserConfig> = {}): AiUserConfig {
return {
provider: 'openai',
apiKey: 'sk-test-1234567890',
endpoint: '',
model: 'gpt-4o-mini',
timeout: 30000,
enabled: true,
updatedAt: 0,
...overrides,
}
}
describe('AI config store', () => {
beforeEach(() => {
localStorage.clear()
})
it('returns null before anything is saved', () => {
const store = createAiConfigStore()
expect(store.getConfig()).toBeNull()
expect(store.getApiKey()).toBeNull()
expect(store.isConfigured()).toBe(false)
})
it('round-trips config including the API key', () => {
const store = createAiConfigStore()
store.saveConfig(makeConfig())
const loaded = store.getConfig()
expect(loaded).not.toBeNull()
expect(loaded!.provider).toBe('openai')
expect(loaded!.model).toBe('gpt-4o-mini')
expect(loaded!.apiKey).toBe('sk-test-1234567890')
})
it('round-trips API keys containing unicode/special characters', () => {
const store = createAiConfigStore()
store.saveConfig(makeConfig({ apiKey: 'key-带中文-!@#$%^&*()' }))
expect(store.getApiKey()).toBe('key-带中文-!@#$%^&*()')
})
it('does not store the API key in plain text', () => {
const store = createAiConfigStore()
store.saveConfig(makeConfig())
const raw = Object.keys(localStorage)
.map((k) => localStorage.getItem(k))
.join('|')
expect(raw).not.toContain('sk-test-1234567890')
})
it('clearConfig removes both config and API key', () => {
const store = createAiConfigStore()
store.saveConfig(makeConfig())
store.clearConfig()
expect(store.getConfig()).toBeNull()
expect(store.getApiKey()).toBeNull()
})
describe('isConfigured()', () => {
it('is true for a complete enabled config', () => {
const store = createAiConfigStore()
store.saveConfig(makeConfig())
expect(store.isConfigured()).toBe(true)
})
it('is false when disabled', () => {
const store = createAiConfigStore()
store.saveConfig(makeConfig({ enabled: false }))
expect(store.isConfigured()).toBe(false)
})
it('is false when the provider requires an API key and none is set', () => {
const store = createAiConfigStore()
store.saveConfig(makeConfig({ apiKey: '' }))
expect(store.isConfigured()).toBe(false)
})
it('requires an endpoint for the custom provider', () => {
const store = createAiConfigStore()
store.saveConfig(makeConfig({ provider: 'custom', endpoint: '' }))
expect(store.isConfigured()).toBe(false)
store.saveConfig(makeConfig({ provider: 'custom', endpoint: 'https://my-llm.example.com/v1' }))
expect(store.isConfigured()).toBe(true)
})
})
})
+1 -1
View File
@@ -132,7 +132,7 @@ export const AI_PROVIDERS: AiProviderInfo[] = [
id: 'ollama',
name: 'Ollama (本地)',
description: '本地运行的开源模型',
defaultEndpoint: 'http://localhost:11434/api',
defaultEndpoint: 'http://localhost:11434/v1',
defaultModel: 'llama3.2',
requiresApiKey: false,
docsUrl: 'https://ollama.com/docs',
@@ -1,7 +0,0 @@
type __VLS_Props = {
title: string;
onClick: () => void;
};
declare const _default: import("vue").DefineComponent<__VLS_Props, {}, {}, {}, {}, import("vue").ComponentOptionsMixin, import("vue").ComponentOptionsMixin, {}, string, import("vue").PublicProps, Readonly<__VLS_Props> & Readonly<{}>, {}, {}, {}, {}, string, import("vue").ComponentProvideOptions, false, {}, any>;
export default _default;
//# sourceMappingURL=ContinueWritingButton.vue.d.ts.map
@@ -1 +0,0 @@
{"version":3,"file":"ContinueWritingButton.vue.d.ts","sourceRoot":"","sources":["ContinueWritingButton.vue"],"names":[],"mappings":"AAmDA,KAAK,WAAW,GAAG;IACjB,KAAK,EAAE,MAAM,CAAA;IACb,OAAO,EAAE,MAAM,IAAI,CAAA;CACpB,CAAC;;AAqEF,wBAMG"}
-19
View File
@@ -1,19 +0,0 @@
import { Extension } from '@tiptap/core';
export interface ContinueWritingOptions {
}
declare module '@tiptap/core' {
interface Commands<ReturnType> {
continueWriting: {
/**
* Trigger AI continue writing
*/
continueWriting: () => ReturnType;
};
}
}
/**
* Continue Writing Extension for Tiptap v3
* @description AI-powered text continuation based on selection
*/
export declare const ContinueWritingExtension: Extension<ContinueWritingOptions, any>;
//# sourceMappingURL=ContinueWritingExtension.d.ts.map
@@ -1 +0,0 @@
{"version":3,"file":"ContinueWritingExtension.d.ts","sourceRoot":"","sources":["ContinueWritingExtension.ts"],"names":[],"mappings":"AAOA,OAAO,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AAkBzC,MAAM,WAAW,sBAAsB;CAAG;AAE1C,OAAO,QAAQ,cAAc,CAAC;IAC5B,UAAU,QAAQ,CAAC,UAAU;QAC3B,eAAe,EAAE;YACf;;eAEG;YACH,eAAe,EAAE,MAAM,UAAU,CAAC;SACnC,CAAC;KACH;CACF;AAED;;;GAGG;AACH,eAAO,MAAM,wBAAwB,wCAwDjC,CAAC"}
-7
View File
@@ -1,7 +0,0 @@
/**
* Continue Writing Feature
* @description AI-powered text continuation based on selection
*/
export { ContinueWritingExtension } from './ContinueWritingExtension';
export type { ContinueWritingOptions } from './ContinueWritingExtension';
//# sourceMappingURL=index.d.ts.map
-1
View File
@@ -1 +0,0 @@
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EAAE,wBAAwB,EAAE,MAAM,4BAA4B,CAAC;AACtE,YAAY,EAAE,sBAAsB,EAAE,MAAM,4BAA4B,CAAC"}
-19
View File
@@ -1,19 +0,0 @@
import { Extension } from '@tiptap/core';
export interface CustomAiOptions {
}
declare module '@tiptap/core' {
interface Commands<ReturnType> {
customAi: {
/**
* Trigger custom AI command
*/
customAi: () => ReturnType;
};
}
}
/**
* Custom AI Extension for Tiptap v3
* @description AI-powered custom text processing with user-defined prompts
*/
export declare const CustomAiExtension: Extension<CustomAiOptions, any>;
//# sourceMappingURL=CustomAiExtension.d.ts.map
@@ -1 +0,0 @@
{"version":3,"file":"CustomAiExtension.d.ts","sourceRoot":"","sources":["CustomAiExtension.ts"],"names":[],"mappings":"AAOA,OAAO,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AAiBzC,MAAM,WAAW,eAAe;CAAG;AAEnC,OAAO,QAAQ,cAAc,CAAC;IAC5B,UAAU,QAAQ,CAAC,UAAU;QAC3B,QAAQ,EAAE;YACR;;eAEG;YACH,QAAQ,EAAE,MAAM,UAAU,CAAC;SAC5B,CAAC;KACH;CACF;AAED;;;GAGG;AACH,eAAO,MAAM,iBAAiB,iCAuC5B,CAAC"}
-7
View File
@@ -1,7 +0,0 @@
/**
* Custom AI Feature
* @description AI-powered custom text processing with user-defined prompts
*/
export { CustomAiExtension } from './CustomAiExtension';
export type { CustomAiOptions } from './CustomAiExtension';
//# sourceMappingURL=index.d.ts.map
-1
View File
@@ -1 +0,0 @@
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EAAE,iBAAiB,EAAE,MAAM,qBAAqB,CAAC;AACxD,YAAY,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC"}
-19
View File
@@ -1,19 +0,0 @@
/**
* AI Adapter Factory
* Automatically creates the correct adapter based on config
*/
import type { AiAdapter, AiConfig, AiProvider } from './types';
/**
* Create AI adapter from environment variables
* Reads VITE_AI_PROVIDER, VITE_AI_API_KEY, etc.
*/
export declare function createAiAdapterFromEnv(): AiAdapter;
/**
* Create AI adapter from config
*/
export declare function createAiAdapter(configInput: Partial<AiConfig>): AiAdapter;
/**
* Create specific provider adapter
*/
export declare function createProviderAdapter(provider: AiProvider, apiKey: string, options?: Partial<Omit<AiConfig, 'provider' | 'apiKey'>>): AiAdapter;
//# sourceMappingURL=factory.d.ts.map
-1
View File
@@ -1 +0,0 @@
{"version":3,"file":"factory.d.ts","sourceRoot":"","sources":["factory.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,KAAK,EAAE,SAAS,EAAE,QAAQ,EAAE,UAAU,EAAE,MAAM,SAAS,CAAA;AAgB9D;;;GAGG;AACH,wBAAgB,sBAAsB,IAAI,SAAS,CAGlD;AAED;;GAEG;AACH,wBAAgB,eAAe,CAAC,WAAW,EAAE,OAAO,CAAC,QAAQ,CAAC,GAAG,SAAS,CASzE;AAED;;GAEG;AACH,wBAAgB,qBAAqB,CACnC,QAAQ,EAAE,UAAU,EACpB,MAAM,EAAE,MAAM,EACd,OAAO,CAAC,EAAE,OAAO,CAAC,IAAI,CAAC,QAAQ,EAAE,UAAU,GAAG,QAAQ,CAAC,CAAC,GACvD,SAAS,CAMX"}
-22
View File
@@ -1,22 +0,0 @@
/**
* AI Features for TiptapPro Tenant
* @description Collection of AI-powered text processing features
*/
export { CustomAiExtension } from './custom-ai';
export type { CustomAiOptions } from './custom-ai';
export { ContinueWritingExtension } from './continue-writing';
export type { ContinueWritingOptions } from './continue-writing';
export { PolishExtension } from './polish';
export type { PolishOptions } from './polish';
export { SummarizeExtension } from './summarize';
export type { SummarizeOptions } from './summarize';
export { TranslationExtension } from './translation';
export type { TranslationOptions } from './translation';
export { AiHighlightMark } from './shared';
export type { AiSuggestionData } from './shared';
export { aiSuggestionManager } from './shared';
export type { AiSuggestionState } from './shared';
export { default as CustomAiPopover } from './shared/CustomAiPopover.vue';
export { default as AiSuggestionPopover } from './shared/AiSuggestionPopover.vue';
export { default as AiMenuButton } from './AiMenuButton.vue';
//# sourceMappingURL=index.d.ts.map
-1
View File
@@ -1 +0,0 @@
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAGH,OAAO,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAC;AAChD,YAAY,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AAGnD,OAAO,EAAE,wBAAwB,EAAE,MAAM,oBAAoB,CAAC;AAC9D,YAAY,EAAE,sBAAsB,EAAE,MAAM,oBAAoB,CAAC;AAGjE,OAAO,EAAE,eAAe,EAAE,MAAM,UAAU,CAAC;AAC3C,YAAY,EAAE,aAAa,EAAE,MAAM,UAAU,CAAC;AAG9C,OAAO,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAC;AACjD,YAAY,EAAE,gBAAgB,EAAE,MAAM,aAAa,CAAC;AAGpD,OAAO,EAAE,oBAAoB,EAAE,MAAM,eAAe,CAAC;AACrD,YAAY,EAAE,kBAAkB,EAAE,MAAM,eAAe,CAAC;AAGxD,OAAO,EAAE,eAAe,EAAE,MAAM,UAAU,CAAC;AAC3C,YAAY,EAAE,gBAAgB,EAAE,MAAM,UAAU,CAAC;AAGjD,OAAO,EAAE,mBAAmB,EAAE,MAAM,UAAU,CAAC;AAC/C,YAAY,EAAE,iBAAiB,EAAE,MAAM,UAAU,CAAC;AAGlD,OAAO,EAAE,OAAO,IAAI,eAAe,EAAE,MAAM,8BAA8B,CAAC;AAC1E,OAAO,EAAE,OAAO,IAAI,mBAAmB,EAAE,MAAM,kCAAkC,CAAC;AAGlF,OAAO,EAAE,OAAO,IAAI,YAAY,EAAE,MAAM,oBAAoB,CAAC"}
+18
View File
@@ -48,6 +48,24 @@ export type { UseAiOptions, UseAiReturn } from './useAi';
// Export types
export type { AiAdapter, AiMessage, AiStreamCallbacks } from './types';
// Export AI document agent(文字指令编辑文档:工具集 + agent 循环 + 聊天面板)
export {
documentTools,
getDocumentTool,
getDocumentOutline,
toOpenAiTools,
runDocumentAgent,
AgentNotConfiguredError,
AiChatPanel,
} from './agent';
export type {
DocumentTool,
AgentCallbacks,
AgentChatMessage,
DocumentAgentResult,
RunDocumentAgentOptions,
} from './agent';
// Export AI config
export { useAiConfig, getAiRequestConfig } from './config/useAiConfig';
export { AI_PROVIDERS, DEFAULT_CONFIG, getProviderInfo } from './config/types';
-7
View File
@@ -1,7 +0,0 @@
type __VLS_Props = {
title: string;
onClick: () => void;
};
declare const _default: import("vue").DefineComponent<__VLS_Props, {}, {}, {}, {}, import("vue").ComponentOptionsMixin, import("vue").ComponentOptionsMixin, {}, string, import("vue").PublicProps, Readonly<__VLS_Props> & Readonly<{}>, {}, {}, {}, {}, string, import("vue").ComponentProvideOptions, false, {}, any>;
export default _default;
//# sourceMappingURL=PolishButton.vue.d.ts.map
-1
View File
@@ -1 +0,0 @@
{"version":3,"file":"PolishButton.vue.d.ts","sourceRoot":"","sources":["PolishButton.vue"],"names":[],"mappings":"AAmDA,KAAK,WAAW,GAAG;IACjB,KAAK,EAAE,MAAM,CAAA;IACb,OAAO,EAAE,MAAM,IAAI,CAAA;CACpB,CAAC;;AAqEF,wBAMG"}
-19
View File
@@ -1,19 +0,0 @@
import { Extension } from '@tiptap/core';
export interface PolishOptions {
}
declare module '@tiptap/core' {
interface Commands<ReturnType> {
polish: {
/**
* Trigger AI polish (refine) text
*/
polish: () => ReturnType;
};
}
}
/**
* Polish Extension for Tiptap v3
* @description AI-powered text polishing/refinement based on selection
*/
export declare const PolishExtension: Extension<PolishOptions, any>;
//# sourceMappingURL=PolishExtension.d.ts.map
-1
View File
@@ -1 +0,0 @@
{"version":3,"file":"PolishExtension.d.ts","sourceRoot":"","sources":["PolishExtension.ts"],"names":[],"mappings":"AAOA,OAAO,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AAkBzC,MAAM,WAAW,aAAa;CAAG;AAEjC,OAAO,QAAQ,cAAc,CAAC;IAC5B,UAAU,QAAQ,CAAC,UAAU;QAC3B,MAAM,EAAE;YACN;;eAEG;YACH,MAAM,EAAE,MAAM,UAAU,CAAC;SAC1B,CAAC;KACH;CACF;AAED;;;GAGG;AACH,eAAO,MAAM,eAAe,+BAiD1B,CAAC"}
-8
View File
@@ -1,8 +0,0 @@
/**
* Polish Feature
* @description AI-powered text polishing/refinement based on selection
*/
export { PolishExtension } from './PolishExtension';
export type { PolishOptions } from './PolishExtension';
export { default as PolishButton } from './PolishButton.vue';
//# sourceMappingURL=index.d.ts.map
-1
View File
@@ -1 +0,0 @@
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EAAE,eAAe,EAAE,MAAM,mBAAmB,CAAC;AACpD,YAAY,EAAE,aAAa,EAAE,MAAM,mBAAmB,CAAC;AACvD,OAAO,EAAE,OAAO,IAAI,YAAY,EAAE,MAAM,oBAAoB,CAAC"}
-37
View File
@@ -1,37 +0,0 @@
/**
* AI Prompts
* System prompts for various AI features
*/
export declare const AI_PROMPTS: {
readonly continueWriting: {
readonly system: "你是一位专业的写作助手。你的任务是根据用户提供的内容进行续写。\n要求:\n- 保持原文的风格和语气\n- 自然流畅地衔接上文\n- 提供有价值的内容扩展\n- 使用与原文相同的语言(中文或英文)\n不要重复用户的内容,直接输出续写的部分。";
readonly en: "You are a professional writing assistant. Your task is to continue writing based on the provided content.\nRequirements:\n- Maintain the original style and tone\n- Seamlessly connect with the previous text\n- Provide valuable content expansion\n- Use the same language as the original text\nDo not repeat the user's content, directly output the continuation.";
};
readonly polish: {
readonly system: "你是一位专业的文字润色专家。你的任务是优化用户提供的文本。\n要求:\n- 提高文本的流畅性和可读性\n- 修正语法和标点错误\n- 优化词汇选择\n- 保持原文的核心意思不变\n- 使用与原文相同的语言\n直接输出润色后的文本,不要添加解释。";
readonly en: "You are a professional text polishing expert. Your task is to optimize the provided text.\nRequirements:\n- Improve fluency and readability\n- Correct grammar and punctuation errors\n- Optimize word choices\n- Keep the core meaning unchanged\n- Use the same language as the original\nOutput the polished text directly without explanations.";
};
readonly summarize: {
readonly system: "你是一位专业的内容总结专家。你的任务是提取用户提供内容的关键要点。\n要求:\n- 准确把握核心内容\n- 用简洁的语言概括要点\n- 保持逻辑清晰\n- 使用与原文相同的语言\n- 以条目形式呈现(如果内容较多)\n直接输出总结内容。";
readonly en: "You are a professional content summarization expert. Your task is to extract key points from the provided content.\nRequirements:\n- Accurately capture the core content\n- Summarize points in concise language\n- Maintain logical clarity\n- Use the same language as the original\n- Present in bullet points if content is substantial\nOutput the summary directly.";
};
readonly translate: {
readonly system: "你是一位专业的翻译专家。你的任务是将文本翻译成指定语言。\n要求:\n- 准确传达原文含义\n- 使译文自然流畅\n- 保持原文风格\n- 处理好文化差异\n直接输出翻译结果,不要添加解释。";
readonly targetLanguages: {
readonly 'zh-CN': "简体中文";
readonly 'zh-TW': "繁體中文";
readonly en: "English";
readonly ja: "日本語";
readonly ko: "한국어";
readonly fr: "Français";
readonly de: "Deutsch";
readonly es: "Español";
};
};
readonly customAi: {
readonly system: "你是一个智能助手。请根据用户的具体指令处理提供的文本内容。\n直接输出处理结果,不要添加额外解释。";
readonly en: "You are an intelligent assistant. Process the provided text according to the user's specific instructions.\nOutput the result directly without additional explanations.";
};
};
export type AiFeature = keyof typeof AI_PROMPTS;
//# sourceMappingURL=prompts.d.ts.map
-1
View File
@@ -1 +0,0 @@
{"version":3,"file":"prompts.d.ts","sourceRoot":"","sources":["prompts.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,eAAO,MAAM,UAAU;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAkFb,CAAA;AAEV,MAAM,MAAM,SAAS,GAAG,MAAM,OAAO,UAAU,CAAA"}
-46
View File
@@ -1,46 +0,0 @@
import type { Editor } from '@tiptap/core';
import { Mark } from '@tiptap/core';
export interface AiHighlightOptions {
HTMLAttributes: Record<string, any>;
}
export interface AiSuggestionData {
originalText: string;
suggestedText: string;
isStreaming: boolean;
}
declare module '@tiptap/core' {
interface Commands<ReturnType> {
aiHighlight: {
/**
* Set AI highlight mark with suggestion data
*/
setAiHighlight: (data?: AiSuggestionData) => ReturnType;
/**
* Unset AI highlight mark
*/
unsetAiHighlight: () => ReturnType;
};
}
}
/**
* AI Highlight Mark Extension
* @description Highlights text that is being processed by AI
*/
export declare const AiHighlightMark: Mark<AiHighlightOptions, any>;
/**
* Helper function to add AI highlight to a specific range
*/
export declare function addAiHighlight(editor: Editor, from: number, to: number, data?: AiSuggestionData): void;
/**
* Helper function to update AI highlight data
*/
export declare function updateAiHighlight(editor: Editor, from: number, to: number, data: Partial<AiSuggestionData>): void;
/**
* Helper function to remove all AI highlights
*/
export declare function removeAiHighlight(editor: Editor): void;
/**
* Helper function to get AI suggestion data from a mark at position
*/
export declare function getAiSuggestionData(editor: Editor, pos: number): AiSuggestionData | null;
//# sourceMappingURL=AiHighlightMark.d.ts.map
-1
View File
@@ -1 +0,0 @@
{"version":3,"file":"AiHighlightMark.d.ts","sourceRoot":"","sources":["AiHighlightMark.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,cAAc,CAAC;AAE3C,OAAO,EAAE,IAAI,EAAmB,MAAM,cAAc,CAAC;AAErD,MAAM,WAAW,kBAAkB;IACjC,cAAc,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC;CACrC;AAED,MAAM,WAAW,gBAAgB;IAC/B,YAAY,EAAE,MAAM,CAAC;IACrB,aAAa,EAAE,MAAM,CAAC;IACtB,WAAW,EAAE,OAAO,CAAC;CACtB;AAED,OAAO,QAAQ,cAAc,CAAC;IAC5B,UAAU,QAAQ,CAAC,UAAU;QAC3B,WAAW,EAAE;YACX;;eAEG;YACH,cAAc,EAAE,CAAC,IAAI,CAAC,EAAE,gBAAgB,KAAK,UAAU,CAAC;YACxD;;eAEG;YACH,gBAAgB,EAAE,MAAM,UAAU,CAAC;SACpC,CAAC;KACH;CACF;AAED;;;GAGG;AACH,eAAO,MAAM,eAAe,+BAwF1B,CAAC;AAEH;;GAEG;AACH,wBAAgB,cAAc,CAC5B,MAAM,EAAE,MAAM,EACd,IAAI,EAAE,MAAM,EACZ,EAAE,EAAE,MAAM,EACV,IAAI,CAAC,EAAE,gBAAgB,GACtB,IAAI,CAmBN;AAED;;GAEG;AACH,wBAAgB,iBAAiB,CAC/B,MAAM,EAAE,MAAM,EACd,IAAI,EAAE,MAAM,EACZ,EAAE,EAAE,MAAM,EACV,IAAI,EAAE,OAAO,CAAC,gBAAgB,CAAC,GAC9B,IAAI,CAmCN;AAED;;GAEG;AACH,wBAAgB,iBAAiB,CAAC,MAAM,EAAE,MAAM,GAAG,IAAI,CAatD;AAED;;GAEG;AACH,wBAAgB,mBAAmB,CACjC,MAAM,EAAE,MAAM,EACd,GAAG,EAAE,MAAM,GACV,gBAAgB,GAAG,IAAI,CAoBzB"}
-29
View File
@@ -1,29 +0,0 @@
export interface AiSuggestionPopoverProps {
visible: boolean;
originalText: string;
suggestedText: string;
isStreaming: boolean;
position?: {
top: number;
left: number;
};
editorElement?: HTMLElement;
}
declare const _default: import("vue").DefineComponent<AiSuggestionPopoverProps, {}, {}, {}, {}, import("vue").ComponentOptionsMixin, import("vue").ComponentOptionsMixin, {
accept: () => any;
reject: () => any;
cancel: () => any;
"update:visible": (value: boolean) => any;
}, string, import("vue").PublicProps, Readonly<AiSuggestionPopoverProps> & Readonly<{
onAccept?: (() => any) | undefined;
onReject?: (() => any) | undefined;
onCancel?: (() => any) | undefined;
"onUpdate:visible"?: ((value: boolean) => any) | undefined;
}>, {
visible: boolean;
originalText: string;
suggestedText: string;
isStreaming: boolean;
}, {}, {}, {}, string, import("vue").ComponentProvideOptions, false, {}, any>;
export default _default;
//# sourceMappingURL=AiSuggestionPopover.vue.d.ts.map
@@ -1 +0,0 @@
{"version":3,"file":"AiSuggestionPopover.vue.d.ts","sourceRoot":"","sources":["AiSuggestionPopover.vue"],"names":[],"mappings":"AAiPA,MAAM,WAAW,wBAAwB;IACvC,OAAO,EAAE,OAAO,CAAC;IACjB,YAAY,EAAE,MAAM,CAAC;IACrB,aAAa,EAAE,MAAM,CAAC;IACtB,WAAW,EAAE,OAAO,CAAC;IACrB,QAAQ,CAAC,EAAE;QAAE,GAAG,EAAE,MAAM,CAAC;QAAC,IAAI,EAAE,MAAM,CAAA;KAAE,CAAC;IACzC,aAAa,CAAC,EAAE,WAAW,CAAC;CAC7B;;;;;;;;;;;;aANU,OAAO;kBACF,MAAM;mBACL,MAAM;iBACR,OAAO;;AAsTtB,wBAQG"}
-35
View File
@@ -1,35 +0,0 @@
export interface CustomAiPopoverProps {
visible: boolean;
originalText: string;
suggestedText: string;
isStreaming: boolean;
isExecuting: boolean;
position?: {
top: number;
left: number;
};
editorElement?: HTMLElement;
}
declare const _default: import("vue").DefineComponent<CustomAiPopoverProps, {}, {}, {}, {}, import("vue").ComponentOptionsMixin, import("vue").ComponentOptionsMixin, {
accept: () => any;
reject: () => any;
cancel: () => any;
"update:visible": (value: boolean) => any;
execute: (prompt: string) => any;
cancelGeneration: () => any;
}, string, import("vue").PublicProps, Readonly<CustomAiPopoverProps> & Readonly<{
onAccept?: (() => any) | undefined;
onReject?: (() => any) | undefined;
onCancel?: (() => any) | undefined;
"onUpdate:visible"?: ((value: boolean) => any) | undefined;
onExecute?: ((prompt: string) => any) | undefined;
onCancelGeneration?: (() => any) | undefined;
}>, {
visible: boolean;
originalText: string;
suggestedText: string;
isStreaming: boolean;
isExecuting: boolean;
}, {}, {}, {}, string, import("vue").ComponentProvideOptions, false, {}, any>;
export default _default;
//# sourceMappingURL=CustomAiPopover.vue.d.ts.map
@@ -1 +0,0 @@
{"version":3,"file":"CustomAiPopover.vue.d.ts","sourceRoot":"","sources":["CustomAiPopover.vue"],"names":[],"mappings":"AAqUA,MAAM,WAAW,oBAAoB;IACnC,OAAO,EAAE,OAAO,CAAC;IACjB,YAAY,EAAE,MAAM,CAAC;IACrB,aAAa,EAAE,MAAM,CAAC;IACtB,WAAW,EAAE,OAAO,CAAC;IACrB,WAAW,EAAE,OAAO,CAAC;IACrB,QAAQ,CAAC,EAAE;QAAE,GAAG,EAAE,MAAM,CAAC;QAAC,IAAI,EAAE,MAAM,CAAA;KAAE,CAAC;IACzC,aAAa,CAAC,EAAE,WAAW,CAAC;CAC7B;;;;;;;;;;;;;;;;aAPU,OAAO;kBACF,MAAM;mBACL,MAAM;iBACR,OAAO;iBACP,OAAO;;AAgdtB,wBAQG"}
-104
View File
@@ -1,104 +0,0 @@
import type { Editor } from '@tiptap/core';
export interface AiSuggestionState {
visible: boolean;
originalText: string;
suggestedText: string;
isStreaming: boolean;
originalSelection: {
from: number;
to: number;
};
}
declare class AiSuggestionManager {
private editor;
private popoverApp;
private container;
private state;
private visibleRef;
private originalTextRef;
private suggestedTextRef;
private isStreamingRef;
private isTemporarilyHidden;
/**
* Initialize the suggestion manager
*/
init(editor: Editor): void;
/**
* Setup click handler for highlighted text
*/
private setupClickHandler;
/**
* Restore existing highlights from the document
*/
private restoreExistingHighlights;
/**
* Restore a suggestion from saved data
*/
private restoreSuggestion;
/**
* Show AI suggestion popover
*/
show(originalText: string, originalSelection: {
from: number;
to: number;
}, editor?: Editor): void;
/**
* Show the popover (for clicking on highlighted text)
*/
private showPopover;
/**
* Update suggested text (for streaming)
*/
updateSuggestion(text: string): void;
/**
* Stop streaming
*/
stopStreaming(): void;
/**
* Accept the suggestion
*/
accept(): void;
/**
* Build paragraph nodes from text with newlines
*/
private buildParagraphNodes;
/**
* Reject the suggestion
*/
reject(): void;
/**
* Cancel (temporarily hide) the suggestion
*/
cancel(): void;
/**
* Hide the popover and cleanup
*/
hide(): void;
/**
* Check if suggestion is visible
*/
isVisible(): boolean;
/**
* Get current state
*/
getState(): AiSuggestionState;
/**
* Mount the popover component
*/
private mountPopover;
/**
* Unmount the popover component
*/
private unmountPopover;
/**
* Calculate popover position based on selection
*/
private calculatePopoverPosition;
/**
* Cleanup
*/
destroy(): void;
}
export declare const aiSuggestionManager: AiSuggestionManager;
export {};
//# sourceMappingURL=aiSuggestionManager.d.ts.map
@@ -1 +0,0 @@
{"version":3,"file":"aiSuggestionManager.d.ts","sourceRoot":"","sources":["aiSuggestionManager.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,cAAc,CAAC;AAc3C,MAAM,WAAW,iBAAiB;IAChC,OAAO,EAAE,OAAO,CAAC;IACjB,YAAY,EAAE,MAAM,CAAC;IACrB,aAAa,EAAE,MAAM,CAAC;IACtB,WAAW,EAAE,OAAO,CAAC;IACrB,iBAAiB,EAAE;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,EAAE,EAAE,MAAM,CAAA;KAAE,CAAC;CACjD;AAED,cAAM,mBAAmB;IACvB,OAAO,CAAC,MAAM,CAAuB;IACrC,OAAO,CAAC,UAAU,CAAoB;IACtC,OAAO,CAAC,SAAS,CAA4B;IAC7C,OAAO,CAAC,KAAK,CAMX;IAGF,OAAO,CAAC,UAAU,CAAc;IAChC,OAAO,CAAC,eAAe,CAAW;IAClC,OAAO,CAAC,gBAAgB,CAAW;IACnC,OAAO,CAAC,cAAc,CAAc;IAGpC,OAAO,CAAC,mBAAmB,CAAS;IAEpC;;OAEG;IACH,IAAI,CAAC,MAAM,EAAE,MAAM,GAAG,IAAI;IAM1B;;OAEG;IACH,OAAO,CAAC,iBAAiB;IAgCzB;;OAEG;IACH,OAAO,CAAC,yBAAyB;IAQjC;;OAEG;IACH,OAAO,CAAC,iBAAiB;IAuCzB;;OAEG;IACH,IAAI,CACF,YAAY,EAAE,MAAM,EACpB,iBAAiB,EAAE;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,EAAE,EAAE,MAAM,CAAA;KAAE,EAC/C,MAAM,CAAC,EAAE,MAAM,GACd,IAAI;IA4CP;;OAEG;IACH,OAAO,CAAC,WAAW;IAKnB;;OAEG;IACH,gBAAgB,CAAC,IAAI,EAAE,MAAM,GAAG,IAAI;IAkBpC;;OAEG;IACH,aAAa,IAAI,IAAI;IAkBrB;;OAEG;IACH,MAAM,IAAI,IAAI;IAoCd;;OAEG;IACH,OAAO,CAAC,mBAAmB;IA0B3B;;OAEG;IACH,MAAM,IAAI,IAAI;IAId;;OAEG;IACH,MAAM,IAAI,IAAI;IAKd;;OAEG;IACH,IAAI,IAAI,IAAI;IAwBZ;;OAEG;IACH,SAAS,IAAI,OAAO;IAIpB;;OAEG;IACH,QAAQ,IAAI,iBAAiB;IAI7B;;OAEG;IACH,OAAO,CAAC,YAAY;IAoDpB;;OAEG;IACH,OAAO,CAAC,cAAc;IAYtB;;OAEG;IACH,OAAO,CAAC,wBAAwB;IAsBhC;;OAEG;IACH,OAAO,IAAI,IAAI;CAIhB;AAGD,eAAO,MAAM,mBAAmB,qBAA4B,CAAC"}
-10
View File
@@ -1,10 +0,0 @@
/**
* AI Shared Components and Utilities
* @description Shared components, utilities, and styles for AI features
*/
export * from './AiHighlightMark';
export * from './aiSuggestionManager';
export { default as CustomAiPopover } from './CustomAiPopover.vue';
export { default as AiSuggestionPopover } from './AiSuggestionPopover.vue';
import './ai-highlight.css';
//# sourceMappingURL=index.d.ts.map
-1
View File
@@ -1 +0,0 @@
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAGH,cAAc,mBAAmB,CAAC;AAGlC,cAAc,uBAAuB,CAAC;AAGtC,OAAO,EAAE,OAAO,IAAI,eAAe,EAAE,MAAM,uBAAuB,CAAC;AACnE,OAAO,EAAE,OAAO,IAAI,mBAAmB,EAAE,MAAM,2BAA2B,CAAC;AAG3E,OAAO,oBAAoB,CAAC"}
-12
View File
@@ -1,12 +0,0 @@
import { Extension } from '@tiptap/core';
export interface SummarizeOptions {
}
declare module '@tiptap/core' {
interface Commands<ReturnType> {
summarize: {
summarize: () => ReturnType;
};
}
}
export declare const SummarizeExtension: Extension<SummarizeOptions, any>;
//# sourceMappingURL=SummarizeExtension.d.ts.map
@@ -1 +0,0 @@
{"version":3,"file":"SummarizeExtension.d.ts","sourceRoot":"","sources":["SummarizeExtension.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AASzC,MAAM,WAAW,gBAAgB;CAAG;AAEpC,OAAO,QAAQ,cAAc,CAAC;IAC5B,UAAU,QAAQ,CAAC,UAAU;QAC3B,SAAS,EAAE;YACT,SAAS,EAAE,MAAM,UAAU,CAAC;SAC7B,CAAC;KACH;CACF;AAED,eAAO,MAAM,kBAAkB,kCA6B7B,CAAC"}
-7
View File
@@ -1,7 +0,0 @@
/**
* Summarize Feature
* @description AI-powered content summarization
*/
export { SummarizeExtension } from './SummarizeExtension';
export type { SummarizeOptions } from './SummarizeExtension';
//# sourceMappingURL=index.d.ts.map
-1
View File
@@ -1 +0,0 @@
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EAAE,kBAAkB,EAAE,MAAM,sBAAsB,CAAC;AAC1D,YAAY,EAAE,gBAAgB,EAAE,MAAM,sBAAsB,CAAC"}
-13
View File
@@ -1,13 +0,0 @@
import { Extension } from '@tiptap/core';
export interface TranslationOptions {
defaultTargetLang?: string;
}
declare module '@tiptap/core' {
interface Commands<ReturnType> {
translation: {
translate: (targetLang?: string) => ReturnType;
};
}
}
export declare const TranslationExtension: Extension<TranslationOptions, any>;
//# sourceMappingURL=TranslationExtension.d.ts.map
@@ -1 +0,0 @@
{"version":3,"file":"TranslationExtension.d.ts","sourceRoot":"","sources":["TranslationExtension.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AAUzC,MAAM,WAAW,kBAAkB;IACjC,iBAAiB,CAAC,EAAE,MAAM,CAAC;CAC5B;AAED,OAAO,QAAQ,cAAc,CAAC;IAC5B,UAAU,QAAQ,CAAC,UAAU;QAC3B,WAAW,EAAE;YACX,SAAS,EAAE,CAAC,UAAU,CAAC,EAAE,MAAM,KAAK,UAAU,CAAC;SAChD,CAAC;KACH;CACF;AAED,eAAO,MAAM,oBAAoB,oCAyC/B,CAAC"}
-10
View File
@@ -1,10 +0,0 @@
/**
* Translation Feature
* @description AI-powered text translation with language selection
*/
export { TranslationExtension } from './TranslationExtension';
export type { TranslationOptions } from './TranslationExtension';
export { LANGUAGE_CODES } from './languageCodes';
export type { LanguageCode } from './languageCodes';
export { currentTranslateLang, setTranslateLang, clearTranslateLang, STORAGE_KEY, } from './translateStore';
//# sourceMappingURL=index.d.ts.map
-1
View File
@@ -1 +0,0 @@
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EAAE,oBAAoB,EAAE,MAAM,wBAAwB,CAAC;AAC9D,YAAY,EAAE,kBAAkB,EAAE,MAAM,wBAAwB,CAAC;AAEjE,OAAO,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAC;AACjD,YAAY,EAAE,YAAY,EAAE,MAAM,iBAAiB,CAAC;AAEpD,OAAO,EACL,oBAAoB,EACpB,gBAAgB,EAChB,kBAAkB,EAClB,WAAW,GACZ,MAAM,kBAAkB,CAAC"}
-14
View File
@@ -1,14 +0,0 @@
/**
* 翻译语言代码配置
* @description 定义支持的语言代码及其映射关系
*/
export interface LanguageCode {
code: string;
key: string;
}
/**
* 支持的语言代码列表
* 用于翻译功能的语言选择
*/
export declare const LANGUAGE_CODES: LanguageCode[];
//# sourceMappingURL=languageCodes.d.ts.map
@@ -1 +0,0 @@
{"version":3,"file":"languageCodes.d.ts","sourceRoot":"","sources":["languageCodes.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,MAAM,WAAW,YAAY;IAC3B,IAAI,EAAE,MAAM,CAAC;IACb,GAAG,EAAE,MAAM,CAAC;CACb;AAED;;;GAGG;AACH,eAAO,MAAM,cAAc,EAAE,YAAY,EAexC,CAAC"}
-13
View File
@@ -1,13 +0,0 @@
declare const STORAGE_KEY = "tiptap_translate_target_lang";
export declare const currentTranslateLang: import("vue").Ref<string, string>;
/**
* 设置语言并持久化到 localStorage
* @param label 语言标签(如 "英文"、"中文" 等)
*/
export declare function setTranslateLang(label: string): void;
/**
* 清除已保存的语言选择
*/
export declare function clearTranslateLang(): void;
export { STORAGE_KEY };
//# sourceMappingURL=translateStore.d.ts.map
@@ -1 +0,0 @@
{"version":3,"file":"translateStore.d.ts","sourceRoot":"","sources":["translateStore.ts"],"names":[],"mappings":"AAMA,QAAA,MAAM,WAAW,iCAAiC,CAAC;AAInD,eAAO,MAAM,oBAAoB,mCAA2B,CAAC;AAE7D;;;GAGG;AACH,wBAAgB,gBAAgB,CAAC,KAAK,EAAE,MAAM,QAS7C;AAED;;GAEG;AACH,wBAAgB,kBAAkB,SASjC;AAGD,OAAO,EAAE,WAAW,EAAE,CAAC"}
-56
View File
@@ -1,56 +0,0 @@
/**
* AI Types
* Common types for AI adapters
*/
/** Supported AI providers */
export type AiProvider = 'openai' | 'aliyun' | 'ollama' | 'deepseek' | 'anthropic' | 'custom';
/** AI configuration from env */
export interface AiConfig {
provider: AiProvider;
apiKey?: string;
apiSecret?: string;
baseUrl?: string;
model?: string;
temperature?: number;
maxTokens?: number;
}
/** Message format */
export interface AiMessage {
role: 'system' | 'user' | 'assistant';
content: string;
}
/** Streaming callbacks */
export interface AiStreamCallbacks {
onStart?: () => void;
onToken?: (token: string) => void;
onComplete?: (fullText: string) => void;
onError?: (error: Error) => void;
}
/** Non-streaming response */
export interface AiResponse {
content: string;
finishReason?: string;
usage?: {
promptTokens: number;
completionTokens: number;
totalTokens: number;
};
}
/** AI adapter interface */
export interface AiAdapter {
/** Provider name */
provider: AiProvider;
/** Chat completion (non-streaming) */
chat(messages: AiMessage[], options?: Partial<AiConfig>): Promise<AiResponse>;
/** Chat completion (streaming) */
chatStream(messages: AiMessage[], callbacks: AiStreamCallbacks, options?: Partial<AiConfig>): Promise<void>;
}
/** AI feature options for editor extensions */
export interface AiFeatureOptions {
adapter: AiAdapter;
systemPrompt?: string;
onStart?: () => void;
onComplete?: (text: string) => void;
onError?: (error: Error) => void;
}
//# sourceMappingURL=types.d.ts.map
-1
View File
@@ -1 +0,0 @@
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["types.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,6BAA6B;AAC7B,MAAM,MAAM,UAAU,GAAG,QAAQ,GAAG,QAAQ,GAAG,QAAQ,GAAG,UAAU,GAAG,WAAW,GAAG,QAAQ,CAAA;AAE7F,gCAAgC;AAChC,MAAM,WAAW,QAAQ;IACvB,QAAQ,EAAE,UAAU,CAAA;IACpB,MAAM,CAAC,EAAE,MAAM,CAAA;IACf,SAAS,CAAC,EAAE,MAAM,CAAA;IAClB,OAAO,CAAC,EAAE,MAAM,CAAA;IAChB,KAAK,CAAC,EAAE,MAAM,CAAA;IACd,WAAW,CAAC,EAAE,MAAM,CAAA;IACpB,SAAS,CAAC,EAAE,MAAM,CAAA;CACnB;AAED,qBAAqB;AACrB,MAAM,WAAW,SAAS;IACxB,IAAI,EAAE,QAAQ,GAAG,MAAM,GAAG,WAAW,CAAA;IACrC,OAAO,EAAE,MAAM,CAAA;CAChB;AAED,0BAA0B;AAC1B,MAAM,WAAW,iBAAiB;IAChC,OAAO,CAAC,EAAE,MAAM,IAAI,CAAA;IACpB,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE,MAAM,KAAK,IAAI,CAAA;IACjC,UAAU,CAAC,EAAE,CAAC,QAAQ,EAAE,MAAM,KAAK,IAAI,CAAA;IACvC,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE,KAAK,KAAK,IAAI,CAAA;CACjC;AAED,6BAA6B;AAC7B,MAAM,WAAW,UAAU;IACzB,OAAO,EAAE,MAAM,CAAA;IACf,YAAY,CAAC,EAAE,MAAM,CAAA;IACrB,KAAK,CAAC,EAAE;QACN,YAAY,EAAE,MAAM,CAAA;QACpB,gBAAgB,EAAE,MAAM,CAAA;QACxB,WAAW,EAAE,MAAM,CAAA;KACpB,CAAA;CACF;AAED,2BAA2B;AAC3B,MAAM,WAAW,SAAS;IACxB,oBAAoB;IACpB,QAAQ,EAAE,UAAU,CAAA;IAEpB,sCAAsC;IACtC,IAAI,CAAC,QAAQ,EAAE,SAAS,EAAE,EAAE,OAAO,CAAC,EAAE,OAAO,CAAC,QAAQ,CAAC,GAAG,OAAO,CAAC,UAAU,CAAC,CAAA;IAE7E,kCAAkC;IAClC,UAAU,CAAC,QAAQ,EAAE,SAAS,EAAE,EAAE,SAAS,EAAE,iBAAiB,EAAE,OAAO,CAAC,EAAE,OAAO,CAAC,QAAQ,CAAC,GAAG,OAAO,CAAC,IAAI,CAAC,CAAA;CAC5G;AAED,+CAA+C;AAC/C,MAAM,WAAW,gBAAgB;IAC/B,OAAO,EAAE,SAAS,CAAA;IAClB,YAAY,CAAC,EAAE,MAAM,CAAA;IACrB,OAAO,CAAC,EAAE,MAAM,IAAI,CAAA;IACpB,UAAU,CAAC,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,IAAI,CAAA;IACnC,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE,KAAK,KAAK,IAAI,CAAA;CACjC"}
-28
View File
@@ -1,28 +0,0 @@
/**
* useAi Composable
* Vue composable for AI features in editor
*/
import { ref, readonly } from 'vue';
import type { AiAdapter, AiStreamCallbacks } from './types';
export interface UseAiOptions {
adapter: AiAdapter;
onError?: (error: Error) => void;
}
export interface UseAiReturn {
isLoading: Readonly<ReturnType<typeof readonly<ReturnType<typeof ref<boolean>>>>>;
result: Readonly<ReturnType<typeof readonly<ReturnType<typeof ref<string>>>>>;
error: Readonly<ReturnType<typeof readonly<ReturnType<typeof ref<Error | null>>>>>;
continueWriting: (text: string) => Promise<string>;
polish: (text: string) => Promise<string>;
summarize: (text: string) => Promise<string>;
translate: (text: string, targetLang: string) => Promise<string>;
customAi: (text: string, instruction: string) => Promise<string>;
continueWritingStream: (text: string, callbacks: AiStreamCallbacks) => Promise<void>;
polishStream: (text: string, callbacks: AiStreamCallbacks) => Promise<void>;
summarizeStream: (text: string, callbacks: AiStreamCallbacks) => Promise<void>;
translateStream: (text: string, targetLang: string, callbacks: AiStreamCallbacks) => Promise<void>;
customAiStream: (text: string, instruction: string, callbacks: AiStreamCallbacks) => Promise<void>;
abort: () => void;
}
export declare function useAi(options: UseAiOptions): UseAiReturn;
//# sourceMappingURL=useAi.d.ts.map
-1
View File
@@ -1 +0,0 @@
{"version":3,"file":"useAi.d.ts","sourceRoot":"","sources":["useAi.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EAAE,GAAG,EAAE,QAAQ,EAAE,MAAM,KAAK,CAAA;AACnC,OAAO,KAAK,EAAE,SAAS,EAAa,iBAAiB,EAAE,MAAM,SAAS,CAAA;AAGtE,MAAM,WAAW,YAAY;IAC3B,OAAO,EAAE,SAAS,CAAA;IAClB,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE,KAAK,KAAK,IAAI,CAAA;CACjC;AAED,MAAM,WAAW,WAAW;IAC1B,SAAS,EAAE,QAAQ,CAAC,UAAU,CAAC,OAAO,QAAQ,CAAC,UAAU,CAAC,OAAO,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC,CAAA;IACjF,MAAM,EAAE,QAAQ,CAAC,UAAU,CAAC,OAAO,QAAQ,CAAC,UAAU,CAAC,OAAO,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC,CAAA;IAC7E,KAAK,EAAE,QAAQ,CAAC,UAAU,CAAC,OAAO,QAAQ,CAAC,UAAU,CAAC,OAAO,GAAG,CAAC,KAAK,GAAG,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,CAAA;IAElF,eAAe,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,OAAO,CAAC,MAAM,CAAC,CAAA;IAClD,MAAM,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,OAAO,CAAC,MAAM,CAAC,CAAA;IACzC,SAAS,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,OAAO,CAAC,MAAM,CAAC,CAAA;IAC5C,SAAS,EAAE,CAAC,IAAI,EAAE,MAAM,EAAE,UAAU,EAAE,MAAM,KAAK,OAAO,CAAC,MAAM,CAAC,CAAA;IAChE,QAAQ,EAAE,CAAC,IAAI,EAAE,MAAM,EAAE,WAAW,EAAE,MAAM,KAAK,OAAO,CAAC,MAAM,CAAC,CAAA;IAEhE,qBAAqB,EAAE,CAAC,IAAI,EAAE,MAAM,EAAE,SAAS,EAAE,iBAAiB,KAAK,OAAO,CAAC,IAAI,CAAC,CAAA;IACpF,YAAY,EAAE,CAAC,IAAI,EAAE,MAAM,EAAE,SAAS,EAAE,iBAAiB,KAAK,OAAO,CAAC,IAAI,CAAC,CAAA;IAC3E,eAAe,EAAE,CAAC,IAAI,EAAE,MAAM,EAAE,SAAS,EAAE,iBAAiB,KAAK,OAAO,CAAC,IAAI,CAAC,CAAA;IAC9E,eAAe,EAAE,CAAC,IAAI,EAAE,MAAM,EAAE,UAAU,EAAE,MAAM,EAAE,SAAS,EAAE,iBAAiB,KAAK,OAAO,CAAC,IAAI,CAAC,CAAA;IAClG,cAAc,EAAE,CAAC,IAAI,EAAE,MAAM,EAAE,WAAW,EAAE,MAAM,EAAE,SAAS,EAAE,iBAAiB,KAAK,OAAO,CAAC,IAAI,CAAC,CAAA;IAElG,KAAK,EAAE,MAAM,IAAI,CAAA;CAClB;AAED,wBAAgB,KAAK,CAAC,OAAO,EAAE,YAAY,GAAG,WAAW,CAuGxD"}
+6 -3
View File
@@ -22,8 +22,9 @@ export interface AiApiResponse {
/**
* Load API configuration
* Priority: User config > Environment variables > Defaults
* @description 也供 ai/agent 的 tool-use 循环复用
*/
function getAiConfig() {
export function getAiConfig() {
// First check user config (localStorage)
const userConfig = getAiRequestConfig()
if (userConfig) {
@@ -48,13 +49,15 @@ function getAiConfig() {
}
// Get base URL for provider
function getBaseUrl(provider: string, customUrl: string): string {
export function getBaseUrl(provider: string, customUrl: string): string {
if (customUrl) return customUrl
const urls: Record<string, string> = {
openai: 'https://api.openai.com/v1',
anthropic: 'https://api.anthropic.com/v1',
aliyun: 'https://dashscope.aliyuncs.com/compatible-mode/v1',
deepseek: 'https://api.deepseek.com/v1',
ollama: 'http://localhost:11434/api',
// Ollama 的 OpenAI 兼容端点(/api 是其私有协议,不兼容 /chat/completions)
ollama: 'http://localhost:11434/v1',
}
return urls[provider] || urls.openai
}
-227
View File
@@ -1,227 +0,0 @@
/**
* Editor Constants
* @description 编辑器常量配置(颜色、字体、字号等)
*/
/**
* 文本颜色选项
*/
export declare const TEXT_COLORS: readonly ["#000000", "#ff0000", "#ff9900", "#ffff00", "#00ff00", "#00ffff", "#0000ff", "#9900ff"];
/**
* 背景颜色选项
*/
export declare const BACKGROUND_COLORS: readonly ["#ffffff", "#f5f5f5", "#e8f5e9", "#e3f2fd", "#fff3e0", "#fce4ec", "#f3e5f5", "#e0f2f1"];
/**
* 表格单元格背景颜色选项
*/
export declare const TABLE_CELL_COLORS: readonly ["#ffffff", "#f5f5f5", "#e8f5e9", "#e3f2fd", "#fff3e0", "#fce4ec", "#f3e5f5", "#e0f2f1"];
/**
* 字体系列选项
*/
export declare const FONT_FAMILIES: readonly [{
readonly label: "PMingLiU";
readonly value: "PMingLiU";
}, {
readonly label: "Microsoft YaHei";
readonly value: "Microsoft YaHei";
}, {
readonly label: "SimSun";
readonly value: "SimSun";
}, {
readonly label: "SimHei";
readonly value: "SimHei";
}, {
readonly label: "Arial";
readonly value: "Arial";
}, {
readonly label: "Times New Roman";
readonly value: "Times New Roman";
}, {
readonly label: "Courier New";
readonly value: "Courier New";
}, {
readonly label: "Monospace";
readonly value: "monospace";
}];
/**
* 字号选项(中文印刷标准)
*/
export declare const FONT_SIZES: readonly [{
readonly label: "12";
readonly value: "12px";
}, {
readonly label: "14";
readonly value: "14px";
}, {
readonly label: "16";
readonly value: "16px";
}, {
readonly label: "18";
readonly value: "18px";
}, {
readonly label: "20";
readonly value: "20px";
}, {
readonly label: "24";
readonly value: "24px";
}, {
readonly label: "28";
readonly value: "28px";
}, {
readonly label: "32";
readonly value: "32px";
}];
/**
* 行间距选项
*/
export declare const LINE_HEIGHTS: readonly [{
readonly label: "1.0";
readonly value: "1";
}, {
readonly label: "1.5";
readonly value: "1.5";
}, {
readonly label: "2.0";
readonly value: "2";
}, {
readonly label: "2.5";
readonly value: "2.5";
}, {
readonly label: "3.0";
readonly value: "3";
}];
/**
* 段落样式选项
*/
export declare const HEADING_OPTIONS: readonly [{
readonly label: "正文";
readonly value: "paragraph";
}, {
readonly label: "H1";
readonly value: "h1";
}, {
readonly label: "H2";
readonly value: "h2";
}, {
readonly label: "H3";
readonly value: "h3";
}, {
readonly label: "H4";
readonly value: "h4";
}, {
readonly label: "H5";
readonly value: "h5";
}, {
readonly label: "H6";
readonly value: "h6";
}];
/**
* 代码块语言选项
*/
export declare const CODE_LANGUAGES: readonly ["javascript", "typescript", "python", "java", "html", "css", "json", "bash", "sql", "php", "go", "rust", "c", "cpp", "csharp", "swift", "kotlin", "ruby", "markdown", "xml"];
/**
* 对齐方式选项
*/
export declare const TEXT_ALIGN_OPTIONS: readonly [{
readonly label: "左对齐";
readonly value: "left";
}, {
readonly label: "居中";
readonly value: "center";
}, {
readonly label: "右对齐";
readonly value: "right";
}, {
readonly label: "两端对齐";
readonly value: "justify";
}];
/**
* 表格边框样式选项
*/
export declare const TABLE_BORDER_STYLES: readonly [{
readonly label: "默认边框";
readonly value: "default";
}, {
readonly label: "无边框";
readonly value: "none";
}, {
readonly label: "外边框";
readonly value: "outer";
}];
/**
* 默认配置值
*/
export declare const DEFAULT_VALUES: {
/** 默认字体 */
readonly fontFamily: "PMingLiU";
/** 默认字号 */
readonly fontSize: "16px";
/** 默认行间距 */
readonly lineHeight: "1.5";
/** 默认文本颜色 */
readonly textColor: "#000000";
/** 默认背景颜色 */
readonly backgroundColor: "#ffffff";
/** 默认对齐方式 */
readonly textAlign: "left";
/** 默认代码语言 */
readonly codeLanguage: "javascript";
};
/**
* 编辑器限制
*/
export declare const EDITOR_LIMITS: {
/** 最小缩放比例 */
readonly minZoom: 50;
/** 最大缩放比例 */
readonly maxZoom: 200;
/** 缩放步长 */
readonly zoomStep: 10;
/** 最大文档长度(字符数) */
readonly maxDocumentLength: 1000000;
/** 最大标题级别 */
readonly maxHeadingLevel: 6;
};
/**
* 快捷键配置
*/
export declare const KEYBOARD_SHORTCUTS: {
readonly bold: "Mod-b";
readonly italic: "Mod-i";
readonly underline: "Mod-u";
readonly strike: "Mod-Shift-s";
readonly code: "Mod-e";
readonly codeBlock: "Mod-Shift-e";
readonly link: "Mod-k";
readonly undo: "Mod-z";
readonly redo: readonly ["Mod-Shift-z", "Mod-y"];
readonly paragraph: "Mod-Alt-0";
readonly heading1: "Mod-Alt-1";
readonly heading2: "Mod-Alt-2";
readonly heading3: "Mod-Alt-3";
readonly bulletList: "Mod-Shift-8";
readonly orderedList: "Mod-Shift-7";
readonly taskList: "Mod-Shift-9";
};
/**
* UI 配置
*/
export declare const UI_CONFIG: {
/** 工具栏按钮尺寸 */
readonly toolbarButtonSize: 28;
/** 工具栏高度 */
readonly toolbarHeight: 56;
/** 工具栏间距 */
readonly toolbarGap: 6;
/** 颜色面板列数 */
readonly colorPanelColumns: 8;
/** 颜色面板色块大小 */
readonly colorItemSize: 24;
/** 浮动菜单偏移 */
readonly bubbleMenuOffset: 8;
};
/**
* @note 所有类型定义已统一迁移到 shared/configs/toolbar.ts
* 如需使用类型,请从 shared/configs/toolbar 导入
* 此文件仅保留常量配置,类型定义已移除
*/
//# sourceMappingURL=editorConstants.d.ts.map
-1
View File
@@ -1 +0,0 @@
{"version":3,"file":"editorConstants.d.ts","sourceRoot":"","sources":["editorConstants.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH;;GAEG;AACH,eAAO,MAAM,WAAW,mGASd,CAAA;AAEV;;GAEG;AACH,eAAO,MAAM,iBAAiB,mGASpB,CAAA;AAEV;;GAEG;AACH,eAAO,MAAM,iBAAiB,mGAAoB,CAAA;AAElD;;GAEG;AACH,eAAO,MAAM,aAAa;;;;;;;;;;;;;;;;;;;;;;;;EAShB,CAAA;AAEV;;GAEG;AACH,eAAO,MAAM,UAAU;;;;;;;;;;;;;;;;;;;;;;;;EASb,CAAA;AAEV;;GAEG;AACH,eAAO,MAAM,YAAY;;;;;;;;;;;;;;;EAMf,CAAA;AAEV;;GAEG;AACH,eAAO,MAAM,eAAe;;;;;;;;;;;;;;;;;;;;;EAQlB,CAAA;AAEV;;GAEG;AACH,eAAO,MAAM,cAAc,wLAqBjB,CAAA;AAEV;;GAEG;AACH,eAAO,MAAM,kBAAkB;;;;;;;;;;;;EAKrB,CAAA;AAEV;;GAEG;AACH,eAAO,MAAM,mBAAmB;;;;;;;;;EAItB,CAAA;AAEV;;GAEG;AACH,eAAO,MAAM,cAAc;IACzB,WAAW;;IAEX,WAAW;;IAEX,YAAY;;IAEZ,aAAa;;IAEb,aAAa;;IAEb,aAAa;;IAEb,aAAa;;CAEL,CAAA;AAEV;;GAEG;AACH,eAAO,MAAM,aAAa;IACxB,aAAa;;IAEb,aAAa;;IAEb,WAAW;;IAEX,kBAAkB;;IAElB,aAAa;;CAEL,CAAA;AAEV;;GAEG;AACH,eAAO,MAAM,kBAAkB;;;;;;;;;;;;;;;;;CAiBrB,CAAA;AAEV;;GAEG;AACH,eAAO,MAAM,SAAS;IACpB,cAAc;;IAEd,YAAY;;IAEZ,YAAY;;IAEZ,aAAa;;IAEb,eAAe;;IAEf,aAAa;;CAEL,CAAA;AAEV;;;;GAIG"}
+9 -6
View File
@@ -40,14 +40,17 @@ export const TABLE_CELL_COLORS = BACKGROUND_COLORS
* 字体系列选项
*/
export const FONT_FAMILIES = [
{ label: 'PMingLiU', value: 'PMingLiU' },
{ label: 'Microsoft YaHei', value: 'Microsoft YaHei' },
{ label: 'SimSun', value: 'SimSun' },
{ label: 'SimHei', value: 'SimHei' },
/** 空值表示不指定字体(跟随主题默认),显示文案由组件用 i18n 渲染 */
{ label: 'Default', value: '' },
{ label: 'Arial', value: 'Arial' },
{ label: 'Georgia', value: 'Georgia' },
{ label: 'Times New Roman', value: 'Times New Roman' },
{ label: 'Courier New', value: 'Courier New' },
{ label: 'Monospace', value: 'monospace' },
{ label: '微软雅黑', value: 'Microsoft YaHei' },
{ label: '宋体', value: 'SimSun' },
{ label: '黑体', value: 'SimHei' },
{ label: '新細明體', value: 'PMingLiU' },
] as const
/**
@@ -137,8 +140,8 @@ export const TABLE_BORDER_STYLES = [
* 默认配置值
*/
export const DEFAULT_VALUES = {
/** 默认字体 */
fontFamily: 'PMingLiU',
/** 默认字体(空值 = 跟随主题默认,不写入 style) */
fontFamily: '',
/** 默认字号 */
fontSize: '16px',
/** 默认行间距 */
-5
View File
@@ -1,5 +0,0 @@
/**
* Configs Entry
*/
export * from './editorConstants';
//# sourceMappingURL=index.d.ts.map
-1
View File
@@ -1 +0,0 @@
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,cAAc,mBAAmB,CAAA"}
Loaded 100 of 357 files, more files were not shown because too many files have changed in this diff. Show more