Feat/webworker for incremental render (#51)
* feat: web worker for incremental render * feat: optimizing incremental render for date archives * feat: more work on web worker * fix: blogmark process handled defaulting wrong --------- Co-authored-by: hugo <hugoms@me.com>
This commit is contained in:
352
tests/engine/ApplyValidationWorkerService.test.ts
Normal file
352
tests/engine/ApplyValidationWorkerService.test.ts
Normal file
@@ -0,0 +1,352 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import {
|
||||
buildApplyValidationWorkerTasks,
|
||||
type ApplyValidationWorkerParams,
|
||||
type ApplyValidationLanguageParams,
|
||||
} from '../../src/main/engine/ApplyValidationWorkerService';
|
||||
import type { PostData } from '../../src/main/engine/PostEngine';
|
||||
import { buildGenerationPostIndex } from '../../src/main/engine/GenerationPostIndexService';
|
||||
import type { TargetedValidationPlan } from '../../src/main/engine/ValidationApplyPlannerService';
|
||||
import type { SerializedBlogGenerationOptions } from '../../src/main/engine/GenerationWorkerData';
|
||||
|
||||
function makePost(overrides: Partial<PostData> = {}): PostData {
|
||||
const createdAt = overrides.createdAt ?? new Date('2025-01-15T10:00:00Z');
|
||||
return {
|
||||
id: overrides.id ?? 'post-1',
|
||||
projectId: 'test',
|
||||
title: overrides.title ?? 'Test Post',
|
||||
slug: overrides.slug ?? 'test-post',
|
||||
content: overrides.content ?? '# Test',
|
||||
status: 'published',
|
||||
createdAt,
|
||||
updatedAt: overrides.updatedAt ?? createdAt,
|
||||
publishedAt: createdAt,
|
||||
tags: overrides.tags ?? [],
|
||||
categories: overrides.categories ?? [],
|
||||
availableLanguages: overrides.availableLanguages ?? [],
|
||||
};
|
||||
}
|
||||
|
||||
function makeBaseParams(overrides?: Partial<ApplyValidationWorkerParams>): ApplyValidationWorkerParams {
|
||||
const options: SerializedBlogGenerationOptions = {
|
||||
projectId: 'test',
|
||||
projectName: 'Test Blog',
|
||||
dataDir: '/data',
|
||||
baseUrl: 'https://example.com',
|
||||
};
|
||||
|
||||
return {
|
||||
options,
|
||||
maxPostsPerPage: 50,
|
||||
htmlDir: '/data/html',
|
||||
mediaItems: [],
|
||||
backlinksRecord: {},
|
||||
hashMapEntries: [],
|
||||
postFilePathEntries: [],
|
||||
postMediaLinksEntries: [],
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function makeEmptyTargetedPlan(overrides?: Partial<TargetedValidationPlan>): TargetedValidationPlan {
|
||||
return {
|
||||
requestedPostIds: new Set(),
|
||||
requestedCategorySet: new Set(),
|
||||
requestedTagSet: new Set(),
|
||||
requestedYears: new Set(),
|
||||
requestedYearMonths: new Set(),
|
||||
requestedYearMonthDays: new Set(),
|
||||
requestedPageSlugs: new Set(),
|
||||
requestRootRoutes: false,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe('buildApplyValidationWorkerTasks', () => {
|
||||
it('returns empty tasks when plan has no requests', () => {
|
||||
const posts = [makePost()];
|
||||
const postIndex = buildGenerationPostIndex(posts);
|
||||
|
||||
const tasks = buildApplyValidationWorkerTasks(
|
||||
makeBaseParams(),
|
||||
{
|
||||
targetedPlan: makeEmptyTargetedPlan(),
|
||||
publishedRoutePosts: posts,
|
||||
publishedListPosts: posts,
|
||||
generationPostIndex: postIndex,
|
||||
years: new Map(),
|
||||
yearMonths: new Map(),
|
||||
yearMonthDays: new Map(),
|
||||
},
|
||||
);
|
||||
|
||||
expect(tasks).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('creates a single-post task containing only requested post IDs', () => {
|
||||
const post1 = makePost({ id: 'p1', slug: 'post-one', tags: ['alpha'], categories: ['news'] });
|
||||
const post2 = makePost({ id: 'p2', slug: 'post-two', tags: ['beta'], categories: ['other'] });
|
||||
const posts = [post1, post2];
|
||||
const postIndex = buildGenerationPostIndex(posts);
|
||||
|
||||
const tasks = buildApplyValidationWorkerTasks(
|
||||
makeBaseParams(),
|
||||
{
|
||||
targetedPlan: makeEmptyTargetedPlan({
|
||||
requestedPostIds: new Set(['p1']),
|
||||
}),
|
||||
publishedRoutePosts: posts,
|
||||
publishedListPosts: posts,
|
||||
generationPostIndex: postIndex,
|
||||
years: new Map(),
|
||||
yearMonths: new Map(),
|
||||
yearMonthDays: new Map(),
|
||||
},
|
||||
);
|
||||
|
||||
const singleTasks = tasks.filter((t) => t.section === 'single');
|
||||
expect(singleTasks).toHaveLength(1);
|
||||
expect(singleTasks[0].posts).toHaveLength(1);
|
||||
expect(singleTasks[0].posts[0].id).toBe('p1');
|
||||
});
|
||||
|
||||
it('creates a category task containing only requested categories', () => {
|
||||
const post1 = makePost({ id: 'p1', categories: ['news'], tags: [] });
|
||||
const post2 = makePost({ id: 'p2', categories: ['other'], tags: [] });
|
||||
const posts = [post1, post2];
|
||||
const postIndex = buildGenerationPostIndex(posts);
|
||||
|
||||
const tasks = buildApplyValidationWorkerTasks(
|
||||
makeBaseParams(),
|
||||
{
|
||||
targetedPlan: makeEmptyTargetedPlan({
|
||||
requestedCategorySet: new Set(['news']),
|
||||
}),
|
||||
publishedRoutePosts: posts,
|
||||
publishedListPosts: posts,
|
||||
generationPostIndex: postIndex,
|
||||
years: new Map(),
|
||||
yearMonths: new Map(),
|
||||
yearMonthDays: new Map(),
|
||||
},
|
||||
);
|
||||
|
||||
const catTasks = tasks.filter((t) => t.section === 'category');
|
||||
expect(catTasks).toHaveLength(1);
|
||||
expect(catTasks[0].allCategories).toEqual(['news']);
|
||||
expect(catTasks[0].postsByCategoryEntries).toHaveLength(1);
|
||||
expect(catTasks[0].postsByCategoryEntries![0][0]).toBe('news');
|
||||
});
|
||||
|
||||
it('creates a tag task containing only requested tags', () => {
|
||||
const post1 = makePost({ id: 'p1', tags: ['alpha'] });
|
||||
const post2 = makePost({ id: 'p2', tags: ['beta'] });
|
||||
const posts = [post1, post2];
|
||||
const postIndex = buildGenerationPostIndex(posts);
|
||||
|
||||
const tasks = buildApplyValidationWorkerTasks(
|
||||
makeBaseParams(),
|
||||
{
|
||||
targetedPlan: makeEmptyTargetedPlan({
|
||||
requestedTagSet: new Set(['alpha']),
|
||||
}),
|
||||
publishedRoutePosts: posts,
|
||||
publishedListPosts: posts,
|
||||
generationPostIndex: postIndex,
|
||||
years: new Map(),
|
||||
yearMonths: new Map(),
|
||||
yearMonthDays: new Map(),
|
||||
},
|
||||
);
|
||||
|
||||
const tagTasks = tasks.filter((t) => t.section === 'tag');
|
||||
expect(tagTasks).toHaveLength(1);
|
||||
expect(tagTasks[0].allTags).toEqual(['alpha']);
|
||||
expect(tagTasks[0].postsByTagEntries).toHaveLength(1);
|
||||
expect(tagTasks[0].postsByTagEntries![0][0]).toBe('alpha');
|
||||
});
|
||||
|
||||
it('creates a date task containing only requested year/month/day archives', () => {
|
||||
const post1 = makePost({ id: 'p1', createdAt: new Date('2025-01-15T10:00:00Z') });
|
||||
const post2 = makePost({ id: 'p2', createdAt: new Date('2024-06-20T10:00:00Z') });
|
||||
const posts = [post1, post2];
|
||||
const postIndex = buildGenerationPostIndex(posts);
|
||||
|
||||
const years = new Map<number, Date>([[2025, new Date()], [2024, new Date()]]);
|
||||
const yearMonths = new Map<string, Date>([['2025/01', new Date()], ['2024/06', new Date()]]);
|
||||
const yearMonthDays = new Map<string, Date>([['2025/01/15', new Date()], ['2024/06/20', new Date()]]);
|
||||
|
||||
const tasks = buildApplyValidationWorkerTasks(
|
||||
makeBaseParams(),
|
||||
{
|
||||
targetedPlan: makeEmptyTargetedPlan({
|
||||
requestedYears: new Set([2025]),
|
||||
requestedYearMonths: new Set(['2025/01']),
|
||||
requestedYearMonthDays: new Set(['2025/01/15']),
|
||||
}),
|
||||
publishedRoutePosts: posts,
|
||||
publishedListPosts: posts,
|
||||
generationPostIndex: postIndex,
|
||||
years,
|
||||
yearMonths,
|
||||
yearMonthDays,
|
||||
},
|
||||
);
|
||||
|
||||
const dateTasks = tasks.filter((t) => t.section === 'date');
|
||||
expect(dateTasks).toHaveLength(1);
|
||||
expect(dateTasks[0].yearsEntries).toHaveLength(1);
|
||||
expect(dateTasks[0].yearsEntries![0][0]).toBe(2025);
|
||||
expect(dateTasks[0].yearMonthsEntries).toHaveLength(1);
|
||||
expect(dateTasks[0].yearMonthsEntries![0][0]).toBe('2025/01');
|
||||
expect(dateTasks[0].yearMonthDaysEntries).toHaveLength(1);
|
||||
expect(dateTasks[0].yearMonthDaysEntries![0][0]).toBe('2025/01/15');
|
||||
});
|
||||
|
||||
it('creates a core task when requestRootRoutes is true', () => {
|
||||
const posts = [makePost()];
|
||||
const postIndex = buildGenerationPostIndex(posts);
|
||||
|
||||
const tasks = buildApplyValidationWorkerTasks(
|
||||
makeBaseParams(),
|
||||
{
|
||||
targetedPlan: makeEmptyTargetedPlan({
|
||||
requestRootRoutes: true,
|
||||
}),
|
||||
publishedRoutePosts: posts,
|
||||
publishedListPosts: posts,
|
||||
generationPostIndex: postIndex,
|
||||
years: new Map(),
|
||||
yearMonths: new Map(),
|
||||
yearMonthDays: new Map(),
|
||||
},
|
||||
);
|
||||
|
||||
const coreTasks = tasks.filter((t) => t.section === 'core');
|
||||
expect(coreTasks).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('does not create core task when requestRootRoutes is false', () => {
|
||||
const posts = [makePost()];
|
||||
const postIndex = buildGenerationPostIndex(posts);
|
||||
|
||||
const tasks = buildApplyValidationWorkerTasks(
|
||||
makeBaseParams(),
|
||||
{
|
||||
targetedPlan: makeEmptyTargetedPlan({
|
||||
requestRootRoutes: false,
|
||||
requestedPostIds: new Set(['post-1']),
|
||||
}),
|
||||
publishedRoutePosts: posts,
|
||||
publishedListPosts: posts,
|
||||
generationPostIndex: postIndex,
|
||||
years: new Map(),
|
||||
yearMonths: new Map(),
|
||||
yearMonthDays: new Map(),
|
||||
},
|
||||
);
|
||||
|
||||
expect(tasks.filter((t) => t.section === 'core')).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('creates tasks across multiple sections for a comprehensive plan', () => {
|
||||
const post1 = makePost({
|
||||
id: 'p1', slug: 'target-post',
|
||||
categories: ['news'], tags: ['alpha'],
|
||||
createdAt: new Date('2025-01-15T10:00:00Z'),
|
||||
});
|
||||
const post2 = makePost({
|
||||
id: 'p2', slug: 'other-post',
|
||||
categories: ['other'], tags: ['beta'],
|
||||
createdAt: new Date('2024-06-20T10:00:00Z'),
|
||||
});
|
||||
const posts = [post1, post2];
|
||||
const postIndex = buildGenerationPostIndex(posts);
|
||||
|
||||
const years = new Map<number, Date>([[2025, new Date()]]);
|
||||
const yearMonths = new Map<string, Date>([['2025/01', new Date()]]);
|
||||
const yearMonthDays = new Map<string, Date>([['2025/01/15', new Date()]]);
|
||||
|
||||
const tasks = buildApplyValidationWorkerTasks(
|
||||
makeBaseParams(),
|
||||
{
|
||||
targetedPlan: makeEmptyTargetedPlan({
|
||||
requestRootRoutes: true,
|
||||
requestedPostIds: new Set(['p1']),
|
||||
requestedCategorySet: new Set(['news']),
|
||||
requestedTagSet: new Set(['alpha']),
|
||||
requestedYears: new Set([2025]),
|
||||
requestedYearMonths: new Set(['2025/01']),
|
||||
requestedYearMonthDays: new Set(['2025/01/15']),
|
||||
}),
|
||||
publishedRoutePosts: posts,
|
||||
publishedListPosts: posts,
|
||||
generationPostIndex: postIndex,
|
||||
years,
|
||||
yearMonths,
|
||||
yearMonthDays,
|
||||
},
|
||||
);
|
||||
|
||||
expect(tasks.filter((t) => t.section === 'core')).toHaveLength(1);
|
||||
expect(tasks.filter((t) => t.section === 'single')).toHaveLength(1);
|
||||
expect(tasks.filter((t) => t.section === 'category')).toHaveLength(1);
|
||||
expect(tasks.filter((t) => t.section === 'tag')).toHaveLength(1);
|
||||
expect(tasks.filter((t) => t.section === 'date')).toHaveLength(1);
|
||||
expect(tasks).toHaveLength(5);
|
||||
});
|
||||
|
||||
it('sets language prefix on tasks for language subtree rendering', () => {
|
||||
const posts = [makePost({ id: 'p1', tags: ['alpha'] })];
|
||||
const postIndex = buildGenerationPostIndex(posts);
|
||||
|
||||
const tasks = buildApplyValidationWorkerTasks(
|
||||
makeBaseParams(),
|
||||
{
|
||||
targetedPlan: makeEmptyTargetedPlan({
|
||||
requestedTagSet: new Set(['alpha']),
|
||||
}),
|
||||
publishedRoutePosts: posts,
|
||||
publishedListPosts: posts,
|
||||
generationPostIndex: postIndex,
|
||||
years: new Map(),
|
||||
yearMonths: new Map(),
|
||||
yearMonthDays: new Map(),
|
||||
languagePrefix: '/fr',
|
||||
mainLanguage: 'en',
|
||||
},
|
||||
);
|
||||
|
||||
expect(tasks).toHaveLength(1);
|
||||
expect(tasks[0].languagePrefix).toBe('/fr');
|
||||
expect(tasks[0].mainLanguage).toBe('en');
|
||||
expect(tasks[0].options.language).toBe('fr');
|
||||
});
|
||||
|
||||
it('uses all route posts as lookupPosts regardless of targeted plan', () => {
|
||||
const post1 = makePost({ id: 'p1', slug: 'target', tags: ['alpha'] });
|
||||
const post2 = makePost({ id: 'p2', slug: 'other', tags: ['beta'] });
|
||||
const posts = [post1, post2];
|
||||
const postIndex = buildGenerationPostIndex(posts);
|
||||
|
||||
const tasks = buildApplyValidationWorkerTasks(
|
||||
makeBaseParams(),
|
||||
{
|
||||
targetedPlan: makeEmptyTargetedPlan({
|
||||
requestedPostIds: new Set(['p1']),
|
||||
}),
|
||||
publishedRoutePosts: posts,
|
||||
publishedListPosts: posts,
|
||||
generationPostIndex: postIndex,
|
||||
years: new Map(),
|
||||
yearMonths: new Map(),
|
||||
yearMonthDays: new Map(),
|
||||
},
|
||||
);
|
||||
|
||||
// Single task has only 1 post to render...
|
||||
expect(tasks[0].posts).toHaveLength(1);
|
||||
// ...but lookupPosts contains ALL posts for slug resolution
|
||||
expect(tasks[0].lookupPosts).toHaveLength(2);
|
||||
});
|
||||
});
|
||||
@@ -1496,7 +1496,7 @@ describe('BlogGenerationEngine', () => {
|
||||
generateSpy.mockRestore();
|
||||
});
|
||||
|
||||
it('applies validation for a missing month by generating that month and its day archives only', async () => {
|
||||
it('applies validation for a missing month by generating that month and parent year only', async () => {
|
||||
const posts = [
|
||||
makePost({ id: '1', slug: 'jan-post', createdAt: new Date('2025-01-15T10:00:00Z') }),
|
||||
makePost({ id: '2', slug: 'feb-post', createdAt: new Date('2025-02-20T10:00:00Z') }),
|
||||
@@ -1520,13 +1520,17 @@ describe('BlogGenerationEngine', () => {
|
||||
existingHtmlUrlCount: 0,
|
||||
}, vi.fn());
|
||||
|
||||
// The requested month and its parent year are rendered
|
||||
expect(await fileExists(path.join(tempDir, 'html', '2025', 'index.html'))).toBe(true);
|
||||
expect(await fileExists(path.join(tempDir, 'html', '2025', '01', 'index.html'))).toBe(true);
|
||||
expect(await fileExists(path.join(tempDir, 'html', '2025', '01', '15', 'index.html'))).toBe(true);
|
||||
// Child day archives are NOT cascaded into — only upward cascade
|
||||
expect(await fileExists(path.join(tempDir, 'html', '2025', '01', '15', 'index.html'))).toBe(false);
|
||||
// Unrelated months are not rendered
|
||||
expect(await fileExists(path.join(tempDir, 'html', '2025', '02', 'index.html'))).toBe(false);
|
||||
expect(await fileExists(path.join(tempDir, 'html', '2025', '02', '20', 'index.html'))).toBe(false);
|
||||
});
|
||||
|
||||
it('applies validation for a missing year by generating that year and nested month/day archives only', async () => {
|
||||
it('applies validation for a missing year by generating only that year archive', async () => {
|
||||
const posts = [
|
||||
makePost({ id: '1', slug: 'year-2025', createdAt: new Date('2025-01-15T10:00:00Z') }),
|
||||
makePost({ id: '2', slug: 'year-2024', createdAt: new Date('2024-02-20T10:00:00Z') }),
|
||||
@@ -1550,9 +1554,11 @@ describe('BlogGenerationEngine', () => {
|
||||
existingHtmlUrlCount: 0,
|
||||
}, vi.fn());
|
||||
|
||||
// Only the requested year archive is rendered — no downward cascade
|
||||
expect(await fileExists(path.join(tempDir, 'html', '2025', 'index.html'))).toBe(true);
|
||||
expect(await fileExists(path.join(tempDir, 'html', '2025', '01', 'index.html'))).toBe(true);
|
||||
expect(await fileExists(path.join(tempDir, 'html', '2025', '01', '15', 'index.html'))).toBe(true);
|
||||
expect(await fileExists(path.join(tempDir, 'html', '2025', '01', 'index.html'))).toBe(false);
|
||||
expect(await fileExists(path.join(tempDir, 'html', '2025', '01', '15', 'index.html'))).toBe(false);
|
||||
// Other years are not rendered
|
||||
expect(await fileExists(path.join(tempDir, 'html', '2024', 'index.html'))).toBe(false);
|
||||
expect(await fileExists(path.join(tempDir, 'html', '2024', '02', 'index.html'))).toBe(false);
|
||||
expect(await fileExists(path.join(tempDir, 'html', '2024', '02', '20', 'index.html'))).toBe(false);
|
||||
|
||||
@@ -86,9 +86,11 @@ describe('ValidationApplyPlannerService', () => {
|
||||
expect(targeted.requestedTagSet.has('tag-1')).toBe(true);
|
||||
expect(targeted.requestedYears.has(2025)).toBe(true);
|
||||
expect(targeted.requestedYearMonths.has('2025/01')).toBe(true);
|
||||
expect(targeted.requestedYearMonths.has('2025/02')).toBe(true);
|
||||
// 2025/02 should NOT be included — only directly affected months are rerendered
|
||||
expect(targeted.requestedYearMonths.has('2025/02')).toBe(false);
|
||||
expect(targeted.requestedYearMonthDays.has('2025/01/15')).toBe(true);
|
||||
expect(targeted.requestedYearMonthDays.has('2025/02/20')).toBe(true);
|
||||
// 2025/02/20 should NOT be included — only directly affected days are rerendered
|
||||
expect(targeted.requestedYearMonthDays.has('2025/02/20')).toBe(false);
|
||||
expect(targeted.requestedPageSlugs.has('about')).toBe(true);
|
||||
expect(targeted.requestRootRoutes).toBe(true);
|
||||
});
|
||||
|
||||
@@ -3236,7 +3236,7 @@ describe('IPC Handlers', () => {
|
||||
});
|
||||
|
||||
describe('blog:applyValidation', () => {
|
||||
it('should run apply via taskManager.runTask', async () => {
|
||||
it('should run grouped tasks via taskManager.runTask', async () => {
|
||||
const mockProject = createMockProject({ id: 'test-project', dataPath: '/mock/data' });
|
||||
mockProjectEngine.getActiveProject.mockResolvedValue(mockProject);
|
||||
mockProjectEngine.getDataDir.mockReturnValue('/mock/data/dir');
|
||||
@@ -3266,9 +3266,12 @@ describe('IPC Handlers', () => {
|
||||
existingHtmlUrlCount: 1,
|
||||
});
|
||||
|
||||
// Should run preparation as a grouped task
|
||||
expect(mockTaskManager.runTask).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
name: 'Apply Site Validation',
|
||||
name: 'Prepare Validation Apply',
|
||||
groupId: expect.stringContaining('site-validate-apply-'),
|
||||
groupName: 'Apply Site Validation',
|
||||
execute: expect.any(Function),
|
||||
}),
|
||||
);
|
||||
|
||||
293
tests/renderer/components/EditorCanonicalLanguageFocus.test.tsx
Normal file
293
tests/renderer/components/EditorCanonicalLanguageFocus.test.tsx
Normal file
@@ -0,0 +1,293 @@
|
||||
import React from 'react';
|
||||
import { describe, it, expect, beforeEach, vi, afterEach } from 'vitest';
|
||||
import { render, screen, act } from '@testing-library/react';
|
||||
|
||||
let monacoOnChange: ((value: string | undefined) => void) | null = null;
|
||||
|
||||
vi.mock('@monaco-editor/react', () => ({
|
||||
default: (props: { value?: string; defaultValue?: string; onChange?: (value: string | undefined) => void; key?: string | number }) => {
|
||||
monacoOnChange = props.onChange ?? null;
|
||||
return <div data-testid="monaco-editor" data-default-value={props.defaultValue} />;
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock('@milkdown/kit/core', () => {
|
||||
const makeChain = () => {
|
||||
const chain = {
|
||||
config: (callback: (ctx: { set: () => void; get: () => { markdownUpdated: () => void } }) => void) => {
|
||||
callback({ set: () => {}, get: () => ({ markdownUpdated: () => {} }) });
|
||||
return chain;
|
||||
},
|
||||
use: () => chain,
|
||||
};
|
||||
return chain;
|
||||
};
|
||||
return {
|
||||
Editor: { make: makeChain },
|
||||
defaultValueCtx: Symbol('defaultValueCtx'),
|
||||
editorViewCtx: Symbol('editorViewCtx'),
|
||||
rootCtx: Symbol('rootCtx'),
|
||||
remarkStringifyOptionsCtx: Symbol('remarkStringifyOptionsCtx'),
|
||||
remarkPluginsCtx: Symbol('remarkPluginsCtx'),
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock('@milkdown/kit/preset/commonmark', () => ({
|
||||
commonmark: {},
|
||||
toggleStrongCommand: { key: 'toggleStrong' },
|
||||
toggleEmphasisCommand: { key: 'toggleEmphasis' },
|
||||
wrapInBlockquoteCommand: { key: 'wrapInBlockquote' },
|
||||
wrapInBulletListCommand: { key: 'wrapInBulletList' },
|
||||
wrapInOrderedListCommand: { key: 'wrapInOrderedList' },
|
||||
insertHrCommand: { key: 'insertHr' },
|
||||
toggleInlineCodeCommand: { key: 'toggleInlineCode' },
|
||||
insertImageCommand: { key: 'insertImage' },
|
||||
toggleLinkCommand: { key: 'toggleLink' },
|
||||
}));
|
||||
|
||||
vi.mock('@milkdown/kit/preset/gfm', () => ({
|
||||
gfm: {},
|
||||
toggleStrikethroughCommand: { key: 'toggleStrike' },
|
||||
}));
|
||||
|
||||
vi.mock('@milkdown/kit/plugin/history', () => ({
|
||||
history: {},
|
||||
undoCommand: { key: 'undo' },
|
||||
redoCommand: { key: 'redo' },
|
||||
}));
|
||||
|
||||
vi.mock('@milkdown/kit/plugin/listener', () => ({
|
||||
listener: {},
|
||||
listenerCtx: Symbol('listenerCtx'),
|
||||
}));
|
||||
|
||||
vi.mock('@milkdown/kit/plugin/clipboard', () => ({ clipboard: {} }));
|
||||
vi.mock('@milkdown/kit/plugin/trailing', () => ({ trailing: {} }));
|
||||
vi.mock('@milkdown/kit/plugin/indent', () => ({ indent: {} }));
|
||||
vi.mock('@milkdown/kit/plugin/cursor', () => ({ cursor: {} }));
|
||||
|
||||
vi.mock('@milkdown/kit/utils', () => ({
|
||||
$node: () => ({}),
|
||||
$inputRule: () => ({}),
|
||||
$remark: () => ({}),
|
||||
$prose: () => ({}),
|
||||
replaceAll: () => () => {},
|
||||
callCommand: () => () => {},
|
||||
}));
|
||||
|
||||
vi.mock('@milkdown/react', () => ({
|
||||
Milkdown: () => <div data-testid="milkdown" />,
|
||||
MilkdownProvider: ({ children }: { children: React.ReactNode }) => <>{children}</>,
|
||||
useInstance: () => [false, () => ({ action: (action: unknown) => {
|
||||
if (typeof action === 'function') {
|
||||
action({ get: () => ({}) });
|
||||
}
|
||||
} })] as const,
|
||||
useEditor: (factory: (root: Node) => unknown) => {
|
||||
factory(document.createElement('div'));
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock('../../../src/renderer/components/Lightbox', () => ({
|
||||
Lightbox: () => null,
|
||||
useMarkdownImages: () => [],
|
||||
}));
|
||||
vi.mock('../../../src/renderer/components/PostLinks', () => ({ PostLinks: () => null }));
|
||||
vi.mock('../../../src/renderer/components/LinkedMediaPanel', () => ({ LinkedMediaPanel: () => null }));
|
||||
vi.mock('../../../src/renderer/components/ErrorModal', () => ({ ErrorModal: () => null }));
|
||||
vi.mock('../../../src/renderer/components/ConfirmDeleteModal', () => ({ ConfirmDeleteModal: () => null }));
|
||||
vi.mock('../../../src/renderer/components/SettingsView', () => ({ SettingsView: () => null }));
|
||||
vi.mock('../../../src/renderer/components/TagsView', () => ({ TagsView: () => null }));
|
||||
vi.mock('../../../src/renderer/components/TagInput', () => ({ TagInput: () => null }));
|
||||
vi.mock('../../../src/renderer/components/ChatPanel', () => ({ ChatPanel: () => null }));
|
||||
vi.mock('../../../src/renderer/components/ImportAnalysisView', () => ({ ImportAnalysisView: () => null }));
|
||||
vi.mock('../../../src/renderer/components/MetadataDiffPanel', () => ({ MetadataDiffPanel: () => null }));
|
||||
vi.mock('../../../src/renderer/components/GitDiffView/GitDiffView', () => ({ GitDiffView: () => null }));
|
||||
vi.mock('../../../src/renderer/components/InsertModal', () => ({ InsertModal: () => null }));
|
||||
vi.mock('../../../src/renderer/components/AISuggestionsModal/AISuggestionsModal', () => ({
|
||||
AISuggestionsModal: () => null,
|
||||
}));
|
||||
vi.mock('../../../src/renderer/components/Toast', () => ({
|
||||
showToast: {
|
||||
success: vi.fn(),
|
||||
error: vi.fn(),
|
||||
info: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
import { PostEditor } from '../../../src/renderer/components/Editor/PostEditor';
|
||||
import { useAppStore } from '../../../src/renderer/store';
|
||||
|
||||
const createPost = (overrides: Record<string, unknown> = {}) => ({
|
||||
id: 'post-1',
|
||||
title: 'Bookmarklet Post',
|
||||
content: '[Example](https://example.com)',
|
||||
excerpt: '',
|
||||
slug: 'bookmarklet-post',
|
||||
status: 'draft' as const,
|
||||
tags: [],
|
||||
categories: ['article'],
|
||||
featuredImage: null,
|
||||
publishedAt: null,
|
||||
createdAt: new Date('2026-03-13T12:00:00.000Z'),
|
||||
updatedAt: new Date('2026-03-13T12:00:00.000Z'),
|
||||
author: undefined,
|
||||
metadata: {},
|
||||
seoTitle: undefined,
|
||||
seoDescription: undefined,
|
||||
canonicalUrl: undefined,
|
||||
projectId: 'project-1',
|
||||
filePath: '',
|
||||
...overrides,
|
||||
});
|
||||
|
||||
describe('Editor keeps canonical language focus on post creation', () => {
|
||||
let metadataResolve: (value: unknown) => void;
|
||||
let eventHandlers: Map<string, EventListener[]>;
|
||||
|
||||
beforeEach(() => {
|
||||
monacoOnChange = null;
|
||||
eventHandlers = new Map();
|
||||
vi.clearAllMocks();
|
||||
|
||||
const neverSettles = new Promise<never>(() => {});
|
||||
|
||||
(window as any).addEventListener = vi.fn((event: string, handler: EventListener) => {
|
||||
if (!eventHandlers.has(event)) eventHandlers.set(event, []);
|
||||
eventHandlers.get(event)!.push(handler);
|
||||
});
|
||||
(window as any).removeEventListener = vi.fn((event: string, handler: EventListener) => {
|
||||
const handlers = eventHandlers.get(event);
|
||||
if (handlers) {
|
||||
const idx = handlers.indexOf(handler);
|
||||
if (idx >= 0) handlers.splice(idx, 1);
|
||||
}
|
||||
});
|
||||
const metadataPromise = new Promise((resolve) => {
|
||||
metadataResolve = resolve;
|
||||
});
|
||||
|
||||
(window as any).electronAPI.posts.get = vi.fn().mockResolvedValue(createPost({ language: null }));
|
||||
(window as any).electronAPI.posts.hasPublishedVersion = vi.fn().mockReturnValue(neverSettles);
|
||||
(window as any).electronAPI.posts.update = vi.fn().mockResolvedValue(null);
|
||||
(window as any).electronAPI.posts.getPreviewUrl = vi.fn().mockResolvedValue('http://localhost:4123/preview');
|
||||
(window as any).electronAPI.posts.getTranslations = vi.fn().mockResolvedValue([]);
|
||||
(window as any).electronAPI.posts.upsertTranslation = vi.fn().mockResolvedValue(null);
|
||||
(window as any).electronAPI.meta.getCategories = vi.fn().mockReturnValue(neverSettles);
|
||||
(window as any).electronAPI.meta.getProjectMetadata = vi.fn().mockReturnValue(metadataPromise);
|
||||
(window as any).electronAPI.templates.getEnabledByKind = vi.fn().mockResolvedValue([]);
|
||||
|
||||
useAppStore.setState({
|
||||
activeProject: { id: 'project-1', name: 'Test Blog', path: '/tmp/test' } as any,
|
||||
preferredEditorMode: 'markdown',
|
||||
posts: [],
|
||||
media: [],
|
||||
dirtyPosts: new Set<string>(),
|
||||
isLoading: false,
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
useAppStore.setState({
|
||||
dirtyPosts: new Set<string>(),
|
||||
});
|
||||
});
|
||||
|
||||
it('updates activeEditingLanguage when projectLanguage loads after initialization', async () => {
|
||||
render(<PostEditor postId="post-1" />);
|
||||
|
||||
// Wait for post data to load and initialization to complete
|
||||
await act(async () => {
|
||||
await Promise.resolve();
|
||||
await Promise.resolve();
|
||||
await Promise.resolve();
|
||||
});
|
||||
|
||||
// Before metadata resolves, the active flag should be 'en' (default projectLanguage)
|
||||
let flagContainer = screen.getByLabelText(/translations/i);
|
||||
let activeButton = flagContainer.querySelector('.active');
|
||||
expect(activeButton).toBeTruthy();
|
||||
expect(activeButton?.getAttribute('aria-label')).toContain('English');
|
||||
|
||||
// Now resolve projectMetadata with mainLanguage = 'de'
|
||||
await act(async () => {
|
||||
metadataResolve({ mainLanguage: 'de' });
|
||||
// Let React process the state updates
|
||||
await Promise.resolve();
|
||||
await Promise.resolve();
|
||||
await Promise.resolve();
|
||||
});
|
||||
|
||||
// After metadata resolves, the active flag should be 'de' (the canonical language)
|
||||
// Re-query DOM since buttons may have been re-rendered
|
||||
flagContainer = screen.getByLabelText(/translations/i);
|
||||
activeButton = flagContainer.querySelector('.active');
|
||||
expect(activeButton).toBeTruthy();
|
||||
expect(activeButton?.getAttribute('aria-label')).toContain('German');
|
||||
});
|
||||
|
||||
it('does not create translation draft when typing after projectLanguage loads', async () => {
|
||||
render(<PostEditor postId="post-1" />);
|
||||
|
||||
// Wait for post data to load and initialization to complete
|
||||
await act(async () => {
|
||||
await Promise.resolve();
|
||||
await Promise.resolve();
|
||||
await Promise.resolve();
|
||||
});
|
||||
|
||||
// Resolve projectMetadata with mainLanguage = 'de'
|
||||
await act(async () => {
|
||||
metadataResolve({ mainLanguage: 'de' });
|
||||
await Promise.resolve();
|
||||
await Promise.resolve();
|
||||
await Promise.resolve();
|
||||
});
|
||||
|
||||
// User types in the editor - this should go to canonical, not create a translation
|
||||
await act(async () => {
|
||||
monacoOnChange?.('[Example](https://example.com)\n\nNew paragraph');
|
||||
});
|
||||
|
||||
// No translation flag should appear for 'en' translation
|
||||
const flagContainer = screen.getByLabelText(/translations/i);
|
||||
const allButtons = flagContainer.querySelectorAll('button');
|
||||
// Should only have 1 button (canonical 'de'), no 'en' translation button
|
||||
expect(allButtons).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('keeps canonical language focus when post has explicit language matching project', async () => {
|
||||
// Post created via IPC handler with language set explicitly
|
||||
(window as any).electronAPI.posts.get = vi.fn().mockResolvedValue(createPost({ language: 'de' }));
|
||||
|
||||
render(<PostEditor postId="post-1" />);
|
||||
|
||||
// Wait for initialization
|
||||
await act(async () => {
|
||||
await Promise.resolve();
|
||||
await Promise.resolve();
|
||||
await Promise.resolve();
|
||||
});
|
||||
|
||||
// Resolve projectMetadata (even though post already has language)
|
||||
await act(async () => {
|
||||
metadataResolve({ mainLanguage: 'de' });
|
||||
await Promise.resolve();
|
||||
await Promise.resolve();
|
||||
});
|
||||
|
||||
// The active flag should be 'de' (canonical)
|
||||
const flagContainer = screen.getByLabelText(/translations/i);
|
||||
const activeButton = flagContainer.querySelector('.active');
|
||||
expect(activeButton).toBeTruthy();
|
||||
expect(activeButton?.getAttribute('aria-label')).toContain('German');
|
||||
|
||||
// Typing should not create translations
|
||||
await act(async () => {
|
||||
monacoOnChange?.('[Example](https://example.com)\n\nNew content');
|
||||
});
|
||||
|
||||
const allButtons = screen.getByLabelText(/translations/i).querySelectorAll('button');
|
||||
expect(allButtons).toHaveLength(1);
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user