feat(markdown): prompt to save before pasting images into untitled docs (#162)

Co-authored-by: Claude <noreply@anthropic.com>
This commit is contained in:
konghaojie-k2
2026-08-27 18:14:38 +08:00
committed by GitHub
co-authored by Claude
parent 607c77086f
commit 583a045212
7 changed files with 274 additions and 2 deletions
+2
View File
@@ -16,6 +16,7 @@ import type { SlashController, SlashMenuState } from './editor/slashCommand'
import { setImageBaseDir } from './editor/localImage'
import { Ribbon } from './components/Ribbon'
import { SlashMenu, type SlashMenuHandle } from './components/SlashMenu'
import { ToastHost } from './components/toast'
import { TableMenu } from './components/TableMenu'
import { FrontmatterPanel } from './components/FrontmatterPanel'
import { AiAskPopover } from './components/AiAskPopover'
@@ -681,6 +682,7 @@ export default function App() {
</div>
</div>
<SlashMenu ref={slashMenuRef} state={slashState} onDismiss={() => setSlashState(null)} />
<ToastHost />
<TableMenu editor={editor} scrollRef={scrollRef} zoom={zoom} />
{editor && status === 'ready' && (
<AiAskPopover
@@ -0,0 +1,19 @@
/** Toast event bus, split from the ToastHost component so this module has no
* component exports: React Fast Refresh replaces mixed-export modules wholesale,
* which strands callers on a stale emitter during dev HMR. */
export interface ToastData {
text: string
kind: 'success' | 'error'
}
let emit: ((toast: ToastData) => void) | null = null
/** Registered by ToastHost on mount; null while unmounted. */
export function setToastEmitter(fn: ((toast: ToastData) => void) | null): void {
emit = fn
}
export function showToast(text: string, kind: 'success' | 'error' = 'success'): void {
emit?.({ text, kind })
}
@@ -0,0 +1,67 @@
/** Transient feedback for user-triggered actions: a fixed top-center pill
* that auto-dismisses. The status bar stays the durable log.
* Trigger via showToast from './toast-bus' (kept component-only here so React
* Fast Refresh works in dev). */
import { useEffect, useState } from 'react'
import { setToastEmitter, type ToastData } from './toast-bus'
export function ToastHost() {
const [toast, setToast] = useState<ToastData | null>(null)
const [visible, setVisible] = useState(false)
useEffect(() => {
let hideTimer: number | undefined
let clearTimer: number | undefined
let raf = 0
setToastEmitter((next) => {
window.clearTimeout(hideTimer)
window.clearTimeout(clearTimer)
window.cancelAnimationFrame(raf)
setToast(next)
// Mount hidden first: CSS transitions don't run on initial mount, so
// the show class lands a frame later for the fade/slide-in to play.
setVisible(false)
raf = window.requestAnimationFrame(() => {
raf = window.requestAnimationFrame(() => setVisible(true))
})
const shownMs = next.kind === 'error' ? 4000 : 2000
hideTimer = window.setTimeout(() => setVisible(false), shownMs)
// keep the node mounted through the fade-out transition
clearTimer = window.setTimeout(() => setToast(null), shownMs + 200)
})
return () => {
setToastEmitter(null)
window.clearTimeout(hideTimer)
window.clearTimeout(clearTimer)
window.cancelAnimationFrame(raf)
}
}, [])
if (!toast) return null
return (
<div className={`app-toast ${toast.kind}${visible ? ' show' : ''}`} role="status">
<svg
className="app-toast-icon"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth={1.5}
strokeLinecap="round"
strokeLinejoin="round"
aria-hidden
>
{toast.kind === 'success' ? (
<>
<circle cx="12" cy="12" r="9" />
<path d="m8.2 12.3 2.6 2.6 5-5" />
</>
) : (
<>
<circle cx="12" cy="12" r="9" />
<path d="M12 7.5v5.3" />
<path d="M12 16.4v.1" />
</>
)}
</svg>
{toast.text}
</div>
)
}
@@ -1,5 +1,7 @@
import { Image } from '@tiptap/extension-image'
import { Plugin, PluginKey } from '@tiptap/pm/state'
import { t } from '../i18n/locale'
import { showToast } from '../components/toast-bus'
/** Directory of the open .md file; relative image paths resolve against it for display */
let imageBaseDir: string | null = null
@@ -72,8 +74,11 @@ async function persistAndInsert(
base64: btoa(binary),
ext: EXT_BY_MIME[file.type]!,
})
// untitled documents have no assets/ directory yet — drop silently
if (!rel) return
// untitled documents have no assets/ directory yet — tell the user to save first
if (!rel) {
showToast(t('imageNeedsSavedDocument'), 'error')
return
}
const alt = file.name.replace(/\.[a-z0-9]+$/i, '')
editor
.chain()
@@ -52,6 +52,7 @@ export const strings = {
saving: '保存中…',
savedOk: '已保存',
saveFailed: '保存失败',
imageNeedsSavedDocument: '请先保存文档,再粘贴图片',
unsaved: '未保存',
placeholder: '开始输入…',
styleParagraph: '正文',
@@ -210,6 +211,7 @@ export const strings = {
saving: 'Saving…',
savedOk: 'Saved',
saveFailed: 'Save failed',
imageNeedsSavedDocument: 'Save the document first, then paste images',
unsaved: 'Unsaved',
placeholder: 'Start typing…',
styleParagraph: 'Text',
@@ -368,6 +370,7 @@ export const strings = {
saving: '保存中…',
savedOk: '保存しました',
saveFailed: '保存に失敗しました',
imageNeedsSavedDocument: '先にドキュメントを保存してから画像を貼り付けてください',
unsaved: '未保存',
placeholder: '入力を開始…',
styleParagraph: '本文',
@@ -527,6 +530,7 @@ export const strings = {
saving: '저장 중…',
savedOk: '저장됨',
saveFailed: '저장 실패',
imageNeedsSavedDocument: '먼저 문서를 저장한 후 이미지를 붙여넣으세요',
unsaved: '저장 안 됨',
placeholder: '입력을 시작하세요…',
styleParagraph: '본문',
@@ -688,6 +692,7 @@ export const strings = {
saving: 'Enregistrement…',
savedOk: 'Enregistré',
saveFailed: "Échec de l'enregistrement",
imageNeedsSavedDocument: "Enregistrez d'abord le document, puis collez des images",
unsaved: 'Non enregistré',
placeholder: 'Commencez à écrire…',
styleParagraph: 'Texte',
@@ -851,6 +856,7 @@ export const strings = {
saving: 'Wird gespeichert…',
savedOk: 'Gespeichert',
saveFailed: 'Speichern fehlgeschlagen',
imageNeedsSavedDocument: 'Speichern Sie das Dokument zuerst und fügen Sie dann Bilder ein',
unsaved: 'Nicht gespeichert',
placeholder: 'Tippen Sie los…',
styleParagraph: 'Text',
@@ -1013,6 +1019,7 @@ export const strings = {
saving: 'Guardando…',
savedOk: 'Guardado',
saveFailed: 'Error al guardar',
imageNeedsSavedDocument: 'Guarde primero el documento y luego pegue las imágenes',
unsaved: 'Sin guardar',
placeholder: 'Empieza a escribir…',
styleParagraph: 'Texto',
@@ -1171,6 +1178,7 @@ export const strings = {
saving: 'กำลังบันทึก…',
savedOk: 'บันทึกแล้ว',
saveFailed: 'บันทึกไม่สำเร็จ',
imageNeedsSavedDocument: 'บันทึกเอกสารก่อน แล้วค่อยวางรูปภาพ',
unsaved: 'ยังไม่ได้บันทึก',
placeholder: 'เริ่มพิมพ์…',
styleParagraph: 'ข้อความ',
@@ -1330,6 +1338,7 @@ export const strings = {
saving: 'Menyimpan…',
savedOk: 'Tersimpan',
saveFailed: 'Gagal menyimpan',
imageNeedsSavedDocument: 'Simpan dokumen terlebih dahulu, lalu tempel gambar',
unsaved: 'Belum disimpan',
placeholder: 'Mulai mengetik…',
styleParagraph: 'Teks',
@@ -1490,6 +1499,7 @@ export const strings = {
saving: 'Сохранение…',
savedOk: 'Сохранено',
saveFailed: 'Ошибка сохранения',
imageNeedsSavedDocument: 'Сначала сохраните документ, затем вставляйте изображения',
unsaved: 'Не сохранено',
placeholder: 'Начните вводить…',
styleParagraph: 'Текст',
@@ -1647,6 +1657,7 @@ export const strings = {
saving: 'جارٍ الحفظ…',
savedOk: 'تم الحفظ',
saveFailed: 'فشل الحفظ',
imageNeedsSavedDocument: 'احفظ المستند أولاً ثم الصق الصور',
unsaved: 'غير محفوظ',
placeholder: 'ابدأ الكتابة…',
styleParagraph: 'نص',
@@ -1808,6 +1819,7 @@ export const strings = {
saving: 'Salvando…',
savedOk: 'Salvo',
saveFailed: 'Falha ao salvar',
imageNeedsSavedDocument: 'Salve o documento primeiro e depois cole as imagens',
unsaved: 'Não salvo',
placeholder: 'Comece a digitar…',
styleParagraph: 'Texto',
@@ -1969,6 +1981,7 @@ export const strings = {
saving: 'Salvataggio…',
savedOk: 'Salvato',
saveFailed: 'Salvataggio non riuscito',
imageNeedsSavedDocument: 'Salva prima il documento, poi incolla le immagini',
unsaved: 'Non salvato',
placeholder: 'Inizia a scrivere…',
styleParagraph: 'Testo',
@@ -2129,6 +2142,7 @@ export const strings = {
saving: 'Zapisywanie…',
savedOk: 'Zapisano',
saveFailed: 'Zapis nie powiódł się',
imageNeedsSavedDocument: 'Najpierw zapisz dokument, a potem wklej obrazy',
unsaved: 'Niezapisane',
placeholder: 'Zacznij pisać…',
styleParagraph: 'Tekst',
@@ -2290,6 +2304,7 @@ export const strings = {
saving: 'Opslaan…',
savedOk: 'Opgeslagen',
saveFailed: 'Opslaan mislukt',
imageNeedsSavedDocument: 'Sla het document eerst op en plak daarna afbeeldingen',
unsaved: 'Niet opgeslagen',
placeholder: 'Begin met typen…',
styleParagraph: 'Tekst',
@@ -2449,6 +2464,7 @@ export const strings = {
saving: 'Menyimpan…',
savedOk: 'Disimpan',
saveFailed: 'Gagal menyimpan',
imageNeedsSavedDocument: 'Simpan dokumen dahulu, kemudian tampal imej',
unsaved: 'Belum disimpan',
placeholder: 'Mula menaip…',
styleParagraph: 'Teks',
@@ -2606,6 +2622,7 @@ export const strings = {
saving: 'שומר…',
savedOk: 'נשמר',
saveFailed: 'השמירה נכשלה',
imageNeedsSavedDocument: 'שמור תחילה את המסמך ואז הדבק תמונות',
unsaved: 'לא נשמר',
placeholder: 'התחילו להקליד…',
styleParagraph: 'טקסט',
@@ -2765,6 +2782,7 @@ export const strings = {
saving: 'सहेजा जा रहा है…',
savedOk: 'सहेजा गया',
saveFailed: 'सहेजना विफल',
imageNeedsSavedDocument: 'पहले दस्तावेज़ सहेजें, फिर चित्र चिपकाएँ',
unsaved: 'सहेजा नहीं गया',
placeholder: 'लिखना शुरू करें…',
styleParagraph: 'सादा पाठ',
@@ -2922,6 +2940,7 @@ export const strings = {
saving: '儲存中…',
savedOk: '已儲存',
saveFailed: '儲存失敗',
imageNeedsSavedDocument: '請先儲存文件,再貼上圖片',
unsaved: '未儲存',
placeholder: '開始輸入…',
styleParagraph: '內文',
+60
View File
@@ -32,6 +32,11 @@
--md-tip-shadow: 0 4px 6px rgb(0 0 0 / 10%);
/* same paper shadow as the pdf app's --pdf-shadow-page */
--md-page-shadow: 0 1px 4px rgb(0 0 0 / 18%);
/* toast pill is a dark surface in both themes */
--md-toast-bg: rgb(35 35 37 / 92%);
--md-toast-error-bg: rgb(196 49 75 / 95%);
--md-toast-ink: #ffffff;
--md-toast-ok: #34c759;
}
[data-theme='dark'] {
@@ -63,6 +68,10 @@
--md-pop-shadow: 0 8px 24px rgb(0 0 0 / 50%);
--md-tip-shadow: 0 4px 6px rgb(0 0 0 / 35%);
--md-page-shadow: 0 1px 4px rgb(0 0 0 / 18%);
--md-toast-bg: rgb(35 35 37 / 92%);
--md-toast-error-bg: rgb(196 49 75 / 95%);
--md-toast-ink: #ffffff;
--md-toast-ok: #34c759;
}
@media (prefers-color-scheme: dark) {
@@ -95,6 +104,10 @@
--md-pop-shadow: 0 8px 24px rgb(0 0 0 / 50%);
--md-tip-shadow: 0 4px 6px rgb(0 0 0 / 35%);
--md-page-shadow: 0 1px 4px rgb(0 0 0 / 18%);
--md-toast-bg: rgb(35 35 37 / 92%);
--md-toast-error-bg: rgb(196 49 75 / 95%);
--md-toast-ink: #ffffff;
--md-toast-ok: #34c759;
}
}
@@ -2707,3 +2720,50 @@ div.tiptap-mathematics-render {
opacity: 0.45;
cursor: default;
}
/* ================= transient toast (action feedback) ================= */
.app-toast {
position: fixed;
top: 64px;
left: 50%;
transform: translate(-50%, -8px);
z-index: 2000;
display: flex;
align-items: center;
gap: 8px;
padding: 8px 16px;
border-radius: 8px;
background: var(--md-toast-bg);
color: var(--md-toast-ink);
font-size: 13px;
box-shadow: var(--md-pop-shadow);
opacity: 0;
pointer-events: none;
transition:
opacity 0.18s ease,
transform 0.18s ease;
max-width: 60vw;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.app-toast.show {
opacity: 1;
transform: translate(-50%, 0);
}
.app-toast.error {
background: var(--md-toast-error-bg);
}
.app-toast-icon {
width: 16px;
height: 16px;
flex: none;
}
.app-toast.success .app-toast-icon {
color: var(--md-toast-ok);
}
@@ -0,0 +1,100 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import { Slice } from '@tiptap/pm/model'
import { setToastEmitter, type ToastData } from '../src/renderer/components/toast-bus'
import { strings } from '../src/renderer/i18n/strings'
// Undestroyed views leave DOMObserver flush timers that fire after jsdom teardown
// ("document is not defined" unhandled error) — destroy every editor we create.
const editors: import('@tiptap/core').Editor[] = []
let toasts: ToastData[] = []
afterEach(() => {
for (const e of editors.splice(0)) e.destroy()
setToastEmitter(null)
toasts = []
vi.restoreAllMocks()
})
function stubSaveImage(result: string | null) {
Object.defineProperty(window, 'markdownApi', {
configurable: true,
value: { saveImage: vi.fn(async () => result) },
})
}
async function newEditor() {
const { Editor } = await import('@tiptap/core')
const { buildExtensions } = await import('../src/renderer/editor/extensions')
const editor = new Editor({
extensions: buildExtensions({
slashController: { onOpen() {}, onUpdate() {}, onKeyDown: () => false, onClose() {} },
slashItems: () => [],
}),
content: '',
})
editors.push(editor)
return editor
}
/** Invoke the editor's handlePaste props with a synthetic clipboard payload.
* Mirrors ProseMirror semantics: first handler returning truthy wins.
* getData is stubbed because CodeBlock's paste handler reads text/html. */
function paste(editor: import('@tiptap/core').Editor, files: File[]): boolean {
const clipboardData = {
files,
getData: () => '',
} as unknown as DataTransfer
const event = { clipboardData } as unknown as ClipboardEvent
let handled = false
editor.view.someProp('handlePaste', (fn) => {
if (handled) return
handled = fn(editor.view, event, Slice.empty) === true
})
return handled
}
function pngFile(): File {
// 4-byte payload is enough — persistAndInsert only reads bytes + MIME type
return new File([new Uint8Array([137, 80, 78, 71])], 'shot.png', { type: 'image/png' })
}
describe('image paste into an untitled document', () => {
it('toasts instead of silently dropping when the image cannot be persisted', async () => {
stubSaveImage(null)
setToastEmitter((toast) => toasts.push(toast))
const editor = await newEditor()
const handled = paste(editor, [pngFile()])
expect(handled).toBe(true)
await vi.waitFor(() => expect(toasts).toHaveLength(1))
expect(toasts[0]).toEqual({ text: strings.zh.imageNeedsSavedDocument, kind: 'error' })
expect(editor.state.doc.toString()).not.toContain('image')
expect(window.markdownApi.saveImage).toHaveBeenCalledOnce()
})
it('inserts the image node when persistence succeeds, without a toast', async () => {
stubSaveImage('assets/shot.png')
setToastEmitter((toast) => toasts.push(toast))
const editor = await newEditor()
paste(editor, [pngFile()])
await vi.waitFor(() => {
let found: string | null = null
editor.state.doc.descendants((node) => {
if (node.type.name === 'image') found = String(node.attrs.src)
return true
})
expect(found).toBe('assets/shot.png')
})
expect(toasts).toHaveLength(0)
})
it('ignores clipboards without image files', async () => {
stubSaveImage('assets/shot.png')
const editor = await newEditor()
const text = new File(['plain'], 'notes.txt', { type: 'text/plain' })
expect(paste(editor, [text])).toBe(false)
expect(window.markdownApi.saveImage).not.toHaveBeenCalled()
})
})