Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions apps/web/src/App.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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', () => {
Expand Down Expand Up @@ -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(<App />);
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', () => {
Expand Down
3 changes: 2 additions & 1 deletion apps/web/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand Down Expand Up @@ -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 {
Expand Down
20 changes: 5 additions & 15 deletions apps/web/src/lib/shareCard.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';

Expand Down Expand Up @@ -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<boolean> {
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;
Expand Down
3 changes: 2 additions & 1 deletion apps/web/test-results/export-png.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,5 +4,6 @@
"width": 1600,
"height": 922,
"distinctColors": 9,
"emptyError": true
"emptyError": true,
"copyBodySeam": true
}
16 changes: 16 additions & 0 deletions apps/web/test/export-png.e2e.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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');
Expand All @@ -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,
Expand Down Expand Up @@ -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) {
Expand All @@ -142,6 +157,7 @@ test.afterAll(() => {
height: pngSize?.height ?? 0,
distinctColors,
emptyError,
copyBodySeam,
},
null,
2,
Expand Down
1 change: 1 addition & 0 deletions packages/app-kit/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
35 changes: 35 additions & 0 deletions packages/app-kit/src/clipboard/index.ts
Original file line number Diff line number Diff line change
@@ -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<boolean> {
try {
return await writer(png);
} catch {
return false;
}
}
53 changes: 53 additions & 0 deletions packages/app-kit/test/clipboard.test.ts
Original file line number Diff line number Diff line change
@@ -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<string, unknown>;
constructor(items: Record<string, unknown>) {
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']);
});
});
Loading