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(export): export a guide as an animated gif

Luis Ortiz73321fc92ebe
diff --git a/package.json b/package.json
index 3a682b0..6355d7b 100644
--- a/package.json
+++ b/package.json
@@ -42,6 +42,7 @@
"dexie": "^4.3.0",
"docx": "^9.6.1",
"fflate": "^0.8.2",
+ "gifenc": "^1.0.3",
"jspdf": "^4.2.1",
"lucide-react": "^0.577.0",
"mediabunny": "^1.52.3",
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 8a638a5..bcf4fda 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -61,6 +61,9 @@ importers:
fflate:
specifier: ^0.8.2
version: 0.8.2
+ gifenc:
+ specifier: ^1.0.3
+ version: 1.0.3
jspdf:
specifier: ^4.2.1
version: 4.2.1(patch_hash=e301aed06890ed05f438774320bce683b16494cc9344453aa36d1d07f2b83e97)
@@ -2269,6 +2272,9 @@ packages:
resolution: {integrity: sha512-I9QVvBw5U/hw3RmWpYKRumUeaDgxTPd401x364rLmWBJcOQ753eov1eTgzDqRG9bqFIfDc7gfzcQEWrUri3o1A==}
+ resolution: {integrity: sha512-xdr6AdrfGBcfzncONUOlXMBuc5wJDtOueE3c5rdG0oNgtINLD+f2iFZltrBRZYzACRbKr+mSVU/x98zv2u3jmw==}
+
resolution: {integrity: sha512-L5bGsVkxJbJgdnwyuheIunkGatUF/zssUoxxjACCseZYAVbaqdh9Tsmmlkl8vYan09H7sbvKt4pS8GqKLBrEzA==}
hasBin: true
@@ -5705,6 +5711,8 @@ snapshots:
+
dependencies:
citty: 0.1.6
diff --git a/src/core/export/__tests__/options.test.ts b/src/core/export/__tests__/options.test.ts
index 0ca6e18..aa44974 100644
--- a/src/core/export/__tests__/options.test.ts
+++ b/src/core/export/__tests__/options.test.ts
@@ -29,9 +29,14 @@ describe('normaliseExportOptions', () => {
imageScale: 'small',
stepDescriptions: DEFAULT_EXPORT_OPTIONS.stepDescriptions,
resolution: DEFAULT_EXPORT_OPTIONS.resolution,
+ gifQuality: DEFAULT_EXPORT_OPTIONS.gifQuality,
});
});
+ it('rejects an unknown gif quality so the encoder never gets bogus dimensions', () => {
+ expect(normaliseExportOptions({ gifQuality: 'huge' }).gifQuality).toBe(DEFAULT_EXPORT_OPTIONS.gifQuality);
+ });
+
it('rejects an unknown resolution so the encoder never gets bogus dimensions', () => {
expect(normaliseExportOptions({ resolution: '4k' }).resolution).toBe(DEFAULT_EXPORT_OPTIONS.resolution);
expect(normaliseExportOptions({ resolution: '1080p' }).resolution).toBe('1080p');
diff --git a/src/core/export/gif-export.ts b/src/core/export/gif-export.ts
new file mode 100644
index 0000000..d873cb8
--- /dev/null
+++ b/src/core/export/gif-export.ts
@@ -0,0 +1,101 @@
+import { loadBranding } from '@/core/export/branding';
+import { type ExportOptions, GIF_SPECS, type GifSpec, loadExportOptions } from '@/core/export/options';
+import { isBlock } from '@/core/guides/blocks';
+import type { Guide, Screenshot, Step } from '@/core/guides/types';
+import { logger } from '@/lib/logger';
+import { composeGuideFrames, totalStepFrames } from './video-export';
+import { FRAME_HEIGHT, FRAME_WIDTH } from './video-support';
+
+export const GIF_MAX_COLORS = 128;
+export const GIF_MIN_DELAY_MS = 20;
+export const GIF_YIELD_EVERY = 8;
+
+export type GifOptions = Pick<ExportOptions, 'cover' | 'stepDescriptions' | 'gifQuality'>;
+
+export interface GifExportControls {
+ onProgress?: (encoded: number, frames: number) => void;
+ signal?: AbortSignal;
+}
+
+export interface GifExportResult {
+ blob: Blob;
+ extension: 'gif';
+}
+
+export function gifDelayMs(durationSec: number): number {
+ return Math.max(GIF_MIN_DELAY_MS, Math.round(durationSec * 100) * 10);
+}
+
+export function gifFrameCount(
+ steps: Step[],
+ screenshots: Map<string, Screenshot>,
+ cover: boolean,
+ spec: GifSpec,
+): number {
+ const frames = steps.filter((step) => isBlock(step) || screenshots.has(step.id));
+ return frames.length === 0 ? 0 : totalStepFrames(frames.length, spec.fps) + (cover ? 2 : 0);
+}
+
+function yieldToEventLoop(): Promise<void> {
+ return new Promise((resolve) => {
+ setTimeout(resolve, 0);
+ });
+}
+
+export async function exportGuideAsGif(
+ guide: Guide,
+ steps: Step[],
+ screenshots: Map<string, Screenshot>,
+ exportOptions?: GifOptions,
+ controls: GifExportControls = {},
+): Promise<GifExportResult> {
+ const frames = steps.filter((step) => isBlock(step) || screenshots.has(step.id));
+ if (frames.length === 0) throw new Error('This guide has no screenshots to turn into a GIF');
+
+ const { GIFEncoder, applyPalette, quantize } = await import('gifenc');
+
+ const [brand, options] = await Promise.all([
+ loadBranding(),
+ exportOptions ? Promise.resolve(exportOptions) : loadExportOptions(),
+ ]);
+
+ const spec = GIF_SPECS[options.gifQuality] ?? GIF_SPECS.medium;
+ const canvas = new OffscreenCanvas(spec.width, spec.height);
+ const ctx = canvas.getContext('2d');
+ if (!ctx) throw new Error('Canvas 2D context unavailable');
+ ctx.scale(spec.width / FRAME_WIDTH, spec.height / FRAME_HEIGHT);
+
+ const total = gifFrameCount(steps, screenshots, Boolean(options.cover), spec);
+ logger.info('[gif] encoding', { steps: frames.length, frames: total, ...spec });
+
+ const gif = GIFEncoder();
+ let written = 0;
+
+ await composeGuideFrames(
+ guide,
+ frames,
+ screenshots,
+ options,
+ brand,
+ ctx,
+ { width: spec.width, height: spec.height },
+ async (_at, duration) => {
+ const { data } = ctx.getImageData(0, 0, spec.width, spec.height);
+ const palette = quantize(data, GIF_MAX_COLORS);
+ gif.writeFrame(applyPalette(data, palette), spec.width, spec.height, {
+ palette,
+ delay: gifDelayMs(duration),
+ ...(written === 0 ? { repeat: 0 } : {}),
+ });
+ written += 1;
+ if (written % GIF_YIELD_EVERY === 0) await yieldToEventLoop();
+ },
+ controls,
+ spec.fps,
+ );
+
+ gif.finish();
+ const blob = new Blob([gif.bytes() as BlobPart], { type: 'image/gif' });
+ logger.info('[gif] encoded', { frames: written, bytes: blob.size });
+ return { blob, extension: 'gif' };
+}
diff --git a/src/core/export/options.ts b/src/core/export/options.ts
index d6b218c..567c3dc 100644
--- a/src/core/export/options.ts
+++ b/src/core/export/options.ts
@@ -12,6 +12,22 @@ export type VideoResolution = '720p' | '1080p';
export const VIDEO_RESOLUTIONS: VideoResolution[] = ['720p', '1080p'];
+export type GifQuality = 'low' | 'medium' | 'high';
+
+export interface GifSpec {
+ width: number;
+ height: number;
+ fps: number;
+}
+
+export const GIF_SPECS: Record<GifQuality, GifSpec> = {
+ low: { width: 320, height: 180, fps: 8 },
+ medium: { width: 480, height: 270, fps: 10 },
+ high: { width: 640, height: 360, fps: 15 },
+};
+
+export const GIF_QUALITIES: GifQuality[] = ['low', 'medium', 'high'];
+
export interface ExportOptions {
cover: boolean;
screenshots: boolean;
@@ -19,6 +35,7 @@ export interface ExportOptions {
imageScale: ImageScale;
stepDescriptions: boolean;
resolution: VideoResolution;
+ gifQuality: GifQuality;
}
export const DEFAULT_EXPORT_OPTIONS: ExportOptions = {
@@ -28,6 +45,7 @@ export const DEFAULT_EXPORT_OPTIONS: ExportOptions = {
imageScale: 'medium',
stepDescriptions: true,
resolution: '720p',
+ gifQuality: 'medium',
};
const bool = (value: unknown, fallback: boolean) => (typeof value === 'boolean' ? value : fallback);
@@ -45,6 +63,7 @@ export function normaliseExportOptions(value: unknown): ExportOptions {
resolution: VIDEO_RESOLUTIONS.includes(raw.resolution as VideoResolution)
? (raw.resolution as VideoResolution)
: DEFAULT_EXPORT_OPTIONS.resolution,
+ gifQuality: raw.gifQuality && raw.gifQuality in GIF_SPECS ? raw.gifQuality : DEFAULT_EXPORT_OPTIONS.gifQuality,
};
}
diff --git a/src/locales/de.yml b/src/locales/de.yml
index f2796a4..c6164f9 100644
--- a/src/locales/de.yml
+++ b/src/locales/de.yml
@@ -294,6 +294,10 @@ exportPreview:
stepDescriptions: "Schritttexte"
stepDescriptionsHint: "Den Schritttext in jedes Videobild einzeichnen"
resolution: "Videoqualität"
+ gifQuality: "GIF-Qualität"
+ gif_low: "Niedrig"
+ gif_medium: "Mittel"
+ gif_high: "Hoch"
res_720p: "720p"
res_1080p: "1080p"
title: "Export-Vorschau"
@@ -327,6 +331,7 @@ exportMenu:
html: HTML
markdown: Markdown
pdf: PDF
+ gif: GIF
video: Video
cancelProgress: "Abbrechen · $1 %"
diff --git a/src/locales/en.yml b/src/locales/en.yml
index 3ef91be..3cb2488 100644
--- a/src/locales/en.yml
+++ b/src/locales/en.yml
@@ -363,6 +363,10 @@ exportPreview:
stepDescriptions: "Step captions"
stepDescriptionsHint: "Draw the step text onto each video frame"
resolution: "Video quality"
+ gifQuality: "GIF quality"
+ gif_low: "Low"
+ gif_medium: "Medium"
+ gif_high: "High"
res_720p: "720p"
res_1080p: "1080p"
title: "Export preview"
@@ -396,6 +400,7 @@ exportMenu:
html: HTML
markdown: Markdown
pdf: PDF
+ gif: GIF
video: Video
cancelProgress: "Cancel · $1%"
diff --git a/src/locales/es.yml b/src/locales/es.yml
index 3b29ef0..6dae1bf 100644
--- a/src/locales/es.yml
+++ b/src/locales/es.yml
@@ -363,6 +363,10 @@ exportPreview:
stepDescriptions: "Textos de paso"
stepDescriptionsHint: "Dibujar el texto del paso en cada fotograma"
resolution: "Calidad de vídeo"
+ gifQuality: "Calidad del GIF"
+ gif_low: "Baja"
+ gif_medium: "Media"
+ gif_high: "Alta"
res_720p: "720p"
res_1080p: "1080p"
title: "Vista previa de exportación"
@@ -396,6 +400,7 @@ exportMenu:
html: HTML
markdown: Markdown
pdf: PDF
+ gif: GIF
video: Vídeo
cancelProgress: "Cancelar · $1 %"
diff --git a/src/locales/fr.yml b/src/locales/fr.yml
index 48c05d0..9bcd7d8 100644
--- a/src/locales/fr.yml
+++ b/src/locales/fr.yml
@@ -363,6 +363,10 @@ exportPreview:
stepDescriptions: "Textes d'étape"
stepDescriptionsHint: "Incruster le texte de l'étape sur chaque image"
resolution: "Qualité vidéo"
+ gifQuality: "Qualité du GIF"
+ gif_low: "Basse"
+ gif_medium: "Moyenne"
+ gif_high: "Haute"
res_720p: "720p"
res_1080p: "1080p"
title: "Aperçu de l’export"
@@ -396,6 +400,7 @@ exportMenu:
html: HTML
markdown: Markdown
pdf: PDF
+ gif: GIF
video: Vidéo
cancelProgress: "Annuler · $1 %"
diff --git a/src/locales/pt-BR.yml b/src/locales/pt-BR.yml
index bd6250e..7c7c92d 100644
--- a/src/locales/pt-BR.yml
+++ b/src/locales/pt-BR.yml
@@ -363,6 +363,10 @@ exportPreview:
stepDescriptions: "Textos da etapa"
stepDescriptionsHint: "Desenhar o texto da etapa em cada quadro"
resolution: "Qualidade do vídeo"
+ gifQuality: "Qualidade do GIF"
+ gif_low: "Baixa"
+ gif_medium: "Média"
+ gif_high: "Alta"
res_720p: "720p"
res_1080p: "1080p"
title: "Prévia da exportação"
@@ -396,6 +400,7 @@ exportMenu:
html: HTML
markdown: Markdown
pdf: PDF
+ gif: GIF
video: Vídeo
cancelProgress: "Cancelar · $1%"
diff --git a/src/locales/zh-CN.yml b/src/locales/zh-CN.yml
index 61a7d10..3c01cb0 100644
--- a/src/locales/zh-CN.yml
+++ b/src/locales/zh-CN.yml
@@ -363,6 +363,10 @@ exportPreview:
stepDescriptions: "步骤说明"
stepDescriptionsHint: "将步骤文字绘制到每一帧视频中"
resolution: "视频质量"
+ gifQuality: "GIF 质量"
+ gif_low: "低"
+ gif_medium: "中"
+ gif_high: "高"
res_720p: "720p"
res_1080p: "1080p"
title: "导出预览"
@@ -396,6 +400,7 @@ exportMenu:
html: HTML
markdown: Markdown
pdf: PDF
+ gif: GIF
video: 视频
cancelProgress: "取消 · $1%"
diff --git a/src/types/gifenc.d.ts b/src/types/gifenc.d.ts
new file mode 100644
index 0000000..4105b40
--- /dev/null
+++ b/src/types/gifenc.d.ts
@@ -0,0 +1,32 @@
+declare module 'gifenc' {
+ export type Palette = number[][];
+
+ export interface WriteFrameOptions {
+ palette?: Palette;
+ delay?: number;
+ transparent?: boolean;
+ dispose?: number;
+ first?: boolean;
+ repeat?: number;
+ }
+
+ export interface Encoder {
+ writeFrame(index: Uint8Array, width: number, height: number, options?: WriteFrameOptions): void;
+ finish(): void;
+ bytes(): Uint8Array;
+ }
+
+ export function GIFEncoder(): Encoder;
+
+ export function quantize(
+ rgba: Uint8Array | Uint8ClampedArray,
+ maxColors: number,
+ options?: { format?: 'rgb565' | 'rgb444' | 'rgba4444'; oneBitAlpha?: boolean; clearAlpha?: boolean },
+ ): Palette;
+
+ export function applyPalette(
+ rgba: Uint8Array | Uint8ClampedArray,
+ palette: Palette,
+ format?: 'rgb565' | 'rgb444' | 'rgba4444',
+ ): Uint8Array;
+}
diff --git a/src/ui/fullview/ExportPreviewModal.tsx b/src/ui/fullview/ExportPreviewModal.tsx
index c9a7904..79e6d91 100644
--- a/src/ui/fullview/ExportPreviewModal.tsx
+++ b/src/ui/fullview/ExportPreviewModal.tsx
@@ -1,4 +1,4 @@
-import { FileCode, FileDown, FileText, Loader2, Video } from 'lucide-react';
+import { FileCode, FileDown, FileImage, FileText, Loader2, Video } from 'lucide-react';
import { lazy, Suspense, useEffect, useRef, useState } from 'react';
import { i18n } from '#imports';
import { downloadBlob, downloadText, safeFilename } from '@/core/export/download';
@@ -6,6 +6,7 @@ import { exportGuideAsHTML } from '@/core/export/html-export';
import {
DEFAULT_EXPORT_OPTIONS,
type ExportOptions,
+ GIF_QUALITIES,
type ImageScale,
loadExportOptions,
saveExportOptions,
@@ -32,7 +33,7 @@ interface ExportPreviewModalProps {
screenshots: Map<string, Screenshot>;
}
-type ExportFormat = 'docx' | 'html' | 'markdown' | 'pdf' | 'video';
+type ExportFormat = 'docx' | 'gif' | 'html' | 'markdown' | 'pdf' | 'video';
type PreviewMode = 'document' | 'video';
export default function ExportPreviewModal({ open, onOpenChange, guide, steps, screenshots }: ExportPreviewModalProps) {
@@ -142,6 +143,16 @@ export default function ExportPreviewModal({ open, onOpenChange, guide, steps, s
} else if (format === 'docx') {
const { exportGuideAsDOCX } = await import('@/core/export/docx-export');
downloadBlob(await exportGuideAsDOCX(guide, steps, screenshots, options), safeFilename(guide.title, 'docx'));
+ } else if (format === 'gif') {
+ const controller = new AbortController();
+ downloadAbort.current = controller;
+ setDownloadProgress(0);
+ const { exportGuideAsGif } = await import('@/core/export/gif-export');
+ const { blob, extension } = await exportGuideAsGif(guide, steps, screenshots, options, {
+ signal: controller.signal,
+ onProgress: (encoded, frames) => setDownloadProgress(frames > 0 ? encoded / frames : 0),
+ });
+ downloadBlob(blob, safeFilename(guide.title, extension));
} else if (format === 'video') {
const controller = new AbortController();
downloadAbort.current = controller;
@@ -186,6 +197,7 @@ export default function ExportPreviewModal({ open, onOpenChange, guide, steps, s
{ key: 'docx', icon: FileText, label: i18n.t('exportMenu.docx') },
{ key: 'html', icon: FileCode, label: i18n.t('exportMenu.html') },
{ key: 'markdown', icon: FileText, label: i18n.t('exportMenu.markdown') },
+ { key: 'gif', icon: FileImage, label: i18n.t('exportMenu.gif') },
...(videoSupported ? [{ key: 'video' as const, icon: Video, label: i18n.t('exportMenu.video') }] : []),
];
@@ -269,9 +281,29 @@ export default function ExportPreviewModal({ open, onOpenChange, guide, steps, s
</div>
)}
+ <div className="pt-3 border-t border-border">
+ <div className="text-[12px] font-semibold text-foreground mb-2">{i18n.t('exportPreview.gifQuality')}</div>
+ <div className="flex gap-1.5">
+ {GIF_QUALITIES.map((value) => (
+ <button
+ key={value}
+ type="button"
+ onClick={() => update({ gifQuality: value })}
+ className={`flex-1 px-2 py-1.5 rounded-lg border text-[11px] transition-colors ${
+ options.gifQuality === value
+ ? 'border-accent text-accent'
+ : 'border-border text-muted-foreground hover:border-accent hover:text-foreground'
+ }`}
+ >
+ {i18n.t(`exportPreview.gif_${value}`)}
+ </button>
+ ))}
+ </div>
+ </div>
+
<div className="pt-3 border-t border-border space-y-1.5">
{formats.map(({ key, icon: Icon, label }) => {
- const cancellable = exporting === key && key === 'video';
+ const cancellable = exporting === key && (key === 'video' || key === 'gif');
return (
<Button
key={key}
diff --git a/src/ui/sidepanel/ExportMenu.tsx b/src/ui/sidepanel/ExportMenu.tsx
index e0776c7..abf4b3c 100644
--- a/src/ui/sidepanel/ExportMenu.tsx
+++ b/src/ui/sidepanel/ExportMenu.tsx
@@ -1,4 +1,4 @@
-import { Download, FileCode, FileDown, FileText, Loader2, Video } from 'lucide-react';
+import { Download, FileCode, FileDown, FileImage, FileText, Loader2, Video } from 'lucide-react';
import { useEffect, useRef, useState } from 'react';
import { i18n } from '#imports';
import { downloadBlob, downloadText, safeFilename } from '@/core/export/download';
@@ -17,7 +17,7 @@ interface ExportMenuProps {
screenshots: Map<string, Screenshot>;
}
-type ExportType = 'docx' | 'html' | 'markdown' | 'pdf' | 'video';
+type ExportType = 'docx' | 'gif' | 'html' | 'markdown' | 'pdf' | 'video';
export default function ExportMenu({
guideId,
@@ -28,9 +28,9 @@ export default function ExportMenu({
const [open, setOpen] = useState(false);
const [exporting, setExporting] = useState(false);
const [videoSupported, setVideoSupported] = useState(false);
- const [videoProgress, setVideoProgress] = useState<number | null>(null);
+ const [progress, setProgress] = useState<number | null>(null);
const menuRef = useRef<HTMLDivElement>(null);
- const videoAbort = useRef<AbortController | null>(null);
+ const abortRef = useRef<AbortController | null>(null);
useEffect(() => {
let active = true;
@@ -68,14 +68,24 @@ export default function ExportMenu({
} else if (type === 'markdown') {
const md = await exportGuideAsMarkdown(guide, steps, screenshots);
downloadText(md, safeFilename(guide.title, 'md'), 'text/markdown');
+ } else if (type === 'gif') {
+ const controller = new AbortController();
+ abortRef.current = controller;
+ setProgress(0);
+ const { exportGuideAsGif } = await import('@/core/export/gif-export');
+ const { blob, extension } = await exportGuideAsGif(guide, steps, screenshots, undefined, {
+ signal: controller.signal,
+ onProgress: (encoded, frames) => setProgress(frames > 0 ? encoded / frames : 0),
+ });
+ downloadBlob(blob, safeFilename(guide.title, extension));
} else if (type === 'video') {
const controller = new AbortController();
- videoAbort.current = controller;
- setVideoProgress(0);
+ abortRef.current = controller;
+ setProgress(0);
const { exportGuideAsVideo } = await import('@/core/export/video-export');
const { blob, extension } = await exportGuideAsVideo(guide, steps, screenshots, undefined, {
signal: controller.signal,
- onProgress: (encoded, frames) => setVideoProgress(frames > 0 ? encoded / frames : 0),
+ onProgress: (encoded, frames) => setProgress(frames > 0 ? encoded / frames : 0),
});
downloadBlob(blob, safeFilename(guide.title, extension));
} else {
@@ -84,8 +94,8 @@ export default function ExportMenu({
} catch (error) {
if (!(error instanceof DOMException && error.name === 'AbortError')) throw error;
} finally {
- videoAbort.current = null;
- setVideoProgress(null);
+ abortRef.current = null;
+ setProgress(null);
setExporting(false);
}
}
@@ -95,6 +105,7 @@ export default function ExportMenu({
{ type: 'html' as const, icon: FileCode, label: i18n.t('exportMenu.html') },
{ type: 'markdown' as const, icon: FileText, label: i18n.t('exportMenu.markdown') },
{ type: 'pdf' as const, icon: FileDown, label: i18n.t('exportMenu.pdf') },
+ { type: 'gif' as const, icon: FileImage, label: i18n.t('exportMenu.gif') },
...(videoSupported ? [{ type: 'video' as const, icon: Video, label: i18n.t('exportMenu.video') }] : []),
];
@@ -102,13 +113,13 @@ export default function ExportMenu({
<div ref={menuRef} className="relative">
<Button
size="sm"
- onClick={() => (videoProgress === null ? setOpen((prev) => !prev) : videoAbort.current?.abort())}
- disabled={exporting && videoProgress === null}
+ onClick={() => (progress === null ? setOpen((prev) => !prev) : abortRef.current?.abort())}
+ disabled={exporting && progress === null}
>
{exporting ? <Loader2 size={14} className="animate-spin" /> : <Download size={14} />}
- {videoProgress === null
+ {progress === null
? i18n.t('common.export')
- : i18n.t('exportMenu.cancelProgress', [String(Math.round(videoProgress * 100))])}
+ : i18n.t('exportMenu.cancelProgress', [String(Math.round(progress * 100))])}
</Button>
{open && !exporting && (