Compare commits
11
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
33f976b1ea | ||
|
|
cbc4d0396f | ||
|
|
0daf36ea24 | ||
|
|
eb8d53611b | ||
|
|
b013d3b557 | ||
|
|
b12cc2c243 | ||
|
|
7ef7653deb | ||
|
|
13bd61326d | ||
|
|
bc375e1b2d | ||
|
|
8d336072b1 | ||
|
|
e81d3058f2 |
@@ -0,0 +1,2 @@
|
||||
/cache
|
||||
/project.local.yml
|
||||
@@ -0,0 +1,154 @@
|
||||
# the name by which the project can be referenced within Serena
|
||||
project_name: "timi-tdesign-mobile"
|
||||
|
||||
|
||||
# list of languages for which language servers are started; choose from:
|
||||
# al bash clojure cpp csharp
|
||||
# csharp_omnisharp dart elixir elm erlang
|
||||
# fortran fsharp go groovy haskell
|
||||
# haxe java julia kotlin lua
|
||||
# markdown
|
||||
# matlab nix pascal perl php
|
||||
# php_phpactor powershell python python_jedi r
|
||||
# rego ruby ruby_solargraph rust scala
|
||||
# swift terraform toml typescript typescript_vts
|
||||
# vue yaml zig
|
||||
# (This list may be outdated. For the current list, see values of Language enum here:
|
||||
# https://github.com/oraios/serena/blob/main/src/solidlsp/ls_config.py
|
||||
# For some languages, there are alternative language servers, e.g. csharp_omnisharp, ruby_solargraph.)
|
||||
# Note:
|
||||
# - For C, use cpp
|
||||
# - For JavaScript, use typescript
|
||||
# - For Free Pascal/Lazarus, use pascal
|
||||
# Special requirements:
|
||||
# Some languages require additional setup/installations.
|
||||
# See here for details: https://oraios.github.io/serena/01-about/020_programming-languages.html#language-servers
|
||||
# When using multiple languages, the first language server that supports a given file will be used for that file.
|
||||
# The first language is the default language and the respective language server will be used as a fallback.
|
||||
# Note that when using the JetBrains backend, language servers are not used and this list is correspondingly ignored.
|
||||
languages:
|
||||
- vue
|
||||
|
||||
# the encoding used by text files in the project
|
||||
# For a list of possible encodings, see https://docs.python.org/3.11/library/codecs.html#standard-encodings
|
||||
encoding: "utf-8"
|
||||
|
||||
# line ending convention to use when writing source files.
|
||||
# Possible values: unset (use global setting), "lf", "crlf", or "native" (platform default)
|
||||
# This does not affect Serena's own files (e.g. memories and configuration files), which always use native line endings.
|
||||
line_ending:
|
||||
|
||||
# The language backend to use for this project.
|
||||
# If not set, the global setting from serena_config.yml is used.
|
||||
# Valid values: LSP, JetBrains
|
||||
# Note: the backend is fixed at startup. If a project with a different backend
|
||||
# is activated post-init, an error will be returned.
|
||||
language_backend:
|
||||
|
||||
# whether to use project's .gitignore files to ignore files
|
||||
ignore_all_files_in_gitignore: true
|
||||
|
||||
# advanced configuration option allowing to configure language server-specific options.
|
||||
# Maps the language key to the options.
|
||||
# Have a look at the docstring of the constructors of the LS implementations within solidlsp (e.g., for C# or PHP) to see which options are available.
|
||||
# No documentation on options means no options are available.
|
||||
ls_specific_settings: {}
|
||||
|
||||
# list of additional paths to ignore in this project.
|
||||
# Same syntax as gitignore, so you can use * and **.
|
||||
# Note: global ignored_paths from serena_config.yml are also applied additively.
|
||||
ignored_paths: []
|
||||
|
||||
# whether the project is in read-only mode
|
||||
# If set to true, all editing tools will be disabled and attempts to use them will result in an error
|
||||
# Added on 2025-04-18
|
||||
read_only: false
|
||||
|
||||
# list of tool names to exclude.
|
||||
# This extends the existing exclusions (e.g. from the global configuration)
|
||||
#
|
||||
# Below is the complete list of tools for convenience.
|
||||
# To make sure you have the latest list of tools, and to view their descriptions,
|
||||
# execute `uv run scripts/print_tool_overview.py`.
|
||||
#
|
||||
# * `activate_project`: Activates a project based on the project name or path.
|
||||
# * `check_onboarding_performed`: Checks whether project onboarding was already performed.
|
||||
# * `create_text_file`: Creates/overwrites a file in the project directory.
|
||||
# * `delete_memory`: Delete a memory file. Should only happen if a user asks for it explicitly,
|
||||
# for example by saying that the information retrieved from a memory file is no longer correct
|
||||
# or no longer relevant for the project.
|
||||
# * `edit_memory`: Replaces content matching a regular expression in a memory.
|
||||
# * `execute_shell_command`: Executes a shell command.
|
||||
# * `find_file`: Finds files in the given relative paths
|
||||
# * `find_referencing_symbols`: Finds symbols that reference the given symbol using the language server backend
|
||||
# * `find_symbol`: Performs a global (or local) search using the language server backend.
|
||||
# * `get_current_config`: Prints the current configuration of the agent, including the active and available projects, tools, contexts, and modes.
|
||||
# * `get_symbols_overview`: Gets an overview of the top-level symbols defined in a given file.
|
||||
# * `initial_instructions`: Provides instructions Serena usage (i.e. the 'Serena Instructions Manual')
|
||||
# for clients that do not read the initial instructions when the MCP server is connected.
|
||||
# * `insert_after_symbol`: Inserts content after the end of the definition of a given symbol.
|
||||
# * `insert_before_symbol`: Inserts content before the beginning of the definition of a given symbol.
|
||||
# * `list_dir`: Lists files and directories in the given directory (optionally with recursion).
|
||||
# * `list_memories`: List available memories. Any memory can be read using the `read_memory` tool.
|
||||
# * `onboarding`: Performs onboarding (identifying the project structure and essential tasks, e.g. for testing or building).
|
||||
# * `read_file`: Reads a file within the project directory.
|
||||
# * `read_memory`: Read the content of a memory file. This tool should only be used if the information
|
||||
# is relevant to the current task. You can infer whether the information
|
||||
# is relevant from the memory file name.
|
||||
# You should not read the same memory file multiple times in the same conversation.
|
||||
# * `rename_memory`: Renames or moves a memory. Moving between project and global scope is supported
|
||||
# (e.g., renaming "global/foo" to "bar" moves it from global to project scope).
|
||||
# * `rename_symbol`: Renames a symbol throughout the codebase using language server refactoring capabilities.
|
||||
# For JB, we use a separate tool.
|
||||
# * `replace_content`: Replaces content in a file (optionally using regular expressions).
|
||||
# * `replace_symbol_body`: Replaces the full definition of a symbol using the language server backend.
|
||||
# * `safe_delete_symbol`:
|
||||
# * `search_for_pattern`: Performs a search for a pattern in the project.
|
||||
# * `write_memory`: Write some information (utf-8-encoded) about this project that can be useful for future tasks to a memory in md format.
|
||||
# The memory name should be meaningful.
|
||||
excluded_tools: []
|
||||
|
||||
# list of tools to include that would otherwise be disabled (particularly optional tools that are disabled by default).
|
||||
# This extends the existing inclusions (e.g. from the global configuration).
|
||||
included_optional_tools: []
|
||||
|
||||
# fixed set of tools to use as the base tool set (if non-empty), replacing Serena's default set of tools.
|
||||
# This cannot be combined with non-empty excluded_tools or included_optional_tools.
|
||||
fixed_tools: []
|
||||
|
||||
# list of mode names to that are always to be included in the set of active modes
|
||||
# The full set of modes to be activated is base_modes + default_modes.
|
||||
# If the setting is undefined, the base_modes from the global configuration (serena_config.yml) apply.
|
||||
# Otherwise, this setting overrides the global configuration.
|
||||
# Set this to [] to disable base modes for this project.
|
||||
# Set this to a list of mode names to always include the respective modes for this project.
|
||||
base_modes:
|
||||
|
||||
# list of mode names that are to be activated by default.
|
||||
# The full set of modes to be activated is base_modes + default_modes.
|
||||
# If the setting is undefined, the default_modes from the global configuration (serena_config.yml) apply.
|
||||
# Otherwise, this overrides the setting from the global configuration (serena_config.yml).
|
||||
# This setting can, in turn, be overridden by CLI parameters (--mode).
|
||||
default_modes:
|
||||
|
||||
# initial prompt for the project. It will always be given to the LLM upon activating the project
|
||||
# (contrary to the memories, which are loaded on demand).
|
||||
initial_prompt: ""
|
||||
|
||||
# time budget (seconds) per tool call for the retrieval of additional symbol information
|
||||
# such as docstrings or parameter information.
|
||||
# This overrides the corresponding setting in the global configuration; see the documentation there.
|
||||
# If null or missing, use the setting from the global configuration.
|
||||
symbol_info_budget:
|
||||
|
||||
# list of regex patterns which, when matched, mark a memory entry as read‑only.
|
||||
# Extends the list from the global configuration, merging the two lists.
|
||||
read_only_memory_patterns: []
|
||||
|
||||
# list of regex patterns for memories to completely ignore.
|
||||
# Matching memories will not appear in list_memories or activate_project output
|
||||
# and cannot be accessed via read_memory or write_memory.
|
||||
# To access ignored memory files, use the read_file tool on the raw file path.
|
||||
# Extends the list from the global configuration, merging the two lists.
|
||||
# Example: ["_archive/.*", "_episodes/.*"]
|
||||
ignored_memory_patterns: []
|
||||
@@ -1,5 +1,34 @@
|
||||
# Vue 3 + TypeScript + Vite
|
||||
# timi-tdesign-mobile
|
||||
|
||||
This template should help get you started developing with Vue 3 and TypeScript in Vite. The template uses Vue 3 `<script setup>` SFCs, check out the [script setup docs](https://v3.vuejs.org/api/sfc-script-setup.html#sfc-script-setup) to learn more.
|
||||
Vue 3 移动端通用组件库,依赖 `timi-web` 提供基础组件和编辑器能力。
|
||||
|
||||
Learn more about the recommended Project Setup and IDE Support in the [Vue Docs TypeScript Guide](https://vuejs.org/guide/typescript/overview.html#project-setup).
|
||||
本包不依赖 `timi-web-api`。业务项目可以只安装本包使用通用组件;需要业务接口、领域类型或用户状态时,再单独安装 `timi-web-api`。
|
||||
|
||||
## 文章和通知组件
|
||||
|
||||
`ArticleEditor`、`ArticleView`、`NotifyEditor`、`NotifyView` 只约束对象的最小字段。`Article`、`Attachment` 和 `NotifyDetail` 支持携带业务自定义字段,不要求对象来自 `timi-web-api`。
|
||||
|
||||
上传和附件地址由业务项目通过回调注入:
|
||||
|
||||
```vue
|
||||
<article-editor
|
||||
:model-value="article"
|
||||
:upload-image="uploadImage"
|
||||
:upload-video="uploadVideo"
|
||||
:resolve-attachment-url="resolveAttachmentUrl"
|
||||
@update:model-value="article = $event"
|
||||
/>
|
||||
<article-view
|
||||
:article="article"
|
||||
:resolve-attachment-url="resolveAttachmentUrl"
|
||||
/>
|
||||
```
|
||||
|
||||
通知组件使用同样的 `uploadImage`、`uploadVideo` 和 `resolveAttachmentUrl` 回调。没有附件上传需求时,可以不传上传回调。
|
||||
|
||||
## 开发
|
||||
|
||||
```bash
|
||||
pnpm install
|
||||
pnpm run build
|
||||
```
|
||||
|
||||
+93
-2
@@ -1,11 +1,102 @@
|
||||
<template>
|
||||
<div class="demo-app">
|
||||
<header class="hero">
|
||||
<div>
|
||||
<t-loading />
|
||||
<p class="eyebrow">timi-tdesign-mobile</p>
|
||||
<h1>移动端组件演示台</h1>
|
||||
<p>每个页面都使用真实公开组件和可重复的本地演示数据。</p>
|
||||
</div>
|
||||
<t-tag theme="primary" variant="light">TDesign Mobile</t-tag>
|
||||
</header>
|
||||
|
||||
<nav class="tabs" aria-label="演示分类">
|
||||
<t-button
|
||||
v-for="item in tabs"
|
||||
:key="item.value"
|
||||
size="small"
|
||||
:theme="activeTab === item.value ? 'primary' : 'default'"
|
||||
variant="outline"
|
||||
@click="activeTab = item.value"
|
||||
v-text="item.label"
|
||||
/>
|
||||
</nav>
|
||||
|
||||
<main>
|
||||
<editor-showcase v-if="activeTab === 'editor'" />
|
||||
<article-showcase v-else-if="activeTab === 'article'" />
|
||||
<notify-showcase v-else-if="activeTab === 'notify'" />
|
||||
<duration-showcase v-else />
|
||||
</main>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script lang="ts" setup></script>
|
||||
<script lang="ts" setup>
|
||||
import ArticleShowcase from "./components/ArticleShowcase.vue";
|
||||
import DurationShowcase from "./components/DurationShowcase.vue";
|
||||
import EditorShowcase from "./components/EditorShowcase.vue";
|
||||
import NotifyShowcase from "./components/NotifyShowcase.vue";
|
||||
|
||||
type TabValue = "editor" | "article" | "notify" | "duration";
|
||||
|
||||
const tabs: Array<{ label: string; value: TabValue }> = [
|
||||
{ label: "编辑器", value: "editor" },
|
||||
{ label: "文章", value: "article" },
|
||||
{ label: "通知", value: "notify" },
|
||||
{ label: "移动端组件", value: "duration" }
|
||||
];
|
||||
const activeTab = ref<TabValue>("editor");
|
||||
</script>
|
||||
|
||||
<style lang="less" scoped>
|
||||
.demo-app {
|
||||
width: min(100% - 2rem, 80rem);
|
||||
min-height: 100vh;
|
||||
margin: 0 auto;
|
||||
padding: 2rem 0 4rem;
|
||||
color: var(--td-text-color-primary);
|
||||
}
|
||||
|
||||
.hero {
|
||||
align-items: flex-start;
|
||||
display: flex;
|
||||
gap: 1rem;
|
||||
justify-content: space-between;
|
||||
margin-bottom: 1.5rem;
|
||||
|
||||
h1 {
|
||||
margin: .25rem 0;
|
||||
font-size: clamp(1.75rem, 6vw, 3rem);
|
||||
}
|
||||
|
||||
p {
|
||||
margin: 0;
|
||||
color: var(--td-text-color-secondary);
|
||||
}
|
||||
}
|
||||
|
||||
.eyebrow {
|
||||
font-size: .75rem;
|
||||
letter-spacing: .08em;
|
||||
text-transform: uppercase;
|
||||
color: var(--td-brand-color);
|
||||
}
|
||||
|
||||
.tabs {
|
||||
display: flex;
|
||||
gap: .5rem;
|
||||
margin-bottom: 1.5rem;
|
||||
overflow-x: auto;
|
||||
padding-bottom: .25rem;
|
||||
}
|
||||
|
||||
@media (max-width: 40rem) {
|
||||
.demo-app {
|
||||
width: min(100% - 1rem, 80rem);
|
||||
padding-top: 1rem;
|
||||
}
|
||||
|
||||
.hero {
|
||||
flex-direction: column;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -0,0 +1,177 @@
|
||||
<template>
|
||||
<section class="demo-section">
|
||||
<div class="section-heading">
|
||||
<div>
|
||||
<p class="eyebrow">文章场景</p>
|
||||
<h2>文章编辑与预览</h2>
|
||||
<p>切换正文类型,验证统一的 Article 数据结构。</p>
|
||||
</div>
|
||||
<div class="actions">
|
||||
<t-button
|
||||
v-for="item in contentTypeOptions"
|
||||
:key="item.value"
|
||||
size="small"
|
||||
:theme="articleValue.contentType === item.value ? 'primary' : 'default'"
|
||||
variant="outline"
|
||||
@click="selectContentType(item.value)"
|
||||
v-text="item.label"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="demo-grid">
|
||||
<article class="demo-card">
|
||||
<div class="card-heading">
|
||||
<h3>ArticleEditor</h3>
|
||||
<t-button size="small" theme="primary" @click="submitArticle">提交文章</t-button>
|
||||
</div>
|
||||
<t-input v-model="articleValue.title" class="title-input" placeholder="文章标题" />
|
||||
<article-editor
|
||||
ref="articleEditorRef"
|
||||
:model-value="articleValue"
|
||||
:upload-image="uploadDemoMedia"
|
||||
:upload-video="uploadDemoMedia"
|
||||
@change="onArticleChange"
|
||||
@update:model-value="onArticleChange"
|
||||
/>
|
||||
<p class="status" v-text="articleStatus" />
|
||||
</article>
|
||||
|
||||
<article class="demo-card">
|
||||
<div class="card-heading">
|
||||
<h3>ArticleView</h3>
|
||||
<span v-text="articleValue.contentType" />
|
||||
</div>
|
||||
<article-view :article="articleValue" />
|
||||
</article>
|
||||
</div>
|
||||
</section>
|
||||
</template>
|
||||
|
||||
<script lang="ts" setup>
|
||||
import {
|
||||
ArticleEditor,
|
||||
ArticleView
|
||||
} from "timi-tdesign-mobile";
|
||||
import type { ArticleEditorExpose } from "timi-tdesign-mobile";
|
||||
import type { Article, ArticleContentType } from "timi-tdesign-mobile";
|
||||
import { DEMO_ARTICLE_CONTENT, cloneArticle, uploadDemoMedia } from "../demo-data";
|
||||
|
||||
const contentTypeOptions: Array<{ label: string; value: ArticleContentType }> = [
|
||||
{ label: "纯文本", value: "TEXT" },
|
||||
{ label: "Markdown", value: "MARKDOWN" },
|
||||
{ label: "Tiptap", value: "TIP_TAP" }
|
||||
];
|
||||
const articleValue = ref<Article>(cloneArticle());
|
||||
const articleEditorRef = ref<ArticleEditorExpose>();
|
||||
const articleStatus = ref("等待提交");
|
||||
|
||||
function selectContentType(contentType: ArticleContentType) {
|
||||
const content = contentType === "TEXT"
|
||||
? "这是一段纯文本示例。"
|
||||
: contentType === "MARKDOWN"
|
||||
? "## Markdown 示例\n\n这是一段 Markdown 正文。"
|
||||
: DEMO_ARTICLE_CONTENT;
|
||||
articleValue.value = {
|
||||
...articleValue.value,
|
||||
contentType,
|
||||
content
|
||||
};
|
||||
}
|
||||
|
||||
function onArticleChange(value: Article) {
|
||||
articleValue.value = value;
|
||||
}
|
||||
|
||||
async function submitArticle() {
|
||||
const value = await articleEditorRef.value?.submit();
|
||||
if (value) {
|
||||
articleValue.value = value;
|
||||
articleStatus.value = `已提交,${value.attachmentList?.length || 0} 个附件`;
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<style lang="less" scoped>
|
||||
.demo-section {
|
||||
.section-heading {
|
||||
align-items: flex-end;
|
||||
display: flex;
|
||||
gap: 1rem;
|
||||
justify-content: space-between;
|
||||
margin-bottom: 1rem;
|
||||
|
||||
h2 {
|
||||
margin: .25rem 0;
|
||||
}
|
||||
|
||||
p {
|
||||
margin: 0;
|
||||
color: var(--td-text-color-secondary);
|
||||
}
|
||||
}
|
||||
|
||||
.eyebrow {
|
||||
font-size: .75rem;
|
||||
letter-spacing: .08em;
|
||||
text-transform: uppercase;
|
||||
color: var(--td-brand-color);
|
||||
}
|
||||
|
||||
.actions,
|
||||
.card-heading {
|
||||
align-items: center;
|
||||
display: flex;
|
||||
gap: .5rem;
|
||||
justify-content: space-between;
|
||||
}
|
||||
|
||||
.demo-grid {
|
||||
display: grid;
|
||||
gap: 1rem;
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
}
|
||||
|
||||
.demo-card {
|
||||
padding: 1rem;
|
||||
border: 1px solid var(--td-component-border);
|
||||
border-radius: .75rem;
|
||||
background: var(--td-bg-color-container);
|
||||
|
||||
h3 {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
span,
|
||||
.status {
|
||||
font-size: .75rem;
|
||||
color: var(--td-text-color-secondary);
|
||||
}
|
||||
}
|
||||
|
||||
.title-input {
|
||||
margin: 1rem 0;
|
||||
}
|
||||
|
||||
.status {
|
||||
margin: 1rem 0 0;
|
||||
}
|
||||
|
||||
@media (max-width: 48rem) {
|
||||
.section-heading,
|
||||
.card-heading {
|
||||
align-items: flex-start;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.actions {
|
||||
flex-wrap: wrap;
|
||||
justify-content: flex-start;
|
||||
}
|
||||
|
||||
.demo-grid {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,88 @@
|
||||
<template>
|
||||
<section class="demo-section">
|
||||
<div class="section-heading">
|
||||
<div>
|
||||
<p class="eyebrow">移动端专属</p>
|
||||
<h2>DurationPicker</h2>
|
||||
<p>验证 Picker 交互和毫秒值双向转换。</p>
|
||||
</div>
|
||||
<span class="value" v-text="`${durationMs} ms`" />
|
||||
</div>
|
||||
<div class="demo-card">
|
||||
<t-cell title="当前毫秒值" arrow @click="visible = true">
|
||||
<span v-text="formatDuration(durationMs)" />
|
||||
</t-cell>
|
||||
</div>
|
||||
<t-popup v-model="visible" placement="bottom" destroy-on-close>
|
||||
<div class="picker-panel">
|
||||
<duration-picker v-model="durationMs" @change="visible = false" />
|
||||
</div>
|
||||
</t-popup>
|
||||
</section>
|
||||
</template>
|
||||
|
||||
<script lang="ts" setup>
|
||||
import { DurationPicker } from "timi-tdesign-mobile";
|
||||
|
||||
const visible = ref(false);
|
||||
const durationMs = ref(1000);
|
||||
|
||||
function formatDuration(value: number) {
|
||||
if (60 * 60 * 1000 <= value && value % (60 * 60 * 1000) === 0) {
|
||||
return `${value / (60 * 60 * 1000)} 小时`;
|
||||
}
|
||||
if (60 * 1000 <= value && value % (60 * 1000) === 0) {
|
||||
return `${value / (60 * 1000)} 分钟`;
|
||||
}
|
||||
if (1000 <= value && value % 1000 === 0) {
|
||||
return `${value / 1000} 秒`;
|
||||
}
|
||||
return `${value} 毫秒`;
|
||||
}
|
||||
</script>
|
||||
|
||||
<style lang="less" scoped>
|
||||
.demo-section {
|
||||
.section-heading {
|
||||
align-items: flex-end;
|
||||
display: flex;
|
||||
gap: 1rem;
|
||||
justify-content: space-between;
|
||||
margin-bottom: 1rem;
|
||||
|
||||
h2 {
|
||||
margin: .25rem 0;
|
||||
}
|
||||
|
||||
p {
|
||||
margin: 0;
|
||||
color: var(--td-text-color-secondary);
|
||||
}
|
||||
}
|
||||
|
||||
.eyebrow {
|
||||
font-size: .75rem;
|
||||
letter-spacing: .08em;
|
||||
text-transform: uppercase;
|
||||
color: var(--td-brand-color);
|
||||
}
|
||||
|
||||
.value {
|
||||
font-size: 1.25rem;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.demo-card {
|
||||
padding: .25rem;
|
||||
border: 1px solid var(--td-component-border);
|
||||
border-radius: .75rem;
|
||||
background: var(--td-bg-color-container);
|
||||
}
|
||||
|
||||
.picker-panel {
|
||||
padding-top: .5rem;
|
||||
border-radius: 1rem 1rem 0 0;
|
||||
background: var(--td-bg-color-container);
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,186 @@
|
||||
<template>
|
||||
<section class="demo-section">
|
||||
<div class="section-heading">
|
||||
<div>
|
||||
<p class="eyebrow">编辑器基础能力</p>
|
||||
<h2>文本、富文本和代码</h2>
|
||||
<p>通过同一组公共数据规则验证移动端 TDesign 交互。</p>
|
||||
</div>
|
||||
<div class="actions">
|
||||
<t-button size="small" theme="primary" @click="openSearch">打开搜索</t-button>
|
||||
<t-button size="small" variant="outline" @click="submitEditor">提交富文本</t-button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="demo-grid">
|
||||
<article class="demo-card wide">
|
||||
<div class="card-heading">
|
||||
<h3>Tiptap 编辑器</h3>
|
||||
<span v-text="editorStatus" />
|
||||
</div>
|
||||
<div class="editor-box rich-editor">
|
||||
<tiptap-editor
|
||||
ref="tiptapEditorRef"
|
||||
v-model="richContent"
|
||||
:upload-image="uploadDemoMedia"
|
||||
:upload-video="uploadDemoMedia"
|
||||
@change="editorStatus = `内容已更新,${$event.length} 个字符`"
|
||||
/>
|
||||
</div>
|
||||
</article>
|
||||
|
||||
<article class="demo-card wide">
|
||||
<div class="card-heading">
|
||||
<h3>Tiptap 只读视图</h3>
|
||||
<t-input v-model="maxHeight" class="height-input" placeholder="最大高度,如 20rem" />
|
||||
</div>
|
||||
<tiptap-view :content="richContent" :max-height="maxHeight" />
|
||||
</article>
|
||||
|
||||
<article class="demo-card wide">
|
||||
<div class="card-heading">
|
||||
<h3>代码编辑器</h3>
|
||||
<t-button size="small" variant="text" @click="resetCode">恢复示例</t-button>
|
||||
</div>
|
||||
<div class="editor-box code-editor">
|
||||
<code-editor
|
||||
ref="codeEditorRef"
|
||||
v-model="codeContent"
|
||||
language="typescript"
|
||||
placeholder="请输入代码"
|
||||
/>
|
||||
</div>
|
||||
</article>
|
||||
</div>
|
||||
</section>
|
||||
</template>
|
||||
|
||||
<script lang="ts" setup>
|
||||
import {
|
||||
CodeEditor,
|
||||
TiptapEditor,
|
||||
TiptapView
|
||||
} from "timi-tdesign-mobile";
|
||||
import type {
|
||||
CodeEditorExpose,
|
||||
TiptapEditorExpose
|
||||
} from "timi-tdesign-mobile";
|
||||
import { DEMO_ARTICLE_CONTENT, DEMO_CODE, uploadDemoMedia } from "../demo-data";
|
||||
|
||||
const richContent = ref(DEMO_ARTICLE_CONTENT);
|
||||
const codeContent = ref(DEMO_CODE);
|
||||
const maxHeight = ref("20rem");
|
||||
const editorStatus = ref("等待编辑");
|
||||
const tiptapEditorRef = ref<TiptapEditorExpose>();
|
||||
const codeEditorRef = ref<CodeEditorExpose>();
|
||||
|
||||
function openSearch() {
|
||||
tiptapEditorRef.value?.openSearch(true);
|
||||
codeEditorRef.value?.openSearch(true);
|
||||
}
|
||||
|
||||
async function submitEditor() {
|
||||
const value = await tiptapEditorRef.value?.submit();
|
||||
if (value !== undefined) {
|
||||
editorStatus.value = `已提交,${value.length} 个字符`;
|
||||
}
|
||||
}
|
||||
|
||||
function resetCode() {
|
||||
codeContent.value = DEMO_CODE;
|
||||
}
|
||||
</script>
|
||||
|
||||
<style lang="less" scoped>
|
||||
.demo-section {
|
||||
.section-heading {
|
||||
align-items: flex-end;
|
||||
display: flex;
|
||||
gap: 1rem;
|
||||
justify-content: space-between;
|
||||
margin-bottom: 1rem;
|
||||
|
||||
h2 {
|
||||
margin: .25rem 0;
|
||||
}
|
||||
|
||||
p {
|
||||
margin: 0;
|
||||
color: var(--td-text-color-secondary);
|
||||
}
|
||||
}
|
||||
|
||||
.eyebrow {
|
||||
font-size: .75rem;
|
||||
letter-spacing: .08em;
|
||||
text-transform: uppercase;
|
||||
color: var(--td-brand-color);
|
||||
}
|
||||
|
||||
.actions,
|
||||
.card-heading {
|
||||
align-items: center;
|
||||
display: flex;
|
||||
gap: .5rem;
|
||||
justify-content: space-between;
|
||||
}
|
||||
|
||||
.demo-grid {
|
||||
display: grid;
|
||||
gap: 1rem;
|
||||
}
|
||||
|
||||
.demo-card {
|
||||
min-width: 0;
|
||||
padding: 1rem;
|
||||
border: 1px solid var(--td-component-border);
|
||||
border-radius: .75rem;
|
||||
background: var(--td-bg-color-container);
|
||||
box-shadow: 0 .25rem 1rem rgba(0, 0, 0, .04);
|
||||
|
||||
h3 {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
span {
|
||||
font-size: .75rem;
|
||||
color: var(--td-text-color-secondary);
|
||||
}
|
||||
}
|
||||
|
||||
.editor-box {
|
||||
width: 100%;
|
||||
min-width: 0;
|
||||
height: 24rem;
|
||||
margin-top: 1rem;
|
||||
}
|
||||
|
||||
.rich-editor {
|
||||
height: 28rem;
|
||||
}
|
||||
|
||||
.height-input {
|
||||
width: 9rem;
|
||||
}
|
||||
|
||||
@media (max-width: 40rem) {
|
||||
.section-heading {
|
||||
align-items: stretch;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.actions {
|
||||
justify-content: flex-start;
|
||||
}
|
||||
|
||||
.card-heading {
|
||||
align-items: flex-start;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.height-input {
|
||||
width: 100%;
|
||||
}
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,137 @@
|
||||
<template>
|
||||
<section class="demo-section">
|
||||
<div class="section-heading">
|
||||
<div>
|
||||
<p class="eyebrow">通知场景</p>
|
||||
<h2>通知编辑与预览</h2>
|
||||
<p>Notify 组件复用文章编辑器,同时保留通知自己的元数据。</p>
|
||||
</div>
|
||||
<t-button size="small" theme="primary" @click="submitNotify">提交通知</t-button>
|
||||
</div>
|
||||
|
||||
<div class="demo-grid">
|
||||
<article class="demo-card">
|
||||
<div class="card-heading">
|
||||
<h3>NotifyEditor</h3>
|
||||
<span v-text="notifyStatus" />
|
||||
</div>
|
||||
<t-input v-model="notifyValue.subject" class="subject-input" placeholder="通知标题" />
|
||||
<notify-editor
|
||||
ref="notifyEditorRef"
|
||||
:model-value="notifyValue"
|
||||
:upload-image="uploadDemoMedia"
|
||||
:upload-video="uploadDemoMedia"
|
||||
@change="onNotifyChange"
|
||||
@update:model-value="onNotifyChange"
|
||||
/>
|
||||
</article>
|
||||
|
||||
<article class="demo-card">
|
||||
<div class="card-heading">
|
||||
<h3>NotifyView</h3>
|
||||
<span v-text="notifyValue.status" />
|
||||
</div>
|
||||
<notify-view :detail="notifyValue" />
|
||||
</article>
|
||||
</div>
|
||||
</section>
|
||||
</template>
|
||||
|
||||
<script lang="ts" setup>
|
||||
import {
|
||||
NotifyEditor,
|
||||
NotifyView
|
||||
} from "timi-tdesign-mobile";
|
||||
import type { NotifyEditorExpose } from "timi-tdesign-mobile";
|
||||
import type { NotifyDetail } from "timi-tdesign-mobile";
|
||||
import { cloneNotify, uploadDemoMedia } from "../demo-data";
|
||||
|
||||
const notifyValue = ref<NotifyDetail>(cloneNotify());
|
||||
const notifyEditorRef = ref<NotifyEditorExpose>();
|
||||
const notifyStatus = ref("等待提交");
|
||||
|
||||
function onNotifyChange(value: NotifyDetail) {
|
||||
notifyValue.value = value;
|
||||
}
|
||||
|
||||
async function submitNotify() {
|
||||
const value = await notifyEditorRef.value?.submit();
|
||||
if (value) {
|
||||
notifyValue.value = value;
|
||||
notifyStatus.value = `已提交,${value.content?.length || 0} 个字符`;
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<style lang="less" scoped>
|
||||
.demo-section {
|
||||
.section-heading {
|
||||
align-items: flex-end;
|
||||
display: flex;
|
||||
gap: 1rem;
|
||||
justify-content: space-between;
|
||||
margin-bottom: 1rem;
|
||||
|
||||
h2 {
|
||||
margin: .25rem 0;
|
||||
}
|
||||
|
||||
p {
|
||||
margin: 0;
|
||||
color: var(--td-text-color-secondary);
|
||||
}
|
||||
}
|
||||
|
||||
.eyebrow {
|
||||
font-size: .75rem;
|
||||
letter-spacing: .08em;
|
||||
text-transform: uppercase;
|
||||
color: var(--td-brand-color);
|
||||
}
|
||||
|
||||
.card-heading {
|
||||
align-items: center;
|
||||
display: flex;
|
||||
gap: .5rem;
|
||||
justify-content: space-between;
|
||||
|
||||
h3 {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
span {
|
||||
font-size: .75rem;
|
||||
color: var(--td-text-color-secondary);
|
||||
}
|
||||
}
|
||||
|
||||
.demo-grid {
|
||||
display: grid;
|
||||
gap: 1rem;
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
}
|
||||
|
||||
.demo-card {
|
||||
padding: 1rem;
|
||||
border: 1px solid var(--td-component-border);
|
||||
border-radius: .75rem;
|
||||
background: var(--td-bg-color-container);
|
||||
}
|
||||
|
||||
.subject-input {
|
||||
margin: 1rem 0;
|
||||
}
|
||||
|
||||
@media (max-width: 48rem) {
|
||||
.section-heading,
|
||||
.card-heading {
|
||||
align-items: flex-start;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.demo-grid {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,59 @@
|
||||
import type { Article, NotifyDetail, UploadResult } from "timi-tdesign-mobile";
|
||||
|
||||
/** 编辑器演示使用的固定内容,避免每个页面各自维护一份 HTML。 */
|
||||
export const DEMO_ARTICLE_CONTENT = `<h2>跨平台编辑器</h2>
|
||||
<p>这段内容同时验证标题、段落、链接、表格和代码块的渲染。</p>
|
||||
<blockquote><p>移动端和 PC 端只替换交互层,共享文档模型。</p></blockquote>
|
||||
<pre><code class="language-typescript">const message: string = "timi editor";</code></pre>`;
|
||||
|
||||
export const DEMO_CODE = `type DemoUser = {
|
||||
\tid: string;
|
||||
\tname: string;
|
||||
};
|
||||
|
||||
const user: DemoUser = {
|
||||
\tid: "demo-001",
|
||||
\tname: "Timi"
|
||||
};
|
||||
|
||||
console.log(user.name);`;
|
||||
|
||||
export const DEMO_ARTICLE: Article = {
|
||||
title: "编辑器组件演示文章",
|
||||
description: "用于验证文章编辑、预览和附件处理。",
|
||||
contentType: "TIP_TAP",
|
||||
content: DEMO_ARTICLE_CONTENT,
|
||||
attachmentList: []
|
||||
};
|
||||
|
||||
export const DEMO_NOTIFY: NotifyDetail = {
|
||||
subject: "编辑器通知演示",
|
||||
msgType: "INTERNAL",
|
||||
contentType: "TIP_TAP",
|
||||
content: DEMO_ARTICLE_CONTENT,
|
||||
status: "WAITING",
|
||||
attachmentList: []
|
||||
};
|
||||
|
||||
export function cloneArticle(): Article {
|
||||
return {
|
||||
...DEMO_ARTICLE,
|
||||
attachmentList: [...(DEMO_ARTICLE.attachmentList || [])]
|
||||
};
|
||||
}
|
||||
|
||||
export function cloneNotify(): NotifyDetail {
|
||||
return {
|
||||
...DEMO_NOTIFY,
|
||||
attachmentList: [...(DEMO_NOTIFY.attachmentList || [])]
|
||||
};
|
||||
}
|
||||
|
||||
/** 返回本地预览地址,让示例无需依赖后端上传接口。 */
|
||||
export async function uploadDemoMedia(file: File): Promise<UploadResult> {
|
||||
return {
|
||||
id: `demo-${Date.now()}-${file.name}`,
|
||||
name: file.name,
|
||||
url: URL.createObjectURL(file)
|
||||
};
|
||||
}
|
||||
+4
-4
@@ -1,12 +1,12 @@
|
||||
import { createApp } from "vue";
|
||||
import Root from "./Root.vue";
|
||||
|
||||
import TimiWebUI from "timi-web";
|
||||
|
||||
import "timi-web/style.css";
|
||||
import "tdesign-mobile-vue/es/style/index.css";
|
||||
import { axios, VPopup } from "timi-web";
|
||||
|
||||
axios.defaults.baseURL = "http://localhost:8091";
|
||||
import "../src/assets/style/tdesign-custom.less";
|
||||
|
||||
const app = createApp(Root);
|
||||
app.directive("popup", VPopup);
|
||||
app.use(TimiWebUI);
|
||||
app.mount("#root");
|
||||
|
||||
+10
-3
@@ -1,9 +1,16 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8"/>
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
|
||||
<title>Vite + Vue + TS</title>
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1, maximum-scale=1, user-scalable=no, viewport-fit=cover" />
|
||||
<meta name="theme-color" content="#f5f5f5"/>
|
||||
<meta name="color-scheme" content="light dark"/>
|
||||
<meta name="format-detection" content="telephone=no"/>
|
||||
<meta name="mobile-web-app-capable" content="yes"/>
|
||||
<meta name="apple-mobile-web-app-capable" content="yes"/>
|
||||
<meta name="apple-mobile-web-app-status-bar-style" content="default"/>
|
||||
<meta name="apple-mobile-web-app-title" content="Timi Mobile"/>
|
||||
<title>Timi TDesign Mobile</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
|
||||
+7
-7
@@ -1,11 +1,11 @@
|
||||
{
|
||||
"name": "timi-tdesign-mobile",
|
||||
"main": "./dist/timi-tdesign-mobile.umd.js",
|
||||
"types": "./dist/src/index.d.ts",
|
||||
"types": "./dist/timi-tdesign-mobile/src/index.d.ts",
|
||||
"module": "./dist/timi-tdesign-mobile.mjs",
|
||||
"style": "./dist/timi-tdesign-mobile.css",
|
||||
"private": false,
|
||||
"version": "0.0.3",
|
||||
"version": "0.0.10",
|
||||
"license": "MIT",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
@@ -26,7 +26,7 @@
|
||||
],
|
||||
"exports": {
|
||||
".": {
|
||||
"types": "./dist/src/index.d.ts",
|
||||
"types": "./dist/timi-tdesign-mobile/src/index.d.ts",
|
||||
"import": "./dist/timi-tdesign-mobile.mjs",
|
||||
"require": "./dist/timi-tdesign-mobile.umd.js"
|
||||
},
|
||||
@@ -36,7 +36,9 @@
|
||||
"node": ">=16.0.0"
|
||||
},
|
||||
"dependencies": {
|
||||
"vue": "^3.5.13",
|
||||
"tdesign-mobile-vue": "^1.13.2",
|
||||
"timi-web": "link:E:/WebProject/timi-web",
|
||||
"vue": "3.5.26",
|
||||
"vue-router": "4.5.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
@@ -63,8 +65,6 @@
|
||||
"vite-plugin-vue-setup-extend": "^0.4.0",
|
||||
"@vue/tsconfig": "^0.7.0",
|
||||
"vite": "7.1.11",
|
||||
"vue-tsc": "^2.2.10",
|
||||
"tdesign-mobile-vue": "^1.13.2",
|
||||
"timi-web": "0.0.2"
|
||||
"vue-tsc": "^2.2.10"
|
||||
}
|
||||
}
|
||||
|
||||
Generated
+393
-440
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,52 @@
|
||||
/* TDesign 腾讯云样式附加修改 */
|
||||
@cellPadding: 10px 16px;
|
||||
.cellStyle() {
|
||||
margin: 0 16px;
|
||||
}
|
||||
.cellSplit() {
|
||||
transform: none;
|
||||
-webkit-transform: none;
|
||||
}
|
||||
|
||||
.t-image-viewer {
|
||||
|
||||
.t-swiper-item {
|
||||
overflow: hidden;
|
||||
}
|
||||
}
|
||||
|
||||
.t-form {
|
||||
.cellStyle();
|
||||
|
||||
.t-form__item {
|
||||
padding: @cellPadding;
|
||||
|
||||
&:not(:last-child)::after {
|
||||
.cellSplit();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.t-cell {
|
||||
padding: @cellPadding;
|
||||
|
||||
&:after {
|
||||
.cellSplit();
|
||||
}
|
||||
|
||||
.t-cell__right-icon {
|
||||
transform: translateX(5px);
|
||||
}
|
||||
}
|
||||
|
||||
.t-divider {
|
||||
|
||||
&::before,
|
||||
&::after {
|
||||
.cellSplit();
|
||||
}
|
||||
|
||||
&.t-divider--horizontal {
|
||||
margin: 0;
|
||||
}
|
||||
}
|
||||
@@ -1,4 +0,0 @@
|
||||
/* TDesign 腾讯云样式附加修改 */
|
||||
.t-popup {
|
||||
transition: all 520ms var(--tui-bezier) !important;
|
||||
}
|
||||
@@ -1,284 +0,0 @@
|
||||
:root, :root[theme-mode="light"] {
|
||||
--td-brand-color-1: #fff0f2;
|
||||
--td-brand-color-2: #ffdae1;
|
||||
--td-brand-color-3: #ffb2c3;
|
||||
--td-brand-color-4: #ff7a9b;
|
||||
--td-brand-color-5: #e16283;
|
||||
--td-brand-color-6: #bd4a69;
|
||||
--td-brand-color-7: #9a3652;
|
||||
--td-brand-color-8: #7b223d;
|
||||
--td-brand-color-9: #600e2a;
|
||||
--td-brand-color-10: #470019;
|
||||
--td-warning-color-1: #fff1e9;
|
||||
--td-warning-color-2: #ffd9c2;
|
||||
--td-warning-color-3: #ffb98c;
|
||||
--td-warning-color-4: #fa9550;
|
||||
--td-warning-color-5: #e37318;
|
||||
--td-warning-color-6: #be5a00;
|
||||
--td-warning-color-7: #954500;
|
||||
--td-warning-color-8: #713300;
|
||||
--td-warning-color-9: #532300;
|
||||
--td-warning-color-10: #3b1700;
|
||||
--td-error-color-1: #fff0ed;
|
||||
--td-error-color-2: #ffd8d2;
|
||||
--td-error-color-3: #ffb9b0;
|
||||
--td-error-color-4: #ff9285;
|
||||
--td-error-color-5: #f6685d;
|
||||
--td-error-color-6: #d54941;
|
||||
--td-error-color-7: #ad352f;
|
||||
--td-error-color-8: #881f1c;
|
||||
--td-error-color-9: #68070a;
|
||||
--td-error-color-10: #490002;
|
||||
--td-success-color-1: #e3f9e9;
|
||||
--td-success-color-2: #c6f3d7;
|
||||
--td-success-color-3: #92dab2;
|
||||
--td-success-color-4: #56c08d;
|
||||
--td-success-color-5: #2ba471;
|
||||
--td-success-color-6: #008858;
|
||||
--td-success-color-7: #006c45;
|
||||
--td-success-color-8: #005334;
|
||||
--td-success-color-9: #003b23;
|
||||
--td-success-color-10: #002515;
|
||||
--td-gray-color-1: #f6f6f6;
|
||||
--td-gray-color-2: #eeeceb;
|
||||
--td-gray-color-3: #dddbdb;
|
||||
--td-gray-color-4: #cac9c9;
|
||||
--td-gray-color-5: #b6b6b6;
|
||||
--td-gray-color-6: #a2a2a2;
|
||||
--td-gray-color-7: #8f8f8f;
|
||||
--td-gray-color-8: #7b7c7c;
|
||||
--td-gray-color-9: #6a6b6b;
|
||||
--td-gray-color-10: #585a5a;
|
||||
--td-gray-color-11: #494a4a;
|
||||
--td-gray-color-12: #3a3b3b;
|
||||
--td-gray-color-13: #2c2e2e;
|
||||
--td-gray-color-14: #202222;
|
||||
--td-font-white-1: rgba(255, 255, 255, 1);
|
||||
--td-font-white-2: rgba(255, 255, 255, .55);
|
||||
--td-font-white-3: rgba(255, 255, 255, .35);
|
||||
--td-font-white-4: rgba(255, 255, 255, .22);
|
||||
--td-font-gray-1: rgba(0, 0, 0, .9);
|
||||
--td-font-gray-2: rgba(0, 0, 0, .6);
|
||||
--td-font-gray-3: rgba(0, 0, 0, .4);
|
||||
--td-font-gray-4: rgba(0, 0, 0, .26);
|
||||
--td-brand-color: var(--td-brand-color-4);
|
||||
--td-warning-color: var(--td-warning-color-5);
|
||||
--td-error-color: var(--td-error-color-6);
|
||||
--td-success-color: var(--td-success-color-5);
|
||||
--td-brand-color-focus: var(--td-brand-color-1);
|
||||
--td-brand-color-active: var(--td-brand-color-5);
|
||||
--td-brand-color-disabled: var(--td-brand-color-3);
|
||||
--td-brand-color-light: var(--td-brand-color-1);
|
||||
--td-brand-color-light-active: var(--td-brand-color-2);
|
||||
--td-warning-color-active: var(--td-warning-color-6);
|
||||
--td-warning-color-disabled: var(--td-warning-color-3);
|
||||
--td-warning-color-focus: var(--td-warning-color-2);
|
||||
--td-warning-color-light: var(--td-warning-color-1);
|
||||
--td-warning-color-light-active: var(--td-warning-color-2);
|
||||
--td-error-color-focus: var(--td-error-color-2);
|
||||
--td-error-color-active: var(--td-error-color-7);
|
||||
--td-error-color-disabled: var(--td-error-color-3);
|
||||
--td-error-color-light: var(--td-error-color-1);
|
||||
--td-error-color-light-active: var(--td-error-color-2);
|
||||
--td-success-color-focus: var(--td-success-color-2);
|
||||
--td-success-color-active: var(--td-success-color-6);
|
||||
--td-success-color-disabled: var(--td-success-color-3);
|
||||
--td-success-color-light: var(--td-success-color-1);
|
||||
--td-success-color-light-active: var(--td-success-color-2);
|
||||
--td-mask-active: rgba(0, 0, 0, .6);
|
||||
--td-mask-disabled: rgba(255, 255, 255, .6);
|
||||
--td-bg-color-page: var(--td-gray-color-1);
|
||||
--td-bg-color-container: var(--td-font-white-1);
|
||||
--td-bg-color-container-active: var(--td-gray-color-3);
|
||||
--td-bg-color-secondarycontainer: var(--td-gray-color-1);
|
||||
--td-bg-color-secondarycontainer-active: var(--td-gray-color-4);
|
||||
--td-bg-color-component: var(--td-gray-color-3);
|
||||
--td-bg-color-component-active: var(--td-gray-color-6);
|
||||
--td-bg-color-component-disabled: var(--td-gray-color-2);
|
||||
--td-bg-color-secondarycomponent: var(--td-gray-color-4);
|
||||
--td-bg-color-secondarycomponent-active: var(--td-gray-color-6);
|
||||
--td-bg-color-specialcomponent: #fff;
|
||||
--td-text-color-primary: var(--td-font-gray-1);
|
||||
--td-text-color-secondary: var(--td-font-gray-2);
|
||||
--td-text-color-placeholder: var(--td-font-gray-3);
|
||||
--td-text-color-disabled: var(--td-font-gray-4);
|
||||
--td-text-color-anti: var(--td-font-white-1);
|
||||
--td-text-color-brand: var(--td-brand-color);
|
||||
--td-text-color-link: var(--td-brand-color);
|
||||
--td-border-level-1-color: var(--td-gray-color-3);
|
||||
--td-component-stroke: var(--td-gray-color-3);
|
||||
--td-border-level-2-color: var(--td-gray-color-4);
|
||||
--td-component-border: var(--td-gray-color-4);
|
||||
--td-shadow-1: 0 1px 10px rgba(0, 0, 0, 5%), 0 4px 5px rgba(0, 0, 0, 8%), 0 2px 4px -1px rgba(0, 0, 0, 12%);
|
||||
--td-shadow-2: 0 3px 14px 2px rgba(0, 0, 0, 5%), 0 8px 10px 1px rgba(0, 0, 0, 6%), 0 5px 5px -3px rgba(0, 0, 0, 10%);
|
||||
--td-shadow-3: 0 6px 30px 5px rgba(0, 0, 0, 5%), 0 16px 24px 2px rgba(0, 0, 0, 4%), 0 8px 10px -5px rgba(0, 0, 0, 8%);
|
||||
--td-shadow-4: 0 2px 8px 0 rgba(0, 0, 0, 6%);
|
||||
--td-shadow-inset-top: inset 0 .5px 0 #dcdcdc;
|
||||
--td-shadow-inset-right: inset .5px 0 0 #dcdcdc;
|
||||
--td-shadow-inset-bottom: inset 0 -.5px 0 #dcdcdc;
|
||||
--td-shadow-inset-left: inset -.5px 0 0 #dcdcdc;
|
||||
--td-table-shadow-color: rgba(0, 0, 0, .08);
|
||||
--td-scrollbar-color: rgba(0, 0, 0, .1);
|
||||
--td-scrollbar-hover-color: rgba(0, 0, 0, .3);
|
||||
--td-scroll-track-color: #fff;
|
||||
}
|
||||
|
||||
:root.dark, :root[theme-mode="dark"] {
|
||||
--td-brand-color-1: #470019;
|
||||
--td-brand-color-2: #600e2a;
|
||||
--td-brand-color-3: #7b223d;
|
||||
--td-brand-color-4: #9a3652;
|
||||
--td-brand-color-5: #bd4a69;
|
||||
--td-brand-color-6: #e16283;
|
||||
--td-brand-color-7: #ff7a9b;
|
||||
--td-brand-color-8: #ffb2c3;
|
||||
--td-brand-color-9: #ffdae1;
|
||||
--td-brand-color-10: #fff0f2;
|
||||
--td-warning-color-1: #4f2a1d;
|
||||
--td-warning-color-2: #582f21;
|
||||
--td-warning-color-3: #733c23;
|
||||
--td-warning-color-4: #a75d2b;
|
||||
--td-warning-color-5: #cf6e2d;
|
||||
--td-warning-color-6: #dc7633;
|
||||
--td-warning-color-7: #e8935c;
|
||||
--td-warning-color-8: #ecbf91;
|
||||
--td-warning-color-9: #eed7bf;
|
||||
--td-warning-color-10: #f3e9dc;
|
||||
--td-error-color-1: #472324;
|
||||
--td-error-color-2: #5e2a2d;
|
||||
--td-error-color-3: #703439;
|
||||
--td-error-color-4: #83383e;
|
||||
--td-error-color-5: #a03f46;
|
||||
--td-error-color-6: #c64751;
|
||||
--td-error-color-7: #de6670;
|
||||
--td-error-color-8: #ec888e;
|
||||
--td-error-color-9: #edb1b6;
|
||||
--td-error-color-10: #eeced0;
|
||||
--td-success-color-1: #193a2a;
|
||||
--td-success-color-2: #1a4230;
|
||||
--td-success-color-3: #17533d;
|
||||
--td-success-color-4: #0d7a55;
|
||||
--td-success-color-5: #059465;
|
||||
--td-success-color-6: #43af8a;
|
||||
--td-success-color-7: #46bf96;
|
||||
--td-success-color-8: #80d2b6;
|
||||
--td-success-color-9: #b4e1d3;
|
||||
--td-success-color-10: #deede8;
|
||||
--td-gray-color-1: #f6f6f6;
|
||||
--td-gray-color-2: #eeeceb;
|
||||
--td-gray-color-3: #dddbdb;
|
||||
--td-gray-color-4: #cac9c9;
|
||||
--td-gray-color-5: #b6b6b6;
|
||||
--td-gray-color-6: #a2a2a2;
|
||||
--td-gray-color-7: #8f8f8f;
|
||||
--td-gray-color-8: #7b7c7c;
|
||||
--td-gray-color-9: #6a6b6b;
|
||||
--td-gray-color-10: #585a5a;
|
||||
--td-gray-color-11: #494a4a;
|
||||
--td-gray-color-12: #3a3b3b;
|
||||
--td-gray-color-13: #2c2e2e;
|
||||
--td-gray-color-14: #202222;
|
||||
--td-font-white-1: rgba(255, 255, 255, .9);
|
||||
--td-font-white-2: rgba(255, 255, 255, .55);
|
||||
--td-font-white-3: rgba(255, 255, 255, .35);
|
||||
--td-font-white-4: rgba(255, 255, 255, .22);
|
||||
--td-font-gray-1: rgba(0, 0, 0, .9);
|
||||
--td-font-gray-2: rgba(0, 0, 0, .6);
|
||||
--td-font-gray-3: rgba(0, 0, 0, .4);
|
||||
--td-font-gray-4: rgba(0, 0, 0, .26);
|
||||
--td-brand-color: var(--td-brand-color-6);
|
||||
--td-warning-color: var(--td-warning-color-5);
|
||||
--td-error-color: var(--td-error-color-6);
|
||||
--td-success-color: var(--td-success-color-5);
|
||||
--td-brand-color-focus: var(--td-brand-color-1);
|
||||
--td-brand-color-active: var(--td-brand-color-7);
|
||||
--td-brand-color-disabled: var(--td-brand-color-3);
|
||||
--td-brand-color-light: var(--td-brand-color-1);
|
||||
--td-brand-color-light-active: var(--td-brand-color-2);
|
||||
--td-warning-color-focus: var(--td-warning-color-2);
|
||||
--td-warning-color-active: var(--td-warning-color-4);
|
||||
--td-warning-color-disabled: var(--td-warning-color-3);
|
||||
--td-warning-color-light: var(--td-warning-color-1);
|
||||
--td-warning-color-light-active: var(--td-warning-color-2);
|
||||
--td-error-color-focus: var(--td-error-color-2);
|
||||
--td-error-color-active: var(--td-error-color-5);
|
||||
--td-error-color-disabled: var(--td-error-color-3);
|
||||
--td-error-color-light: var(--td-error-color-1);
|
||||
--td-error-color-light-active: var(--td-error-color-2);
|
||||
--td-success-color-focus: var(--td-success-color-2);
|
||||
--td-success-color-active: var(--td-success-color-4);
|
||||
--td-success-color-disabled: var(--td-success-color-3);
|
||||
--td-success-color-light: var(--td-success-color-1);
|
||||
--td-success-color-light-active: var(--td-success-color-2);
|
||||
--td-mask-active: rgba(0, 0, 0, .4);
|
||||
--td-mask-disabled: rgba(0, 0, 0, .6);
|
||||
--td-bg-color-page: var(--td-gray-color-14);
|
||||
--td-bg-color-container: var(--td-gray-color-13);
|
||||
--td-bg-color-secondarycontainer: var(--td-gray-color-12);
|
||||
--td-bg-color-component: var(--td-gray-color-11);
|
||||
--td-bg-color-container-active: var(--td-gray-color-12);
|
||||
--td-bg-color-secondarycontainer-active: var(--td-gray-color-11);
|
||||
--td-bg-color-component-active: var(--td-gray-color-10);
|
||||
--td-bg-color-component-disabled: var(--td-gray-color-12);
|
||||
--td-bg-color-specialcomponent: transparent;
|
||||
--td-text-color-primary: var(--td-font-white-1);
|
||||
--td-text-color-secondary: var(--td-font-white-2);
|
||||
--td-text-color-placeholder: var(--td-font-white-3);
|
||||
--td-text-color-disabled: var(--td-font-white-4);
|
||||
--td-text-color-anti: var(--td-font-white-1);
|
||||
--td-text-color-brand: var(--td-brand-color-8);
|
||||
--td-text-color-link: var(--td-brand-color-8);
|
||||
--td-border-level-1-color: var(--td-gray-color-11);
|
||||
--td-component-stroke: var(--td-gray-color-11);
|
||||
--td-border-level-2-color: var(--td-gray-color-9);
|
||||
--td-component-border: var(--td-gray-color-9);
|
||||
--td-shadow-1: 0 4px 6px rgba(0, 0, 0, 6%), 0 1px 10px rgba(0, 0, 0, 8%), 0 2px 4px rgba(0, 0, 0, 12%);
|
||||
--td-shadow-2: 0 8px 10px rgba(0, 0, 0, 12%), 0 3px 14px rgba(0, 0, 0, 10%), 0 5px 5px rgba(0, 0, 0, 16%);
|
||||
--td-shadow-3: 0 16px 24px rgba(0, 0, 0, 14%), 0 6px 30px rgba(0, 0, 0, 12%), 0 8px 10px rgba(0, 0, 0, 20%);
|
||||
--td-shadow-inset-top: inset 0 .5px 0 #5e5e5e;
|
||||
--td-shadow-inset-right: inset .5px 0 0 #5e5e5e;
|
||||
--td-shadow-inset-bottom: inset 0 -.5px 0 #5e5e5e;
|
||||
--td-shadow-inset-left: inset -.5px 0 0 #5e5e5e;
|
||||
--td-table-shadow-color: rgba(0, 0, 0, .55);
|
||||
--td-scrollbar-color: rgba(255, 255, 255, .1);
|
||||
--td-scroll-track-color: #333;
|
||||
}
|
||||
|
||||
:root {
|
||||
--td-font-family: pingfang sc, microsoft yahei, arial regular;
|
||||
--td-font-family-medium: pingfang sc, microsoft yahei, arial medium;
|
||||
--td-font-size-link-small: 12px;
|
||||
--td-font-size-link-medium: 14px;
|
||||
--td-font-size-link-large: 16px;
|
||||
--td-font-size-mark-extraSmall: 10px;
|
||||
--td-font-size-mark-small: 12px;
|
||||
--td-font-size-mark-medium: 14px;
|
||||
--td-font-size-mark-large: 16px;
|
||||
--td-font-size-body-extraSmall: 10px;
|
||||
--td-font-size-body-small: 12px;
|
||||
--td-font-size-body-medium: 14px;
|
||||
--td-font-size-body-large: 16px;
|
||||
--td-font-size-title-small: 14px;
|
||||
--td-font-size-title-medium: 16px;
|
||||
--td-font-size-title-large: 18px;
|
||||
--td-font-size-title-extraLarge: 20px;
|
||||
--td-font-size-headline-small: 24px;
|
||||
--td-font-size-headline-medium: 28px;
|
||||
--td-font-size-headline-large: 36px;
|
||||
--td-font-size-display-medium: 48px;
|
||||
--td-font-size-display-large: 64px;
|
||||
--td-font-size: 10px;
|
||||
--td-font-size-xs: var(--td-font-size-body-extraSmall);
|
||||
--td-font-size-s: var(--td-font-size-body-small);
|
||||
--td-font-size-base: var(--td-font-size-title-small);
|
||||
--td-font-size-m: var(--td-font-size-title-medium);
|
||||
--td-font-size-l: var(--td-font-size-title-large);
|
||||
--td-font-size-xl: var(--td-font-size-title-extraLarge);
|
||||
--td-font-size-xxl: var(--td-font-size-headline-large);
|
||||
--td-radius-small: 3px;
|
||||
--td-radius-default: 4px;
|
||||
--td-radius-large: 12px;
|
||||
--td-radius-extraLarge: 16px;
|
||||
--td-radius-round: 999px;
|
||||
--td-radius-circle: 50%;
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
import {
|
||||
ATTACHMENT_ID_ATTR,
|
||||
TEMP_FILE_ID_ATTR,
|
||||
isLocalMediaId,
|
||||
normalizeContent
|
||||
} from "timi-web/editor";
|
||||
import type { ArticleContentType, Attachment } from "./types";
|
||||
|
||||
/** 文章内容中附件和临时文件的标识前缀。 */
|
||||
export const ATTACHMENT_ID_PREFIX = "attachment-id:";
|
||||
export const TEMP_FILE_ID_PREFIX = "temp-file-id:";
|
||||
|
||||
const DEFAULT_ARTICLE_CONTENT_TYPE: ArticleContentType = "TIP_TAP";
|
||||
const ARTICLE_CONTENT_TYPE_LIST: ArticleContentType[] = ["TEXT", "MARKDOWN", "TIP_TAP"];
|
||||
|
||||
/** 将未知正文类型归一化为组件支持的类型。 */
|
||||
export function normalizeArticleContentType(contentType?: string): ArticleContentType {
|
||||
return ARTICLE_CONTENT_TYPE_LIST.includes(contentType as ArticleContentType)
|
||||
? contentType as ArticleContentType
|
||||
: DEFAULT_ARTICLE_CONTENT_TYPE;
|
||||
}
|
||||
|
||||
/** 将空正文转换为空字符串。 */
|
||||
export function normalizeRawArticleContent(content?: string): string {
|
||||
return content || "";
|
||||
}
|
||||
|
||||
/** 从媒体地址中读取附件 ID。 */
|
||||
export function getAttachmentIdFromSrc(src?: string): string {
|
||||
if (!src?.startsWith(ATTACHMENT_ID_PREFIX)) {
|
||||
return "";
|
||||
}
|
||||
return src.slice(ATTACHMENT_ID_PREFIX.length);
|
||||
}
|
||||
|
||||
/** 从媒体地址中读取临时文件 ID。 */
|
||||
export function getTempFileIdFromSrc(src?: string): string {
|
||||
if (!src?.startsWith(TEMP_FILE_ID_PREFIX)) {
|
||||
return "";
|
||||
}
|
||||
return src.slice(TEMP_FILE_ID_PREFIX.length);
|
||||
}
|
||||
|
||||
/** 构造带有附件 ID 的内部媒体地址。 */
|
||||
function buildAttachmentIdSrc(attachmentId: string): string {
|
||||
return `${ATTACHMENT_ID_PREFIX}${attachmentId}`;
|
||||
}
|
||||
|
||||
/** 仅为本地预览地址保留预览元数据。 */
|
||||
function buildAttachmentMetadata(src: string): Record<string, string> | undefined {
|
||||
if (!src.startsWith("blob:")) {
|
||||
return undefined;
|
||||
}
|
||||
return {
|
||||
previewUrl: src
|
||||
};
|
||||
}
|
||||
|
||||
/** 过滤前端本地占位 ID。 */
|
||||
function normalizeAttachmentTempFileId(tempFileId?: string): string | undefined {
|
||||
if (!tempFileId || isLocalMediaId(tempFileId)) {
|
||||
return undefined;
|
||||
}
|
||||
return tempFileId;
|
||||
}
|
||||
|
||||
/** 从正文中提取媒体附件,返回组件需要的最小对象。 */
|
||||
export function buildAttachmentListFromContent(content?: string, sourceList?: readonly Attachment[]): Attachment[] {
|
||||
const rawContent = normalizeContent(content);
|
||||
if (!rawContent) {
|
||||
return [];
|
||||
}
|
||||
const parser = new DOMParser();
|
||||
const doc = parser.parseFromString(rawContent, "text/html");
|
||||
const sourceMap = new Map<string, Attachment>();
|
||||
for (const item of sourceList || []) {
|
||||
if (item.id) {
|
||||
sourceMap.set(item.id, item);
|
||||
}
|
||||
if (item.tempFileId) {
|
||||
sourceMap.set(item.tempFileId, item);
|
||||
}
|
||||
}
|
||||
const attachmentMap = new Map<string, Attachment>();
|
||||
|
||||
for (const media of Array.from(doc.querySelectorAll("img, video"))) {
|
||||
const src = media.getAttribute("src") || "";
|
||||
const attachmentId = media.getAttribute(ATTACHMENT_ID_ATTR) || getAttachmentIdFromSrc(src);
|
||||
const tempFileId = media.getAttribute(TEMP_FILE_ID_ATTR) || getTempFileIdFromSrc(src);
|
||||
const key = attachmentId || tempFileId;
|
||||
if (!key || attachmentMap.has(key)) {
|
||||
continue;
|
||||
}
|
||||
const sourceAttachment = sourceMap.get(key);
|
||||
const previewUrl = buildAttachmentMetadata(src);
|
||||
attachmentMap.set(key, {
|
||||
...(sourceAttachment || {}),
|
||||
id: attachmentId || sourceAttachment?.id || key,
|
||||
tempFileId: normalizeAttachmentTempFileId(tempFileId) || normalizeAttachmentTempFileId(sourceAttachment?.tempFileId),
|
||||
name: media.getAttribute("title") || media.getAttribute("alt") || sourceAttachment?.name || "",
|
||||
metadata: previewUrl || sourceAttachment?.metadata
|
||||
});
|
||||
}
|
||||
|
||||
return Array.from(attachmentMap.values());
|
||||
}
|
||||
|
||||
/** 将媒体地址转换为组件统一的附件标识地址。 */
|
||||
export function normalizeContentForStore(content?: string): string {
|
||||
const rawContent = normalizeContent(content);
|
||||
if (!rawContent) {
|
||||
return "";
|
||||
}
|
||||
const parser = new DOMParser();
|
||||
const doc = parser.parseFromString(rawContent, "text/html");
|
||||
for (const media of Array.from(doc.querySelectorAll("img, video"))) {
|
||||
const src = media.getAttribute("src") || "";
|
||||
const attachmentId = media.getAttribute(ATTACHMENT_ID_ATTR) || getAttachmentIdFromSrc(src);
|
||||
const tempFileId = media.getAttribute(TEMP_FILE_ID_ATTR) || getTempFileIdFromSrc(src);
|
||||
const finalAttachmentId = attachmentId || tempFileId;
|
||||
if (!finalAttachmentId) {
|
||||
continue;
|
||||
}
|
||||
media.setAttribute(ATTACHMENT_ID_ATTR, finalAttachmentId);
|
||||
media.removeAttribute(TEMP_FILE_ID_ATTR);
|
||||
media.setAttribute("src", buildAttachmentIdSrc(finalAttachmentId));
|
||||
}
|
||||
return normalizeContent(doc.body.innerHTML);
|
||||
}
|
||||
|
||||
/** 比较附件列表的通用字段,不比较对象引用。 */
|
||||
export function sameAttachmentList(left?: readonly Attachment[], right?: readonly Attachment[]): boolean {
|
||||
const leftList = left || [];
|
||||
const rightList = right || [];
|
||||
if (leftList.length !== rightList.length) {
|
||||
return false;
|
||||
}
|
||||
for (let i = 0; i < leftList.length; i += 1) {
|
||||
const leftItem = leftList[i];
|
||||
const rightItem = rightList[i];
|
||||
if (!rightItem || leftItem.id !== rightItem.id) {
|
||||
return false;
|
||||
}
|
||||
if ((leftItem.tempFileId || "") !== (rightItem.tempFileId || "")) {
|
||||
return false;
|
||||
}
|
||||
if ((leftItem.accessKey?.value || "") !== (rightItem.accessKey?.value || "")) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
import view from "./index.vue";
|
||||
import { WebToolkit } from "timi-web";
|
||||
import type { Article } from "./types";
|
||||
|
||||
export type {
|
||||
Article,
|
||||
ArticleContentType,
|
||||
Attachment,
|
||||
UploadResult
|
||||
} from "./types";
|
||||
|
||||
export type ArticleEditorExpose = {
|
||||
submit: () => Promise<Article>;
|
||||
getPendingMediaCount: () => number;
|
||||
};
|
||||
|
||||
export const ArticleEditor = WebToolkit.withInstall(view);
|
||||
export default ArticleEditor;
|
||||
@@ -0,0 +1,274 @@
|
||||
<template>
|
||||
<t-textarea
|
||||
v-if="isTextContent"
|
||||
:model-value="editorContent"
|
||||
:autosize="textareaAutosize"
|
||||
:placeholder="placeholder"
|
||||
@update:model-value="onSimpleEditorCommit"
|
||||
/>
|
||||
<markdown-editor
|
||||
v-else-if="isMarkdownContent"
|
||||
:data="editorContent"
|
||||
@update:data="onSimpleEditorCommit"
|
||||
/>
|
||||
<tiptap-editor
|
||||
v-else
|
||||
ref="tiptapEditorRef"
|
||||
:model-value="editorContent"
|
||||
:placeholder="placeholder"
|
||||
:upload-image="handleUploadImage"
|
||||
:upload-video="handleUploadVideo"
|
||||
@change="onEditorChange"
|
||||
@update:model-value="onEditorCommit"
|
||||
/>
|
||||
</template>
|
||||
|
||||
<script lang="ts" setup>
|
||||
import type { Article, ArticleContentType, Attachment, UploadResult } from "./types";
|
||||
import { MarkdownEditor } from "timi-web";
|
||||
import { TiptapEditor } from "../tiptap-editor";
|
||||
import type { TiptapEditorExpose } from "../tiptap-editor";
|
||||
import {
|
||||
buildAttachmentListFromContent,
|
||||
getAttachmentIdFromSrc,
|
||||
getTempFileIdFromSrc,
|
||||
normalizeArticleContentType,
|
||||
normalizeContentForStore,
|
||||
normalizeRawArticleContent,
|
||||
sameAttachmentList
|
||||
} from "./content";
|
||||
import {
|
||||
ATTACHMENT_ID_ATTR,
|
||||
TEMP_FILE_ID_ATTR,
|
||||
normalizeContent
|
||||
} from "timi-web/editor";
|
||||
|
||||
defineOptions({
|
||||
name: "ArticleEditor"
|
||||
});
|
||||
|
||||
const props = withDefaults(defineProps<{
|
||||
modelValue?: Article;
|
||||
placeholder?: string;
|
||||
uploadImage?: (file: File) => Promise<UploadResult>;
|
||||
uploadVideo?: (file: File) => Promise<UploadResult>;
|
||||
resolveAttachmentUrl?: (attachmentId: string, attachment?: Attachment) => string | Promise<string>;
|
||||
resolveTempUrl?: (tempFileId: string) => string | Promise<string>;
|
||||
}>(), {
|
||||
modelValue: () => ({}),
|
||||
placeholder: "请输入文章正文内容"
|
||||
});
|
||||
|
||||
const emit = defineEmits<{
|
||||
"change": [value: Article];
|
||||
"update:modelValue": [value: Article];
|
||||
}>();
|
||||
|
||||
const textareaAutosize = {
|
||||
minRows: 8,
|
||||
maxRows: 32
|
||||
};
|
||||
|
||||
const editorContent = ref("");
|
||||
const tiptapEditorRef = ref<TiptapEditorExpose>();
|
||||
const lastOutgoingContent = ref("");
|
||||
const lastOutgoingAttachmentList = ref<Attachment[]>([]);
|
||||
|
||||
const contentType = computed(() => {
|
||||
return normalizeArticleContentType(props.modelValue?.contentType);
|
||||
});
|
||||
const isTextContent = computed(() => contentType.value === "TEXT");
|
||||
const isMarkdownContent = computed(() => contentType.value === "MARKDOWN");
|
||||
|
||||
const attachmentMap = computed(() => {
|
||||
return new Map((props.modelValue?.attachmentList || []).map(item => [item.id, item]));
|
||||
});
|
||||
|
||||
async function handleUploadImage(file: File) {
|
||||
if (!props.uploadImage) {
|
||||
throw new Error("请为 ArticleEditor 配置 uploadImage");
|
||||
}
|
||||
return await props.uploadImage(file);
|
||||
}
|
||||
|
||||
async function handleUploadVideo(file: File) {
|
||||
if (!props.uploadVideo) {
|
||||
throw new Error("请为 ArticleEditor 配置 uploadVideo");
|
||||
}
|
||||
return await props.uploadVideo(file);
|
||||
}
|
||||
|
||||
async function resolveAttachmentPreviewUrl(attachmentId: string) {
|
||||
const attachment = attachmentMap.value.get(attachmentId);
|
||||
if (props.resolveAttachmentUrl) {
|
||||
const customUrl = await props.resolveAttachmentUrl(attachmentId, attachment);
|
||||
if (customUrl) {
|
||||
return customUrl;
|
||||
}
|
||||
}
|
||||
const previewUrl = typeof attachment?.metadata?.previewUrl === "string"
|
||||
? attachment.metadata.previewUrl
|
||||
: "";
|
||||
if (previewUrl) {
|
||||
return previewUrl;
|
||||
}
|
||||
return attachment?.url || "";
|
||||
}
|
||||
|
||||
async function resolveTempPreviewUrl(tempFileId: string) {
|
||||
if (props.resolveTempUrl) {
|
||||
return await props.resolveTempUrl(tempFileId);
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
async function convertContentForEditor(value?: string) {
|
||||
if (contentType.value !== "TIP_TAP") {
|
||||
return normalizeRawArticleContent(value);
|
||||
}
|
||||
const rawContent = normalizeContent(value);
|
||||
if (!rawContent) {
|
||||
return "";
|
||||
}
|
||||
const parser = new DOMParser();
|
||||
const doc = parser.parseFromString(rawContent, "text/html");
|
||||
const mediaList = Array.from(doc.querySelectorAll("img, video"));
|
||||
for (const media of mediaList) {
|
||||
const src = media.getAttribute("src") || "";
|
||||
const attachmentId = media.getAttribute(ATTACHMENT_ID_ATTR) || getAttachmentIdFromSrc(src);
|
||||
const tempFileId = media.getAttribute(TEMP_FILE_ID_ATTR) || getTempFileIdFromSrc(src);
|
||||
if (tempFileId) {
|
||||
media.setAttribute(TEMP_FILE_ID_ATTR, tempFileId);
|
||||
media.setAttribute(ATTACHMENT_ID_ATTR, attachmentId || tempFileId);
|
||||
const previewUrl = await resolveTempPreviewUrl(tempFileId);
|
||||
if (previewUrl) {
|
||||
media.setAttribute("src", previewUrl);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (!attachmentId) {
|
||||
continue;
|
||||
}
|
||||
media.setAttribute(ATTACHMENT_ID_ATTR, attachmentId);
|
||||
const previewUrl = await resolveAttachmentPreviewUrl(attachmentId);
|
||||
if (previewUrl) {
|
||||
media.setAttribute("src", previewUrl);
|
||||
}
|
||||
}
|
||||
return normalizeContent(doc.body.innerHTML);
|
||||
}
|
||||
|
||||
function normalizeIncomingArticleContent(content: string | undefined, currentContentType: ArticleContentType) {
|
||||
if (currentContentType === "TIP_TAP") {
|
||||
return normalizeContent(content);
|
||||
}
|
||||
return normalizeRawArticleContent(content);
|
||||
}
|
||||
|
||||
function buildStoredContent(content: string, currentContentType: ArticleContentType) {
|
||||
if (currentContentType === "TIP_TAP") {
|
||||
return normalizeContentForStore(content);
|
||||
}
|
||||
return normalizeRawArticleContent(content);
|
||||
}
|
||||
|
||||
function buildArticleAttachmentList(content: string, currentContentType: ArticleContentType) {
|
||||
if (currentContentType === "TIP_TAP") {
|
||||
return buildAttachmentListFromContent(content, props.modelValue?.attachmentList);
|
||||
}
|
||||
return props.modelValue?.attachmentList || [];
|
||||
}
|
||||
|
||||
function buildArticleValue(content: string) {
|
||||
const nextContentType = contentType.value;
|
||||
return {
|
||||
...(props.modelValue || {}),
|
||||
contentType: nextContentType,
|
||||
content: buildStoredContent(content, nextContentType),
|
||||
attachmentList: buildArticleAttachmentList(content, nextContentType)
|
||||
};
|
||||
}
|
||||
|
||||
function syncLastOutgoingArticle(value: Article) {
|
||||
const nextContentType = normalizeArticleContentType(value.contentType);
|
||||
lastOutgoingContent.value = normalizeIncomingArticleContent(value.content, nextContentType);
|
||||
lastOutgoingAttachmentList.value = value.attachmentList || [];
|
||||
}
|
||||
|
||||
// 实时变更只给预览态使用,不能反向驱动编辑器提交态
|
||||
function onEditorChange(value: string) {
|
||||
const nextValue = buildArticleValue(value);
|
||||
syncLastOutgoingArticle(nextValue);
|
||||
emit("change", {
|
||||
...nextValue
|
||||
});
|
||||
}
|
||||
|
||||
// 提交态只在离开代码块后的同步时机更新
|
||||
function onEditorCommit(value: string) {
|
||||
editorContent.value = value;
|
||||
const nextValue = buildArticleValue(value);
|
||||
syncLastOutgoingArticle(nextValue);
|
||||
emit("update:modelValue", {
|
||||
...nextValue
|
||||
});
|
||||
}
|
||||
|
||||
function onSimpleEditorCommit(value: string) {
|
||||
editorContent.value = value;
|
||||
const nextValue = buildArticleValue(value);
|
||||
syncLastOutgoingArticle(nextValue);
|
||||
emit("change", {
|
||||
...nextValue
|
||||
});
|
||||
emit("update:modelValue", {
|
||||
...nextValue
|
||||
});
|
||||
}
|
||||
|
||||
watch(() => [props.modelValue?.content, contentType.value] as const, async ([value, nextContentType]) => {
|
||||
const nextValue = normalizeIncomingArticleContent(value, nextContentType);
|
||||
if (nextValue === lastOutgoingContent.value) {
|
||||
return;
|
||||
}
|
||||
if (buildStoredContent(editorContent.value, nextContentType) === nextValue) {
|
||||
return;
|
||||
}
|
||||
const nextContent = await convertContentForEditor(nextValue);
|
||||
if (nextContent === editorContent.value) {
|
||||
return;
|
||||
}
|
||||
editorContent.value = nextContent;
|
||||
}, { immediate: true });
|
||||
|
||||
watch(() => props.modelValue?.attachmentList, async (value) => {
|
||||
if (contentType.value !== "TIP_TAP") {
|
||||
return;
|
||||
}
|
||||
if (sameAttachmentList(lastOutgoingAttachmentList.value, value)) {
|
||||
return;
|
||||
}
|
||||
if (sameAttachmentList(buildAttachmentListFromContent(editorContent.value, value), value)) {
|
||||
return;
|
||||
}
|
||||
const nextContent = await convertContentForEditor(props.modelValue?.content);
|
||||
if (nextContent === editorContent.value) {
|
||||
return;
|
||||
}
|
||||
editorContent.value = nextContent;
|
||||
}, { deep: true });
|
||||
|
||||
async function submit() {
|
||||
const nextEditorContent = contentType.value === "TIP_TAP" && tiptapEditorRef.value ? await tiptapEditorRef.value.submit() : editorContent.value;
|
||||
const nextValue = buildArticleValue(nextEditorContent);
|
||||
editorContent.value = nextEditorContent;
|
||||
syncLastOutgoingArticle(nextValue);
|
||||
emit("update:modelValue", nextValue);
|
||||
return nextValue;
|
||||
}
|
||||
|
||||
defineExpose({
|
||||
submit,
|
||||
getPendingMediaCount: () => tiptapEditorRef.value?.getPendingMediaCount() || 0
|
||||
});
|
||||
</script>
|
||||
@@ -0,0 +1,28 @@
|
||||
import type { UploadResult as EditorUploadResult } from "timi-web/editor";
|
||||
|
||||
/** 文章编辑器支持的正文类型。 */
|
||||
export type ArticleContentType = "TEXT" | "MARKDOWN" | "TIP_TAP";
|
||||
|
||||
/** 文章编辑器需要的附件最小结构,允许业务对象携带其他字段。 */
|
||||
export type Attachment = {
|
||||
[key: string]: unknown;
|
||||
id?: string;
|
||||
tempFileId?: string;
|
||||
name?: string;
|
||||
url?: string;
|
||||
metadata?: Record<string, unknown>;
|
||||
accessKey?: {
|
||||
value?: string;
|
||||
};
|
||||
};
|
||||
|
||||
/** 文章编辑器需要的文章最小结构,业务对象的其他字段会原样保留。 */
|
||||
export type Article = {
|
||||
[key: string]: unknown;
|
||||
contentType?: string;
|
||||
content?: string;
|
||||
attachmentList?: Attachment[];
|
||||
};
|
||||
|
||||
/** 媒体上传结果。 */
|
||||
export type UploadResult = EditorUploadResult;
|
||||
@@ -0,0 +1,5 @@
|
||||
import view from "./index.vue";
|
||||
import { WebToolkit } from "timi-web";
|
||||
|
||||
export const ArticleView = WebToolkit.withInstall(view);
|
||||
export default ArticleView;
|
||||
@@ -0,0 +1,118 @@
|
||||
<template>
|
||||
<t-textarea
|
||||
v-if="isTextContent && hasRawContent"
|
||||
class="text-view"
|
||||
:model-value="rawContent"
|
||||
:autosize="textareaAutosize"
|
||||
readonly
|
||||
/>
|
||||
<t-empty v-else-if="isTextContent" :description="emptyText" />
|
||||
<markdown-view v-else-if="isMarkdownContent && hasRawContent" :content="rawContent" />
|
||||
<t-empty v-else-if="isMarkdownContent" :description="emptyText" />
|
||||
<tiptap-view v-else :content="renderContent" :empty-text="emptyText" />
|
||||
</template>
|
||||
|
||||
<script lang="ts" setup>
|
||||
import type { Article, Attachment } from "../article-editor/types";
|
||||
import { MarkdownView } from "timi-web";
|
||||
import { TiptapView } from "../tiptap-view";
|
||||
import {
|
||||
getAttachmentIdFromSrc,
|
||||
normalizeArticleContentType,
|
||||
normalizeRawArticleContent
|
||||
} from "../article-editor/content";
|
||||
import { ATTACHMENT_ID_ATTR, normalizeContent } from "timi-web/editor";
|
||||
|
||||
defineOptions({
|
||||
name: "ArticleView"
|
||||
});
|
||||
|
||||
const props = withDefaults(defineProps<{
|
||||
article?: Article;
|
||||
emptyText?: string;
|
||||
resolveAttachmentUrl?: (attachmentId: string, attachment?: Attachment) => string | Promise<string>;
|
||||
}>(), {
|
||||
article: () => ({}),
|
||||
emptyText: "暂无正文内容"
|
||||
});
|
||||
|
||||
const textareaAutosize = {
|
||||
minRows: 8,
|
||||
maxRows: 32
|
||||
};
|
||||
|
||||
const renderContent = ref("");
|
||||
|
||||
const contentType = computed(() => {
|
||||
return normalizeArticleContentType(props.article?.contentType);
|
||||
});
|
||||
const isTextContent = computed(() => contentType.value === "TEXT");
|
||||
const isMarkdownContent = computed(() => contentType.value === "MARKDOWN");
|
||||
const rawContent = computed(() => {
|
||||
return normalizeRawArticleContent(props.article?.content);
|
||||
});
|
||||
const hasRawContent = computed(() => {
|
||||
return 0 < rawContent.value.trim().length;
|
||||
});
|
||||
|
||||
const attachmentMap = computed(() => {
|
||||
return new Map((props.article?.attachmentList || []).map(item => [item.id, item]));
|
||||
});
|
||||
|
||||
async function buildAttachmentPreviewUrl(attachmentId: string) {
|
||||
const attachment = attachmentMap.value.get(attachmentId);
|
||||
if (props.resolveAttachmentUrl) {
|
||||
const customUrl = await props.resolveAttachmentUrl(attachmentId, attachment);
|
||||
if (customUrl) {
|
||||
return customUrl;
|
||||
}
|
||||
}
|
||||
const previewUrl = typeof attachment?.metadata?.previewUrl === "string"
|
||||
? attachment.metadata.previewUrl
|
||||
: "";
|
||||
if (previewUrl) {
|
||||
return previewUrl;
|
||||
}
|
||||
return attachment?.url || "";
|
||||
}
|
||||
|
||||
async function buildRenderContent(content?: string) {
|
||||
const rawContent = normalizeContent(content);
|
||||
if (!rawContent) {
|
||||
return "";
|
||||
}
|
||||
const parser = new DOMParser();
|
||||
const doc = parser.parseFromString(rawContent, "text/html");
|
||||
const nodes = Array.from(doc.querySelectorAll("img, video, source"));
|
||||
for (const node of nodes) {
|
||||
const src = node.getAttribute("src") || "";
|
||||
const attachmentId = node.getAttribute(ATTACHMENT_ID_ATTR) || getAttachmentIdFromSrc(src);
|
||||
if (!attachmentId) {
|
||||
continue;
|
||||
}
|
||||
const previewUrl = await buildAttachmentPreviewUrl(attachmentId);
|
||||
if (previewUrl) {
|
||||
node.setAttribute("src", previewUrl);
|
||||
}
|
||||
}
|
||||
return normalizeContent(doc.body.innerHTML);
|
||||
}
|
||||
|
||||
watch(
|
||||
() => [props.article?.content, props.article?.attachmentList, contentType.value] as const,
|
||||
async ([, , nextContentType]) => {
|
||||
if (nextContentType !== "TIP_TAP") {
|
||||
renderContent.value = "";
|
||||
return;
|
||||
}
|
||||
renderContent.value = await buildRenderContent(props.article?.content);
|
||||
},
|
||||
{ immediate: true, deep: true }
|
||||
);
|
||||
</script>
|
||||
|
||||
<style lang="less" scoped>
|
||||
.text-view {
|
||||
width: 100%;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,5 @@
|
||||
import view from "./index.vue";
|
||||
import { WebToolkit } from "timi-web";
|
||||
|
||||
export const BottomPopup = WebToolkit.withInstall(view);
|
||||
export default BottomPopup;
|
||||
@@ -0,0 +1,132 @@
|
||||
<template>
|
||||
<t-popup v-model="visible" placement="bottom">
|
||||
<div class="bottom-popup" :style="{ height: props.height }">
|
||||
<div v-if="hasHeader" class="header">
|
||||
<div class="button left">
|
||||
<slot name="leftButton" :on-click="emitLeftButtonClick">
|
||||
<t-button v-if="leftButtonText" variant="text" size="small" @click="emitLeftButtonClick">
|
||||
<span v-text="leftButtonText" />
|
||||
</t-button>
|
||||
</slot>
|
||||
</div>
|
||||
<div class="title text-bold">
|
||||
<slot name="title">
|
||||
<span v-text="title" />
|
||||
</slot>
|
||||
</div>
|
||||
<div class="button right">
|
||||
<slot name="rightButton" :on-click="emitRightButtonClick">
|
||||
<t-button v-if="rightButtonText" theme="primary" variant="text" size="small" @click="emitRightButtonClick">
|
||||
<span v-text="rightButtonText" />
|
||||
</t-button>
|
||||
</slot>
|
||||
</div>
|
||||
</div>
|
||||
<div class="body">
|
||||
<slot />
|
||||
</div>
|
||||
</div>
|
||||
</t-popup>
|
||||
</template>
|
||||
|
||||
<script lang="ts" setup>
|
||||
defineOptions({
|
||||
name: "BottomPopup"
|
||||
});
|
||||
|
||||
export interface BottomPopupProps {
|
||||
modelValue?: boolean;
|
||||
leftButtonText?: string;
|
||||
rightButtonText?: string;
|
||||
height?: string | number;
|
||||
title?: string;
|
||||
}
|
||||
|
||||
export interface BottomPopupSlots {
|
||||
default?: () => unknown;
|
||||
title?: () => unknown;
|
||||
leftButton?: (props: { onClick: () => void }) => unknown;
|
||||
rightButton?: (props: { onClick: () => void }) => unknown;
|
||||
}
|
||||
|
||||
const props = withDefaults(defineProps<BottomPopupProps>(), {
|
||||
modelValue: false,
|
||||
leftButtonText: "取消",
|
||||
rightButtonText: "确定",
|
||||
height: "auto",
|
||||
title: ""
|
||||
});
|
||||
|
||||
const emit = defineEmits<{
|
||||
"update:modelValue": [value: boolean];
|
||||
leftButtonClick: [];
|
||||
rightButtonClick: [];
|
||||
}>();
|
||||
|
||||
const slots = useSlots() as BottomPopupSlots;
|
||||
const visible = computed({
|
||||
get: () => props.modelValue,
|
||||
set: value => emit("update:modelValue", value)
|
||||
});
|
||||
const hasHeader = computed<boolean>(() => Boolean(
|
||||
props.title
|
||||
|| props.leftButtonText
|
||||
|| props.rightButtonText
|
||||
|| slots.title
|
||||
|| slots.leftButton
|
||||
|| slots.rightButton
|
||||
));
|
||||
|
||||
function emitLeftButtonClick(): void {
|
||||
emit("leftButtonClick");
|
||||
}
|
||||
|
||||
function emitRightButtonClick(): void {
|
||||
emit("rightButtonClick");
|
||||
}
|
||||
|
||||
defineSlots<BottomPopupSlots>();
|
||||
</script>
|
||||
|
||||
<style lang="less" scoped>
|
||||
.bottom-popup {
|
||||
display: flex;
|
||||
overflow: hidden;
|
||||
padding-top: 1rem;
|
||||
background: var(--td-bg-color-container, #fff);
|
||||
border-radius: 1.25rem 1.25rem 0 0;
|
||||
flex-direction: column;
|
||||
|
||||
.header {
|
||||
flex: none;
|
||||
padding: 0 1rem;
|
||||
display: grid;
|
||||
align-items: center;
|
||||
grid-template-columns: 4rem 1fr 4rem;
|
||||
}
|
||||
|
||||
.button {
|
||||
min-width: 0;
|
||||
display: flex;
|
||||
|
||||
&.right {
|
||||
justify-content: flex-end;
|
||||
}
|
||||
}
|
||||
|
||||
.title {
|
||||
margin: 0;
|
||||
overflow: hidden;
|
||||
text-align: center;
|
||||
white-space: nowrap;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
.body {
|
||||
flex: 1;
|
||||
padding: .75rem 0 env(safe-area-inset-bottom, 0);
|
||||
overflow: auto;
|
||||
min-height: 0;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,25 @@
|
||||
import view from "./index.vue";
|
||||
import { WebToolkit } from "timi-web";
|
||||
import "./style.less";
|
||||
|
||||
export type CodeEditorScrollState = {
|
||||
top: number;
|
||||
left: number;
|
||||
};
|
||||
|
||||
export type CodeEditorExpose = {
|
||||
focus: () => void;
|
||||
blur: () => void;
|
||||
getScrollState: () => CodeEditorScrollState;
|
||||
setScrollState: (state: Partial<CodeEditorScrollState>) => void;
|
||||
findNext: () => boolean;
|
||||
findPrevious: () => boolean;
|
||||
replaceCurrent: () => boolean;
|
||||
replaceAll: () => number;
|
||||
openSearch: (showReplace: boolean) => void;
|
||||
closeSearch: () => void;
|
||||
textareaRef?: HTMLTextAreaElement;
|
||||
};
|
||||
|
||||
export const CodeEditor = WebToolkit.withInstall(view);
|
||||
export default CodeEditor;
|
||||
@@ -0,0 +1,434 @@
|
||||
<template>
|
||||
<div
|
||||
ref="rootRef"
|
||||
class="tui-code-editor"
|
||||
:class="{
|
||||
readonly,
|
||||
disabled,
|
||||
'with-line-numbers': lineNumbers
|
||||
}"
|
||||
>
|
||||
<div v-if="lineNumbers" ref="gutterRef" class="gutter diselect" aria-hidden="true">
|
||||
<span v-for="line in lineCount" :key="line" v-text="line" />
|
||||
</div>
|
||||
<div class="body">
|
||||
<editor-search-bar
|
||||
ref="searchBarRef"
|
||||
:visible="searchVisible"
|
||||
:expanded="replaceExpanded"
|
||||
:keyword="searchKeyword"
|
||||
:replace-value="replaceKeyword"
|
||||
:status-error="searchError"
|
||||
:match-index="searchMatchIndex"
|
||||
:match-count="searchMatchList.length"
|
||||
:case-sensitive="searchOptions.caseSensitive"
|
||||
:use-regex="searchOptions.useRegex"
|
||||
@update:expanded="replaceExpanded = $event"
|
||||
@update:keyword="searchKeyword = $event"
|
||||
@update:replace-value="replaceKeyword = $event"
|
||||
@update:case-sensitive="searchOptions.caseSensitive = $event"
|
||||
@update:use-regex="searchOptions.useRegex = $event"
|
||||
@previous="findPrevious"
|
||||
@next="onSearchNext"
|
||||
@replace="replaceCurrent"
|
||||
@replace-all="replaceAll"
|
||||
@close="closeSearch"
|
||||
/>
|
||||
<pre
|
||||
ref="preRef"
|
||||
class="preview cur-text"
|
||||
:class="languageClass"
|
||||
@scroll="onPreviewScroll"
|
||||
><code :class="languageClass" v-html="highlightedHTML"></code></pre>
|
||||
<textarea
|
||||
v-if="!readonly"
|
||||
ref="textareaRef"
|
||||
v-model="currentValue"
|
||||
class="input"
|
||||
:placeholder="placeholder"
|
||||
:disabled="disabled"
|
||||
wrap="off"
|
||||
:spellcheck="false"
|
||||
@input="onInput"
|
||||
@scroll="onScroll"
|
||||
@keydown="onKeydown"
|
||||
></textarea>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script lang="ts" setup>
|
||||
import EditorSearchBar from "../editor-search/index.vue";
|
||||
import {
|
||||
findTextMatches,
|
||||
replaceAllText,
|
||||
replaceMatchText,
|
||||
type TextSearchMatch,
|
||||
type TextSearchOptions
|
||||
} from "timi-web/editor";
|
||||
import { highlightCode, resolveCodeEditorKeydown, resolvePrismLanguage } from "timi-web/editor";
|
||||
|
||||
defineOptions({
|
||||
name: "CodeEditor"
|
||||
});
|
||||
|
||||
type ScrollState = {
|
||||
top: number;
|
||||
left: number;
|
||||
};
|
||||
|
||||
type EditorSearchBarExpose = {
|
||||
focusKeyword: (selectAll?: boolean) => void;
|
||||
focusReplace: (selectAll?: boolean) => void;
|
||||
};
|
||||
|
||||
const props = withDefaults(defineProps<{
|
||||
modelValue?: string;
|
||||
value?: string;
|
||||
language?: string;
|
||||
placeholder?: string;
|
||||
readonly?: boolean;
|
||||
disabled?: boolean;
|
||||
lineNumbers?: boolean;
|
||||
}>(), {
|
||||
modelValue: "",
|
||||
language: "typescript",
|
||||
placeholder: "",
|
||||
readonly: false,
|
||||
disabled: false,
|
||||
lineNumbers: true
|
||||
});
|
||||
|
||||
const emit = defineEmits<{
|
||||
(event: "update:modelValue", value: string): void;
|
||||
(event: "change", value: string): void;
|
||||
}>();
|
||||
|
||||
const bindValue = computed(() => props.value ?? props.modelValue);
|
||||
const currentValue = ref(bindValue.value);
|
||||
const rootRef = ref<HTMLDivElement>();
|
||||
const gutterRef = ref<HTMLDivElement>();
|
||||
const preRef = ref<HTMLPreElement>();
|
||||
const textareaRef = ref<HTMLTextAreaElement>();
|
||||
const searchBarRef = ref<EditorSearchBarExpose>();
|
||||
const searchVisible = ref(false);
|
||||
const replaceExpanded = ref(false);
|
||||
const searchKeyword = ref("");
|
||||
const replaceKeyword = ref("");
|
||||
const searchError = ref("");
|
||||
const searchMatchIndex = ref(-1);
|
||||
const searchMatchList = ref<TextSearchMatch[]>([]);
|
||||
const scrollState = reactive<ScrollState>({
|
||||
top: 0,
|
||||
left: 0
|
||||
});
|
||||
const searchOptions = reactive<TextSearchOptions>({
|
||||
caseSensitive: false,
|
||||
useRegex: false
|
||||
});
|
||||
|
||||
const resolvedLanguage = computed(() => resolvePrismLanguage(props.language));
|
||||
const languageClass = computed(() => resolvedLanguage.value ? `language-${resolvedLanguage.value}` : "");
|
||||
const lineCount = computed(() => Math.max(currentValue.value.split("\n").length, 1));
|
||||
const highlightedHTML = computed(() => {
|
||||
return highlightCode(currentValue.value, resolvedLanguage.value);
|
||||
});
|
||||
|
||||
watch(bindValue, (value) => {
|
||||
if (value === currentValue.value) {
|
||||
return;
|
||||
}
|
||||
currentValue.value = value;
|
||||
refreshSearchMatchState();
|
||||
nextTick(syncScrollPosition);
|
||||
});
|
||||
|
||||
watch([searchKeyword, () => searchOptions.caseSensitive, () => searchOptions.useRegex], () => {
|
||||
refreshSearchMatchState();
|
||||
});
|
||||
|
||||
const onInput = () => {
|
||||
emit("update:modelValue", currentValue.value);
|
||||
emit("change", currentValue.value);
|
||||
refreshSearchMatchState();
|
||||
};
|
||||
|
||||
const onScroll = () => {
|
||||
syncScrollPosition();
|
||||
};
|
||||
|
||||
const onPreviewScroll = () => {
|
||||
if (!props.readonly || !preRef.value || !gutterRef.value) {
|
||||
return;
|
||||
}
|
||||
scrollState.top = preRef.value.scrollTop;
|
||||
scrollState.left = preRef.value.scrollLeft;
|
||||
gutterRef.value.scrollTop = preRef.value.scrollTop;
|
||||
};
|
||||
|
||||
const onKeydown = (event: KeyboardEvent) => {
|
||||
if ((event.ctrlKey || event.metaKey) && !event.altKey) {
|
||||
const key = event.key.toLowerCase();
|
||||
if ("f" === key) {
|
||||
event.preventDefault();
|
||||
openSearch(false);
|
||||
return;
|
||||
}
|
||||
if ("h" === key && !props.readonly) {
|
||||
event.preventDefault();
|
||||
openSearch(true);
|
||||
return;
|
||||
}
|
||||
}
|
||||
if (props.readonly || props.disabled || !textareaRef.value) {
|
||||
return;
|
||||
}
|
||||
|
||||
const textarea = textareaRef.value;
|
||||
const nextState = resolveCodeEditorKeydown(currentValue.value, {
|
||||
start: textarea.selectionStart,
|
||||
end: textarea.selectionEnd
|
||||
}, event);
|
||||
if (!nextState) {
|
||||
return;
|
||||
}
|
||||
|
||||
event.preventDefault();
|
||||
currentValue.value = nextState.value;
|
||||
emit("update:modelValue", currentValue.value);
|
||||
emit("change", currentValue.value);
|
||||
refreshSearchMatchState();
|
||||
nextTick(() => {
|
||||
textarea.selectionStart = nextState.start;
|
||||
textarea.selectionEnd = nextState.end;
|
||||
syncScrollPosition();
|
||||
});
|
||||
};
|
||||
|
||||
const getScrollState = (): ScrollState => ({
|
||||
top: scrollState.top,
|
||||
left: scrollState.left
|
||||
});
|
||||
|
||||
const setScrollState = (nextState: Partial<ScrollState>) => {
|
||||
scrollState.top = Math.max(0, nextState.top || 0);
|
||||
scrollState.left = Math.max(0, nextState.left || 0);
|
||||
applyScrollState();
|
||||
};
|
||||
|
||||
const syncScrollPosition = () => {
|
||||
if (textareaRef.value) {
|
||||
scrollState.top = textareaRef.value.scrollTop;
|
||||
scrollState.left = textareaRef.value.scrollLeft;
|
||||
applyScrollState();
|
||||
return;
|
||||
}
|
||||
if (props.readonly && preRef.value) {
|
||||
scrollState.top = preRef.value.scrollTop;
|
||||
scrollState.left = preRef.value.scrollLeft;
|
||||
applyScrollState();
|
||||
}
|
||||
};
|
||||
|
||||
const applyScrollState = () => {
|
||||
if (textareaRef.value) {
|
||||
textareaRef.value.scrollTop = scrollState.top;
|
||||
textareaRef.value.scrollLeft = scrollState.left;
|
||||
}
|
||||
if (preRef.value) {
|
||||
preRef.value.scrollTop = scrollState.top;
|
||||
preRef.value.scrollLeft = scrollState.left;
|
||||
}
|
||||
if (gutterRef.value) {
|
||||
gutterRef.value.scrollTop = scrollState.top;
|
||||
}
|
||||
};
|
||||
|
||||
const getSelectionKeyword = () => {
|
||||
if (!textareaRef.value) {
|
||||
return "";
|
||||
}
|
||||
const { selectionStart, selectionEnd } = textareaRef.value;
|
||||
if (selectionStart === selectionEnd) {
|
||||
return "";
|
||||
}
|
||||
return currentValue.value.slice(selectionStart, selectionEnd);
|
||||
};
|
||||
|
||||
const refreshSearchMatchState = () => {
|
||||
const result = findTextMatches(currentValue.value, searchKeyword.value, searchOptions);
|
||||
searchError.value = result.error;
|
||||
searchMatchList.value = result.matches;
|
||||
if (searchError.value || !textareaRef.value || 1 > searchMatchList.value.length) {
|
||||
searchMatchIndex.value = -1;
|
||||
return;
|
||||
}
|
||||
const { selectionStart, selectionEnd } = textareaRef.value;
|
||||
searchMatchIndex.value = searchMatchList.value.findIndex((match) => (
|
||||
match.start === selectionStart && match.end === selectionEnd
|
||||
));
|
||||
if (0 > searchMatchIndex.value) {
|
||||
searchMatchIndex.value = 0;
|
||||
}
|
||||
};
|
||||
|
||||
const openSearch = (showReplace: boolean) => {
|
||||
searchVisible.value = true;
|
||||
replaceExpanded.value = showReplace;
|
||||
const selectedText = getSelectionKeyword();
|
||||
if (selectedText) {
|
||||
searchKeyword.value = selectedText;
|
||||
}
|
||||
refreshSearchMatchState();
|
||||
nextTick(() => {
|
||||
searchBarRef.value?.focusKeyword(true);
|
||||
});
|
||||
};
|
||||
|
||||
const closeSearch = () => {
|
||||
searchVisible.value = false;
|
||||
replaceExpanded.value = false;
|
||||
focus();
|
||||
};
|
||||
|
||||
const selectMatch = (match: TextSearchMatch, matchIndex: number) => {
|
||||
if (!textareaRef.value) {
|
||||
return false;
|
||||
}
|
||||
textareaRef.value.focus();
|
||||
textareaRef.value.selectionStart = match.start;
|
||||
textareaRef.value.selectionEnd = match.end;
|
||||
textareaRef.value.setSelectionRange(match.start, match.end);
|
||||
textareaRef.value.scrollIntoView({ block: "nearest", inline: "nearest" });
|
||||
scrollState.top = textareaRef.value.scrollTop;
|
||||
scrollState.left = textareaRef.value.scrollLeft;
|
||||
applyScrollState();
|
||||
searchMatchIndex.value = matchIndex;
|
||||
return true;
|
||||
};
|
||||
|
||||
const findNext = () => {
|
||||
if (searchError.value || !textareaRef.value || 1 > searchMatchList.value.length) {
|
||||
return false;
|
||||
}
|
||||
const { selectionEnd } = textareaRef.value;
|
||||
const nextIndex = searchMatchList.value.findIndex((match) => match.start >= selectionEnd);
|
||||
const targetIndex = 0 <= nextIndex ? nextIndex : 0;
|
||||
return selectMatch(searchMatchList.value[targetIndex], targetIndex);
|
||||
};
|
||||
|
||||
const findPrevious = () => {
|
||||
if (searchError.value || !textareaRef.value || 1 > searchMatchList.value.length) {
|
||||
return false;
|
||||
}
|
||||
const { selectionStart } = textareaRef.value;
|
||||
let targetIndex = searchMatchList.value.length - 1;
|
||||
for (let index = searchMatchList.value.length - 1; 0 <= index; index -= 1) {
|
||||
if (searchMatchList.value[index].start < selectionStart) {
|
||||
targetIndex = index;
|
||||
break;
|
||||
}
|
||||
}
|
||||
return selectMatch(searchMatchList.value[targetIndex], targetIndex);
|
||||
};
|
||||
|
||||
const onSearchNext = (shiftKey: boolean) => {
|
||||
if (shiftKey) {
|
||||
findPrevious();
|
||||
return;
|
||||
}
|
||||
findNext();
|
||||
};
|
||||
|
||||
const replaceSelection = (match: TextSearchMatch) => {
|
||||
const nextText = replaceMatchText(match.text, searchKeyword.value, replaceKeyword.value, searchOptions);
|
||||
currentValue.value = currentValue.value.slice(0, match.start) + nextText + currentValue.value.slice(match.end);
|
||||
emit("update:modelValue", currentValue.value);
|
||||
emit("change", currentValue.value);
|
||||
};
|
||||
|
||||
const replaceCurrent = () => {
|
||||
if (props.readonly || !textareaRef.value || !searchKeyword.value) {
|
||||
return false;
|
||||
}
|
||||
const { selectionStart, selectionEnd } = textareaRef.value;
|
||||
let currentMatchIndex = searchMatchList.value.findIndex((match) => (
|
||||
match.start === selectionStart && match.end === selectionEnd
|
||||
));
|
||||
if (0 > currentMatchIndex) {
|
||||
if (!findNext()) {
|
||||
return false;
|
||||
}
|
||||
currentMatchIndex = searchMatchIndex.value;
|
||||
}
|
||||
const currentMatch = searchMatchList.value[currentMatchIndex];
|
||||
if (!currentMatch) {
|
||||
return false;
|
||||
}
|
||||
replaceSelection(currentMatch);
|
||||
refreshSearchMatchState();
|
||||
nextTick(() => {
|
||||
const nextMatch = searchMatchList.value[currentMatchIndex] || searchMatchList.value[currentMatchIndex - 1];
|
||||
if (!nextMatch) {
|
||||
focus();
|
||||
return;
|
||||
}
|
||||
selectMatch(nextMatch, Math.min(currentMatchIndex, searchMatchList.value.length - 1));
|
||||
});
|
||||
return true;
|
||||
};
|
||||
|
||||
const replaceAll = () => {
|
||||
if (props.readonly || !searchKeyword.value) {
|
||||
return 0;
|
||||
}
|
||||
const result = replaceAllText(currentValue.value, searchKeyword.value, replaceKeyword.value, searchOptions);
|
||||
searchError.value = result.error;
|
||||
if (result.error || 1 > result.count) {
|
||||
refreshSearchMatchState();
|
||||
return 0;
|
||||
}
|
||||
currentValue.value = result.value;
|
||||
emit("update:modelValue", currentValue.value);
|
||||
emit("change", currentValue.value);
|
||||
refreshSearchMatchState();
|
||||
nextTick(() => {
|
||||
if (searchMatchList.value[0]) {
|
||||
selectMatch(searchMatchList.value[0], 0);
|
||||
return;
|
||||
}
|
||||
focus();
|
||||
});
|
||||
return result.count;
|
||||
};
|
||||
|
||||
const focus = () => {
|
||||
textareaRef.value?.focus();
|
||||
};
|
||||
|
||||
const blur = () => {
|
||||
textareaRef.value?.blur();
|
||||
};
|
||||
|
||||
onActivated(() => {
|
||||
nextTick(() => {
|
||||
applyScrollState();
|
||||
});
|
||||
});
|
||||
|
||||
defineExpose({
|
||||
rootRef,
|
||||
textareaRef,
|
||||
focus,
|
||||
blur,
|
||||
getScrollState,
|
||||
setScrollState,
|
||||
findNext,
|
||||
findPrevious,
|
||||
replaceCurrent,
|
||||
replaceAll,
|
||||
openSearch,
|
||||
closeSearch
|
||||
});
|
||||
|
||||
</script>
|
||||
@@ -0,0 +1,202 @@
|
||||
.tui-code-editor {
|
||||
width: calc(100% - 2px);
|
||||
min-width: 0;
|
||||
border: 1px solid var(--td-component-stroke, #B8BBC9);
|
||||
display: flex;
|
||||
overflow: hidden;
|
||||
background: transparent;
|
||||
border-radius: var(--td-radius-medium, 0);
|
||||
|
||||
.gutter {
|
||||
flex: none;
|
||||
color: var(--td-text-color-placeholder, #999);
|
||||
overflow: hidden;
|
||||
text-align: right;
|
||||
background: #F2F2F2E6;
|
||||
border-right: 1px solid var(--td-component-stroke, #B8BBC9);
|
||||
|
||||
> span {
|
||||
width: 3.25rem;
|
||||
height: 1.5rem;
|
||||
display: block;
|
||||
font-size: 1rem;
|
||||
font-family: "JetBrains Mono", "Fira Code", Consolas, "Courier New", monospace;
|
||||
line-height: 1.5rem;
|
||||
padding-right: .25rem;
|
||||
}
|
||||
}
|
||||
|
||||
.body {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
min-height: 0;
|
||||
position: relative;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.search-bar {
|
||||
top: .5rem;
|
||||
right: .5rem;
|
||||
gap: .5rem;
|
||||
z-index: 3;
|
||||
display: flex;
|
||||
padding: .5rem;
|
||||
position: absolute;
|
||||
align-items: center;
|
||||
border-radius: var(--td-radius-default, .375rem);
|
||||
background: var(--td-bg-color-container, #fff);
|
||||
border: 1px solid var(--td-component-stroke, #B8BBC9);
|
||||
box-shadow: 0 .25rem .75rem rgba(0, 0, 0, .12);
|
||||
}
|
||||
|
||||
.search-input {
|
||||
width: 10rem;
|
||||
height: 2rem;
|
||||
padding: 0 .5rem;
|
||||
color: var(--td-text-color-primary, #111);
|
||||
border: 1px solid var(--td-component-stroke, #B8BBC9);
|
||||
background: var(--td-bg-color-container, #fff);
|
||||
border-radius: var(--td-radius-default, .375rem);
|
||||
font: inherit;
|
||||
}
|
||||
|
||||
.search-actions {
|
||||
gap: .25rem;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.search-button {
|
||||
height: 2rem;
|
||||
padding: 0 .625rem;
|
||||
color: var(--td-text-color-primary, #111);
|
||||
border: 1px solid var(--td-component-stroke, #B8BBC9);
|
||||
background: var(--td-bg-color-container, #fff);
|
||||
border-radius: var(--td-radius-default, .375rem);
|
||||
cursor: pointer;
|
||||
|
||||
&:hover {
|
||||
background: var(--td-bg-color-container-hover, #f6f6f6);
|
||||
}
|
||||
}
|
||||
|
||||
.search-status {
|
||||
color: var(--td-text-color-secondary, #666);
|
||||
white-space: nowrap;
|
||||
font-size: .875rem;
|
||||
}
|
||||
|
||||
.preview,
|
||||
.input {
|
||||
inset: 0;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
margin: 0;
|
||||
tab-size: 4;
|
||||
overflow: auto;
|
||||
max-width: 100%;
|
||||
min-width: 0;
|
||||
line-height: 1.5rem;
|
||||
font-size: 1rem;
|
||||
box-sizing: border-box;
|
||||
font-family: "JetBrains Mono", "Fira Code", Consolas, "Courier New", monospace;
|
||||
}
|
||||
|
||||
.preview {
|
||||
top: 0;
|
||||
left: 0;
|
||||
border: none;
|
||||
position: absolute;
|
||||
word-break: normal;
|
||||
background: transparent;
|
||||
transition: none;
|
||||
white-space: pre;
|
||||
border-radius: 0;
|
||||
pointer-events: none;
|
||||
|
||||
code {
|
||||
padding: 0;
|
||||
display: block;
|
||||
width: max-content;
|
||||
min-width: 100%;
|
||||
min-height: 100%;
|
||||
color: inherit;
|
||||
background: transparent;
|
||||
text-shadow: none;
|
||||
font-size: inherit;
|
||||
line-height: inherit;
|
||||
font-family: inherit;
|
||||
}
|
||||
}
|
||||
|
||||
.input {
|
||||
top: 0;
|
||||
left: 0;
|
||||
color: transparent;
|
||||
resize: none;
|
||||
border: none;
|
||||
outline: none;
|
||||
position: absolute;
|
||||
background: transparent;
|
||||
white-space: pre;
|
||||
word-break: normal;
|
||||
overflow-wrap: normal;
|
||||
caret-color: var(--td-text-color-primary, #111);
|
||||
-webkit-text-fill-color: transparent;
|
||||
}
|
||||
|
||||
.input::placeholder {
|
||||
color: var(--td-text-color-placeholder, #999);
|
||||
-webkit-text-fill-color: var(--td-text-color-placeholder, #999);
|
||||
}
|
||||
|
||||
.input::selection {
|
||||
background: rgb(0 122 255 / 18%);
|
||||
}
|
||||
|
||||
&.disabled {
|
||||
opacity: .65;
|
||||
}
|
||||
|
||||
&.readonly {
|
||||
.preview {
|
||||
pointer-events: auto;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@media (prefers-color-scheme: dark) {
|
||||
.tui-code-editor {
|
||||
border-color: var(--td-component-stroke, #434343);
|
||||
|
||||
.gutter {
|
||||
border-right-color: var(--td-component-stroke, #434343);
|
||||
}
|
||||
|
||||
.search-bar {
|
||||
background: var(--td-bg-color-container, #1f1f1f);
|
||||
border-color: var(--td-component-stroke, #434343);
|
||||
box-shadow: 0 .25rem .75rem rgba(0, 0, 0, .28);
|
||||
}
|
||||
|
||||
.search-input,
|
||||
.search-button {
|
||||
color: var(--td-text-color-primary, #F5F5F5);
|
||||
border-color: var(--td-component-stroke, #434343);
|
||||
background: var(--td-bg-color-container, #1f1f1f);
|
||||
}
|
||||
|
||||
.search-button:hover {
|
||||
background: var(--td-bg-color-container-hover, #2b2b2b);
|
||||
}
|
||||
|
||||
.input {
|
||||
caret-color: var(--td-text-color-primary, #F5F5F5);
|
||||
}
|
||||
|
||||
.input::selection {
|
||||
background: rgb(64 153 255 / 28%);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
import view from "./index.vue";
|
||||
import { WebToolkit } from "timi-web";
|
||||
|
||||
export const DurationPicker = WebToolkit.withInstall(view);
|
||||
export default DurationPicker;
|
||||
@@ -0,0 +1,158 @@
|
||||
<template>
|
||||
<t-picker
|
||||
:model-value="pickerValue"
|
||||
:columns="pickerColumns"
|
||||
@pick="handlePickerPick"
|
||||
@change="handlePickerConfirm"
|
||||
@confirm="handlePickerConfirm"
|
||||
/>
|
||||
</template>
|
||||
|
||||
<script lang="ts" setup>
|
||||
import type { PickerColumnItem, PickerValue } from "tdesign-mobile-vue";
|
||||
|
||||
defineOptions({
|
||||
name: "DurationPicker"
|
||||
});
|
||||
|
||||
type DurationUnit = "year" | "day" | "hour" | "minute" | "second" | "millisecond";
|
||||
|
||||
interface UnitConfig {
|
||||
label: string;
|
||||
max: number;
|
||||
min: number;
|
||||
step: number;
|
||||
toMs: number;
|
||||
value: DurationUnit;
|
||||
}
|
||||
|
||||
const UNIT_CONFIG_LIST: UnitConfig[] = [
|
||||
{ label: "年", value: "year", min: 1, max: 100, step: 1, toMs: 365 * 24 * 60 * 60 * 1000 },
|
||||
{ label: "天", value: "day", min: 1, max: 364, step: 1, toMs: 24 * 60 * 60 * 1000 },
|
||||
{ label: "小时", value: "hour", min: 1, max: 23, step: 1, toMs: 60 * 60 * 1000 },
|
||||
{ label: "分钟", value: "minute", min: 1, max: 59, step: 1, toMs: 60 * 1000 },
|
||||
{ label: "秒", value: "second", min: 1, max: 59, step: 1, toMs: 1000 },
|
||||
{ label: "毫秒", value: "millisecond", min: 50, max: 950, step: 50, toMs: 1 }
|
||||
];
|
||||
|
||||
const UNIT_MAP = new Map<DurationUnit, UnitConfig>(
|
||||
UNIT_CONFIG_LIST.map((unit) => [unit.value, unit])
|
||||
);
|
||||
|
||||
const props = withDefaults(defineProps<{
|
||||
modelValue?: number;
|
||||
}>(), {
|
||||
modelValue: 1000
|
||||
});
|
||||
|
||||
const emit = defineEmits<{
|
||||
(e: "update:modelValue", value: number): void;
|
||||
(e: "change", value: number): void;
|
||||
}>();
|
||||
|
||||
const selectedUnit = ref<DurationUnit>("second");
|
||||
const selectedValue = ref<number>(1);
|
||||
|
||||
const activeUnitConfig = computed(() => UNIT_MAP.get(selectedUnit.value) ?? UNIT_CONFIG_LIST[0]);
|
||||
|
||||
const valueColumn = computed(() => {
|
||||
const items: PickerColumnItem[] = [];
|
||||
const unit = activeUnitConfig.value;
|
||||
|
||||
for (let index = unit.min; index <= unit.max; index += unit.step) {
|
||||
items.push({
|
||||
label: String(index),
|
||||
value: String(index)
|
||||
});
|
||||
}
|
||||
|
||||
return items;
|
||||
});
|
||||
|
||||
const unitColumn = computed(() => UNIT_CONFIG_LIST.map((item) => ({
|
||||
label: item.label,
|
||||
value: item.value
|
||||
})));
|
||||
|
||||
const pickerColumns = computed(() => [
|
||||
valueColumn.value,
|
||||
unitColumn.value
|
||||
]);
|
||||
|
||||
const pickerValue = computed<PickerValue[]>(() => [
|
||||
String(selectedValue.value),
|
||||
selectedUnit.value
|
||||
]);
|
||||
|
||||
const currentMs = computed(() => {
|
||||
const unit = activeUnitConfig.value;
|
||||
return selectedValue.value * unit.toMs;
|
||||
});
|
||||
|
||||
function clampByUnit(value: number, unit: UnitConfig): number {
|
||||
if (value < unit.min) {
|
||||
return unit.min;
|
||||
}
|
||||
if (unit.max < value) {
|
||||
return unit.max;
|
||||
}
|
||||
const offset = value - unit.min;
|
||||
const stepCount = Math.round(offset / unit.step);
|
||||
return unit.min + stepCount * unit.step;
|
||||
}
|
||||
|
||||
function pickStateFromMs(inputMs: number): { value: number; unit: DurationUnit } {
|
||||
const positiveMs = Math.max(1, Math.floor(inputMs));
|
||||
|
||||
for (const unit of UNIT_CONFIG_LIST) {
|
||||
if (unit.toMs <= positiveMs && positiveMs % unit.toMs === 0) {
|
||||
const candidate = positiveMs / unit.toMs;
|
||||
if (unit.min <= candidate && candidate <= unit.max && (candidate - unit.min) % unit.step === 0) {
|
||||
return {
|
||||
value: candidate,
|
||||
unit: unit.value
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const msUnit = UNIT_MAP.get("millisecond") as UnitConfig;
|
||||
return {
|
||||
value: clampByUnit(positiveMs, msUnit),
|
||||
unit: "millisecond"
|
||||
};
|
||||
}
|
||||
|
||||
function applyMsState(inputMs: number): void {
|
||||
const state = pickStateFromMs(inputMs);
|
||||
selectedUnit.value = state.unit;
|
||||
selectedValue.value = state.value;
|
||||
}
|
||||
|
||||
function handlePickerPick(values: PickerValue[]): void {
|
||||
applyPickerValues(values);
|
||||
}
|
||||
|
||||
function handlePickerConfirm(values: PickerValue[]): void {
|
||||
applyPickerValues(values);
|
||||
const nextMs = currentMs.value;
|
||||
emit("update:modelValue", nextMs);
|
||||
emit("change", nextMs);
|
||||
}
|
||||
|
||||
function applyPickerValues(values: PickerValue[]): void {
|
||||
const nextValue = Number(values[0]);
|
||||
const nextUnit = String(values[1]) as DurationUnit;
|
||||
const targetUnit = UNIT_MAP.get(nextUnit) ?? UNIT_CONFIG_LIST[0];
|
||||
|
||||
selectedUnit.value = targetUnit.value;
|
||||
selectedValue.value = clampByUnit(nextValue, targetUnit);
|
||||
}
|
||||
|
||||
watch(() => props.modelValue, (value) => {
|
||||
if (value === currentMs.value) {
|
||||
return;
|
||||
}
|
||||
applyMsState(value);
|
||||
}, { immediate: true });
|
||||
</script>
|
||||
@@ -0,0 +1,273 @@
|
||||
<template>
|
||||
<div v-if="visible" class="tui-editor-search" @mousedown.stop>
|
||||
<div class="row">
|
||||
<t-button
|
||||
class="toggle-btn"
|
||||
shape="square"
|
||||
size="small"
|
||||
type="button"
|
||||
variant="outline"
|
||||
:title="expanded ? '收起替换' : '展开替换'"
|
||||
@click="emit('update:expanded', !expanded)"
|
||||
>
|
||||
<t-icon :name="expanded ? 'chevron-down-s' : 'chevron-right-s'" />
|
||||
</t-button>
|
||||
<t-input
|
||||
ref="keywordInputRef"
|
||||
:value="keyword"
|
||||
class="text-input"
|
||||
placeholder="查找"
|
||||
size="small"
|
||||
@change="onKeywordChange"
|
||||
@keydown="onKeywordKeydown"
|
||||
>
|
||||
<template #suffix-icon>
|
||||
<t-button
|
||||
shape="square"
|
||||
size="small"
|
||||
type="button"
|
||||
variant="text"
|
||||
:theme="caseSensitive ? 'primary' : 'default'"
|
||||
title="大小写匹配"
|
||||
@click="emit('update:case-sensitive', !caseSensitive)"
|
||||
>
|
||||
Aa
|
||||
</t-button>
|
||||
<t-button
|
||||
shape="square"
|
||||
size="small"
|
||||
type="button"
|
||||
variant="text"
|
||||
:theme="useRegex ? 'primary' : 'default'"
|
||||
title="正则搜索"
|
||||
@click="emit('update:use-regex', !useRegex)"
|
||||
>
|
||||
.*
|
||||
</t-button>
|
||||
</template>
|
||||
</t-input>
|
||||
<span class="status" v-text="resolvedStatusText" />
|
||||
<t-button shape="square" size="small" type="button" variant="text" title="上一个" @click="emit('previous')">
|
||||
<t-icon name="arrow-up" />
|
||||
</t-button>
|
||||
<t-button shape="square" size="small" type="button" variant="text" title="下一个" @click="emit('next', false)">
|
||||
<t-icon name="arrow-down" />
|
||||
</t-button>
|
||||
<t-button shape="square" size="small" type="button" variant="text" title="关闭" @click="emit('close')">
|
||||
<t-icon name="close" />
|
||||
</t-button>
|
||||
</div>
|
||||
<div v-if="expanded" class="row replace-row">
|
||||
<div class="toggle-holder" />
|
||||
<t-input
|
||||
ref="replaceInputRef"
|
||||
:value="replaceValue"
|
||||
class="text-input"
|
||||
placeholder="替换"
|
||||
size="small"
|
||||
@change="onReplaceChange"
|
||||
@keydown="onReplaceKeydown"
|
||||
/>
|
||||
<div class="replace-actions">
|
||||
<t-button size="small" type="button" theme="primary" @click="emit('replace')">替换</t-button>
|
||||
<t-button size="small" type="button" variant="outline" @click="emit('replace-all')">全部替换</t-button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script lang="ts" setup>
|
||||
import type { ComponentPublicInstance } from "vue";
|
||||
|
||||
defineOptions({
|
||||
name: "EditorSearchBar"
|
||||
});
|
||||
|
||||
const props = withDefaults(defineProps<{
|
||||
visible?: boolean;
|
||||
expanded?: boolean;
|
||||
keyword?: string;
|
||||
replaceValue?: string;
|
||||
statusText?: string;
|
||||
statusError?: string;
|
||||
matchIndex?: number;
|
||||
matchCount?: number;
|
||||
caseSensitive?: boolean;
|
||||
useRegex?: boolean;
|
||||
}>(), {
|
||||
visible: false,
|
||||
expanded: false,
|
||||
keyword: "",
|
||||
replaceValue: "",
|
||||
statusText: undefined,
|
||||
statusError: "",
|
||||
matchIndex: -1,
|
||||
matchCount: 0,
|
||||
caseSensitive: false,
|
||||
useRegex: false
|
||||
});
|
||||
|
||||
const emit = defineEmits<{
|
||||
(event: "update:expanded", value: boolean): void;
|
||||
(event: "update:keyword", value: string): void;
|
||||
(event: "update:replace-value", value: string): void;
|
||||
(event: "update:case-sensitive", value: boolean): void;
|
||||
(event: "update:use-regex", value: boolean): void;
|
||||
(event: "previous"): void;
|
||||
(event: "next", shiftKey: boolean): void;
|
||||
(event: "replace"): void;
|
||||
(event: "replace-all"): void;
|
||||
(event: "close"): void;
|
||||
}>();
|
||||
|
||||
type InputInstance = ComponentPublicInstance & {
|
||||
$el: HTMLElement;
|
||||
};
|
||||
|
||||
type InputKeyboardContext = {
|
||||
e: KeyboardEvent;
|
||||
};
|
||||
|
||||
const keywordInputRef = ref<InputInstance>();
|
||||
const replaceInputRef = ref<InputInstance>();
|
||||
|
||||
const resolvedStatusText = computed(() => {
|
||||
if (undefined !== props.statusText) {
|
||||
return props.statusText;
|
||||
}
|
||||
if (props.statusError) {
|
||||
return props.statusError;
|
||||
}
|
||||
if (!props.keyword) {
|
||||
return "无结果";
|
||||
}
|
||||
if (1 > props.matchCount) {
|
||||
return "未找到";
|
||||
}
|
||||
return `${props.matchIndex + 1} / ${props.matchCount}`;
|
||||
});
|
||||
|
||||
const onKeywordChange = (value: string | number) => {
|
||||
emit("update:keyword", `${value}`);
|
||||
};
|
||||
|
||||
const onReplaceChange = (value: string | number) => {
|
||||
emit("update:replace-value", `${value}`);
|
||||
};
|
||||
|
||||
const onKeywordKeydown = (_value: string | number, context: InputKeyboardContext) => {
|
||||
if ("Enter" === context.e.key) {
|
||||
emit("next", context.e.shiftKey);
|
||||
return;
|
||||
}
|
||||
if ("Escape" !== context.e.key) {
|
||||
return;
|
||||
}
|
||||
context.e.preventDefault();
|
||||
emit("close");
|
||||
};
|
||||
|
||||
const onReplaceKeydown = (_value: string | number, context: InputKeyboardContext) => {
|
||||
if ("Enter" === context.e.key) {
|
||||
emit("replace");
|
||||
return;
|
||||
}
|
||||
if ("Escape" !== context.e.key) {
|
||||
return;
|
||||
}
|
||||
context.e.preventDefault();
|
||||
emit("close");
|
||||
};
|
||||
|
||||
const getNativeInput = (instance?: InputInstance) => instance?.$el.querySelector("input") || undefined;
|
||||
|
||||
const focusKeyword = (selectAll = false) => {
|
||||
const input = getNativeInput(keywordInputRef.value);
|
||||
input?.focus();
|
||||
if (selectAll && input) {
|
||||
input.selectionStart = 0;
|
||||
input.selectionEnd = input.value.length;
|
||||
}
|
||||
};
|
||||
|
||||
const focusReplace = (selectAll = false) => {
|
||||
const input = getNativeInput(replaceInputRef.value);
|
||||
input?.focus();
|
||||
if (selectAll && input) {
|
||||
input.selectionStart = 0;
|
||||
input.selectionEnd = input.value.length;
|
||||
}
|
||||
};
|
||||
|
||||
defineExpose({
|
||||
focusKeyword,
|
||||
focusReplace,
|
||||
keywordInputRef,
|
||||
replaceInputRef
|
||||
});
|
||||
</script>
|
||||
|
||||
<style lang="less" scoped>
|
||||
.tui-editor-search {
|
||||
top: .5rem;
|
||||
right: .5rem;
|
||||
gap: .375rem;
|
||||
z-index: 3;
|
||||
display: flex;
|
||||
padding: .5rem;
|
||||
position: absolute;
|
||||
min-width: 20rem;
|
||||
max-width: calc(100% - 1rem);
|
||||
box-sizing: border-box;
|
||||
border-radius: var(--td-radius-default, .375rem);
|
||||
background: var(--td-bg-color-container, #fff);
|
||||
border: 1px solid var(--td-component-stroke, #B8BBC9);
|
||||
box-shadow: 0 .25rem .75rem rgba(0, 0, 0, .12);
|
||||
flex-direction: column;
|
||||
|
||||
.row {
|
||||
gap: .375rem;
|
||||
display: flex;
|
||||
min-width: 0;
|
||||
align-items: center;
|
||||
|
||||
.toggle-holder {
|
||||
flex: none;
|
||||
width: 24px;
|
||||
}
|
||||
|
||||
.toggle-btn {
|
||||
flex: none;
|
||||
}
|
||||
|
||||
.text-input {
|
||||
width: 12rem;
|
||||
|
||||
:deep(.t-input) {
|
||||
padding-right: 0;
|
||||
}
|
||||
}
|
||||
|
||||
.status {
|
||||
width: 3rem;
|
||||
color: var(--td-text-color-secondary, #666);
|
||||
font-size: .875rem;
|
||||
white-space: nowrap;
|
||||
}
|
||||
}
|
||||
|
||||
.replace-actions {
|
||||
gap: .375rem;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
}
|
||||
}
|
||||
|
||||
@media (prefers-color-scheme: dark) {
|
||||
.tui-editor-search {
|
||||
background: var(--td-bg-color-container, #1f1f1f);
|
||||
border-color: var(--td-component-stroke, #434343);
|
||||
box-shadow: 0 .25rem .75rem rgba(0, 0, 0, .28);
|
||||
}
|
||||
}
|
||||
</style>
|
||||
+57
-2
@@ -1,10 +1,65 @@
|
||||
/** 导出所有组件 */
|
||||
import RootLayout from "./root-layout";
|
||||
import DurationPicker from "./duration-picker";
|
||||
import CodeEditor from "./code-editor";
|
||||
import TiptapEditor from "./tiptap-editor";
|
||||
import TiptapView from "./tiptap-view";
|
||||
import ArticleEditor from "./article-editor";
|
||||
import ArticleView from "./article-view";
|
||||
import NotifyEditor from "./notify-editor";
|
||||
import NotifyView from "./notify-view";
|
||||
import BottomPopup from "./bottom-popup";
|
||||
|
||||
export default [
|
||||
RootLayout
|
||||
RootLayout,
|
||||
DurationPicker,
|
||||
CodeEditor,
|
||||
TiptapEditor,
|
||||
TiptapView,
|
||||
ArticleEditor,
|
||||
ArticleView,
|
||||
NotifyEditor,
|
||||
NotifyView,
|
||||
BottomPopup
|
||||
];
|
||||
|
||||
export {
|
||||
RootLayout
|
||||
RootLayout,
|
||||
DurationPicker,
|
||||
CodeEditor,
|
||||
TiptapEditor,
|
||||
TiptapView,
|
||||
ArticleEditor,
|
||||
ArticleView,
|
||||
NotifyEditor,
|
||||
NotifyView,
|
||||
BottomPopup
|
||||
};
|
||||
|
||||
export type {
|
||||
CodeEditorExpose
|
||||
} from "./code-editor";
|
||||
|
||||
export type {
|
||||
TiptapEditorExpose
|
||||
} from "./tiptap-editor";
|
||||
|
||||
export type {
|
||||
ArticleEditorExpose
|
||||
} from "./article-editor";
|
||||
|
||||
export type {
|
||||
NotifyEditorExpose
|
||||
} from "./notify-editor";
|
||||
|
||||
export type {
|
||||
Article,
|
||||
ArticleContentType,
|
||||
Attachment,
|
||||
UploadResult
|
||||
} from "./article-editor";
|
||||
|
||||
export type {
|
||||
NotifyContentType,
|
||||
NotifyDetail
|
||||
} from "./notify-editor";
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
import { ToastPlugin } from "tdesign-mobile-vue";
|
||||
|
||||
type MessageType = "warning" | "error";
|
||||
|
||||
export async function showPlatformMessage(type: MessageType, content: string) {
|
||||
await Promise.resolve(ToastPlugin[type]({
|
||||
message: content
|
||||
}));
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
import type { NotifyContentType } from "./types";
|
||||
|
||||
/** 将未知通知正文类型归一化为组件支持的类型。 */
|
||||
export function normalizeNotifyContentType(contentType?: string): NotifyContentType {
|
||||
return contentType === "TEXT" ? "TEXT" : "TIP_TAP";
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
import view from "./index.vue";
|
||||
import { WebToolkit } from "timi-web";
|
||||
import type { NotifyDetail } from "./types";
|
||||
|
||||
export type { NotifyContentType, NotifyDetail } from "./types";
|
||||
|
||||
export type NotifyEditorExpose = {
|
||||
submit: () => Promise<NotifyDetail>;
|
||||
getPendingMediaCount: () => number;
|
||||
};
|
||||
|
||||
export const NotifyEditor = WebToolkit.withInstall(view);
|
||||
export default NotifyEditor;
|
||||
@@ -0,0 +1,77 @@
|
||||
<template>
|
||||
<article-editor
|
||||
ref="articleEditorRef"
|
||||
:model-value="articleValue"
|
||||
:placeholder="placeholder"
|
||||
:upload-image="uploadImage"
|
||||
:upload-video="uploadVideo"
|
||||
:resolve-attachment-url="resolveAttachmentUrl"
|
||||
:resolve-temp-url="resolveTempUrl"
|
||||
@change="onArticleChange"
|
||||
@update:model-value="onArticleCommit"
|
||||
/>
|
||||
</template>
|
||||
|
||||
<script lang="ts" setup>
|
||||
import type { Article, ArticleContentType, Attachment, UploadResult } from "../article-editor/types";
|
||||
import type { NotifyDetail } from "./types";
|
||||
import type { ArticleEditorExpose } from "../article-editor";
|
||||
import { ArticleEditor } from "../article-editor";
|
||||
import { normalizeNotifyContentType } from "./content";
|
||||
|
||||
defineOptions({
|
||||
name: "NotifyEditor"
|
||||
});
|
||||
|
||||
const props = withDefaults(defineProps<{
|
||||
modelValue?: NotifyDetail;
|
||||
placeholder?: string;
|
||||
uploadImage?: (file: File) => Promise<UploadResult>;
|
||||
uploadVideo?: (file: File) => Promise<UploadResult>;
|
||||
resolveAttachmentUrl?: (attachmentId: string, attachment?: Attachment) => string | Promise<string>;
|
||||
resolveTempUrl?: (tempFileId: string) => string | Promise<string>;
|
||||
}>(), {
|
||||
modelValue: () => ({}),
|
||||
placeholder: "请输入通知内容"
|
||||
});
|
||||
|
||||
const emit = defineEmits<{
|
||||
change: [value: NotifyDetail];
|
||||
"update:modelValue": [value: NotifyDetail];
|
||||
}>();
|
||||
|
||||
const articleEditorRef = ref<ArticleEditorExpose>();
|
||||
|
||||
const articleValue = computed<Article>(() => ({
|
||||
contentType: normalizeNotifyContentType(props.modelValue?.contentType) as ArticleContentType,
|
||||
content: props.modelValue?.content || "",
|
||||
attachmentList: props.modelValue?.attachmentList
|
||||
}));
|
||||
|
||||
function buildNotifyValue(value: Article): NotifyDetail {
|
||||
return {
|
||||
...(props.modelValue || {}),
|
||||
contentType: normalizeNotifyContentType(value.contentType),
|
||||
content: value.content || "",
|
||||
attachmentList: value.attachmentList || []
|
||||
};
|
||||
}
|
||||
|
||||
function onArticleChange(value: Article) {
|
||||
emit("change", buildNotifyValue(value));
|
||||
}
|
||||
|
||||
function onArticleCommit(value: Article) {
|
||||
emit("update:modelValue", buildNotifyValue(value));
|
||||
}
|
||||
|
||||
async function submit() {
|
||||
const value = await articleEditorRef.value?.submit();
|
||||
return buildNotifyValue(value || articleValue.value);
|
||||
}
|
||||
|
||||
defineExpose({
|
||||
submit,
|
||||
getPendingMediaCount: () => articleEditorRef.value?.getPendingMediaCount() || 0
|
||||
});
|
||||
</script>
|
||||
@@ -0,0 +1,15 @@
|
||||
import type { Article, Attachment } from "../article-editor/types";
|
||||
|
||||
/** 通知内容支持的正文类型。 */
|
||||
export type NotifyContentType = "TEXT" | "TIP_TAP";
|
||||
|
||||
/** 通知编辑器需要的通知最小结构。 */
|
||||
export type NotifyDetail = {
|
||||
[key: string]: unknown;
|
||||
content?: string;
|
||||
contentType?: string;
|
||||
attachmentList?: Attachment[];
|
||||
};
|
||||
|
||||
/** 通知内部复用文章编辑器的对象结构。 */
|
||||
export type NotifyArticle = Article;
|
||||
@@ -0,0 +1,5 @@
|
||||
import view from "./index.vue";
|
||||
import { WebToolkit } from "timi-web";
|
||||
|
||||
export const NotifyView = WebToolkit.withInstall(view);
|
||||
export default NotifyView;
|
||||
@@ -0,0 +1,33 @@
|
||||
<template>
|
||||
<article-view
|
||||
:article="articleValue"
|
||||
:empty-text="emptyText"
|
||||
:resolve-attachment-url="resolveAttachmentUrl"
|
||||
/>
|
||||
</template>
|
||||
|
||||
<script lang="ts" setup>
|
||||
import type { Article, ArticleContentType, Attachment } from "../article-editor/types";
|
||||
import type { NotifyDetail } from "../notify-editor/types";
|
||||
import { ArticleView } from "../article-view";
|
||||
import { normalizeNotifyContentType } from "../notify-editor/content";
|
||||
|
||||
defineOptions({
|
||||
name: "NotifyView"
|
||||
});
|
||||
|
||||
const props = withDefaults(defineProps<{
|
||||
detail?: NotifyDetail;
|
||||
emptyText?: string;
|
||||
resolveAttachmentUrl?: (attachmentId: string, attachment?: Attachment) => string | Promise<string>;
|
||||
}>(), {
|
||||
detail: () => ({}),
|
||||
emptyText: "暂无通知内容"
|
||||
});
|
||||
|
||||
const articleValue = computed<Article>(() => ({
|
||||
contentType: normalizeNotifyContentType(props.detail?.contentType) as ArticleContentType,
|
||||
content: props.detail?.content || "",
|
||||
attachmentList: props.detail?.attachmentList
|
||||
}));
|
||||
</script>
|
||||
@@ -1,5 +1,5 @@
|
||||
import view from "./index.vue";
|
||||
import { Toolkit } from "timi-web";
|
||||
import { WebToolkit } from "timi-web";
|
||||
|
||||
export const RootLayout = Toolkit.withInstall(view);
|
||||
export const RootLayout = WebToolkit.withInstall(view);
|
||||
export default RootLayout;
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
.tp-content-theme() {
|
||||
color: var(--td-text-color-primary);
|
||||
line-height: 1.6;
|
||||
|
||||
p {
|
||||
margin: 0 0 .75rem;
|
||||
}
|
||||
|
||||
p:empty:before {
|
||||
content: "\00a0";
|
||||
}
|
||||
|
||||
ul,
|
||||
ol {
|
||||
margin: 0 0 .75rem;
|
||||
padding-left: 1.25rem;
|
||||
}
|
||||
|
||||
table {
|
||||
width: 100%;
|
||||
margin: .75rem 0;
|
||||
table-layout: fixed;
|
||||
border-collapse: collapse;
|
||||
}
|
||||
|
||||
th,
|
||||
td {
|
||||
border: 1px solid var(--td-component-border);
|
||||
}
|
||||
|
||||
th {
|
||||
background: var(--td-bg-color-secondarycontainer);
|
||||
}
|
||||
|
||||
img,
|
||||
video,
|
||||
iframe {
|
||||
margin: 0 auto;
|
||||
max-width: 100%;
|
||||
}
|
||||
}
|
||||
|
||||
.tp-content-body {
|
||||
.tp-content-theme();
|
||||
}
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
<template>
|
||||
<t-button v-popup="'代码块'" :variant="active ? 'base' : 'text'" :theme="active ? 'light' : 'default'" @click="openDialog">
|
||||
<t-icon name="code" />
|
||||
</t-button>
|
||||
<t-popup
|
||||
v-model="visible"
|
||||
placement="bottom"
|
||||
height="30vh"
|
||||
destroy-on-close
|
||||
>
|
||||
<t-picker
|
||||
title="插入代码块"
|
||||
:model-value="pickerValue"
|
||||
:columns="pickerColumns"
|
||||
@confirm="onConfirm"
|
||||
@cancel="visible = false"
|
||||
@pick="handlePickerPick"
|
||||
/>
|
||||
</t-popup>
|
||||
</template>
|
||||
|
||||
<script lang="ts" setup>
|
||||
import type { PickerValue } from "tdesign-mobile-vue";
|
||||
import { supportedCodeLanguages } from "timi-web/editor";
|
||||
import type { TiptapEditorInstance } from "timi-web/editor";
|
||||
import BottomPopup from "../bottom-popup/index.vue";
|
||||
|
||||
defineOptions({
|
||||
name: "TiptapCodeBlockButton"
|
||||
});
|
||||
|
||||
const props = defineProps<{
|
||||
editor?: TiptapEditorInstance;
|
||||
active: boolean;
|
||||
}>();
|
||||
|
||||
// markup-templating 仅作为内部依赖语法,不作为独立选项。
|
||||
const OTHER_LANGUAGE_VALUE = "other";
|
||||
const codeLanguageOptions = [
|
||||
...supportedCodeLanguages,
|
||||
{ label: "其他", value: OTHER_LANGUAGE_VALUE }
|
||||
];
|
||||
|
||||
const visible = ref(false);
|
||||
const codeLanguage = ref("");
|
||||
const pickerValue = computed<PickerValue[]>(() => [codeLanguage.value || OTHER_LANGUAGE_VALUE]);
|
||||
const pickerColumns = [codeLanguageOptions];
|
||||
|
||||
function openDialog() {
|
||||
if (!props.editor) {
|
||||
return;
|
||||
}
|
||||
codeLanguage.value = "";
|
||||
visible.value = true;
|
||||
}
|
||||
|
||||
function handlePickerPick(values: PickerValue[]) {
|
||||
const language = String(values[0] ?? OTHER_LANGUAGE_VALUE);
|
||||
codeLanguage.value = language === OTHER_LANGUAGE_VALUE ? "" : language;
|
||||
}
|
||||
|
||||
function onConfirm() {
|
||||
if (!props.editor) {
|
||||
return;
|
||||
}
|
||||
const language = codeLanguage.value.trim();
|
||||
if (language) {
|
||||
props.editor.chain().focus().setCodeBlock({ language }).run();
|
||||
} else {
|
||||
props.editor.chain().focus().setCodeBlock().run();
|
||||
}
|
||||
visible.value = false;
|
||||
}
|
||||
</script>
|
||||
@@ -0,0 +1,160 @@
|
||||
<template>
|
||||
<t-button :variant="active ? 'base' : 'text'" :theme="active ? 'light' : 'default'" @click="openDialog">
|
||||
<t-icon name="web" />
|
||||
</t-button>
|
||||
<bottom-popup
|
||||
v-model="visible"
|
||||
placement="bottom"
|
||||
title="插入内嵌网页"
|
||||
left-button-text="取消"
|
||||
right-button-text="插入"
|
||||
@left-button-click="visible = false"
|
||||
@right-button-click="onConfirm"
|
||||
destroy-on-close
|
||||
>
|
||||
<t-form class="popup" label-align="left" label-width="auto">
|
||||
<t-form-item label="网页地址">
|
||||
<t-input
|
||||
v-model="iframeForm.src"
|
||||
placeholder="请输入网页地址"
|
||||
borderless
|
||||
/>
|
||||
</t-form-item>
|
||||
<t-form-item label="网页标题">
|
||||
<t-input
|
||||
v-model="iframeForm.title"
|
||||
placeholder="请输入网页标题,可留空"
|
||||
borderless
|
||||
/>
|
||||
</t-form-item>
|
||||
<t-form-item label="宽度">
|
||||
<div class="field">
|
||||
<t-input
|
||||
v-model="iframeForm.width"
|
||||
placeholder="请输入宽度,默认 100%"
|
||||
borderless
|
||||
/>
|
||||
<t-button size="extra-small" variant="outline" @click="setWidth('auto')">
|
||||
自动
|
||||
</t-button>
|
||||
<t-button size="extra-small" variant="outline" @click="setWidth('100%')">
|
||||
铺满
|
||||
</t-button>
|
||||
</div>
|
||||
</t-form-item>
|
||||
<t-form-item label="高度">
|
||||
<div class="field">
|
||||
<t-input
|
||||
v-model="iframeForm.height"
|
||||
placeholder="请输入高度,默认 28rem"
|
||||
borderless
|
||||
/>
|
||||
<t-button size="extra-small" variant="outline" @click="setHeight">
|
||||
自动
|
||||
</t-button>
|
||||
</div>
|
||||
</t-form-item>
|
||||
</t-form>
|
||||
</bottom-popup>
|
||||
</template>
|
||||
|
||||
<script lang="ts" setup>
|
||||
import { showPlatformMessage } from "../message";
|
||||
import type { TiptapEditorInstance } from "timi-web/editor";
|
||||
import BottomPopup from "../bottom-popup/index.vue";
|
||||
|
||||
defineOptions({
|
||||
name: "TiptapIframeButton"
|
||||
});
|
||||
|
||||
const props = defineProps<{
|
||||
editor?: TiptapEditorInstance;
|
||||
active: boolean;
|
||||
}>();
|
||||
|
||||
const visible = ref(false);
|
||||
const iframeForm = reactive({
|
||||
src: "",
|
||||
title: "",
|
||||
width: "100%",
|
||||
height: "28rem"
|
||||
});
|
||||
|
||||
function setWidth(width: "auto" | "100%") {
|
||||
iframeForm.width = width;
|
||||
}
|
||||
|
||||
function setHeight() {
|
||||
iframeForm.height = "auto";
|
||||
}
|
||||
|
||||
function openDialog() {
|
||||
if (!props.editor) {
|
||||
return;
|
||||
}
|
||||
const attributes = props.editor.getAttributes("iframe");
|
||||
iframeForm.src = (attributes.src as string) || "https://";
|
||||
iframeForm.title = (attributes.title as string) || "";
|
||||
iframeForm.width = (attributes.width as string) || "100%";
|
||||
iframeForm.height = (attributes.height as string) || "28rem";
|
||||
visible.value = true;
|
||||
}
|
||||
|
||||
function isValidHttpUrl(value: string) {
|
||||
try {
|
||||
const url = new URL(value);
|
||||
return url.protocol === "http:" || url.protocol === "https:";
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
async function onConfirm() {
|
||||
if (!props.editor) {
|
||||
return;
|
||||
}
|
||||
const src = iframeForm.src.trim();
|
||||
if (!src) {
|
||||
visible.value = false;
|
||||
return;
|
||||
}
|
||||
if (!isValidHttpUrl(src)) {
|
||||
await showPlatformMessage("warning", "请输入有效的 http 或 https 地址");
|
||||
return;
|
||||
}
|
||||
props.editor
|
||||
.chain()
|
||||
.focus()
|
||||
.insertContent({
|
||||
type: "iframe",
|
||||
attrs: {
|
||||
src,
|
||||
title: iframeForm.title.trim() || "内嵌网页",
|
||||
width: iframeForm.width.trim() || "100%",
|
||||
height: iframeForm.height.trim() || "28rem"
|
||||
}
|
||||
})
|
||||
.run();
|
||||
visible.value = false;
|
||||
}
|
||||
</script>
|
||||
|
||||
<style lang="less" scoped>
|
||||
.popup {
|
||||
margin: 0;
|
||||
padding: 0 1rem calc(1rem + env(safe-area-inset-bottom));
|
||||
background: var(--td-bg-color-container);
|
||||
|
||||
.field {
|
||||
gap: .5rem;
|
||||
width: 100%;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
|
||||
:deep(.t-input) {
|
||||
min-width: 0;
|
||||
flex: 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,116 @@
|
||||
<template>
|
||||
<t-button
|
||||
:variant="active ? 'base' : 'text'"
|
||||
:theme="active ? 'light' : 'default'"
|
||||
@click="openDialog"
|
||||
>
|
||||
<t-icon name="link-1" />
|
||||
</t-button>
|
||||
<bottom-popup
|
||||
v-model="visible"
|
||||
placement="bottom"
|
||||
title="插入链接"
|
||||
left-button-text="取消"
|
||||
right-button-text="插入"
|
||||
@left-button-click="visible = false"
|
||||
@right-button-click="onConfirm"
|
||||
destroy-on-close
|
||||
>
|
||||
<t-form class="popup">
|
||||
<t-form-item label="地址">
|
||||
<t-input v-model="linkForm.href" borderless />
|
||||
</t-form-item>
|
||||
<t-form-item label="显示文本">
|
||||
<t-input v-model="linkForm.text" borderless />
|
||||
</t-form-item>
|
||||
<t-form-item content-align="right">
|
||||
<t-checkbox
|
||||
class="sync"
|
||||
v-model="linkForm.syncToHref"
|
||||
borderless
|
||||
>显示文本同步为链接</t-checkbox>
|
||||
</t-form-item>
|
||||
</t-form>
|
||||
</bottom-popup>
|
||||
</template>
|
||||
|
||||
<script lang="ts" setup>
|
||||
import type { TiptapEditorInstance } from "timi-web/editor";
|
||||
import BottomPopup from "../bottom-popup/index.vue";
|
||||
|
||||
defineOptions({
|
||||
name: "TiptapLinkButton"
|
||||
});
|
||||
|
||||
const props = defineProps<{
|
||||
editor?: TiptapEditorInstance;
|
||||
active: boolean;
|
||||
}>();
|
||||
|
||||
const visible = ref(false);
|
||||
const linkForm = reactive({
|
||||
href: "",
|
||||
text: "",
|
||||
syncToHref: false
|
||||
});
|
||||
|
||||
function openDialog() {
|
||||
if (!props.editor) {
|
||||
return;
|
||||
}
|
||||
const previousUrl = (props.editor.getAttributes("link").href as string) || "";
|
||||
const selectedText = props.editor.state.doc.textBetween(
|
||||
props.editor.state.selection.from,
|
||||
props.editor.state.selection.to,
|
||||
""
|
||||
);
|
||||
linkForm.href = previousUrl || "https://";
|
||||
linkForm.text = selectedText || "";
|
||||
linkForm.syncToHref = false;
|
||||
visible.value = true;
|
||||
}
|
||||
|
||||
function onConfirm() {
|
||||
if (!props.editor) {
|
||||
return;
|
||||
}
|
||||
const href = linkForm.href.trim();
|
||||
if (!href) {
|
||||
props.editor.chain().focus().unsetLink().run();
|
||||
visible.value = false;
|
||||
return;
|
||||
}
|
||||
const text = linkForm.syncToHref ? href : linkForm.text.trim();
|
||||
if (text) {
|
||||
props.editor
|
||||
.chain()
|
||||
.focus()
|
||||
.insertContent({
|
||||
type: "text",
|
||||
text,
|
||||
marks: [{ type: "link", attrs: { href } }]
|
||||
})
|
||||
.run();
|
||||
} else {
|
||||
props.editor.chain().focus().extendMarkRange("link").setLink({ href }).run();
|
||||
}
|
||||
visible.value = false;
|
||||
}
|
||||
</script>
|
||||
|
||||
<style lang="less" scoped>
|
||||
.link-form {
|
||||
gap: .75rem;
|
||||
padding: 0 1rem calc(1rem + env(safe-area-inset-bottom));
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.popup {
|
||||
margin: 0;
|
||||
|
||||
.sync {
|
||||
padding: 0;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,263 @@
|
||||
<template>
|
||||
<t-button :variant="active ? 'base' : 'text'" :theme="active ? 'light' : 'default'" :loading="uploading" @click="openDialog">
|
||||
<t-icon :name="iconName" />
|
||||
</t-button>
|
||||
<bottom-popup
|
||||
v-model="visible"
|
||||
placement="bottom"
|
||||
:title="`插入${typeLabel}`"
|
||||
left-button-text="取消"
|
||||
right-button-text="插入"
|
||||
@left-button-click="visible = false"
|
||||
@right-button-click="onConfirm"
|
||||
destroy-on-close
|
||||
>
|
||||
<template #rightButton="{ onClick }">
|
||||
<t-button
|
||||
theme="primary"
|
||||
variant="text"
|
||||
size="small"
|
||||
:loading="uploading"
|
||||
:disabled="uploading"
|
||||
@click="onClick"
|
||||
content="插入"
|
||||
/>
|
||||
</template>
|
||||
<t-form class="popup" label-align="left" label-width="auto">
|
||||
<t-form-item label="文件">
|
||||
<div class="field">
|
||||
<t-input
|
||||
:value="selectedFile?.name || `未选择${typeLabel}文件`"
|
||||
readonly
|
||||
borderless
|
||||
/>
|
||||
<t-button
|
||||
size="extra-small"
|
||||
variant="outline"
|
||||
@click="pickFile"
|
||||
>
|
||||
<span v-text="selectedFile ? '重新选择' : `选择${typeLabel}`" />
|
||||
</t-button>
|
||||
</div>
|
||||
</t-form-item>
|
||||
<t-form-item label="标题">
|
||||
<t-input
|
||||
v-model="mediaForm.title"
|
||||
:placeholder="`请输入${typeLabel}标题,可留空`"
|
||||
borderless
|
||||
/>
|
||||
</t-form-item>
|
||||
<t-form-item label="宽度">
|
||||
<div class="field">
|
||||
<t-input
|
||||
v-model="mediaForm.width"
|
||||
placeholder="请输入宽度,默认 100%"
|
||||
borderless
|
||||
/>
|
||||
<t-button
|
||||
size="extra-small"
|
||||
variant="outline"
|
||||
@click="setWidth('auto')"
|
||||
content="自动"
|
||||
/>
|
||||
<t-button
|
||||
size="extra-small"
|
||||
variant="outline"
|
||||
@click="setWidth('100%')"
|
||||
content="铺满"
|
||||
/>
|
||||
</div>
|
||||
</t-form-item>
|
||||
<t-form-item label="高度">
|
||||
<div class="field">
|
||||
<t-input
|
||||
v-model="mediaForm.height"
|
||||
placeholder="请输入高度,默认 auto"
|
||||
borderless
|
||||
/>
|
||||
<t-button
|
||||
size="extra-small"
|
||||
variant="outline"
|
||||
@click="setHeight"
|
||||
content="自动"
|
||||
/>
|
||||
</div>
|
||||
</t-form-item>
|
||||
</t-form>
|
||||
</bottom-popup>
|
||||
<input ref="fileInputRef" class="file-input" type="file" :accept="accept" @change="onFileChange" />
|
||||
</template>
|
||||
|
||||
<script lang="ts" setup>
|
||||
import { showPlatformMessage } from "../message";
|
||||
import type { TiptapEditorInstance, UploadResult } from "timi-web/editor";
|
||||
import BottomPopup from "../bottom-popup/index.vue";
|
||||
|
||||
defineOptions({
|
||||
name: "TiptapMediaButton"
|
||||
});
|
||||
|
||||
const props = defineProps<{
|
||||
editor?: TiptapEditorInstance;
|
||||
active: boolean;
|
||||
type: "image" | "video";
|
||||
upload?: (file: File) => Promise<UploadResult>;
|
||||
}>();
|
||||
|
||||
const visible = ref(false);
|
||||
const uploading = ref(false);
|
||||
const selectedFile = ref<File>();
|
||||
const fileInputRef = ref<HTMLInputElement>();
|
||||
const mediaForm = reactive({
|
||||
title: "",
|
||||
width: "100%",
|
||||
height: ""
|
||||
});
|
||||
|
||||
const typeLabel = computed(() => {
|
||||
return props.type === "image" ? "图片" : "视频";
|
||||
});
|
||||
|
||||
const iconName = computed(() => {
|
||||
return props.type === "image" ? "image-add" : "video";
|
||||
});
|
||||
|
||||
const accept = computed(() => {
|
||||
return props.type === "image" ? "image/*" : "video/*";
|
||||
});
|
||||
|
||||
function buildDefaultHeight() {
|
||||
return "auto";
|
||||
}
|
||||
|
||||
function setWidth(width: "auto" | "100%") {
|
||||
mediaForm.width = width;
|
||||
}
|
||||
|
||||
function setHeight() {
|
||||
mediaForm.height = buildDefaultHeight();
|
||||
}
|
||||
|
||||
function pickFile(event?: MouseEvent) {
|
||||
event?.stopPropagation();
|
||||
fileInputRef.value?.click();
|
||||
}
|
||||
|
||||
function openDialog() {
|
||||
if (!props.editor) {
|
||||
return;
|
||||
}
|
||||
selectedFile.value = undefined;
|
||||
const attributes = props.editor.getAttributes(props.type);
|
||||
mediaForm.title = (attributes.title as string) || "";
|
||||
mediaForm.width = (attributes.width as string) || "100%";
|
||||
mediaForm.height = (attributes.height as string) || buildDefaultHeight();
|
||||
visible.value = true;
|
||||
}
|
||||
|
||||
function onFileChange(event: Event) {
|
||||
const target = event.target as HTMLInputElement;
|
||||
selectedFile.value = target.files?.[0];
|
||||
target.value = "";
|
||||
if (!selectedFile.value) {
|
||||
return;
|
||||
}
|
||||
if (!mediaForm.title.trim()) {
|
||||
mediaForm.title = selectedFile.value.name;
|
||||
}
|
||||
}
|
||||
|
||||
async function onConfirm() {
|
||||
if (!props.editor) {
|
||||
return;
|
||||
}
|
||||
if (!props.upload) {
|
||||
await showPlatformMessage("warning", `${typeLabel.value}上传功能未启用`);
|
||||
return;
|
||||
}
|
||||
if (!selectedFile.value) {
|
||||
await showPlatformMessage("warning", `请选择${typeLabel.value}文件`);
|
||||
return;
|
||||
}
|
||||
uploading.value = true;
|
||||
try {
|
||||
const file = selectedFile.value;
|
||||
const result = await props.upload(file);
|
||||
const title = mediaForm.title.trim() || result.name || file.name;
|
||||
const attrs = {
|
||||
src: result.url,
|
||||
title,
|
||||
width: mediaForm.width.trim() || "100%",
|
||||
height: mediaForm.height.trim() || buildDefaultHeight(),
|
||||
attachmentId: result.id,
|
||||
tempFileId: result.id
|
||||
};
|
||||
if (props.type === "image") {
|
||||
props.editor
|
||||
.chain()
|
||||
.focus()
|
||||
.setImage({
|
||||
src: attrs.src,
|
||||
alt: title,
|
||||
title
|
||||
})
|
||||
.updateAttributes("image", {
|
||||
attachmentId: attrs.attachmentId,
|
||||
tempFileId: attrs.tempFileId,
|
||||
width: attrs.width,
|
||||
height: attrs.height
|
||||
})
|
||||
.run();
|
||||
} else {
|
||||
props.editor
|
||||
.chain()
|
||||
.focus()
|
||||
.insertContent({
|
||||
type: "video",
|
||||
attrs
|
||||
})
|
||||
.run();
|
||||
}
|
||||
visible.value = false;
|
||||
} catch (error) {
|
||||
console.error(`上传${typeLabel.value}失败:`, error);
|
||||
await showPlatformMessage("error", `上传${typeLabel.value}失败`);
|
||||
} finally {
|
||||
uploading.value = false;
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<style lang="less" scoped>
|
||||
.popup {
|
||||
margin: 0;
|
||||
padding: 0 1rem calc(1rem + env(safe-area-inset-bottom));
|
||||
overflow-y: auto;
|
||||
background: var(--td-bg-color-container);
|
||||
|
||||
.field {
|
||||
gap: .5rem;
|
||||
width: 100%;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
|
||||
:deep(.t-input) {
|
||||
min-width: 0;
|
||||
flex: 1;
|
||||
}
|
||||
}
|
||||
|
||||
.selector {
|
||||
--td-button-extra-small-height: 24px;
|
||||
|
||||
width: 100%;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
}
|
||||
}
|
||||
|
||||
.file-input {
|
||||
display: none;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,183 @@
|
||||
<template>
|
||||
<t-popover
|
||||
v-if="active"
|
||||
v-model="actionVisible"
|
||||
class="popover"
|
||||
placement="bottom"
|
||||
theme="light"
|
||||
:show-arrow="false"
|
||||
>
|
||||
<t-button variant="base" theme="light">
|
||||
<t-icon name="table" />
|
||||
</t-button>
|
||||
<template #content>
|
||||
<div class="actions">
|
||||
<t-button
|
||||
class="action"
|
||||
size="extra-small"
|
||||
variant="text"
|
||||
block
|
||||
@click="onContinueInsert"
|
||||
>继续插入</t-button>
|
||||
<t-button
|
||||
class="action"
|
||||
size="extra-small"
|
||||
variant="text"
|
||||
theme="danger"
|
||||
block
|
||||
@click="onDeleteTable"
|
||||
>删除表格</t-button>
|
||||
</div>
|
||||
</template>
|
||||
</t-popover>
|
||||
<t-button v-else v-popup="'插入表格'" variant="text" @click="openPopup">
|
||||
<t-icon name="table" />
|
||||
</t-button>
|
||||
<bottom-popup
|
||||
v-model="visible"
|
||||
placement="bottom"
|
||||
title="插入表格"
|
||||
left-button-text="取消"
|
||||
right-button-text="确定"
|
||||
@left-button-click="visible = false"
|
||||
@right-button-click="visible = false"
|
||||
destroy-on-close
|
||||
>
|
||||
<div class="table-picker" @mouseleave="onReset">
|
||||
<div class="tip" v-text="`${hoverRow} × ${hoverCol}`" />
|
||||
<div class="grid">
|
||||
<button
|
||||
v-for="item in tablePickerItems"
|
||||
:key="item.key"
|
||||
class="cell"
|
||||
:class="{ active: item.active }"
|
||||
type="button"
|
||||
@mousemove="onHover(item.row, item.col)"
|
||||
@click="onSelect(item.row, item.col)"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</bottom-popup>
|
||||
</template>
|
||||
|
||||
<script lang="ts" setup>
|
||||
import { TABLE_PICKER_SIZE } from "timi-web/editor";
|
||||
import type { TiptapEditorInstance } from "timi-web/editor";
|
||||
import BottomPopup from "../bottom-popup/index.vue";
|
||||
|
||||
defineOptions({
|
||||
name: "TiptapTableButton"
|
||||
});
|
||||
|
||||
const props = defineProps<{
|
||||
editor?: TiptapEditorInstance;
|
||||
active: boolean;
|
||||
}>();
|
||||
|
||||
const visible = ref(false);
|
||||
const actionVisible = ref(false);
|
||||
const hoverRow = ref(1);
|
||||
const hoverCol = ref(1);
|
||||
|
||||
const tablePickerItems = computed(() => {
|
||||
const items: { key: string; row: number; col: number; active: boolean }[] = [];
|
||||
for (let row = 1; row < TABLE_PICKER_SIZE + 1; row += 1) {
|
||||
for (let col = 1; col < TABLE_PICKER_SIZE + 1; col += 1) {
|
||||
items.push({
|
||||
key: `${row}-${col}`,
|
||||
row,
|
||||
col,
|
||||
active: row < hoverRow.value + 1 && col < hoverCol.value + 1
|
||||
});
|
||||
}
|
||||
}
|
||||
return items;
|
||||
});
|
||||
|
||||
function openPopup() {
|
||||
hoverRow.value = 1;
|
||||
hoverCol.value = 1;
|
||||
visible.value = true;
|
||||
}
|
||||
|
||||
function onContinueInsert() {
|
||||
actionVisible.value = false;
|
||||
openPopup();
|
||||
}
|
||||
|
||||
function onDeleteTable() {
|
||||
actionVisible.value = false;
|
||||
props.editor?.chain().focus().deleteTable().run();
|
||||
}
|
||||
|
||||
function onReset() {
|
||||
hoverRow.value = 1;
|
||||
hoverCol.value = 1;
|
||||
}
|
||||
|
||||
function onHover(row: number, col: number) {
|
||||
hoverRow.value = row;
|
||||
hoverCol.value = col;
|
||||
}
|
||||
|
||||
function onSelect(row: number, col: number) {
|
||||
if (!props.editor) {
|
||||
return;
|
||||
}
|
||||
props.editor.chain().focus().insertTable({ rows: row, cols: col, withHeaderRow: true }).run();
|
||||
}
|
||||
|
||||
watch(() => props.active, (active) => {
|
||||
if (!active) {
|
||||
actionVisible.value = false;
|
||||
}
|
||||
});
|
||||
</script>
|
||||
|
||||
<style lang="less" scoped>
|
||||
.table-picker {
|
||||
padding: 0 1rem calc(1rem + env(safe-area-inset-bottom));
|
||||
display: flex;
|
||||
box-sizing: border-box;
|
||||
background: var(--td-bg-color-container, #fff);
|
||||
justify-content: center;
|
||||
flex-direction: column;
|
||||
|
||||
.tip {
|
||||
height: 1.5rem;
|
||||
color: var(--td-text-color-secondary, #666);
|
||||
font-size: .75rem;
|
||||
text-align: center;
|
||||
line-height: 1.5rem;
|
||||
}
|
||||
|
||||
.grid {
|
||||
gap: .5rem;
|
||||
width: fit-content;
|
||||
display: grid;
|
||||
margin: 0 auto;
|
||||
grid-template-columns: repeat(7, 1fr);
|
||||
|
||||
.cell {
|
||||
width: 2rem;
|
||||
height: 2rem;
|
||||
border: 1px solid var(--td-component-border, #dcdcdc);
|
||||
padding: 0;
|
||||
background: var(--td-bg-color-container, #fff);
|
||||
|
||||
&.active {
|
||||
border-color: var(--td-brand-color, #0052d9);
|
||||
background: var(--td-brand-color-light, #e0edff);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.actions {
|
||||
padding: 0 1rem;
|
||||
|
||||
.action {
|
||||
height: 2rem !important;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,529 @@
|
||||
<template>
|
||||
<div class="toolbar">
|
||||
<div class="toolbar-head">
|
||||
<div class="history" :class="{ 'toolbar-disabled': sourceCodeMode }">
|
||||
<t-button v-popup="'撤销'" variant="text" :disabled="!canExec('undo')" @click="run('undo')">
|
||||
<t-icon name="rollback" />
|
||||
</t-button>
|
||||
<t-button v-popup="'重做'" variant="text" :disabled="!canExec('redo')" @click="run('redo')">
|
||||
<t-icon name="rollfront" />
|
||||
</t-button>
|
||||
<t-button v-popup="'清除格式'" variant="text" @click="run('clear')">
|
||||
<t-icon name="clear-formatting" />
|
||||
</t-button>
|
||||
</div>
|
||||
<t-button
|
||||
v-popup="sourceCodeMode ? '富文本' : '源码'"
|
||||
class="source-btn"
|
||||
:variant="sourceCodeMode ? 'base' : 'text'"
|
||||
:theme="sourceCodeMode ? 'light' : 'default'"
|
||||
@click="emit('toggle-source-code')"
|
||||
>
|
||||
<t-icon v-if="sourceCodeMode" name="edit-1" />
|
||||
<t-icon v-else name="braces" />
|
||||
</t-button>
|
||||
</div>
|
||||
<div class="scroll" :class="{ 'toolbar-disabled': sourceCodeMode }">
|
||||
<div class="actions">
|
||||
<t-button v-popup="'标题'" :variant="isHeadingActive ? 'base' : 'text'" :theme="isHeadingActive ? 'light' : 'default'" @click="headingVisible = true">
|
||||
<t-icon name="text" />
|
||||
</t-button>
|
||||
<bottom-popup
|
||||
v-model="headingVisible"
|
||||
placement="bottom"
|
||||
title="选择标题"
|
||||
left-button-text="取消"
|
||||
right-button-text="确定"
|
||||
@left-button-click="headingVisible = false"
|
||||
@right-button-click="headingVisible = false"
|
||||
destroy-on-close
|
||||
>
|
||||
<div class="heading-picker">
|
||||
<t-button
|
||||
v-for="option in headingMeta"
|
||||
:key="option.value"
|
||||
variant="text"
|
||||
block
|
||||
@click="onHeadingSelect(option)"
|
||||
>
|
||||
<span :class="['tp-heading-option', option.className]" v-text="option.label" />
|
||||
</t-button>
|
||||
</div>
|
||||
</bottom-popup>
|
||||
<t-button v-popup="'加粗'" :variant="isActive('bold') ? 'base' : 'text'" :theme="isActive('bold') ? 'light' : 'default'" @click="run('bold')">
|
||||
<t-icon name="textformat-bold" />
|
||||
</t-button>
|
||||
<t-button v-popup="'斜体'" :variant="isActive('italic') ? 'base' : 'text'" :theme="isActive('italic') ? 'light' : 'default'" @click="run('italic')">
|
||||
<t-icon name="textformat-italic" />
|
||||
</t-button>
|
||||
<t-button v-popup="'下划线'" :variant="isActive('underline') ? 'base' : 'text'" :theme="isActive('underline') ? 'light' : 'default'" @click="run('underline')">
|
||||
<t-icon name="textformat-underline" />
|
||||
</t-button>
|
||||
<t-button v-popup="'删除线'" :variant="isActive('strike') ? 'base' : 'text'" :theme="isActive('strike') ? 'light' : 'default'" @click="run('strike')">
|
||||
<t-icon name="textformat-strikethrough" />
|
||||
</t-button>
|
||||
<t-button v-popup="'前景色'" variant="text" @click="pickColor('text')">
|
||||
<t-icon name="textformat-color" />
|
||||
</t-button>
|
||||
<t-button v-popup="'背景色'" variant="text" @click="pickColor('bg')">
|
||||
<t-icon name="fill-color-1" />
|
||||
</t-button>
|
||||
<t-button v-popup="'有序列表'" :variant="isActive('orderedList') ? 'base' : 'text'" :theme="isActive('orderedList') ? 'light' : 'default'" @click="run('orderedList')">
|
||||
<t-icon name="order-list" />
|
||||
</t-button>
|
||||
<tiptap-table-button :editor="editor" :active="tableActive" />
|
||||
<t-button v-popup="'无序列表'" :variant="isActive('bulletList') ? 'base' : 'text'" :theme="isActive('bulletList') ? 'light' : 'default'" @click="run('bulletList')">
|
||||
<t-icon name="bulletpoint" />
|
||||
</t-button>
|
||||
<t-button v-popup="'行内代码'" :variant="isActive('code') ? 'base' : 'text'" :theme="isActive('code') ? 'light' : 'default'" @click="run('code')">
|
||||
<t-icon name="highlighted-block" />
|
||||
</t-button>
|
||||
<tiptap-code-block-button :editor="editor" :active="isActive('codeBlock')" />
|
||||
<t-button v-popup="'下标'" :variant="isActive('subscript') ? 'base' : 'text'" :theme="isActive('subscript') ? 'light' : 'default'" @click="run('subscript')">
|
||||
<t-icon name="subscript" />
|
||||
</t-button>
|
||||
<t-button v-popup="'上标'" :variant="isActive('superscript') ? 'base' : 'text'" :theme="isActive('superscript') ? 'light' : 'default'" @click="run('superscript')">
|
||||
<t-icon name="superscript" />
|
||||
</t-button>
|
||||
<t-button v-popup="'左对齐'" :variant="isAlignActive('left') ? 'base' : 'text'" :theme="isAlignActive('left') ? 'light' : 'default'" @click="setAlign('left')">
|
||||
<t-icon name="format-vertical-align-left" />
|
||||
</t-button>
|
||||
<t-button v-popup="'居中对齐'" :variant="isAlignActive('center') ? 'base' : 'text'" :theme="isAlignActive('center') ? 'light' : 'default'" @click="setAlign('center')">
|
||||
<t-icon name="format-vertical-align-center" />
|
||||
</t-button>
|
||||
<t-button v-popup="'右对齐'" :variant="isAlignActive('right') ? 'base' : 'text'" :theme="isAlignActive('right') ? 'light' : 'default'" @click="setAlign('right')">
|
||||
<t-icon name="format-vertical-align-right" />
|
||||
</t-button>
|
||||
<t-button
|
||||
v-popup="'两端对齐'"
|
||||
:variant="isAlignActive('justify') ? 'base' : 'text'"
|
||||
:theme="isAlignActive('justify') ? 'light' : 'default'"
|
||||
@click="setAlign('justify')"
|
||||
>
|
||||
<t-icon name="expand-horizontal" />
|
||||
</t-button>
|
||||
<t-button v-popup="'分割线'" variant="text" @click="run('horizontalRule')">
|
||||
<t-icon name="divider-1" />
|
||||
</t-button>
|
||||
<tiptap-link-button :editor="editor" :active="isActive('link')" />
|
||||
<tiptap-media-button :editor="editor" :active="isActive('image')" type="image" :upload="uploadImage" />
|
||||
<tiptap-media-button :editor="editor" :active="isActive('video')" type="video" :upload="uploadVideo" />
|
||||
<tiptap-iframe-button :editor="editor" :active="isActive('iframe')" />
|
||||
</div>
|
||||
</div>
|
||||
<bottom-popup
|
||||
v-model="colorPickerVisible"
|
||||
placement="bottom"
|
||||
:title="colorPickerType === 'text' ? '前景色' : '背景色'"
|
||||
left-button-text="取消"
|
||||
right-button-text="确定"
|
||||
@left-button-click="colorPickerVisible = false"
|
||||
@right-button-click="confirmColor"
|
||||
destroy-on-close
|
||||
>
|
||||
<div class="color-picker-popup">
|
||||
<template v-if="colorPickerType === 'text'">
|
||||
<t-color-picker
|
||||
v-model="textColorDraft"
|
||||
type="multiple"
|
||||
format="HEX"
|
||||
:fixed="true"
|
||||
:swatch-colors="colorSwatchColors"
|
||||
@change="onTextColorChange"
|
||||
@palette-bar-change="onTextPaletteBarChange"
|
||||
/>
|
||||
</template>
|
||||
<template v-else>
|
||||
<t-color-picker
|
||||
v-model="bgColorDraft"
|
||||
type="multiple"
|
||||
format="HEX"
|
||||
:fixed="true"
|
||||
:swatch-colors="colorSwatchColors"
|
||||
@change="onBgColorChange"
|
||||
@palette-bar-change="onBgPaletteBarChange"
|
||||
/>
|
||||
</template>
|
||||
</div>
|
||||
</bottom-popup>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script lang="ts" setup>
|
||||
import type { ColorObject } from "tdesign-mobile-vue";
|
||||
import type { AlignType, UploadResult, TiptapEditorInstance } from "timi-web/editor";
|
||||
import { headingMeta } from "timi-web/editor";
|
||||
import TiptapCodeBlockButton from "./TiptapCodeBlockButton.vue";
|
||||
import TiptapIframeButton from "./TiptapIframeButton.vue";
|
||||
import TiptapLinkButton from "./TiptapLinkButton.vue";
|
||||
import TiptapMediaButton from "./TiptapMediaButton.vue";
|
||||
import TiptapTableButton from "./TiptapTableButton.vue";
|
||||
import BottomPopup from "../bottom-popup/index.vue";
|
||||
|
||||
defineOptions({
|
||||
name: "TiptapToolbar"
|
||||
});
|
||||
|
||||
const props = withDefaults(defineProps<{
|
||||
editor?: TiptapEditorInstance;
|
||||
uploadImage?: (file: File) => Promise<UploadResult>;
|
||||
uploadVideo?: (file: File) => Promise<UploadResult>;
|
||||
sourceCodeMode?: boolean;
|
||||
}>(), {
|
||||
sourceCodeMode: false
|
||||
});
|
||||
|
||||
const emit = defineEmits<{
|
||||
"toggle-source-code": [];
|
||||
}>();
|
||||
|
||||
type RunType =
|
||||
| "undo"
|
||||
| "redo"
|
||||
| "bold"
|
||||
| "italic"
|
||||
| "underline"
|
||||
| "strike"
|
||||
| "orderedList"
|
||||
| "bulletList"
|
||||
| "code"
|
||||
| "subscript"
|
||||
| "superscript"
|
||||
| "horizontalRule"
|
||||
| "clear";
|
||||
|
||||
type TiptapEditorEventApi = TiptapEditorInstance & {
|
||||
on: (event: "selectionUpdate" | "transaction", callback: () => void) => void;
|
||||
off: (event: "selectionUpdate" | "transaction", callback: () => void) => void;
|
||||
};
|
||||
|
||||
const textColorDraft = ref("#000000");
|
||||
const bgColorDraft = ref("#ffff00");
|
||||
const tableActive = ref(false);
|
||||
const headingVisible = ref(false);
|
||||
const colorPickerVisible = ref(false);
|
||||
const colorPickerType = ref<"text" | "bg">("text");
|
||||
const colorSwatchColors = [
|
||||
"#F5222D",
|
||||
"#FF7875",
|
||||
"#FA541C",
|
||||
"#FA8C16",
|
||||
"#FADB14",
|
||||
"#A0D911",
|
||||
"#52C41A",
|
||||
"#13C2C2",
|
||||
"#1890FF",
|
||||
"#2F54EB",
|
||||
"#722ED1",
|
||||
"#EB2F96",
|
||||
"#8C8C8C",
|
||||
"#D9D9D9"
|
||||
];
|
||||
|
||||
const currentHeadingValue = computed(() => {
|
||||
if (!props.editor) {
|
||||
return "p";
|
||||
}
|
||||
for (let level = 1; level < 7; level += 1) {
|
||||
if (props.editor.isActive("heading", { level })) {
|
||||
return `h${level}`;
|
||||
}
|
||||
}
|
||||
return "p";
|
||||
});
|
||||
|
||||
const isHeadingActive = computed(() => {
|
||||
return currentHeadingValue.value !== "p";
|
||||
});
|
||||
|
||||
function canExec(type: "undo" | "redo") {
|
||||
if (!props.editor) {
|
||||
return false;
|
||||
}
|
||||
switch (type) {
|
||||
case "undo":
|
||||
return props.editor.can().undo();
|
||||
case "redo":
|
||||
return props.editor.can().redo();
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function isActive(type: string) {
|
||||
if (!props.editor) {
|
||||
return false;
|
||||
}
|
||||
return props.editor.isActive(type);
|
||||
}
|
||||
|
||||
function syncTableActive() {
|
||||
tableActive.value = props.editor?.isActive("table") ?? false;
|
||||
}
|
||||
|
||||
watch(() => props.editor, (editor, previousEditor) => {
|
||||
const previousEventApi = previousEditor as TiptapEditorEventApi | undefined;
|
||||
previousEventApi?.off("selectionUpdate", syncTableActive);
|
||||
previousEventApi?.off("transaction", syncTableActive);
|
||||
|
||||
const eventApi = editor as TiptapEditorEventApi | undefined;
|
||||
eventApi?.on("selectionUpdate", syncTableActive);
|
||||
eventApi?.on("transaction", syncTableActive);
|
||||
syncTableActive();
|
||||
}, { immediate: true });
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
const eventApi = props.editor as TiptapEditorEventApi | undefined;
|
||||
eventApi?.off("selectionUpdate", syncTableActive);
|
||||
eventApi?.off("transaction", syncTableActive);
|
||||
});
|
||||
|
||||
function isAlignActive(align: AlignType) {
|
||||
if (!props.editor) {
|
||||
return false;
|
||||
}
|
||||
return props.editor.isActive({ textAlign: align });
|
||||
}
|
||||
|
||||
function run(type: RunType) {
|
||||
if (!props.editor) {
|
||||
return;
|
||||
}
|
||||
const chain = props.editor.chain().focus();
|
||||
switch (type) {
|
||||
case "undo":
|
||||
chain.undo().run();
|
||||
return;
|
||||
case "redo":
|
||||
chain.redo().run();
|
||||
return;
|
||||
case "bold":
|
||||
chain.toggleBold().run();
|
||||
return;
|
||||
case "italic":
|
||||
chain.toggleItalic().run();
|
||||
return;
|
||||
case "underline":
|
||||
chain.toggleUnderline().run();
|
||||
return;
|
||||
case "strike":
|
||||
chain.toggleStrike().run();
|
||||
return;
|
||||
case "orderedList":
|
||||
chain.toggleOrderedList().run();
|
||||
return;
|
||||
case "bulletList":
|
||||
chain.toggleBulletList().run();
|
||||
return;
|
||||
case "code":
|
||||
chain.toggleCode().run();
|
||||
return;
|
||||
case "subscript":
|
||||
chain.toggleSubscript().run();
|
||||
return;
|
||||
case "superscript":
|
||||
chain.toggleSuperscript().run();
|
||||
return;
|
||||
case "horizontalRule":
|
||||
chain.setHorizontalRule().run();
|
||||
return;
|
||||
case "clear":
|
||||
chain.clearNodes().unsetAllMarks().run();
|
||||
return;
|
||||
default:
|
||||
}
|
||||
}
|
||||
|
||||
function setAlign(align: AlignType) {
|
||||
props.editor?.chain().focus().setTextAlign(align).run();
|
||||
}
|
||||
|
||||
function onHeadingSelect(option: { value?: string | number | Record<string, unknown> }) {
|
||||
headingVisible.value = false;
|
||||
if (!props.editor) {
|
||||
return;
|
||||
}
|
||||
const value = `${option?.value || "p"}`;
|
||||
const chain = props.editor.chain().focus();
|
||||
if (value === "p") {
|
||||
chain.setParagraph().run();
|
||||
return;
|
||||
}
|
||||
const level = Number(value.replace("h", ""));
|
||||
if (0 < level && level < 7) {
|
||||
chain.setHeading({ level: level as 1 | 2 | 3 | 4 | 5 | 6 }).run();
|
||||
}
|
||||
}
|
||||
|
||||
function pickColor(type: "text" | "bg") {
|
||||
const textStyleAttributes = props.editor?.getAttributes("textStyle") ?? {};
|
||||
if (type === "text") {
|
||||
const color = textStyleAttributes.color;
|
||||
textColorDraft.value = typeof color === "string" && color ? color : "#000000";
|
||||
} else {
|
||||
const backgroundColor = textStyleAttributes.backgroundColor;
|
||||
bgColorDraft.value = typeof backgroundColor === "string" && backgroundColor ? backgroundColor : "#ffff00";
|
||||
}
|
||||
colorPickerType.value = type;
|
||||
colorPickerVisible.value = true;
|
||||
}
|
||||
|
||||
function onTextColorChange(value: string) {
|
||||
textColorDraft.value = value;
|
||||
}
|
||||
|
||||
function onBgColorChange(value: string) {
|
||||
bgColorDraft.value = value;
|
||||
}
|
||||
|
||||
function onTextPaletteBarChange(context: { color: ColorObject }) {
|
||||
textColorDraft.value = context.color.hex;
|
||||
}
|
||||
|
||||
function onBgPaletteBarChange(context: { color: ColorObject }) {
|
||||
bgColorDraft.value = context.color.hex;
|
||||
}
|
||||
|
||||
function confirmColor() {
|
||||
if (!props.editor) {
|
||||
colorPickerVisible.value = false;
|
||||
return;
|
||||
}
|
||||
const chain = props.editor.chain().focus();
|
||||
if (colorPickerType.value === "text") {
|
||||
chain.setColor(textColorDraft.value).run();
|
||||
} else {
|
||||
chain.setMark("textStyle", { backgroundColor: bgColorDraft.value }).run();
|
||||
}
|
||||
colorPickerVisible.value = false;
|
||||
}
|
||||
|
||||
</script>
|
||||
|
||||
<style lang="less" scoped>
|
||||
.toolbar {
|
||||
--td-popover-padding: .25rem .5rem;
|
||||
|
||||
width: 100%;
|
||||
position: relative;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
min-width: 0;
|
||||
max-width: 100%;
|
||||
border-bottom: 1px solid var(--td-component-border);
|
||||
background: var(--td-bg-color-container);
|
||||
|
||||
&:after {
|
||||
content: "";
|
||||
display: none;
|
||||
}
|
||||
|
||||
.hidden {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.toolbar-head {
|
||||
width: 100%;
|
||||
display: flex;
|
||||
gap: .5rem;
|
||||
align-items: center;
|
||||
min-width: 0;
|
||||
min-height: 3.25rem;
|
||||
padding: .5rem .625rem;
|
||||
box-sizing: border-box;
|
||||
border-bottom: 1px solid var(--td-component-border);
|
||||
|
||||
:deep(.t-button) {
|
||||
flex: none;
|
||||
width: 2.5rem;
|
||||
height: 2.5rem;
|
||||
padding: 0;
|
||||
}
|
||||
}
|
||||
|
||||
.history {
|
||||
display: flex;
|
||||
gap: .5rem;
|
||||
}
|
||||
|
||||
.source-btn {
|
||||
margin-left: auto;
|
||||
}
|
||||
|
||||
.scroll {
|
||||
width: 100%;
|
||||
min-width: 0;
|
||||
max-width: 100%;
|
||||
overflow-x: auto;
|
||||
overflow-y: hidden;
|
||||
-webkit-overflow-scrolling: touch;
|
||||
scrollbar-width: none;
|
||||
|
||||
&::-webkit-scrollbar {
|
||||
display: none;
|
||||
}
|
||||
}
|
||||
|
||||
.actions {
|
||||
gap: .375rem;
|
||||
display: flex;
|
||||
width: max-content;
|
||||
min-width: 100%;
|
||||
padding: .5rem .625rem;
|
||||
box-sizing: border-box;
|
||||
|
||||
> * {
|
||||
flex: none;
|
||||
}
|
||||
|
||||
:deep(.t-button) {
|
||||
width: 2.5rem;
|
||||
height: 2.5rem;
|
||||
padding: 0;
|
||||
}
|
||||
}
|
||||
|
||||
:deep(.t-button.t-button--text.t-button--hover::after) {
|
||||
background: var(--td-brand-color-light);
|
||||
}
|
||||
|
||||
:deep(.t-button--text.t-button--disabled) {
|
||||
background: none;
|
||||
opacity: .5;
|
||||
}
|
||||
|
||||
.toolbar-disabled {
|
||||
opacity: .55;
|
||||
pointer-events: none;
|
||||
}
|
||||
}
|
||||
|
||||
:global(.tp-heading-option) {
|
||||
display: block;
|
||||
line-height: 1.2;
|
||||
}
|
||||
|
||||
.heading-size(@name, @size, @weight) {
|
||||
:global(.tp-heading-option.@{name}) {
|
||||
font-size: @size;
|
||||
font-weight: @weight;
|
||||
}
|
||||
}
|
||||
|
||||
.heading-size(p, 1rem, 400);
|
||||
.heading-size(h1, 2rem, 700);
|
||||
.heading-size(h2, 1.5rem, 700);
|
||||
.heading-size(h3, 1.17rem, 700);
|
||||
.heading-size(h4, 1rem, 700);
|
||||
.heading-size(h5, .83rem, 700);
|
||||
.heading-size(h6, .67rem, 700);
|
||||
|
||||
.heading-picker {
|
||||
width: min(22rem, calc(100vw - 2rem));
|
||||
padding: .5rem .75rem calc(.5rem + env(safe-area-inset-bottom));
|
||||
}
|
||||
|
||||
.color-picker-popup {
|
||||
background: var(--td-bg-color-container);
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,19 @@
|
||||
import view from "./index.vue";
|
||||
import { WebToolkit } from "timi-web";
|
||||
import type { TiptapEditorInstance } from "timi-web/editor";
|
||||
|
||||
export * from "timi-web/editor";
|
||||
export type TiptapEditorExpose = {
|
||||
submit: () => Promise<string>;
|
||||
getPendingMediaCount: () => number;
|
||||
openSearch: (showReplace: boolean) => void;
|
||||
closeSearch: () => void;
|
||||
findNext: () => boolean;
|
||||
findPrevious: () => boolean;
|
||||
replaceCurrent: () => boolean;
|
||||
replaceAll: () => number;
|
||||
editor?: TiptapEditorInstance;
|
||||
};
|
||||
|
||||
export const TiptapEditor = WebToolkit.withInstall(view);
|
||||
export default TiptapEditor;
|
||||
@@ -0,0 +1,603 @@
|
||||
<template>
|
||||
<div class="tp-editor">
|
||||
<tiptap-toolbar
|
||||
:editor="editorInstance"
|
||||
:source-code-mode="sourceCodeMode"
|
||||
:upload-image="handleInsertImage"
|
||||
:upload-video="handleInsertVideo"
|
||||
@toggle-source-code="toggleSourceCodeMode"
|
||||
/>
|
||||
<div class="content">
|
||||
<code-editor
|
||||
v-if="sourceCodeMode"
|
||||
ref="sourceEditorRef"
|
||||
v-model="sourceCode"
|
||||
class="source-editor"
|
||||
language="html"
|
||||
placeholder="请输入 HTML 源码"
|
||||
/>
|
||||
<div v-else-if="editorInstance" class="value-wrap">
|
||||
<editor-search-bar
|
||||
ref="searchBarRef"
|
||||
:visible="searchVisible"
|
||||
:expanded="replaceExpanded"
|
||||
:keyword="searchKeyword"
|
||||
:replace-value="replaceKeyword"
|
||||
:status-error="searchError"
|
||||
:match-index="searchMatchIndex"
|
||||
:match-count="searchMatchList.length"
|
||||
:case-sensitive="searchOptions.caseSensitive"
|
||||
:use-regex="searchOptions.useRegex"
|
||||
@update:expanded="replaceExpanded = $event"
|
||||
@update:keyword="searchKeyword = $event"
|
||||
@update:replace-value="replaceKeyword = $event"
|
||||
@update:case-sensitive="searchOptions.caseSensitive = $event"
|
||||
@update:use-regex="searchOptions.useRegex = $event"
|
||||
@previous="findPrevious"
|
||||
@next="onSearchNext"
|
||||
@replace="replaceCurrent"
|
||||
@replace-all="replaceAll"
|
||||
@close="closeSearch"
|
||||
/>
|
||||
<editor-content
|
||||
class="value"
|
||||
:editor="editorInstance"
|
||||
:spellcheck="false"
|
||||
@keydown.capture="onRichEditorKeydown"
|
||||
/>
|
||||
</div>
|
||||
<t-empty v-else description="编辑器初始化中" />
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script lang="ts" setup>
|
||||
import CodeEditor from "../code-editor/index.vue";
|
||||
import EditorSearchBar from "../editor-search/index.vue";
|
||||
import {
|
||||
buildSearchRegex,
|
||||
replaceMatchText,
|
||||
type TextSearchOptions
|
||||
} from "timi-web/editor";
|
||||
import { Toolkit } from "timi-web";
|
||||
import type { PendingMediaItem, UploadMediaType, UploadResult } from "timi-web/editor";
|
||||
import TiptapToolbar from "./TiptapToolbar.vue";
|
||||
import { useTiptapEditor } from "timi-web/editor";
|
||||
import {
|
||||
ATTACHMENT_ID_ATTR,
|
||||
LOCAL_MEDIA_ID_PREFIX,
|
||||
TEMP_FILE_ID_ATTR,
|
||||
isLocalMediaId,
|
||||
normalizeContent
|
||||
} from "timi-web/editor";
|
||||
|
||||
defineOptions({
|
||||
name: "TiptapEditor"
|
||||
});
|
||||
|
||||
type EditorSearchBarExpose = {
|
||||
focusKeyword: (selectAll?: boolean) => void;
|
||||
focusReplace: (selectAll?: boolean) => void;
|
||||
};
|
||||
|
||||
type CodeEditorExpose = {
|
||||
openSearch: (showReplace: boolean) => void;
|
||||
};
|
||||
|
||||
type RichTextMatch = {
|
||||
from: number;
|
||||
to: number;
|
||||
text: string;
|
||||
};
|
||||
|
||||
const props = withDefaults(defineProps<{
|
||||
modelValue: string;
|
||||
placeholder?: string;
|
||||
uploadImage?: (file: File) => Promise<UploadResult>;
|
||||
uploadVideo?: (file: File) => Promise<UploadResult>;
|
||||
}>(), {
|
||||
modelValue: "",
|
||||
placeholder: "请输入内容"
|
||||
});
|
||||
|
||||
const emit = defineEmits<{
|
||||
"update:modelValue": [value: string];
|
||||
"change": [value: string];
|
||||
}>();
|
||||
|
||||
const { EditorContent, editor } = useTiptapEditor(props, emit);
|
||||
const editorInstance = computed(() => editor.value);
|
||||
const pendingMediaMap = reactive(new Map<string, PendingMediaItem>());
|
||||
const sourceCodeMode = ref(false);
|
||||
const sourceCode = ref("");
|
||||
const sourceEditorRef = ref<CodeEditorExpose>();
|
||||
const searchBarRef = ref<EditorSearchBarExpose>();
|
||||
const searchVisible = ref(false);
|
||||
const replaceExpanded = ref(false);
|
||||
const searchKeyword = ref("");
|
||||
const replaceKeyword = ref("");
|
||||
const searchError = ref("");
|
||||
const searchMatchIndex = ref(-1);
|
||||
const searchMatchList = ref<RichTextMatch[]>([]);
|
||||
const searchOptions = reactive<TextSearchOptions>({
|
||||
caseSensitive: false,
|
||||
useRegex: false
|
||||
});
|
||||
|
||||
|
||||
function buildLocalMediaId() {
|
||||
return `${LOCAL_MEDIA_ID_PREFIX}${Toolkit.uuid()}`;
|
||||
}
|
||||
|
||||
function revokeMediaUrl(url?: string) {
|
||||
if (url?.startsWith("blob:")) {
|
||||
URL.revokeObjectURL(url);
|
||||
}
|
||||
}
|
||||
|
||||
function removePendingMedia(id: string) {
|
||||
const item = pendingMediaMap.get(id);
|
||||
if (!item) {
|
||||
return;
|
||||
}
|
||||
revokeMediaUrl(item.url);
|
||||
pendingMediaMap.delete(id);
|
||||
}
|
||||
|
||||
function clearPendingMedia() {
|
||||
Array.from(pendingMediaMap.keys()).forEach(removePendingMedia);
|
||||
}
|
||||
|
||||
function collectMediaIds(content?: string) {
|
||||
const rawContent = normalizeContent(content);
|
||||
if (!rawContent) {
|
||||
return new Set<string>();
|
||||
}
|
||||
const parser = new DOMParser();
|
||||
const doc = parser.parseFromString(rawContent, "text/html");
|
||||
const mediaList = Array.from(doc.querySelectorAll("img, video"));
|
||||
return new Set(
|
||||
mediaList
|
||||
.map(item => item.getAttribute(ATTACHMENT_ID_ATTR) || item.getAttribute(TEMP_FILE_ID_ATTR) || "")
|
||||
.filter(Boolean)
|
||||
);
|
||||
}
|
||||
|
||||
function syncPendingMedia(content?: string) {
|
||||
const mediaIdSet = collectMediaIds(content);
|
||||
Array.from(pendingMediaMap.keys()).forEach((id) => {
|
||||
if (!mediaIdSet.has(id)) {
|
||||
removePendingMedia(id);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
async function handleInsertMedia(file: File, type: UploadMediaType): Promise<UploadResult> {
|
||||
const id = buildLocalMediaId();
|
||||
const url = URL.createObjectURL(file);
|
||||
pendingMediaMap.set(id, {
|
||||
id,
|
||||
type,
|
||||
name: file.name,
|
||||
file,
|
||||
url
|
||||
});
|
||||
return {
|
||||
id,
|
||||
url,
|
||||
name: file.name
|
||||
};
|
||||
}
|
||||
|
||||
async function handleInsertImage(file: File) {
|
||||
return handleInsertMedia(file, "image");
|
||||
}
|
||||
|
||||
async function handleInsertVideo(file: File) {
|
||||
return handleInsertMedia(file, "video");
|
||||
}
|
||||
|
||||
async function submit() {
|
||||
const instance = editor.value;
|
||||
if (!instance) {
|
||||
return normalizeContent(props.modelValue);
|
||||
}
|
||||
const rawContent = normalizeContent(instance.getHTML());
|
||||
if (!rawContent) {
|
||||
clearPendingMedia();
|
||||
return "";
|
||||
}
|
||||
const parser = new DOMParser();
|
||||
const doc = parser.parseFromString(rawContent, "text/html");
|
||||
const mediaList = Array.from(doc.querySelectorAll("img, video"));
|
||||
const uploadedMediaIdList: string[] = [];
|
||||
|
||||
for (const media of mediaList) {
|
||||
const attachmentId = media.getAttribute(ATTACHMENT_ID_ATTR) || media.getAttribute(TEMP_FILE_ID_ATTR) || "";
|
||||
if (!isLocalMediaId(attachmentId)) {
|
||||
continue;
|
||||
}
|
||||
const pendingMedia = pendingMediaMap.get(attachmentId);
|
||||
if (!pendingMedia) {
|
||||
continue;
|
||||
}
|
||||
const uploadFn = pendingMedia.type === "image" ? props.uploadImage : props.uploadVideo;
|
||||
if (!uploadFn) {
|
||||
throw new Error(`未配置${pendingMedia.type === "image" ? "图片" : "视频"}上传方法`);
|
||||
}
|
||||
const result = await uploadFn(pendingMedia.file);
|
||||
media.setAttribute("src", result.url);
|
||||
media.setAttribute(ATTACHMENT_ID_ATTR, result.id);
|
||||
media.setAttribute(TEMP_FILE_ID_ATTR, result.id);
|
||||
if (media.tagName.toLowerCase() === "img") {
|
||||
media.setAttribute("alt", result.name || pendingMedia.name);
|
||||
media.setAttribute("title", result.name || pendingMedia.name);
|
||||
} else {
|
||||
media.setAttribute("title", result.name || pendingMedia.name);
|
||||
}
|
||||
uploadedMediaIdList.push(attachmentId);
|
||||
}
|
||||
|
||||
const nextContent = normalizeContent(doc.body.innerHTML);
|
||||
if (nextContent !== rawContent) {
|
||||
instance.commands.setContent(nextContent || "<p></p>");
|
||||
}
|
||||
uploadedMediaIdList.forEach(removePendingMedia);
|
||||
syncPendingMedia(nextContent);
|
||||
return nextContent;
|
||||
}
|
||||
|
||||
function syncSourceCode(value?: string) {
|
||||
sourceCode.value = value || "";
|
||||
}
|
||||
|
||||
function onSourceCodeChange(value: string) {
|
||||
sourceCode.value = value;
|
||||
emit("change", value);
|
||||
emit("update:modelValue", value);
|
||||
}
|
||||
|
||||
function getSelectedEditorText() {
|
||||
const instance = editor.value;
|
||||
if (!instance) {
|
||||
return "";
|
||||
}
|
||||
const { from, to } = instance.state.selection;
|
||||
if (from === to) {
|
||||
return "";
|
||||
}
|
||||
return instance.state.doc.textBetween(from, to, "\n", "\n");
|
||||
}
|
||||
|
||||
function refreshSearchMatchState() {
|
||||
const instance = editor.value;
|
||||
if (!instance || sourceCodeMode.value) {
|
||||
searchError.value = "";
|
||||
searchMatchList.value = [];
|
||||
searchMatchIndex.value = -1;
|
||||
return;
|
||||
}
|
||||
const { regex, error } = buildSearchRegex(searchKeyword.value, searchOptions, true);
|
||||
searchError.value = error;
|
||||
if (!regex || error || !searchKeyword.value) {
|
||||
searchMatchList.value = [];
|
||||
searchMatchIndex.value = -1;
|
||||
return;
|
||||
}
|
||||
const matchList: RichTextMatch[] = [];
|
||||
instance.state.doc.descendants((node, pos) => {
|
||||
if (!node.isText || !node.text) {
|
||||
return;
|
||||
}
|
||||
regex.lastIndex = 0;
|
||||
let match = regex.exec(node.text);
|
||||
while (match) {
|
||||
if (!match[0]) {
|
||||
searchError.value = "正则不能匹配空文本";
|
||||
searchMatchList.value = [];
|
||||
searchMatchIndex.value = -1;
|
||||
return false;
|
||||
}
|
||||
matchList.push({
|
||||
from: pos + match.index,
|
||||
to: pos + match.index + match[0].length,
|
||||
text: match[0]
|
||||
});
|
||||
match = regex.exec(node.text);
|
||||
}
|
||||
});
|
||||
searchMatchList.value = matchList;
|
||||
const { from, to } = instance.state.selection;
|
||||
searchMatchIndex.value = matchList.findIndex((match) => match.from === from && match.to === to);
|
||||
if (0 > searchMatchIndex.value && 0 < matchList.length) {
|
||||
searchMatchIndex.value = 0;
|
||||
}
|
||||
}
|
||||
|
||||
function openSearch(showReplace: boolean) {
|
||||
if (sourceCodeMode.value) {
|
||||
sourceEditorRef.value?.openSearch(showReplace);
|
||||
return;
|
||||
}
|
||||
searchVisible.value = true;
|
||||
replaceExpanded.value = showReplace;
|
||||
const selectedText = getSelectedEditorText();
|
||||
if (selectedText) {
|
||||
searchKeyword.value = selectedText;
|
||||
}
|
||||
refreshSearchMatchState();
|
||||
nextTick(() => {
|
||||
searchBarRef.value?.focusKeyword(true);
|
||||
});
|
||||
}
|
||||
|
||||
function closeSearch() {
|
||||
searchVisible.value = false;
|
||||
replaceExpanded.value = false;
|
||||
editor.value?.commands.focus();
|
||||
}
|
||||
|
||||
function selectMatch(match: RichTextMatch, matchIndex: number) {
|
||||
const instance = editor.value;
|
||||
if (!instance) {
|
||||
return false;
|
||||
}
|
||||
instance.chain().focus().setTextSelection({ from: match.from, to: match.to }).scrollIntoView().run();
|
||||
searchMatchIndex.value = matchIndex;
|
||||
return true;
|
||||
}
|
||||
|
||||
function findNext() {
|
||||
const instance = editor.value;
|
||||
if (!instance || searchError.value || 1 > searchMatchList.value.length) {
|
||||
return false;
|
||||
}
|
||||
const currentTo = instance.state.selection.to;
|
||||
const nextIndex = searchMatchList.value.findIndex((match) => match.from >= currentTo);
|
||||
const targetIndex = 0 <= nextIndex ? nextIndex : 0;
|
||||
return selectMatch(searchMatchList.value[targetIndex], targetIndex);
|
||||
}
|
||||
|
||||
function findPrevious() {
|
||||
const instance = editor.value;
|
||||
if (!instance || searchError.value || 1 > searchMatchList.value.length) {
|
||||
return false;
|
||||
}
|
||||
const currentFrom = instance.state.selection.from;
|
||||
let targetIndex = searchMatchList.value.length - 1;
|
||||
for (let index = searchMatchList.value.length - 1; 0 <= index; index -= 1) {
|
||||
if (searchMatchList.value[index].from < currentFrom) {
|
||||
targetIndex = index;
|
||||
break;
|
||||
}
|
||||
}
|
||||
return selectMatch(searchMatchList.value[targetIndex], targetIndex);
|
||||
}
|
||||
|
||||
function replaceCurrent() {
|
||||
const instance = editor.value;
|
||||
if (!instance || !searchKeyword.value) {
|
||||
return false;
|
||||
}
|
||||
let currentMatchIndex = searchMatchList.value.findIndex((match) => (
|
||||
match.from === instance.state.selection.from && match.to === instance.state.selection.to
|
||||
));
|
||||
if (0 > currentMatchIndex) {
|
||||
if (!findNext()) {
|
||||
return false;
|
||||
}
|
||||
currentMatchIndex = searchMatchIndex.value;
|
||||
}
|
||||
const currentMatch = searchMatchList.value[currentMatchIndex];
|
||||
if (!currentMatch) {
|
||||
return false;
|
||||
}
|
||||
const nextText = replaceMatchText(currentMatch.text, searchKeyword.value, replaceKeyword.value, searchOptions);
|
||||
const transaction = instance.state.tr.insertText(nextText, currentMatch.from, currentMatch.to);
|
||||
instance.view.dispatch(transaction);
|
||||
refreshSearchMatchState();
|
||||
nextTick(() => {
|
||||
const nextMatch = searchMatchList.value[currentMatchIndex] || searchMatchList.value[currentMatchIndex - 1];
|
||||
if (!nextMatch) {
|
||||
instance.commands.focus();
|
||||
return;
|
||||
}
|
||||
selectMatch(nextMatch, Math.min(currentMatchIndex, searchMatchList.value.length - 1));
|
||||
});
|
||||
return true;
|
||||
}
|
||||
|
||||
function replaceAll() {
|
||||
const instance = editor.value;
|
||||
if (!instance || !searchKeyword.value) {
|
||||
return 0;
|
||||
}
|
||||
if (searchError.value || 1 > searchMatchList.value.length) {
|
||||
refreshSearchMatchState();
|
||||
return 0;
|
||||
}
|
||||
const replaceCount = searchMatchList.value.length;
|
||||
const transaction = instance.state.tr;
|
||||
for (let index = searchMatchList.value.length - 1; 0 <= index; index -= 1) {
|
||||
const match = searchMatchList.value[index];
|
||||
const nextText = replaceMatchText(match.text, searchKeyword.value, replaceKeyword.value, searchOptions);
|
||||
transaction.insertText(nextText, match.from, match.to);
|
||||
}
|
||||
instance.view.dispatch(transaction);
|
||||
refreshSearchMatchState();
|
||||
nextTick(() => {
|
||||
if (searchMatchList.value[0]) {
|
||||
selectMatch(searchMatchList.value[0], 0);
|
||||
return;
|
||||
}
|
||||
instance.commands.focus();
|
||||
});
|
||||
return replaceCount;
|
||||
}
|
||||
|
||||
function onSearchNext(shiftKey: boolean) {
|
||||
if (shiftKey) {
|
||||
findPrevious();
|
||||
return;
|
||||
}
|
||||
findNext();
|
||||
}
|
||||
|
||||
function onRichEditorKeydown(event: KeyboardEvent) {
|
||||
if (sourceCodeMode.value || event.altKey || !(event.ctrlKey || event.metaKey)) {
|
||||
return;
|
||||
}
|
||||
const key = event.key.toLowerCase();
|
||||
if ("f" === key) {
|
||||
event.preventDefault();
|
||||
openSearch(false);
|
||||
return;
|
||||
}
|
||||
if ("h" === key) {
|
||||
event.preventDefault();
|
||||
openSearch(true);
|
||||
}
|
||||
}
|
||||
|
||||
function toggleSourceCodeMode() {
|
||||
const nextMode = !sourceCodeMode.value;
|
||||
closeSearch();
|
||||
if (nextMode) {
|
||||
syncSourceCode(normalizeContent(editor.value?.getHTML()) || props.modelValue);
|
||||
sourceCodeMode.value = true;
|
||||
return;
|
||||
}
|
||||
sourceCodeMode.value = false;
|
||||
const nextContent = normalizeContent(sourceCode.value);
|
||||
if (editor.value) {
|
||||
editor.value.commands.setContent(nextContent || "<p></p>");
|
||||
}
|
||||
}
|
||||
|
||||
watch(() => props.modelValue, (value) => {
|
||||
syncPendingMedia(value);
|
||||
syncSourceCode(value);
|
||||
}, { immediate: true });
|
||||
|
||||
watch(sourceCode, (value) => {
|
||||
if (!sourceCodeMode.value) {
|
||||
return;
|
||||
}
|
||||
onSourceCodeChange(value);
|
||||
});
|
||||
|
||||
watch([searchKeyword, () => searchOptions.caseSensitive, () => searchOptions.useRegex, sourceCodeMode], () => {
|
||||
refreshSearchMatchState();
|
||||
});
|
||||
|
||||
watch(() => editor.value?.state.selection.from, () => {
|
||||
if (!searchVisible.value || sourceCodeMode.value) {
|
||||
return;
|
||||
}
|
||||
refreshSearchMatchState();
|
||||
});
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
clearPendingMedia();
|
||||
});
|
||||
|
||||
defineExpose({
|
||||
editor,
|
||||
submit,
|
||||
getPendingMediaCount: () => pendingMediaMap.size,
|
||||
openSearch,
|
||||
closeSearch,
|
||||
findNext,
|
||||
findPrevious,
|
||||
replaceCurrent,
|
||||
replaceAll
|
||||
});
|
||||
</script>
|
||||
|
||||
<style lang="less" scoped>
|
||||
.tp-editor {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
max-width: 100%;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
min-width: 0;
|
||||
min-height: 0;
|
||||
border: 1px solid var(--td-component-border);
|
||||
border-radius: var(--td-radius-default);
|
||||
overflow: hidden;
|
||||
background: var(--td-bg-color-page);
|
||||
|
||||
.content {
|
||||
flex: 1;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
display: flex;
|
||||
min-width: 0;
|
||||
min-height: 0;
|
||||
padding: .5rem;
|
||||
overflow: auto;
|
||||
box-sizing: border-box;
|
||||
cursor: text;
|
||||
background: var(--td-bg-color-page);
|
||||
|
||||
.value-wrap {
|
||||
flex: 1;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
min-width: 0;
|
||||
min-height: 100%;
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.value {
|
||||
flex: 1;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
min-width: 0;
|
||||
min-height: 100%;
|
||||
overflow: auto;
|
||||
background: var(--td-bg-color-container);
|
||||
border-radius: var(--td-radius-default);
|
||||
box-sizing: border-box;
|
||||
box-shadow: var(--td-shadow-1);
|
||||
|
||||
:deep(.editor-body) {
|
||||
outline: none;
|
||||
padding: 1rem .875rem;
|
||||
min-height: 100%;
|
||||
box-sizing: border-box;
|
||||
overflow-wrap: anywhere;
|
||||
|
||||
pre[class*='language-'] > code {
|
||||
padding: .25rem .5rem;
|
||||
}
|
||||
|
||||
p.is-editor-empty:first-child:before {
|
||||
height: 0;
|
||||
float: left;
|
||||
color: var(--td-text-color-placeholder);
|
||||
content: attr(data-placeholder);
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
iframe.tp-iframe {
|
||||
margin-right: auto;
|
||||
margin-left: auto;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.source-editor {
|
||||
flex: 1;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
min-width: 0;
|
||||
min-height: 20rem;
|
||||
background: var(--td-bg-color-container);
|
||||
border-radius: var(--td-radius-default);
|
||||
box-shadow: var(--td-shadow-1);
|
||||
}
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,5 @@
|
||||
import view from "./index.vue";
|
||||
import { WebToolkit } from "timi-web";
|
||||
|
||||
export const TiptapView = WebToolkit.withInstall(view);
|
||||
export default TiptapView;
|
||||
@@ -0,0 +1,54 @@
|
||||
<template>
|
||||
<div class="tp-view selectable">
|
||||
<div v-if="renderContent && editorInstance" ref="contentRef" class="content-wrap" :data-max-height="maxHeight">
|
||||
<editor-content class="content" :editor="editorInstance" />
|
||||
</div>
|
||||
<div v-else class="empty">
|
||||
<span v-text="emptyText" />
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script lang="ts" setup>
|
||||
import { normalizeContent, useTiptapView } from "timi-web/editor";
|
||||
|
||||
defineOptions({
|
||||
name: "TiptapView"
|
||||
});
|
||||
|
||||
const props = withDefaults(defineProps<{
|
||||
content?: string;
|
||||
emptyText?: string;
|
||||
maxHeight?: string;
|
||||
}>(), {
|
||||
content: "",
|
||||
emptyText: "暂无内容",
|
||||
maxHeight: "400px"
|
||||
});
|
||||
|
||||
const renderContent = computed(() => {
|
||||
return normalizeContent(props.content);
|
||||
});
|
||||
const { EditorContent, contentRef, editor } = useTiptapView(renderContent, toRef(props, "maxHeight"));
|
||||
const editorInstance = computed(() => editor.value);
|
||||
</script>
|
||||
|
||||
<style lang="less" scoped>
|
||||
.tp-view {
|
||||
width: 100%;
|
||||
.empty {
|
||||
padding: 1rem;
|
||||
border-radius: .375rem;
|
||||
color: var(--td-text-color-placeholder);
|
||||
background: var(--td-bg-color-container);
|
||||
border: 1px solid var(--td-component-border);
|
||||
}
|
||||
|
||||
.content {
|
||||
border: 1px solid var(--td-component-border);
|
||||
padding: 1rem;
|
||||
min-height: 12rem;
|
||||
background: var(--td-bg-color-container);
|
||||
}
|
||||
}
|
||||
</style>
|
||||
+4
-2
@@ -1,5 +1,7 @@
|
||||
import "./assets/style/tencent-cloud.less";
|
||||
import "./assets/style/tencent-cloud-custom.less";
|
||||
import "./assets/style/tdesign-custom.less";
|
||||
import "./components/tiptap-content.less";
|
||||
import "timi-web/style.css";
|
||||
import "../../timi-web/src/components/prism-code-block.less";
|
||||
|
||||
export * from "./components";
|
||||
|
||||
|
||||
@@ -20,6 +20,9 @@
|
||||
"@/*": [
|
||||
"./examples/*"
|
||||
],
|
||||
"timi-web/editor": [
|
||||
"../timi-web/src/editor/index.ts"
|
||||
],
|
||||
"timi-tdesign-mobile": [
|
||||
"./src/index.ts"
|
||||
]
|
||||
|
||||
+8
-1
@@ -12,6 +12,10 @@ const alias: Alias[] = [
|
||||
find: "@",
|
||||
replacement: resolve(__dirname, "./examples")
|
||||
},
|
||||
{
|
||||
find: /^timi-web\/editor$/,
|
||||
replacement: resolve(__dirname, "../timi-web/src/editor/index.ts")
|
||||
},
|
||||
{
|
||||
find: /^timi-tdesign-mobile(\/(es|lib))?$/,
|
||||
replacement: resolve(__dirname, "./src/index.ts")
|
||||
@@ -54,7 +58,10 @@ export default defineConfig({
|
||||
include: [/\.vue$/, /\.md$/]
|
||||
}),
|
||||
VueSetupExtend(),
|
||||
dts(),
|
||||
dts({
|
||||
pathsToAliases: false,
|
||||
aliasesExclude: [/^timi-web\/editor$/]
|
||||
}),
|
||||
AutoImport({
|
||||
imports: [
|
||||
"vue",
|
||||
|
||||
Reference in New Issue
Block a user