Skip to content

armgit / mimik

Public Imported from GitHub
0

🎬 A browser extension and desktop app that turns your clicks into step-by-step guides with annotated screenshots πŸ“–

feat(guides): copy a guide into an independent one

davbio870b67a158a8
diff --git a/src/core/guides/__tests__/duplicate.test.ts b/src/core/guides/__tests__/duplicate.test.ts
new file mode 100644
index 0000000..dfc17b7
--- /dev/null
+++ b/src/core/guides/__tests__/duplicate.test.ts
@@ -0,0 +1,194 @@
+import 'fake-indexeddb/auto';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+const { broadcasts } = vi.hoisted(() => {
+ const broadcasts: unknown[] = [];
+ globalThis.BroadcastChannel = class BroadcastChannel {
+ name: string;
+ constructor(name: string) {
+ this.name = name;
+ }
+ postMessage(message: unknown) {
+ broadcasts.push(message);
+ }
+ addEventListener() {}
+ removeEventListener() {}
+ close() {}
+ onmessage = null;
+ onmessageerror = null;
+ dispatchEvent() {
+ return true;
+ }
+ } as unknown as typeof BroadcastChannel;
+ return { broadcasts };
+});
+
+import { db } from '../db';
+import { createSnapshot, duplicateGuide, getGuide, getSnapshots, replaceScreenshot } from '../service';
+import type { Guide, Screenshot, Step } from '../types';
+
+function makeStep(overrides: Partial<Step> & { id: string; guideId: string }): Step {
+ return {
+ index: 0,
+ description: 'Test step',
+ action: 'click',
+ url: 'https://example.com',
+ timestamp: Date.now(),
+ ...overrides,
+ };
+}
+
+function makeScreenshot(overrides: Partial<Screenshot> & { id: string; stepId: string }): Screenshot {
+ return {
+ blob: new Blob(['img'], { type: 'image/png' }),
+ mimeType: 'image/png',
+ width: 800,
+ height: 600,
+ ...overrides,
+ };
+}
+
+async function seedGuide(id: string, extras?: Partial<Guide>): Promise<Guide> {
+ const guide: Guide = {
+ id,
+ title: 'Test Guide',
+ createdAt: Date.now(),
+ updatedAt: Date.now(),
+ stepIds: [],
+ starred: false,
+ deletedAt: null,
+ ...extras,
+ };
+ await db.guides.add(guide);
+ return guide;
+}
+
+afterEach(async () => {
+ await db.guides.clear();
+ await db.steps.clear();
+ await db.screenshots.clear();
+ await db.snapshots.clear();
+ await db.transcripts.clear();
+ broadcasts.length = 0;
+});
+
+describe('duplicateGuide', () => {
+ it('returns null for a guide that does not exist', async () => {
+ expect(await duplicateGuide('missing')).toBeNull();
+ });
+
+ it('copies steps and screenshots under fresh ids', async () => {
+ await seedGuide('g1', { stepIds: ['s1', 's2'] });
+ await db.steps.add(makeStep({ id: 's1', guideId: 'g1', index: 0, screenshotId: 'sc1' }));
+ await db.steps.add(makeStep({ id: 's2', guideId: 'g1', index: 1, screenshotId: 'sc2' }));
+ await db.screenshots.bulkAdd([
+ makeScreenshot({ id: 'sc1', stepId: 's1' }),
+ makeScreenshot({ id: 'sc2', stepId: 's2' }),
+ ]);
+
+ const copyId = await duplicateGuide('g1');
+ expect(copyId).not.toBeNull();
+ expect(copyId).not.toBe('g1');
+
+ const copy = await getGuide(copyId!);
+ expect(copy?.steps).toHaveLength(2);
+ expect(copy?.steps.map((s) => s.id)).not.toContain('s1');
+ expect(copy?.steps.map((s) => s.index)).toEqual([0, 1]);
+ expect(copy?.guide.stepIds).toEqual(copy?.steps.map((s) => s.id));
+ expect(copy?.steps.every((s) => s.guideId === copyId)).toBe(true);
+
+ // Each copied step points at a screenshot of its own, not the source's.
+ const copiedIds = copy?.steps.map((s) => s.screenshotId);
+ expect(copiedIds).not.toContain('sc1');
+ expect(copiedIds).not.toContain('sc2');
+ expect(copy?.screenshots.size).toBe(2);
+ });
+
+ it('leaves the source guide untouched', async () => {
+ await seedGuide('g1', { stepIds: ['s1'], title: 'Original' });
+ await db.steps.add(makeStep({ id: 's1', guideId: 'g1', screenshotId: 'sc1' }));
+ await db.screenshots.add(makeScreenshot({ id: 'sc1', stepId: 's1' }));
+
+ await duplicateGuide('g1');
+
+ const source = await getGuide('g1');
+ expect(source?.guide.title).toBe('Original');
+ expect(source?.guide.stepIds).toEqual(['s1']);
+ expect(source?.steps[0].screenshotId).toBe('sc1');
+ });
+
+ it('gives the copy screenshot rows of its own so edits do not leak between guides', async () => {
+ await seedGuide('g1', { stepIds: ['s1'] });
+ await db.steps.add(makeStep({ id: 's1', guideId: 'g1', screenshotId: 'sc1' }));
+ await db.screenshots.add(makeScreenshot({ id: 'sc1', stepId: 's1' }));
+
+ const copyId = await duplicateGuide('g1');
+ const copy = await getGuide(copyId!);
+ const copiedRow = copy!.screenshots.get(copy!.steps[0].id)!;
+
+ await db.screenshots.update(copiedRow.id, { edits: { alt: 'edited in the copy only' } });
+
+ expect((await db.screenshots.get('sc1'))?.edits).toBeUndefined();
+ });
+
+ it('starts the copy with no version history of its own', async () => {
+ await seedGuide('g1', { stepIds: ['s1'] });
+ await db.steps.add(makeStep({ id: 's1', guideId: 'g1', screenshotId: 'sc1' }));
+ await db.screenshots.add(makeScreenshot({ id: 'sc1', stepId: 's1' }));
+ await createSnapshot('g1');
+
+ const copyId = await duplicateGuide('g1');
+
+ expect(await getSnapshots(copyId!)).toHaveLength(0);
+ expect(await getSnapshots('g1')).toHaveLength(1);
+ });
+
+ it('does not carry the transcript over', async () => {
+ await seedGuide('g1', { stepIds: ['s1'] });
+ await db.steps.add(makeStep({ id: 's1', guideId: 'g1', narratedDescription: 'what I said' }));
+ await db.transcripts.add({
+ id: 't1',
+ guideId: 'g1',
+ epochMs: Date.now(),
+ lines: [{ text: 'what I said', startSeconds: 0, endSeconds: 1, stepId: 's1' }],
+ } as never);
+
+ const copyId = await duplicateGuide('g1');
+
+ expect(await db.transcripts.where('guideId').equals(copyId!).count()).toBe(0);
+ // The spoken original still rides along on the step itself.
+ const copy = await getGuide(copyId!);
+ expect(copy?.steps[0].narratedDescription).toBe('what I said');
+ });
+
+ it('copies only the screenshot each step currently points at', async () => {
+ await seedGuide('g1', { stepIds: ['s1'] });
+ await db.steps.add(makeStep({ id: 's1', guideId: 'g1', screenshotId: 'sc1' }));
+ await db.screenshots.add(makeScreenshot({ id: 'sc1', stepId: 's1' }));
+ // Leaves the superseded 'sc1' row behind for version history to revert to.
+ await replaceScreenshot('s1', new Blob(['new'], { type: 'image/png' }), { width: 10, height: 10 });
+ expect(await db.screenshots.where('stepId').equals('s1').count()).toBe(2);
+
+ const copyId = await duplicateGuide('g1');
+ const copy = await getGuide(copyId!);
+
+ expect(await db.screenshots.where('stepId').equals(copy!.steps[0].id).count()).toBe(1);
+ });
+
+ it('does not inherit starred, trashed or staging state', async () => {
+ await seedGuide('g1', { stepIds: [], starred: true, deletedAt: 123, staging: true });
+
+ const copyId = await duplicateGuide('g1');
+ const copy = await db.guides.get(copyId!);
+
+ expect(copy?.starred).toBe(false);
+ expect(copy?.deletedAt).toBeNull();
+ expect(copy?.staging).toBeUndefined();
+ });
+
+ it('announces the new guide on the guides channel', async () => {
+ await seedGuide('g1', { stepIds: [] });
+ await duplicateGuide('g1');
+ expect(broadcasts).toContainEqual({ type: 'mutated' });
+ });
+});
diff --git a/src/core/guides/service.ts b/src/core/guides/service.ts
index d9364d2..0028272 100644
--- a/src/core/guides/service.ts
+++ b/src/core/guides/service.ts
@@ -211,6 +211,69 @@ export async function createStep(step: Step): Promise<void> {
await db.steps.add(step);
}
+/**
+ * Copies a guide into a new, independent one β€” the long recording a user then trims down into
+ * several shorter guides. Steps and screenshot rows are copied outright under fresh ids, so the
+ * copy shares nothing that can be edited: {@link updateScreenshotEdits} writes a row in place, and
+ * a shared row would mean annotating one guide silently annotated the other.
+ *
+ * Snapshots are deliberately not carried over β€” the copy's original is the moment it was made, and
+ * a snapshot's screenshot rows point at ids that only exist in the source. Transcripts are not
+ * carried over either: their lines key to step ids that all changed here, and a verbatim transcript
+ * is the most sensitive thing stored, so it stays with the one guide the user recorded it on. The
+ * spoken text itself survives per step in `narratedDescription`, so "restore what I said" still
+ * works in the copy.
+ */
+export async function duplicateGuide(guideId: string): Promise<string | null> {
+ const copyId = await db.transaction('rw', db.guides, db.steps, db.screenshots, async () => {
+ const guide = await db.guides.get(guideId);
+ if (!guide) return null;
+ const steps = await db.steps.where('guideId').equals(guideId).sortBy('index');
+ // By id, not by stepId: replaceScreenshot leaves the superseded rows behind for version history
+ // to revert to, and the copy has no history that could ever reach them.
+ const screenshots = await db.screenshots
+ .where('id')
+ .anyOf(steps.map((s) => s.screenshotId).filter((id): id is string => !!id))
+ .toArray();
+
+ const newGuideId = crypto.randomUUID();
+ const stepIdMap = new Map(steps.map((step) => [step.id, crypto.randomUUID()]));
+ const screenshotIdMap = new Map(screenshots.map((row) => [row.id, crypto.randomUUID()]));
+ const now = Date.now();
+
+ const { staging: _staging, ...rest } = guide;
+ await db.guides.add({
+ ...rest,
+ id: newGuideId,
+ title: i18n.t('library.copyOfTitle', [guide.title]),
+ createdAt: now,
+ updatedAt: now,
+ stepIds: steps.map((step) => stepIdMap.get(step.id)!),
+ starred: false,
+ deletedAt: null,
+ });
+ await db.steps.bulkAdd(
+ steps.map((step, index) => ({
+ ...step,
+ id: stepIdMap.get(step.id)!,
+ guideId: newGuideId,
+ index,
+ screenshotId: step.screenshotId ? screenshotIdMap.get(step.screenshotId) : undefined,
+ })),
+ );
+ await db.screenshots.bulkAdd(
+ screenshots.map((row) => ({
+ ...row,
+ id: screenshotIdMap.get(row.id)!,
+ stepId: stepIdMap.get(row.stepId)!,
+ })),
+ );
+ return newGuideId;
+ });
+ if (copyId) notifyGuidesChanged({ type: 'mutated' });
+ return copyId;
+}
+
export async function mergeGuideInto(sourceGuideId: string, targetGuideId: string, atIndex: number): Promise<number> {
const moved = await db.transaction('rw', db.steps, db.guides, db.transcripts, db.guideMerges, async () => {
const incoming = await db.steps.where('guideId').equals(sourceGuideId).sortBy('index');