From 0f29ffe5ea6ca0812c22da4a1cfd2380e53c0379 Mon Sep 17 00:00:00 2001 From: lqtdys Date: Mon, 2 Nov 2026 00:59:25 +0800 Subject: [PATCH] =?UTF-8?q?feat(app-kit):=20=E5=89=AA=E8=B4=B4=E6=9D=BF?= =?UTF-8?q?=E8=83=BD=E5=8A=9B=E5=8A=A0=20seam=EF=BC=88copyImage=20?= =?UTF-8?q?=E5=8F=AF=E6=B3=A8=E5=85=A5=EF=BC=89=EF=BC=88#511=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 新增 @md-bundle/app-kit/clipboard:copyImageToClipboard(png, writer?) 与 browserClipboardWriter;公开契约沿用 contracts.ts 的 ClipboardWriter —— 永不抛错, 失败返回 false,调用方据此走兜底下载; - 边界处再兜一层 try/catch:注入的实现自己抛错也收敛为 false,不让 seam 变成新的崩溃面; - 「复制正文为图片」改走 app-kit 入口;shareCard.ts 里的 copyToClipboard 实现体删除, 只留旧名字的别名给邀请卡链路 —— 剪贴板逻辑全仓回到一处; - 测试:app-kit 4 条(注入 writer / writer 抛错 / 缺 API / 真实写入 image/png), App.test.tsx 补兜底分支(jsdom 无 ClipboardItem → 「正文图片已下载」), export-png e2e 补一条真实浏览器用例(「已复制」或「已下载」二选一收尾)。 单测:renderer 121 / editor 957 / app-kit 18 / web 417 全绿;typecheck、lint、build 通过。 refs #511 --- apps/web/src/App.test.tsx | 20 ++++++++++ apps/web/src/App.tsx | 3 +- apps/web/src/lib/shareCard.ts | 20 +++------- apps/web/test-results/export-png.json | 3 +- apps/web/test/export-png.e2e.spec.ts | 16 ++++++++ packages/app-kit/package.json | 1 + packages/app-kit/src/clipboard/index.ts | 35 ++++++++++++++++ packages/app-kit/test/clipboard.test.ts | 53 +++++++++++++++++++++++++ 8 files changed, 134 insertions(+), 17 deletions(-) create mode 100644 packages/app-kit/src/clipboard/index.ts create mode 100644 packages/app-kit/test/clipboard.test.ts diff --git a/apps/web/src/App.test.tsx b/apps/web/src/App.test.tsx index 2ead32e..921e1f6 100644 --- a/apps/web/src/App.test.tsx +++ b/apps/web/src/App.test.tsx @@ -9,6 +9,13 @@ vi.mock('./lib/openFile', () => ({ openFile: vi.fn(async () => ({ kind: 'md', name: 'hello.md', content: '# Hello\n\n正文段落' })), })); +// 「复制正文为图片」的真实 PNG 栅格化在 jsdom 里跑不了;这里测的是 App 的接线分支: +// 复制失败(jsdom 无 ClipboardItem)→ 兜底下载路径 → 对应 toast。生成器本身由 +// exportPng.test.ts / export-png.e2e.spec.ts 覆盖。 +vi.mock('./lib/exportPng', () => ({ + exportPngFromMarkdown: async () => new Blob([new Uint8Array([0x89, 0x50, 0x4e, 0x47])], { type: 'image/png' }), +})); + afterEach(cleanup); describe('App', () => { @@ -38,6 +45,19 @@ describe('App', () => { // 复制正文为图片按钮存在 expect(screen.getByTestId('copy-body-image-btn')).toBeInTheDocument(); }); + + it('clicking 复制正文为图片 falls back to download toast when the clipboard is unavailable', async () => { + render(); + const file = new File(['# Hello'], 'hello.md', { type: 'text/markdown' }); + fireEvent.change(screen.getByTestId('file-input'), { target: { files: [file] } }); + await waitFor(() => expect(screen.getByTestId('tab-strip')).toBeInTheDocument()); + + fireEvent.click(screen.getByTestId('copy-body-image-btn')); + + await waitFor(() => + expect(screen.getByRole('status').textContent).toBe('正文图片已下载'), + ); + }); }); describe('Toolbar', () => { diff --git a/apps/web/src/App.tsx b/apps/web/src/App.tsx index 05de4f9..78fa852 100644 --- a/apps/web/src/App.tsx +++ b/apps/web/src/App.tsx @@ -35,6 +35,7 @@ import { exportMdpkg, ENTRY_FILENAME } from './lib/exportMdpkg' import { WARNING_EXPORT_MD } from './lib/export' import { exportDocx } from './lib/exportDocx' import { toZip, toMarkdown } from '@md-bundle/app-kit/vendor' +import { copyImageToClipboard } from '@md-bundle/app-kit/clipboard' import { buildHtmlDocument } from './lib/exportHtml' import { exportPngFromMarkdown } from './lib/exportPng' import { downloadBlob, downloadText } from './lib/download' @@ -945,7 +946,7 @@ export default function App() { assets: activeTab.assets, theme: resolveEffectiveTheme(themePref), }) - const copied = await copyToClipboard(blob) + const copied = await copyImageToClipboard(blob) if (copied) { showInviteCardStatus('正文已复制为图片') } else { diff --git a/apps/web/src/lib/shareCard.ts b/apps/web/src/lib/shareCard.ts index 57ef0d0..7bc7711 100644 --- a/apps/web/src/lib/shareCard.ts +++ b/apps/web/src/lib/shareCard.ts @@ -3,13 +3,14 @@ // buildShareCardHtml(暗色卡片:标题 + 首行预览 + 字数/图数 + 角落 byline) // → shareCardSvg(svgFromHtml 委托,600×300 定尺寸) // → cardToPngBlob(svgToPngBlob 委托,canvas/Image 可注入) -// → copyToClipboard(ClipboardItem 剪贴板 seam,无 API 立即 false) +// → copyToClipboard(@app-kit/clipboard 的 image/png seam,无 API 立即 false) // → shareCardAsImage(组装全流程,返回 { copied, blob } —— 调用方决定兜底下载) // → canShare(无文档数据时禁用按钮的判定) // 单测(node)注入 fake canvas/Image 与 copy seam;真机/CI 走默认实现。 import { renderMarkdown } from '@md-bundle/renderer'; import { getThemeColor, type ThemeName } from '@md-bundle/editor'; +import { copyImageToClipboard } from '@md-bundle/app-kit/clipboard'; import { svgFromHtml, svgToPngBlob } from './exportPng'; import { bylineCornerBadgeHtml } from './byline'; @@ -139,21 +140,10 @@ export function cardToPngBlob(svg: string, opts: CardToPngBlobOptions = {}): Pro } /** - * Blob → 剪贴板(image/png)。默认实现:ClipboardItem + navigator.clipboard.write, - * try/catch 收敛为 boolean。守卫:无 ClipboardItem API(node/jsdom/旧浏览器)→ - * 立即返回 false,绝不抛错 —— 调用方走下载兜底。 + * Blob → 剪贴板(image/png)。实现已迁入 @md-bundle/app-kit/clipboard(#511), + * 这里保留旧名字给分享卡链路;「复制正文为图片」直接消费 app-kit 入口。 */ -export async function copyToClipboard(blob: Blob): Promise { - try { - if (typeof navigator === 'undefined' || typeof ClipboardItem === 'undefined') { - return false; - } - await navigator.clipboard.write([new ClipboardItem({ 'image/png': blob })]); - return true; - } catch { - return false; - } -} +export const copyToClipboard = copyImageToClipboard; export interface ShareCardAsImageOptions { title: string; diff --git a/apps/web/test-results/export-png.json b/apps/web/test-results/export-png.json index bec1f6a..63f1992 100644 --- a/apps/web/test-results/export-png.json +++ b/apps/web/test-results/export-png.json @@ -4,5 +4,6 @@ "width": 1600, "height": 922, "distinctColors": 9, - "emptyError": true + "emptyError": true, + "copyBodySeam": true } \ No newline at end of file diff --git a/apps/web/test/export-png.e2e.spec.ts b/apps/web/test/export-png.e2e.spec.ts index 30d2226..3ff5d7a 100644 --- a/apps/web/test/export-png.e2e.spec.ts +++ b/apps/web/test/export-png.e2e.spec.ts @@ -13,6 +13,7 @@ import { parsePngSize } from '../src/lib/pngMeta'; // 两个测试共享模块级证据状态(artifactBytes/pngSize/emptyError),且 afterAll 汇总落盘 // —— 必须串行:fullyParallel 会把同文件测试拆到不同 worker,模块状态互不可见,证据会丢。 test.describe.configure({ mode: 'serial' }); +test.use({ permissions: ['clipboard-write'] }); const here = dirname(fileURLToPath(import.meta.url)); const RES = join(here, '..', 'test-results'); @@ -26,6 +27,7 @@ let artifactBytes: number[] = []; let pngSize: { width: number; height: number } | null = null; let distinctColors = 0; let emptyError = false; +let copyBodySeam = false; test('exportPngFromMarkdown rasterizes CJK + emoji + inlined image in real Chromium', async ({ page, @@ -127,6 +129,19 @@ test('empty markdown → rejects with 文档为空 (deterministic, no corrupt PN emptyError = true; }); +test('顶栏「复制正文为图片」→ 以「已复制」或「已下载」收尾(seam 生效)', async ({ page }) => { + await page.goto('/'); + await page.getByTestId('file-input').setInputFiles(join(here, 'fixtures', 'hello.md')); + await page.getByTestId('copy-body-image-btn').click(); + // 两条分支都是票面 AC 允许的终态:复制成功 → 「正文已复制为图片」; + // 剪贴板不可用 → 「正文图片已下载」。断言语义是「有明确终态」,不是「某一条必须成功」。 + // 徽章 toast 同为 role=status,故按文案定位邀请卡状态条,避免 strict mode 歧义。 + await expect( + page.getByRole('status').filter({ hasText: /正文(已复制为图片|图片已下载)/ }), + ).toHaveCount(1); + copyBodySeam = true; +}); + test.afterAll(() => { mkdirSync(RES, { recursive: true }); if (artifactBytes.length > 8) { @@ -142,6 +157,7 @@ test.afterAll(() => { height: pngSize?.height ?? 0, distinctColors, emptyError, + copyBodySeam, }, null, 2, diff --git a/packages/app-kit/package.json b/packages/app-kit/package.json index d961d6a..815b69f 100644 --- a/packages/app-kit/package.json +++ b/packages/app-kit/package.json @@ -31,6 +31,7 @@ "./vendor": "./vendor/mdpkg-web.js", "./export": "./src/export/index.ts", "./export/*": "./src/export/*.ts", + "./clipboard": "./src/clipboard/index.ts", "./outline": "./src/outline/index.ts", "./outline/headings": "./src/outline/headings.ts", "./outline/OutlineMenu": "./src/outline/OutlineMenu.tsx" diff --git a/packages/app-kit/src/clipboard/index.ts b/packages/app-kit/src/clipboard/index.ts new file mode 100644 index 0000000..e4e78ea --- /dev/null +++ b/packages/app-kit/src/clipboard/index.ts @@ -0,0 +1,35 @@ +/** + * `@md-bundle/app-kit/clipboard` — 图片剪贴板公共入口(#511)。 + * 公开契约:永不抛错;成功 true,失败 false(调用方据此走兜底下载)。 + */ +import type { ClipboardWriter } from '../contracts'; + +/** + * 浏览器默认实现:ClipboardItem + navigator.clipboard.write。 + * 缺 API(node / jsdom / 旧浏览器)或写入被拒 → false。 + */ +export const browserClipboardWriter: ClipboardWriter = async (png) => { + try { + if (typeof navigator === 'undefined' || typeof ClipboardItem === 'undefined') return false; + if (!navigator.clipboard?.write) return false; + await navigator.clipboard.write([new ClipboardItem({ 'image/png': png })]); + return true; + } catch { + return false; + } +}; + +/** + * 把 PNG 放进剪贴板。Clairis 传 Electron 的 clipboard.writeImage 适配器。 + * 边界处再兜一层 try/catch —— 契约是「永不抛错」,注入实现也不例外。 + */ +export async function copyImageToClipboard( + png: Blob, + writer: ClipboardWriter = browserClipboardWriter, +): Promise { + try { + return await writer(png); + } catch { + return false; + } +} diff --git a/packages/app-kit/test/clipboard.test.ts b/packages/app-kit/test/clipboard.test.ts new file mode 100644 index 0000000..fa6e101 --- /dev/null +++ b/packages/app-kit/test/clipboard.test.ts @@ -0,0 +1,53 @@ +// #511:图片剪贴板 seam。公开契约只有一条:永不抛错,失败返回 false, +// 调用方据此走「兜底下载 + toast」。 +// @vitest-environment jsdom +import { afterEach, describe, expect, it, vi } from 'vitest'; + +const clipboard = await import('../src/clipboard/index'); + +const PNG = () => new Blob([new Uint8Array([0x89, 0x50, 0x4e, 0x47])], { type: 'image/png' }); + +class FakeClipboardItem { + items: Record; + constructor(items: Record) { + this.items = items; + } +} + +afterEach(() => { + vi.restoreAllMocks(); + delete (globalThis as { ClipboardItem?: unknown }).ClipboardItem; + delete (navigator as { clipboard?: unknown }).clipboard; +}); + +describe('app-kit clipboard surface', () => { + it('注入 writer 时走 writer,并把 blob 原样交给它', async () => { + const writer = vi.fn(async (_png: Blob) => true); + const png = PNG(); + await expect(clipboard.copyImageToClipboard(png, writer)).resolves.toBe(true); + expect(writer).toHaveBeenCalledTimes(1); + expect(writer.mock.calls[0]![0]).toBe(png); + }); + + it('writer 抛错也收敛为 false,绝不抛出', async () => { + const writer = vi.fn(async (_png: Blob) => { + throw new Error('clipboard denied'); + }); + await expect(clipboard.copyImageToClipboard(PNG(), writer)).resolves.toBe(false); + }); + + it('缺 ClipboardItem / clipboard.write 的默认实现返回 false', async () => { + await expect(clipboard.copyImageToClipboard(PNG())).resolves.toBe(false); + }); + + it('默认实现以 image/png 写入剪贴板', async () => { + const write = vi.fn(async (_items: FakeClipboardItem[]) => undefined); + (globalThis as { ClipboardItem?: unknown }).ClipboardItem = FakeClipboardItem; + Object.defineProperty(navigator, 'clipboard', { value: { write }, configurable: true }); + + await expect(clipboard.copyImageToClipboard(PNG())).resolves.toBe(true); + expect(write).toHaveBeenCalledTimes(1); + const arg = write.mock.calls[0]![0]![0]!; + expect(Object.keys(arg.items)).toEqual(['image/png']); + }); +});