feat(editor): add themed callouts and desktop command boundary

This commit is contained in:
2026-09-06 11:33:19 +08:00
parent fcc319d5e1
commit 415efc4444
26 changed files with 759 additions and 13 deletions
+19 -1
View File
@@ -1,6 +1,6 @@
theme_id: paper-moments
name: 纸间时光 · Paper Moments
version: 1.6.2
version: 1.7.0
author: NotesAgent
description: 奶油纸张、手帐虚线与粉蓝胶带,把每天的灵感好好收藏。
min_app_version: 0.2.0
@@ -9,6 +9,12 @@ css_entry: theme.css
license: MIT
---
[data-theme="paper-moments"] {
--color-callout-info: #406b7b;
--color-callout-success: #536f43;
--color-callout-warning: #875f25;
--color-callout-danger: #a34e42;
--color-callout-important: #805c7e;
--color-callout-quote: #6e6053;
color-scheme: light;
--color-background-primary: #faf7ee;
--color-background-secondary: #f3eee3;
@@ -322,3 +328,15 @@ license: MIT
/* Nested choices retain a quiet paper border without repeating tape/shadows. */
[data-theme="paper-moments"] .surface-nested { border: 1px dashed #c5b9a7; background: #fffdf5; border-radius: 6px; }
[data-theme="paper-moments"] .surface-nested.selected { border-color: var(--color-accent-primary); background: var(--color-accent-soft); }
/* Callout paper: no tape over titles, no repeated shadows in nested blocks. */
[data-theme="paper-moments"] .markdown-callout,
[data-theme="paper-moments"] .milkdown .ProseMirror blockquote.markdown-callout {
border-radius: 10px 3px 10px 3px;
outline: 1px dashed color-mix(in srgb, var(--callout-color) 30%, transparent);
outline-offset: -6px;
box-shadow: 3px 3px 0 color-mix(in srgb, var(--callout-color) 12%, transparent);
padding: 14px 18px;
}
[data-theme="paper-moments"] .markdown-callout .markdown-callout { box-shadow: none; }
[data-theme="paper-moments"] .markdown-callout > .callout-title { font-family: Georgia, 'Noto Serif SC', 'Songti SC', SimSun, serif; }
@@ -13,6 +13,8 @@ import { useThemeStore } from '@/stores/theme'
import { codeBlockConfig } from '@milkdown/kit/component/code-block'
import { EditorView as CodeMirror } from '@codemirror/view'
import { renderMarkdown } from '@/utils/markdown'
import { useEditorStore } from '@/stores/editor'
import { executeEditorCommand } from '@/services/editorCommandService'
type EditorComponent = { getEditor: () => Editor | undefined }
@@ -51,6 +53,45 @@ afterEach(() => {
})
describe('VisualMarkdownEditor formatting toolbars', () => {
it('renders and folds callouts without losing portable Markdown on serialization', async () => {
const source = '> [!WARNING]- 注意\n>\n> **正文**\n>\n> > [!TIP] 内层\n> > 内容'
const wrapper = mount(VisualMarkdownEditor, { props: { initialContent: source }, attachTo: document.body })
mounted.push(wrapper)
const editor = await waitForEditor(wrapper)
expect(wrapper.findAll('.markdown-callout')).toHaveLength(2)
expect(wrapper.get('.markdown-callout').attributes('data-collapsed')).toBe('true')
await wrapper.get('.callout-title').trigger('click')
expect(wrapper.get('.markdown-callout').attributes('data-collapsed')).toBe('false')
const markdown = editor.action(getMarkdown())
expect(markdown.trim()).toBe(source)
})
it('dispatches native-ready commands through editor transactions and rejects invalid parameters', async () => {
useEditorStore().currentFilePath = 'test.md'
const wrapper = mount(VisualMarkdownEditor, { props: { initialContent: 'text' }, attachTo: document.body })
mounted.push(wrapper)
const editor = await waitForEditor(wrapper)
expect(await executeEditorCommand('editor.heading', 8)).toEqual({ ok: false, reason: 'invalid-params' })
expect(await executeEditorCommand('editor.heading', 2)).toEqual({ ok: true })
expect(editor.action(getMarkdown())).toContain('## text')
expect(await executeEditorCommand('editor.callout', { type: 'tip', body: '**test**' })).toEqual({ ok: true })
expect(wrapper.find('.markdown-callout').exists()).toBe(true)
useEditorStore().saveStatus = 'conflict'
expect(await executeEditorCommand('editor.bold')).toEqual({ ok: false, reason: 'unavailable' })
})
it('keeps code examples as ordinary quotes and renders newly typed markers', async () => {
const wrapper = mount(VisualMarkdownEditor, { props: { initialContent: '> `[!NOTE]`\n\n> text' }, attachTo: document.body })
mounted.push(wrapper)
const editor = await waitForEditor(wrapper)
expect(wrapper.find('.markdown-callout').exists()).toBe(false)
editor.action(ctx => {
const view = ctx.get(editorViewCtx)
let position = 0
view.state.doc.descendants((node, pos) => { if (node.isText && node.text === 'text') position = pos })
view.dispatch(view.state.tr.insertText('[!TIP]', position, position + 4))
})
expect(wrapper.find('.markdown-callout').exists()).toBe(true)
expect(editor.action(getMarkdown())).toContain('[!TIP]')
})
it('renders the supported format matrix and preserves inline code', async () => {
const source = ['# H1','## H2','### H3','#### H4','##### H5','###### H6',
'正文 **粗体** *斜体* ~~删除~~ `s` 与 ``a`b``', '> 引用', '- 项目\n - 子项', '1. 第一\n2. 第二',
@@ -28,7 +28,9 @@ import {
wrapInHeadingCommand,
wrapInOrderedListCommand,
} from '@milkdown/kit/preset/commonmark'
import { commandsCtx, editorViewCtx } from '@milkdown/kit/core'
import { commandsCtx, editorViewCtx, parserCtx } from '@milkdown/kit/core'
import { Slice } from '@milkdown/kit/prose/model'
import { registerEditorCommands, type CommandHandler, type EditorCommandId } from '@/services/editorCommandService'
import { TextSelection } from '@milkdown/kit/prose/state'
import { callCommand } from '@milkdown/kit/utils'
import AppIcon from '@/components/common/AppIcon.vue'
@@ -37,6 +39,8 @@ import { useSettingsStore } from '@/stores/settings'
import { useThemeStore } from '@/stores/theme'
import { applyMarkdownFontSize, fontSizeMarkdownPlugin } from './fontSizeMarkdown'
import { inlineCodeInputPlugin } from './inlineCodeInput'
import { calloutPlugin, configureCalloutSerialization } from './calloutPlugin'
import { calloutTypes } from '@/utils/callouts'
import { t } from '@/i18n'
import '@milkdown/crepe/theme/common/style.css'
import '@milkdown/crepe/theme/frame.css'
@@ -67,6 +71,61 @@ const fontSizeInput = ref(16)
let crepe: Crepe | null = null
let disposeLanguagePicker: (() => void) | undefined
let disposeCodeLabels: (() => void) | undefined
let disposeCommands: (() => void) | undefined
let disposed = false
function insertMarkdown(source: string) {
crepe?.editor.action(ctx => {
const doc = ctx.get(parserCtx)(source)
if (!doc) throw new Error('Invalid Markdown')
const view = ctx.get(editorViewCtx)
view.dispatch(view.state.tr.replaceSelection(new Slice(doc.content, 0, 0)).scrollIntoView())
view.focus()
})
}
function insertCallout(event: Event) {
const select = event.target as HTMLSelectElement
if (select.value) insertMarkdown(`> [!${select.value.toUpperCase()}]\n> ${t('提示内容', 'Callout content')}`)
select.value = ''
}
function installCommands() {
const targetPath = editorStore.currentFilePath
const handlers: Partial<Record<EditorCommandId, CommandHandler>> = {}
const toolbar: ToolbarCommand[] = ['bold', 'italic', 'ordered-list', 'bullet-list', 'inline-code', 'code-block', 'inline-math', 'math-block']
for (const command of toolbar) handlers[`editor.${command}`] = () => { runCommand(command); return { ok: true } }
handlers['editor.paragraph'] = () => { crepe!.editor.action(callCommand(turnIntoTextCommand.key)); return { ok: true } }
handlers['editor.heading'] = params => {
if (!Number.isInteger(params) || Number(params) < 1 || Number(params) > 6) return { ok: false, reason: 'invalid-params' }
crepe!.editor.action(callCommand(wrapInHeadingCommand.key, Number(params)))
return { ok: true }
}
handlers['editor.font-size'] = params => {
if (typeof params !== 'number' || !Number.isFinite(params) || params < 8 || params > 96) return { ok: false, reason: 'invalid-params' }
fontSizeInput.value = params
applyFontSizeValue()
return { ok: true }
}
handlers['editor.insert-markdown'] = params => {
if (typeof params !== 'string' || !params.trim() || params.length > 100000) return { ok: false, reason: 'invalid-params' }
insertMarkdown(params)
return { ok: true }
}
handlers['editor.callout'] = params => {
if (!params || typeof params !== 'object') return { ok: false, reason: 'invalid-params' }
const { type, title = '', body = '', fold = '' } = params as Record<string, unknown>
if (typeof type !== 'string' || !/^[\w-]{1,64}$/.test(type) || typeof title !== 'string' || /[\r\n]/.test(title)
|| typeof body !== 'string' || !['', '+', '-'].includes(String(fold)) || title.length + body.length > 100000) return { ok: false, reason: 'invalid-params' }
insertMarkdown(`> [!${type}]${fold} ${title}\n${body.split(/\r?\n/).map(line => `> ${line}`).join('\n')}`)
return { ok: true }
}
disposeCommands = registerEditorCommands({
available: () => !loading.value && !!crepe && editorStore.mode === 'wysiwyg' && editorStore.saveStatus !== 'conflict'
&& !!targetPath && targetPath === editorStore.currentFilePath && crepe.editor.action(ctx => ctx.get(editorViewCtx).editable),
handlers,
})
}
const diagramPreviews = new Map<string, { source: string; apply: (value: HTMLElement) => void }>()
function renderDiagram(source: string, apply: (value: HTMLElement) => void) {
for (const [id, entry] of diagramPreviews) {
@@ -251,6 +310,8 @@ onMounted(async () => {
})))
crepe.editor.use(fontSizeMarkdownPlugin)
crepe.editor.use(inlineCodeInputPlugin)
crepe.editor.use(calloutPlugin)
crepe.editor.config(configureCalloutSerialization)
crepe.on((listener) => {
listener.markdownUpdated((_ctx, markdown, previousMarkdown) => {
// 忽略编辑器初始化/回显事件,防止无内容变化时触发自动保存循环。
@@ -265,6 +326,7 @@ onMounted(async () => {
if (editorRoot.value) disposeCodeLabels = installCodeBlockLabels(editorRoot.value)
applyProofingPreferences()
loading.value = false
if (!disposed) installCommands()
})
watch([() => settingsStore.spellCheck, () => settingsStore.language], applyProofingPreferences)
@@ -282,7 +344,7 @@ watch(() => editorStore.headingRequest, request => {
})
})
onBeforeUnmount(() => { diagramPreviews.clear(); disposeCodeLabels?.(); disposeLanguagePicker?.(); void crepe?.destroy() })
onBeforeUnmount(() => { disposed = true; disposeCommands?.(); diagramPreviews.clear(); disposeCodeLabels?.(); disposeLanguagePicker?.(); void crepe?.destroy() })
defineExpose({ getEditor: () => crepe?.editor })
</script>
@@ -324,6 +386,12 @@ defineExpose({ getEditor: () => crepe?.editor })
<button type="button" :title="t('行内公式', 'Inline formula')" :aria-label="t('行内公式', 'Inline formula')" @pointerdown.prevent="runCommand('inline-math')"><span class="math-glyph">ƒx</span></button>
<button type="button" :title="t('公式块', 'Formula block')" :aria-label="t('公式块', 'Formula block')" @pointerdown.prevent="runCommand('math-block')"><span class="math-glyph"></span></button>
<button type="button" :title="t('插入链接', 'Insert link')" :aria-label="t('插入链接', 'Insert link')" @pointerdown.prevent="applyLink"><AppIcon :icon="Link" :size="17" /></button>
<label class="toolbar-select">
<select :aria-label="t('插入警告框', 'Insert callout')" @change="insertCallout">
<option value="">{{ t('提示框', 'Callout') }}</option>
<option v-for="(_, type) in calloutTypes" :key="type" :value="type">{{ type }}</option>
</select>
</label>
</div>
<div v-if="loading" class="editor-loading">{{ t('正在加载编辑器', 'Loading editor') }}</div>
<div class="milkdown-host" :class="{ loading }">
@@ -0,0 +1,89 @@
import { $prose } from '@milkdown/kit/utils'
import { Plugin } from '@milkdown/kit/prose/state'
import { Decoration, DecorationSet } from '@milkdown/kit/prose/view'
import { parseCallout } from '@/utils/callouts'
import '@/styles/callouts.css'
import { remarkStringifyOptionsCtx, type Editor } from '@milkdown/kit/core'
export const configureCalloutSerialization: Parameters<Editor['config']>[0] = ctx => {
ctx.update(remarkStringifyOptionsCtx, options => ({
...options,
handlers: { ...options.handlers, blockquote(node, _parent, state, info) {
const exit = state.enter('blockquote')
const tracker = state.createTracker(info)
tracker.move('> ')
tracker.shift(2)
const result = state.indentLines(state.containerFlow(node, tracker.current()), (line, _index, blank) => `>${blank ? '' : ' '}${line}`)
exit()
// Only remove escaping from a leading callout marker, never body literals.
return result.replace(/^(> )\\\[!([\w-]+)\\?\]/, '$1[!$2]')
} },
}))
}
// Keep native blockquotes in the document: typing, undo and Markdown serialization
// remain Milkdown transactions; the view never rewrites a user's callout source.
export const calloutPlugin = $prose(() => new Plugin({
props: {
decorations(state) {
const decorations: Decoration[] = []
state.doc.descendants((node, position) => {
if (node.type.name !== 'blockquote' || node.firstChild?.type.name !== 'paragraph' || node.firstChild.firstChild?.marks.length) return
const callout = parseCallout(node.firstChild.textBetween(0, node.firstChild.content.size, '\n', '\n'))
if (!callout) return
const from = position + 2
const to = from + callout.markerLength
const editing = state.selection.from <= to && state.selection.to >= from
decorations.push(Decoration.inline(from, to, { class: editing ? 'callout-marker-editing' : 'callout-marker' }))
})
return DecorationSet.create(state.doc, decorations)
},
nodeViews: {
blockquote(initialNode) {
const dom = document.createElement('blockquote')
const header = document.createElement('button')
header.type = 'button'
header.className = 'callout-title'
header.contentEditable = 'false'
const contentDOM = document.createElement('div')
contentDOM.className = 'callout-body'
dom.append(header, contentDOM)
let signature = ''
let foldable = false
const update = (node: typeof initialNode) => {
if (node.type.name !== 'blockquote') return false
const callout = node.firstChild?.type.name === 'paragraph' && !node.firstChild.firstChild?.marks.length
? parseCallout(node.firstChild.textBetween(0, node.firstChild.content.size, '\n', '\n')) : null
dom.className = callout ? 'markdown-callout' : ''
header.hidden = !callout
foldable = !!callout?.fold
header.disabled = !foldable
if (callout) {
dom.dataset.callout = callout.type
const next = `${callout.name}:${callout.fold}`
if (signature !== next) dom.dataset.collapsed = String(callout.fold === '-')
signature = next
header.textContent = `${foldable ? (dom.dataset.collapsed === 'true' ? '▸ ' : '▾ ') : ''}${callout.title}`
if (foldable) header.setAttribute('aria-expanded', String(dom.dataset.collapsed !== 'true'))
else header.removeAttribute('aria-expanded')
} else {
delete dom.dataset.callout
delete dom.dataset.collapsed
signature = ''
}
return true
}
let current = initialNode
header.onclick = () => {
if (!foldable) return
dom.dataset.collapsed = String(dom.dataset.collapsed !== 'true')
update(current)
}
update(initialNode)
return { dom, contentDOM, update(node) { current = node; return update(node) },
stopEvent: event => header.contains(event.target as Node),
ignoreMutation: mutation => mutation.type !== 'selection' && !contentDOM.contains(mutation.target) }
},
},
},
}))
@@ -4,6 +4,7 @@ import { mount } from '@vue/test-utils'
// Vitest disables CSS by default, including CSS raw imports. Load the real files here.
vi.mock('@/styles/features.css?raw', async () => ({ default: (await import('node:fs')).readFileSync(process.cwd() + '/src/styles/features.css', 'utf8') }))
vi.mock('@/styles/tokens.css?raw', async () => ({ default: (await import('node:fs')).readFileSync(process.cwd() + '/src/styles/tokens.css', 'utf8') }))
vi.mock('@/styles/callouts.css?raw', async () => ({ default: (await import('node:fs')).readFileSync(process.cwd() + '/src/styles/callouts.css', 'utf8') }))
import CommunityThemePreview from './CommunityThemePreview.vue'
import { mockCommunityThemes } from '@/services/themePackageService'
const themes = [...['light','dark','sepia'].map(theme_id => ({theme_id,name:theme_id,builtin:true})), ...mockCommunityThemes.map(t => ({...t,builtin:false}))]
@@ -15,6 +16,10 @@ it.each(themes)('previews shared component states safely for $theme_id', theme =
const doc = new DOMParser().parseFromString(iframe.attributes('srcdoc')!, 'text/html')
expect(doc.documentElement.dataset.theme).toBe(theme.theme_id)
expect(doc.querySelector('script')).toBeNull()
expect(doc.querySelectorAll('.specimen-callouts > aside.markdown-callout')).toHaveLength(14)
expect(doc.querySelector('.specimen-callouts > details[open]')).not.toBeNull()
expect(doc.querySelector('.specimen-callouts > details:not([open])')).not.toBeNull()
expect(doc.querySelector('style')!.textContent).toContain('.callout-title:focus-visible')
expect(doc.querySelector('meta[http-equiv="Content-Security-Policy"]')?.getAttribute('content')).toContain("default-src 'none'")
for (const selector of ['input.input','input:disabled','textarea.textarea','select.select','.ui-disclosure[open]','.ui-disclosure:not([open])','.button-primary:disabled','.badge.success','.error-banner','.specimen-markdown code','.specimen-markdown table','.specimen-chart','.specimen-long']) expect(doc.querySelector(selector), selector).not.toBeNull()
expect(doc.querySelector('style')!.textContent).toContain('.button-primary:hover')
@@ -5,6 +5,8 @@ import { t } from '@/i18n'
import { getCommunityThemePreviewCss, mockCommunityThemes } from '@/services/themePackageService'
import tokensCss from '@/styles/tokens.css?raw'
import featuresCss from '@/styles/features.css?raw'
import calloutsCss from '@/styles/callouts.css?raw'
import { calloutTypes } from '@/utils/callouts'
import specimenHtml from './themeSpecimen.html?raw'
const props = defineProps<{ themeId: string; name?: string; css?: string }>()
@@ -20,7 +22,7 @@ const previewDocument = computed(() => {
policy.content = "default-src 'none'; style-src 'unsafe-inline'; img-src data:; font-src data:; base-uri 'none'; form-action 'none'"
doc.head.append(policy)
const style = doc.createElement('style')
style.textContent = `${tokensCss}\n${featuresCss}\n${props.css ?? getCommunityThemePreviewCss(props.themeId)}\nhtml { height:100% !important; overflow-y:auto !important; overflow-x:hidden !important; overscroll-behavior:contain; } body { height:auto !important; min-height:100%; overflow:visible !important; margin:0; padding:24px; background:var(--color-background-primary); color:var(--color-text-primary); font:16px/1.6 system-ui; } article { min-width:0; } .theme-specimen { display:grid; gap:16px; margin-top:20px; } .surface-nested { padding:12px; border:1px solid var(--color-border-default); border-radius:var(--radius-md); } .specimen-markdown { overflow:auto; } .specimen-markdown code { background:var(--color-code-background, var(--color-background-secondary)); color:var(--color-code-text, var(--color-text-primary)); padding:3px 6px; border-radius:4px; } .specimen-markdown pre { padding:12px; background:var(--color-background-secondary); } .specimen-markdown blockquote { border-left:3px solid var(--color-accent-primary); padding-left:12px; } .specimen-markdown table { width:100%; border-collapse:collapse; } .specimen-markdown td,.specimen-markdown th { padding:8px; border:1px solid var(--color-border-default); } .specimen-markdown th { background:var(--color-markdown-table-header); } .specimen-chart > div { display:flex; align-items:flex-end; gap:12px; height:100px; border-bottom:1px solid var(--color-border-default); } .specimen-chart span { width:36px; } .specimen-long { overflow-wrap:anywhere; } @media(max-width:480px) { body { padding:12px; } .form-grid { grid-template-columns:minmax(0,1fr); } }`
style.textContent = `${tokensCss}\n${featuresCss}\n${calloutsCss}\n${props.css ?? getCommunityThemePreviewCss(props.themeId)}\nhtml { height:100% !important; overflow-y:auto !important; overflow-x:hidden !important; overscroll-behavior:contain; } body { height:auto !important; min-height:100%; overflow:visible !important; margin:0; padding:24px; background:var(--color-background-primary); color:var(--color-text-primary); font:16px/1.6 system-ui; } article { min-width:0; } .theme-specimen { display:grid; gap:16px; margin-top:20px; } .surface-nested { padding:12px; border:1px solid var(--color-border-default); border-radius:var(--radius-md); } .specimen-markdown { overflow:auto; } .specimen-markdown code { background:var(--color-code-background, var(--color-background-secondary)); color:var(--color-code-text, var(--color-text-primary)); padding:3px 6px; border-radius:4px; } .specimen-markdown pre { padding:12px; background:var(--color-background-secondary); } .specimen-markdown blockquote { border-left:3px solid var(--color-accent-primary); padding-left:12px; } .specimen-markdown table { width:100%; border-collapse:collapse; } .specimen-markdown td,.specimen-markdown th { padding:8px; border:1px solid var(--color-border-default); } .specimen-markdown th { background:var(--color-markdown-table-header); } .specimen-chart > div { display:flex; align-items:flex-end; gap:12px; height:100px; border-bottom:1px solid var(--color-border-default); } .specimen-chart span { width:36px; } .specimen-long { overflow-wrap:anywhere; } @media(max-width:480px) { body { padding:12px; } .form-grid { grid-template-columns:minmax(0,1fr); } }`
doc.head.append(style)
const article = doc.createElement('article')
@@ -33,6 +35,22 @@ const previewDocument = computed(() => {
const button = doc.createElement('button'); button.className = 'button-primary'; button.textContent = t('示例按钮', 'Example button')
journal.append(text)
const specimen = doc.createElement('template'); specimen.innerHTML = specimenHtml
const callouts = doc.createElement('section'); callouts.className = 'specimen-callouts'
const caption = doc.createElement('h2'); caption.textContent = t('警告框与提示框', 'Alerts and callouts'); callouts.append(caption)
for (const type of Object.keys(calloutTypes)) {
const block = doc.createElement('aside'); block.className = 'markdown-callout'; block.dataset.callout = type
const title = doc.createElement('div'); title.className = 'callout-title'; title.textContent = type
const body = doc.createElement('div'); body.className = 'callout-body'; body.textContent = t('提示正文:检查文字、边框与主题配色。', 'Callout body: check text, borders and theme colors.')
block.append(title, body); callouts.append(block)
}
for (const open of [false, true]) {
const details = doc.createElement('details'); details.className = 'markdown-callout'; details.dataset.callout = 'warning'; details.open = open
const summary = doc.createElement('summary'); summary.className = 'callout-title'; summary.textContent = t('可折叠警告框', 'Collapsible callout')
const body = doc.createElement('div'); body.className = 'callout-body'
const nested = doc.createElement('aside'); nested.className = 'markdown-callout'; nested.dataset.callout = 'tip'; nested.textContent = t('嵌套提示内容', 'Nested callout content')
body.append(nested); details.append(summary, body); callouts.append(details)
}
specimen.content.append(callouts)
article.append(header, journal, button, specimen.content); doc.body.append(article)
return '<!doctype html>' + doc.documentElement.outerHTML
})
@@ -96,7 +96,7 @@ it.each(mockCommunityThemes)('previews uninstalled $theme_id using its actual CS
it('offers and applies the paper theme update without discarding the active theme', async () => {
const store = useThemeStore()
const old = await inspectThemePackage(paperPackage.replace('version: 1.6.2', 'version: 1.6.1'))
const old = await inspectThemePackage(paperPackage.replace('version: 1.7.0', 'version: 1.6.1'))
await store.installThemeFromInspection(old.manifest, old.css)
store.applyTheme('paper-moments')
wrapper = mount(ThemesView, { global: { stubs: { MarkdownContent: true } } })
@@ -105,6 +105,6 @@ it('offers and applies the paper theme update without discarding the active them
const card = wrapper.findAll('article.theme-card').find(item => item.text().includes('Paper Moments'))!
await card.findAll('button').find(button => button.text() === '更新')!.trigger('click')
await flushPromises()
expect(store.allThemes.find(theme => theme.theme_id === 'paper-moments')?.version).toBe('1.6.2')
expect(store.allThemes.find(theme => theme.theme_id === 'paper-moments')?.version).toBe('1.7.0')
expect(document.getElementById('theme-style-paper-moments')!.textContent).toContain('.surface-nested')
})
@@ -0,0 +1,25 @@
import { afterEach, expect, it, vi } from 'vitest'
import { executeEditorCommand, registerEditorCommands, getEditorCommandCapabilities } from './editorCommandService'
let dispose: (() => void) | undefined
afterEach(() => dispose?.())
it('reports unsupported, disabled and invalid commands without side effects', async () => {
expect(await executeEditorCommand('editor.bold')).toEqual({ ok: false, reason: 'unavailable' })
const handler = vi.fn(() => ({ ok: true as const }))
let available = false
dispose = registerEditorCommands({ available: () => available, handlers: { 'editor.bold': handler } })
expect(getEditorCommandCapabilities().find(item => item.id === 'editor.bold')).toMatchObject({ supported: true, enabled: false })
await executeEditorCommand('editor.bold')
expect(handler).not.toHaveBeenCalled()
available = true
expect(await executeEditorCommand('editor.bold')).toEqual({ ok: true })
expect(await executeEditorCommand('editor.metadata.edit')).toEqual({ ok: false, reason: 'unsupported' })
expect(await executeEditorCommand('arbitrary-command')).toEqual({ ok: false, reason: 'unsupported' })
})
it('old editor disposal cannot unregister the replacement editor', async () => {
const old = registerEditorCommands({ available: () => true, handlers: {} })
dispose = registerEditorCommands({ available: () => true, handlers: { 'editor.bold': () => ({ ok: true }) } })
old()
expect(await executeEditorCommand('editor.bold')).toEqual({ ok: true })
dispose()
expect(await executeEditorCommand('editor.bold')).toEqual({ ok: false, reason: 'unavailable' })
})
@@ -0,0 +1,33 @@
/** Versioned frontend boundary for future native menus/shortcuts; no Tauri IPC yet. */
export const editorCommandVersion = 1
export const editorCommandIds = [
'editor.bold', 'editor.italic', 'editor.strikethrough', 'editor.inline-code',
'editor.paragraph', 'editor.heading', 'editor.bullet-list', 'editor.ordered-list',
'editor.task-list', 'editor.blockquote', 'editor.callout', 'editor.code-block',
'editor.inline-math', 'editor.math-block', 'editor.mermaid', 'editor.link',
'editor.image', 'editor.table', 'editor.horizontal-rule', 'editor.hard-break',
'editor.font-size', 'editor.insert-markdown', 'editor.import-note-properties',
'editor.metadata.edit', 'editor.metadata.title', 'editor.metadata.tags',
'editor.reference-link', 'editor.html', 'editor.undo', 'editor.redo',
] as const
export type EditorCommandId = typeof editorCommandIds[number]
export type CommandResult = { ok: true } | { ok: false; reason: 'unsupported' | 'unavailable' | 'invalid-params' | 'failed' }
export type CommandHandler = (params: unknown) => CommandResult | Promise<CommandResult>
type Target = { available: () => boolean; handlers: Partial<Record<EditorCommandId, CommandHandler>> }
let active: Target | undefined
export function registerEditorCommands(target: Target) {
active = target
return () => { if (active === target) active = undefined }
}
export function getEditorCommandCapabilities() {
return editorCommandIds.map(id => ({ id, supported: !!active?.handlers[id], enabled: !!active?.handlers[id] && active.available() }))
}
export async function executeEditorCommand(id: string, params?: unknown): Promise<CommandResult> {
if (!(editorCommandIds as readonly string[]).includes(id)) return { ok: false, reason: 'unsupported' }
const target = active
if (!target || !target.available()) return { ok: false, reason: 'unavailable' }
const handler = target.handlers[id as EditorCommandId]
if (!handler) return { ok: false, reason: 'unsupported' }
try { return await handler(params) } catch { return { ok: false, reason: 'failed' } }
}
+8 -2
View File
@@ -361,7 +361,7 @@ export const mockCommunityThemes: ThemeManifest[] = [
{
theme_id: 'ocean-blue',
name: 'Ocean Blue',
version: '1.3.1',
version: '1.4.0',
author: 'community',
description: '宁静的海洋蓝色主题,适合长时间阅读',
min_app_version: '0.2.0',
@@ -373,7 +373,7 @@ export const mockCommunityThemes: ThemeManifest[] = [
{
theme_id: 'midnight-purple',
name: 'Midnight Purple',
version: '2.1.1',
version: '2.2.0',
author: 'night-owl',
description: '深紫色暗夜主题,适合编码',
min_app_version: '0.2.0',
@@ -464,6 +464,12 @@ export function getCommunityThemePreviewCss(themeId: string): string {
return buildCommunityThemeCss(themeId, t.is_dark) + `
[data-theme="${themeId}"] {
color-scheme: ${t.is_dark ? 'dark' : 'light'};
--color-callout-info: ${t.is_dark ? '#9dbbff' : '#126589'};
--color-callout-success: ${t.is_dark ? '#a7d58c' : '#267049'};
--color-callout-warning: ${t.is_dark ? '#efc886' : '#885c13'};
--color-callout-danger: ${t.is_dark ? '#ff9caf' : '#b13d4d'};
--color-callout-important: ${t.is_dark ? '#d4afff' : '#7050a3'};
--color-callout-quote: ${t.is_dark ? '#b0b9dd' : '#53697d'};
--color-text-inverse: ${t.is_dark ? '#1a1b26' : '#ffffff'};
--color-text-disabled: color-mix(in srgb, var(--color-text-primary) 45%, var(--color-surface-primary));
--color-background-overlay: ${t.is_dark ? '#000000a6' : '#00000073'};
+3 -3
View File
@@ -5,9 +5,9 @@ import * as themePkg from '@/services/themePackageService'
import { t } from '@/i18n'
const builtinThemes = (): ThemeConfig[] => [
{ theme_id: 'light', name: t('浅色', 'Light'), version: '1.1.1', description: t('默认浅色主题', 'Default light theme'), is_dark: false, builtin: true, code_theme: 'github-light' },
{ theme_id: 'dark', name: t('深色', 'Dark'), version: '1.1.1', description: t('默认深色主题', 'Default dark theme'), is_dark: true, builtin: true, code_theme: 'github-dark' },
{ theme_id: 'sepia', name: t('护眼', 'Sepia'), version: '1.1.1', description: t('护眼暖色调', 'Warm, low-glare theme'), is_dark: false, builtin: true, code_theme: 'github-light' },
{ theme_id: 'light', name: t('浅色', 'Light'), version: '1.2.0', description: t('默认浅色主题', 'Default light theme'), is_dark: false, builtin: true, code_theme: 'github-light' },
{ theme_id: 'dark', name: t('深色', 'Dark'), version: '1.2.0', description: t('默认深色主题', 'Default dark theme'), is_dark: true, builtin: true, code_theme: 'github-dark' },
{ theme_id: 'sepia', name: t('护眼', 'Sepia'), version: '1.2.0', description: t('护眼暖色调', 'Warm, low-glare theme'), is_dark: false, builtin: true, code_theme: 'github-light' },
]
export type CodeBlockThemePreference = 'auto' | 'github-light' | 'github-dark'
+28
View File
@@ -0,0 +1,28 @@
/* Semantic tokens inherit every installed theme, including imported themes. */
:where(.markdown-callout) { --callout-color: var(--color-callout-info, var(--color-info)); }
.markdown-callout, .milkdown .ProseMirror blockquote.markdown-callout {
border: 1px solid color-mix(in srgb, var(--callout-color) 35%, transparent);
border-inline-start: 4px solid var(--callout-color);
border-radius: var(--radius-md, 8px);
background: color-mix(in srgb, var(--callout-color) 8%, var(--color-surface-primary, var(--paper, #fffdf7)));
color: var(--color-text-primary, var(--ink, inherit));
margin: 12px 0; padding: 12px 16px; min-width: 0;
}
.markdown-callout[data-callout='warning'], .markdown-callout[data-callout='question'] { --callout-color: var(--color-callout-warning, var(--color-warning)); }
.markdown-callout[data-callout='danger'], .markdown-callout[data-callout='failure'], .markdown-callout[data-callout='bug'] { --callout-color: var(--color-callout-danger, var(--color-error)); }
.markdown-callout[data-callout='success'], .markdown-callout[data-callout='tip'] { --callout-color: var(--color-callout-success, var(--color-success)); }
.markdown-callout[data-callout='abstract'], .markdown-callout[data-callout='important'], .markdown-callout[data-callout='example'] { --callout-color: var(--color-callout-important, var(--color-accent-secondary)); }
.markdown-callout[data-callout='quote'] { --callout-color: var(--color-callout-quote, var(--color-text-secondary)); }
.markdown-callout[data-callout='todo'] { --callout-color: var(--color-callout-info, var(--color-accent-primary)); }
.markdown-callout > .callout-title { color: var(--callout-color); font-weight: 700; line-height: 1.5; overflow-wrap: anywhere; }
.markdown-callout > button.callout-title { background: transparent; border: 0; padding: 0; width: 100%; text-align: start; cursor: pointer; }
.markdown-callout > button.callout-title:disabled { opacity: 1; cursor: default; color: var(--callout-color); }
.markdown-callout > summary.callout-title { cursor: pointer; }
.markdown-callout > :is(button, summary).callout-title:focus-visible { outline: 2px solid var(--color-border-focus); outline-offset: 4px; border-radius: var(--radius-sm); }
.markdown-callout > :is(button:not(:disabled), summary).callout-title:hover { text-decoration: underline; text-underline-offset: 3px; }
.markdown-callout .callout-body { min-width: 0; overflow-wrap: anywhere; }
.markdown-callout .callout-body > :last-child { margin-bottom: 0; }
.markdown-callout[data-collapsed='true'] > .callout-body { display: none; }
.callout-marker { display: none; }
.callout-title[hidden] { display: none !important; }
.callout-marker-editing { opacity: .65; font-family: monospace; }
+44
View File
@@ -22,3 +22,47 @@ it.each(mockCommunityThemes)('provides interaction and Markdown colors in $theme
}
expect(css).toContain(`color-scheme: ${theme.is_dark ? 'dark' : 'light'}`)
})
const calloutThemes = ['light', 'dark', 'sepia', ...mockCommunityThemes.map(theme => theme.theme_id)]
const calloutTones = ['info', 'success', 'warning', 'danger', 'important', 'quote']
it.each(calloutThemes)('keeps callout headings readable against tinted surfaces in %s', themeId => {
const doc = document.implementation.createHTMLDocument('theme contrast')
const style = doc.createElement('style')
style.textContent = files['styles/tokens.css'] ?? files['styles\\tokens.css']!
style.textContent += getCommunityThemePreviewCss(themeId)
doc.head.append(style)
const values = new Map<string, string>()
for (const rule of Array.from(doc.styleSheets[0]!.cssRules) as CSSStyleRule[]) {
if (![':root', `[data-theme='${themeId}']`, `[data-theme="${themeId}"]`].includes(rule.selectorText)) continue
for (const name of ['--color-surface-primary', ...calloutTones.map(tone => `--color-callout-${tone}`)]) {
const value = rule.style.getPropertyValue(name).trim()
if (value) values.set(name, value)
}
}
const rgb = (hex: string) => [1, 3, 5].map(offset => parseInt(hex.slice(offset, offset + 2), 16) / 255)
const luminance = (color: number[]) => color.map(value => value <= .04045 ? value / 12.92 : ((value + .055) / 1.055) ** 2.4).reduce((sum, value, index) => sum + value * [.2126, .7152, .0722][index]!, 0)
const surface = rgb(values.get('--color-surface-primary')!)
for (const tone of calloutTones) {
const hex = values.get(`--color-callout-${tone}`)!
expect(hex).toMatch(/^#[\da-f]{6}$/i)
const ink = rgb(hex)
const background = surface.map((value, index) => value * .92 + ink[index]! * .08)
const first = luminance(ink), second = luminance(background)
expect((Math.max(first, second) + .05) / (Math.min(first, second) + .05), tone).toBeGreaterThanOrEqual(4.5)
}
})
it('preserves warning and success colors inside the editor selector cascade', () => {
const style = document.createElement('style')
style.textContent = readFileSync(join(root, 'styles/callouts.css'), 'utf8')
document.head.append(style)
const host = document.createElement('div')
host.className = 'milkdown'
host.innerHTML = '<div class="ProseMirror"><blockquote class="markdown-callout" data-callout="warning"></blockquote><blockquote class="markdown-callout" data-callout="success"></blockquote></div>'
document.body.append(host)
try {
const blocks = host.querySelectorAll('blockquote')
expect(getComputedStyle(blocks[0]!).getPropertyValue('--callout-color')).toContain('--color-callout-warning')
expect(getComputedStyle(blocks[1]!).getPropertyValue('--callout-color')).toContain('--color-callout-success')
} finally { host.remove(); style.remove() }
})
+28
View File
@@ -1,4 +1,11 @@
:root {
/* Callout heading colors also serve as borders; keep text readable on tint. */
--color-callout-info: var(--color-info);
--color-callout-success: var(--color-success);
--color-callout-warning: var(--color-warning);
--color-callout-danger: var(--color-error);
--color-callout-important: var(--color-accent-secondary);
--color-callout-quote: var(--color-text-secondary);
/* Background */
--color-background-primary: #ffffff;
--color-background-secondary: #f7f8fa;
@@ -117,7 +124,22 @@
--statusbar-height: 28px;
}
[data-theme='light'] {
--color-callout-info: #175da6;
--color-callout-success: #236b3b;
--color-callout-warning: #855700;
--color-callout-danger: #ad2935;
--color-callout-important: #7443ad;
--color-callout-quote: #59636e;
}
[data-theme='dark'] {
--color-callout-info: #8bbdff;
--color-callout-success: #80ce93;
--color-callout-warning: #efc66f;
--color-callout-danger: #ff9b9b;
--color-callout-important: #c8a5ff;
--color-callout-quote: #abb6c2;
--color-background-primary: #0d1117;
--color-background-secondary: #161b22;
--color-background-tertiary: #21262d;
@@ -168,6 +190,12 @@
}
[data-theme='sepia'] {
--color-callout-info: #396578;
--color-callout-success: #496b3b;
--color-callout-warning: #805918;
--color-callout-danger: #a04438;
--color-callout-important: #785476;
--color-callout-quote: #746653;
--color-background-primary: #fbf3df;
--color-background-secondary: #f4e8ca;
--color-background-tertiary: #eadbb8;
+39
View File
@@ -0,0 +1,39 @@
// @vitest-environment jsdom
import { describe, expect, it } from 'vitest'
import { calloutTypes, parseCallout } from './callouts'
import { renderMarkdown } from './markdown'
describe('callouts', () => {
for (const [type, aliases] of Object.entries(calloutTypes)) {
for (const alias of aliases) it(`renders ${alias}`, async () => {
const root = document.createElement('div')
root.innerHTML = await renderMarkdown(`> [!${alias.toUpperCase()}] 标题\n> **正文** 与 \`code\`\n>\n> - 条目`)
expect(root.querySelector('.markdown-callout')?.getAttribute('data-callout')).toBe(type)
expect(root.querySelector('.callout-title')?.textContent).toBe('标题')
expect(root.querySelector('strong')?.textContent).toBe('正文')
expect(root.querySelector('li')?.textContent).toBe('条目')
})
}
it('supports folding, nesting, unknown types, empty bodies and safe titles', async () => {
const root = document.createElement('div')
root.innerHTML = await renderMarkdown('> [!WARNING]- 外层\n>\n> > [!tip]+ 内层\n> > 内容\n\n> [!custom] <img src=x onerror=alert(1)>\n\n> [!NOTE]')
expect(root.querySelector('details')?.hasAttribute('open')).toBe(false)
expect(root.querySelector('details details')?.hasAttribute('open')).toBe(true)
expect(root.querySelectorAll('.markdown-callout')).toHaveLength(4)
expect(root.querySelector('img')).toBeNull()
expect(root.textContent).toContain('<img src=x onerror=alert(1)>')
})
it('renders the editor serialization of nested folded callouts', async () => {
const root = document.createElement('div')
root.innerHTML = await renderMarkdown('> [!WARNING]- 注意\n>\n> **正文**\n>\n> > [!TIP] 内层\n> > 内容\n')
expect(root.querySelectorAll('.markdown-callout')).toHaveLength(2)
expect(root.querySelector('strong')?.textContent).toBe('正文')
})
it('does not convert ordinary quotes, inline code, escaped markers or fenced examples', async () => {
const root = document.createElement('div')
root.innerHTML = await renderMarkdown('> ordinary\n\n> \\[!NOTE]\n\n`[!TIP]`\n\n```text\n> [!WARNING]\n```')
expect(root.querySelector('.markdown-callout')).toBeNull()
expect(root.querySelectorAll('blockquote')).toHaveLength(2)
expect(parseCallout('prefix [!NOTE]')).toBeNull()
})
})
+21
View File
@@ -0,0 +1,21 @@
/** GitHub alerts and Obsidian callouts share the same portable Markdown syntax. */
export const calloutTypes = {
note: ['note'], abstract: ['abstract', 'summary', 'tldr'], info: ['info'],
todo: ['todo'], tip: ['tip', 'hint'], important: ['important'], success: ['success', 'check', 'done'],
question: ['question', 'help', 'faq'], warning: ['warning', 'caution', 'attention'],
failure: ['failure', 'fail', 'missing'], danger: ['danger', 'error'], bug: ['bug'],
example: ['example'], quote: ['quote', 'cite'],
} as const
export function parseCallout(text: string) {
const match = /^\[!([\w-]+)\]([+-]?)[ \t]*([^\n]*)(?:\n|$)/.exec(text)
if (!match) return null
const name = match[1]!.toLowerCase()
const type = Object.entries(calloutTypes).find(([, aliases]) => (aliases as readonly string[]).includes(name))?.[0] ?? 'note'
return { name, type, title: match[3]!.trim() || name.charAt(0).toUpperCase() + name.slice(1),
fold: match[2] || null, markerLength: match[0].replace(/\n$/, '').length, body: text.slice(match[0].length) }
}
export function escapeCalloutTitle(text: string) {
return text.replace(/[&<>"']/g, character => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[character]!)
}
+13
View File
@@ -9,6 +9,19 @@ import { renderMermaid } from '@/services/mermaidService'
import { appendDiagramControls } from './diagramControls'
import katex from 'katex'
import 'katex/dist/katex.min.css'
import { parseCallout, escapeCalloutTitle } from './callouts'
import '@/styles/callouts.css'
marked.use({ renderer: { blockquote(token) {
const callout = parseCallout(token.text)
if (!callout) return false
const title = escapeCalloutTitle(callout.title)
const body = marked.parse(callout.body, { async: false }) as string
const attributes = `class="markdown-callout" data-callout="${callout.type}"`
return callout.fold
? `<details ${attributes}${callout.fold === '+' ? ' open' : ''}><summary class="callout-title">${title}</summary><div class="callout-body">${body}</div></details>`
: `<aside ${attributes}><div class="callout-title">${title}</div><div class="callout-body">${body}</div></aside>`
} } })
function mathHtml(source: string, displayMode: boolean) {
const result = katex.renderToString(source, {displayMode, throwOnError:false, trust:false, maxExpand:1000, output:'html'})