π¬ A browser extension and desktop app that turns your clicks into step-by-step guides with annotated screenshots π
TypeScript browser-extensionchrome-extensiondocumentationfirefox-extensionguide-generatorlocal-firstmanifest-v3privacy-firstproductivityreactscreenshotstep-by-step-guidetutorialtypescriptworkflowwxt
feat(export): encode a guide as an animated mp4 or webm video
Luis Ortiz68b76c9b64fc
diff --git a/package.json b/package.jsonindex 9097512..3a6073c 100644--- a/package.json+++ b/package.json@@ -42,6 +42,7 @@"fflate": "^0.8.2","jspdf": "^4.2.1","lucide-react": "^0.577.0",+ "mediabunny": "^1.52.3","p-queue": "^9.1.1","radix-ui": "^1.4.3","react": "^19.2.4",diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex efc7915..e9c7529 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -64,6 +64,9 @@ importers:lucide-react:specifier: ^0.577.0version: 0.577.0([email protected])+ mediabunny:+ specifier: ^1.52.3+ version: 1.52.3p-queue:specifier: ^9.1.1version: 9.1.1@@ -1553,6 +1556,12 @@ packages:'@types/[email protected]':resolution: {integrity: sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw==}+ '@types/[email protected]':+ resolution: {integrity: sha512-d7/QsLRwF864A5mgIM/YrfiglHoYn7zgCcAoJgW404r+2DwnNr7EBbLnCWpmOMgH8y0te73L1AV6H1bmauaWFw==}++ '@types/[email protected]':+ resolution: {integrity: sha512-O5hkiFIcjjszPIYyUSyvScyvrBoV3NOEEZx/pMlsu44TKzWNkLVBBxnxJz42in5n3QIolYOcBYFCPZZ0h8SkwQ==}+'@types/[email protected]':resolution: {integrity: sha512-dWHzHa2WqEXI/O1E9OjrocMTKJl2mSrEolh1Iomrv6U+JuNwaHXsXx9bLu5gG7BUWFIN0skIQJQ/L1rIex4X6w==}@@ -2693,6 +2702,9 @@ packages:resolution: {integrity: sha512-9Yubnt3e8A0OKwxYSXyhLymGW4sCufcLG6VdiDdUGVkPhpqLxlvP5vl1983gQjJl3tqbrM731mjaZaP68AgosQ==}+ resolution: {integrity: sha512-rMGwH5fykDCSA55LG9aWkE433wwHrycq3J5mRf+djBnHBZzmJGvIwg6Qfcfr4rRkzkmrdmewxQozLkOM1H1C6Q==}+resolution: {integrity: sha512-8q7VEgMJW4J8tcfVPy8g09NcQwZdbwFEqhe/WZkoIzjn/3TGDwtOCYtXGxA3O8tPzpczCCDgv+P2P5y00ZJOOg==}engines: {node: '>= 8'}@@ -4981,6 +4993,12 @@ snapshots:'@types/[email protected]': {}+ '@types/[email protected]':+ dependencies:+ '@types/dom-webcodecs': 0.1.13++ '@types/[email protected]': {}+'@types/[email protected]': {}'@types/[email protected]':@@ -6079,6 +6097,11 @@ snapshots:+ dependencies:+ '@types/dom-mediacapture-transform': 0.1.12+ '@types/dom-webcodecs': 0.1.13+diff --git a/src/core/export/__tests__/video-export.test.ts b/src/core/export/__tests__/video-export.test.tsnew file mode 100644index 0000000..7b4ab3e--- /dev/null+++ b/src/core/export/__tests__/video-export.test.ts@@ -0,0 +1,296 @@+// @vitest-environment jsdom+import { describe, expect, it } from 'vitest';+import {+ easeInOut,+ FPS,+ findIdealZoomLevel,+ letterbox,+ overlapFrames,+ STEP_SECONDS,+ stepFrames,+ toFrames,+ tooltipPlacement,+ totalStepFrames,+ wrapLines,+ zoomCrop,+ zoomProgress,+} from '@/core/export/video-export';+import { FRAME_HEIGHT, FRAME_WIDTH } from '@/core/export/video-support';++const measure = (line: string) => line.length * 10;++describe('step timing', () => {+ it('holds every step for the structural 5.23 seconds', () => {+ expect(STEP_SECONDS).toBeCloseTo(5.23, 10);+ });++ it('rounds a step to 157 frames at 30 fps', () => {+ expect(FPS).toBe(30);+ expect(stepFrames()).toBe(157);+ });++ it('overlaps consecutive steps by ten frames', () => {+ expect(overlapFrames()).toBe(10);+ expect(toFrames(0.33)).toBe(10);+ });++ it('emits a single step without subtracting an overlap', () => {+ expect(totalStepFrames(1)).toBe(157);+ });++ it('subtracts one overlap per seam', () => {+ expect(totalStepFrames(2)).toBe(157 * 2 - 10);+ expect(totalStepFrames(6)).toBe(157 * 6 - 10 * 5);+ expect(totalStepFrames(6)).toBe(892);+ });++ it('returns nothing for a guide with no usable steps', () => {+ expect(totalStepFrames(0)).toBe(0);+ });+});++describe('zoomProgress', () => {+ it('stays fully zoomed out through the opening hold', () => {+ expect(zoomProgress(0)).toBe(0);+ expect(zoomProgress(44)).toBe(0);+ expect(zoomProgress(45)).toBe(0);+ });++ it('ramps across the transition window', () => {+ expect(zoomProgress(56)).toBeCloseTo(0.5, 2);+ });++ it('is fully zoomed in for the closing hold', () => {+ expect(zoomProgress(67)).toBe(1);+ expect(zoomProgress(156)).toBe(1);+ });++ it('rises monotonically', () => {+ let last = -1;+ for (let frame = 0; frame <= stepFrames(); frame++) {+ const value = zoomProgress(frame);+ expect(value).toBeGreaterThanOrEqual(last);+ last = value;+ }+ });+});++describe('easeInOut', () => {+ it('pins the endpoints exactly', () => {+ expect(easeInOut(0)).toBe(0);+ expect(easeInOut(1)).toBe(1);+ });++ it('passes through the midpoint', () => {+ expect(easeInOut(0.5)).toBeCloseTo(0.5, 10);+ });++ it('is symmetric about the midpoint', () => {+ for (const d of [0.05, 0.17, 0.3, 0.45]) {+ expect(easeInOut(0.5 + d)).toBeCloseTo(1 - easeInOut(0.5 - d), 10);+ }+ });++ it('increases monotonically', () => {+ let last = -1;+ for (let i = 0; i <= 100; i++) {+ const value = easeInOut(i / 100);+ expect(value).toBeGreaterThan(last);+ last = value;+ }+ });++ it('eases in slowly and out slowly', () => {+ expect(easeInOut(0.25)).toBeLessThan(0.25);+ expect(easeInOut(0.75)).toBeGreaterThan(0.75);+ });++ it('clamps input outside the unit range', () => {+ expect(easeInOut(-2)).toBe(0);+ expect(easeInOut(4)).toBe(1);+ });+});++describe('findIdealZoomLevel', () => {+ const zoom = (rect: { x: number; y: number; width: number; height: number }) =>+ findIdealZoomLevel(rect, 1000, 800, FRAME_WIDTH, FRAME_HEIGHT);++ it('refuses to zoom when the target already fills the frame', () => {+ expect(zoom({ x: 0, y: 0, width: 1000, height: 800 })).toBe(1);+ });++ it('caps at the composition ceiling for a target hugging the bottom-right', () => {+ expect(zoom({ x: 800, y: 640, width: 20, height: 16 })).toBe(3.5);+ });++ it('zooms further on a small target than on a large one', () => {+ const small = zoom({ x: 480, y: 380, width: 40, height: 40 });+ const large = zoom({ x: 300, y: 240, width: 400, height: 320 });+ expect(small).toBeGreaterThan(large);+ expect(large).toBeGreaterThanOrEqual(1);+ expect(small).toBeLessThanOrEqual(3.5);+ });++ it('never leaves the one-to-ceiling band', () => {+ for (const rect of [+ { x: 0, y: 0, width: 1, height: 1 },+ { x: 999, y: 799, width: 1, height: 1 },+ { x: 0, y: 0, width: 5000, height: 5000 },+ { x: 1000, y: 800, width: 10, height: 10 },+ ]) {+ const level = zoom(rect);+ expect(level).toBeGreaterThanOrEqual(1);+ expect(level).toBeLessThanOrEqual(3.5);+ }+ });+});++describe('zoomCrop', () => {+ const image = { width: 1000, height: 800 };+ const target = { x: 480, y: 380, width: 40, height: 40 };++ it('starts on the whole image', () => {+ expect(zoomCrop(image, target, 0)).toEqual({ x: 0, y: 0, width: 1000, height: 800 });+ });++ it('ends on a crop centred on the target', () => {+ const crop = zoomCrop(image, target, 1);+ const level = findIdealZoomLevel(target, image.width, image.height, FRAME_WIDTH, FRAME_HEIGHT);+ expect(crop.width).toBeCloseTo(image.width / level, 6);+ expect(crop.height).toBeCloseTo(image.height / level, 6);+ expect(crop.x + crop.width / 2).toBeCloseTo(target.x + target.width / 2, 6);+ expect(crop.y + crop.height / 2).toBeCloseTo(target.y + target.height / 2, 6);+ });++ it('lands halfway between the two at the midpoint', () => {+ const start = zoomCrop(image, target, 0);+ const middle = zoomCrop(image, target, 0.5);+ const end = zoomCrop(image, target, 1);+ expect(middle.width).toBeCloseTo((start.width + end.width) / 2, 6);+ expect(middle.x).toBeCloseTo((start.x + end.x) / 2, 6);+ expect(middle.width).toBeLessThan(start.width);+ expect(middle.width).toBeGreaterThan(end.width);+ });++ it('keeps the image aspect ratio at every point of the ramp', () => {+ for (let i = 0; i <= 20; i++) {+ const crop = zoomCrop(image, target, i / 20);+ expect(crop.width / crop.height).toBeCloseTo(image.width / image.height, 6);+ }+ });++ it('never samples outside the image', () => {+ const corners = [+ { x: 0, y: 0, width: 30, height: 20 },+ { x: 970, y: 780, width: 30, height: 20 },+ { x: 0, y: 780, width: 30, height: 20 },+ { x: 970, y: 0, width: 30, height: 20 },+ { x: 480, y: 380, width: 40, height: 40 },+ ];+ for (const rect of corners) {+ for (let i = 0; i <= 20; i++) {+ const crop = zoomCrop(image, rect, i / 20);+ expect(crop.x).toBeGreaterThanOrEqual(0);+ expect(crop.y).toBeGreaterThanOrEqual(0);+ expect(crop.x + crop.width).toBeLessThanOrEqual(image.width + 1e-9);+ expect(crop.y + crop.height).toBeLessThanOrEqual(image.height + 1e-9);+ }+ }+ });++ it('holds the full frame for a step with no target', () => {+ for (const t of [0, 0.5, 1]) {+ expect(zoomCrop(image, null, t)).toEqual({ x: 0, y: 0, width: 1000, height: 800 });+ }+ });++ it('holds the full frame when the ideal zoom is already one', () => {+ const filling = { x: 0, y: 0, width: 1000, height: 800 };+ expect(zoomCrop(image, filling, 1)).toEqual({ x: 0, y: 0, width: 1000, height: 800 });+ });+});++describe('letterbox', () => {+ it('centres a 16:10 capture inside a 16:9 frame with bars top and bottom', () => {+ const fit = letterbox(1280, 800, FRAME_WIDTH, FRAME_HEIGHT);+ expect(fit.width).toBe(1152);+ expect(fit.height).toBe(720);+ expect(fit.y).toBe(0);+ expect(fit.x).toBeCloseTo(64);+ });++ it('fills exactly when the aspect ratio already matches', () => {+ const fit = letterbox(1920, 1080, FRAME_WIDTH, FRAME_HEIGHT);+ expect(fit).toMatchObject({ width: 1280, height: 720, x: 0, y: 0 });+ });++ it('scales up a small capture instead of leaving it tiny', () => {+ expect(letterbox(640, 360, FRAME_WIDTH, FRAME_HEIGHT).scale).toBe(2);+ });++ it('preserves aspect ratio', () => {+ const fit = letterbox(3000, 1000, FRAME_WIDTH, FRAME_HEIGHT);+ expect(fit.width / fit.height).toBeCloseTo(3, 5);+ });+});++describe('wrapLines', () => {+ it('keeps a short description on one line', () => {+ expect(wrapLines('Click on branquias', 300, measure)).toEqual(['Click on branquias']);+ });++ it('wraps onto the next line when the current one overflows', () => {+ expect(wrapLines('aaa bbb ccc', 70, measure)).toEqual(['aaa bbb', 'ccc']);+ });++ it('truncates with an ellipsis at the line cap', () => {+ const lines = wrapLines('aaa bbb ccc ddd eee fff', 30, measure, 2);+ expect(lines).toHaveLength(2);+ expect(lines[1].endsWith('β¦')).toBe(true);+ });++ it('does not ellipsize when everything fits inside the cap', () => {+ expect(wrapLines('aaa bbb', 30, measure, 2).join(' ')).not.toContain('β¦');+ });++ it('returns nothing for blank text', () => {+ expect(wrapLines(' ', 300, measure)).toEqual([]);+ });+});++describe('tooltipPlacement', () => {+ const tooltip = { width: 400, height: 80 };++ it('sits below the target when there is room', () => {+ const at = tooltipPlacement({ x: 500, y: 200, width: 120, height: 40 }, tooltip);+ expect(at.below).toBe(true);+ expect(at.y).toBeGreaterThan(240);+ });++ it('flips above the target when below would overflow the frame', () => {+ const at = tooltipPlacement({ x: 500, y: 660, width: 120, height: 40 }, tooltip);+ expect(at.below).toBe(false);+ expect(at.y).toBeLessThan(660);+ });++ it('centres horizontally on the target', () => {+ const at = tooltipPlacement({ x: 440, y: 200, width: 400, height: 40 }, tooltip);+ expect(at.x).toBeCloseTo(440);+ });++ it('clamps to the left edge for a target near x=0', () => {+ const at = tooltipPlacement({ x: 0, y: 200, width: 40, height: 40 }, tooltip);+ expect(at.x).toBe(20);+ });++ it('clamps to the right edge for a target near the frame width', () => {+ const at = tooltipPlacement({ x: FRAME_WIDTH - 40, y: 200, width: 40, height: 40 }, tooltip);+ expect(at.x).toBe(FRAME_WIDTH - tooltip.width - 20);+ });++ it('keeps the tooltip inside the frame even when the target is offscreen low', () => {+ const at = tooltipPlacement({ x: 500, y: FRAME_HEIGHT, width: 0, height: 0 }, tooltip);+ expect(at.y).toBeGreaterThanOrEqual(20);+ expect(at.y + tooltip.height).toBeLessThanOrEqual(FRAME_HEIGHT - 20);+ });+});diff --git a/src/core/export/__tests__/video-support.test.ts b/src/core/export/__tests__/video-support.test.tsnew file mode 100644index 0000000..3d0e9d9--- /dev/null+++ b/src/core/export/__tests__/video-support.test.ts@@ -0,0 +1,126 @@+// @vitest-environment jsdom+import { afterEach, describe, expect, it, vi } from 'vitest';+import { AVC_CODEC, FRAME_HEIGHT, FRAME_WIDTH, VP9_CODEC } from '@/core/export/video-support';++interface ProbedConfig {+ codec: string;+ width: number;+ height: number;+}++afterEach(() => vi.unstubAllGlobals());++async function freshModule() {+ vi.resetModules();+ return import('@/core/export/video-support');+}++function stubEncoder(supported: (codec: string) => boolean, probed: ProbedConfig[] = []) {+ vi.stubGlobal('VideoEncoder', {+ isConfigSupported: async (config: ProbedConfig) => {+ probed.push(config);+ return { supported: supported(config.codec) };+ },+ });+ return probed;+}++describe('codec strings', () => {+ it('is the exact H.264 string mediabunny emits for 1280x720 at high quality', () => {+ expect(AVC_CODEC).toBe('avc1.64001f');+ });++ it('is the exact VP9 string mediabunny emits for 1280x720 at high quality', () => {+ expect(VP9_CODEC).toBe('vp09.00.31.08');+ });+});++describe('pickContainer', () => {+ it('returns mp4 when the High Profile string encodes', async () => {+ stubEncoder((codec) => codec === AVC_CODEC);+ const { pickContainer } = await freshModule();+ expect(await pickContainer()).toBe('mp4');+ });++ it('probes at the frame size the encoder will use, since the level depends on it', async () => {+ const probed = stubEncoder(() => false);+ const { pickContainer } = await freshModule();+ await pickContainer();+ expect(probed.length).toBeGreaterThan(0);+ expect(probed.every((c) => c.width === FRAME_WIDTH && c.height === FRAME_HEIGHT)).toBe(true);+ });++ it('never asks for a level below the one that carries 1280x720', async () => {+ const probed = stubEncoder(() => false);+ const { pickContainer } = await freshModule();+ await pickContainer();+ expect(probed.some((c) => c.codec.startsWith('avc1.6400'))).toBe(true);+ expect(probed.some((c) => /^avc1\.6400(0[0-9a-f]|1[0-9a-e])$/i.test(c.codec))).toBe(false);+ });++ it('falls back to webm when only Baseline encodes, since mediabunny would still ask for High', async () => {+ stubEncoder((codec) => codec.startsWith('avc1.42E0') || codec.startsWith('vp09'));+ const { pickContainer } = await freshModule();+ expect(await pickContainer()).toBe('webm');+ });++ it('falls back to webm when avc does not encode but vp9 does', async () => {+ stubEncoder((codec) => codec === VP9_CODEC);+ const { pickContainer } = await freshModule();+ expect(await pickContainer()).toBe('webm');+ });++ it('returns null when nothing encodes', async () => {+ stubEncoder(() => false);+ const { pickContainer } = await freshModule();+ expect(await pickContainer()).toBeNull();+ });++ it('returns null when WebCodecs is absent entirely', async () => {+ vi.stubGlobal('VideoEncoder', undefined);+ const { pickContainer } = await freshModule();+ expect(await pickContainer()).toBeNull();+ });++ it('treats a throwing probe as unsupported rather than crashing', async () => {+ vi.stubGlobal('VideoEncoder', {+ isConfigSupported: async () => {+ throw new TypeError('bad config');+ },+ });+ const { pickContainer } = await freshModule();+ expect(await pickContainer()).toBeNull();+ });++ it('probes the browser only once across repeated calls', async () => {+ const probed = stubEncoder(() => false);+ const { pickContainer } = await freshModule();+ await pickContainer();+ const afterFirst = probed.length;+ await pickContainer();+ expect(probed.length).toBe(afterFirst);+ });+});++describe('canExportVideo', () => {+ it('is true when the browser can encode the container we would write', async () => {+ stubEncoder((codec) => codec === AVC_CODEC);+ const { canExportVideo } = await freshModule();+ expect(await canExportVideo()).toBe(true);+ });++ it('is false when no codec we would request encodes', async () => {+ stubEncoder(() => false);+ const { canExportVideo } = await freshModule();+ expect(await canExportVideo()).toBe(false);+ });++ it('shares the memoised probe rather than testing the browser again', async () => {+ const probed = stubEncoder((codec) => codec === AVC_CODEC);+ const { canExportVideo, pickContainer } = await freshModule();+ await canExportVideo();+ const afterFirst = probed.length;+ await pickContainer();+ expect(probed.length).toBe(afterFirst);+ });+});diff --git a/src/core/export/video-export.ts b/src/core/export/video-export.tsnew file mode 100644index 0000000..004b5f7--- /dev/null+++ b/src/core/export/video-export.ts@@ -0,0 +1,459 @@+import { i18n } from '#imports';+import type { Branding } from '@/core/export/branding';+import { dataUrlToBytes, fitLogo, loadBranding } from '@/core/export/branding';+import type { ExportOptions } from '@/core/export/options';+import { loadExportOptions } from '@/core/export/options';+import { extractDomain, formatDate } from '@/core/export/utils';+import { FRAME_HEIGHT, FRAME_WIDTH, pickContainer } from '@/core/export/video-support';+import type { Guide, Screenshot, Step } from '@/core/guides/types';+import type { Ctx } from '@/core/screenshot/draw';+import { drawRoundedRect } from '@/core/screenshot/draw';+import { clamp, resolveTarget, resolveViewport } from '@/core/screenshot/geometry';+import { renderScreenshot } from '@/core/screenshot/render';++export const FPS = 30;+const STEP_ZOOMED_OUT_SEC = 1.5;+const STEP_ZOOM_TRANSITION_SEC = 0.73;+const STEP_ZOOMED_IN_SEC = 3;+const TRANSITION_DURATION_SEC = 0.33;+const COVER_SECONDS = 3;+const KEY_FRAME_INTERVAL_SEC = 2;++const ZOOM_MIN = 1;+const ZOOM_MAX = 3.5;+const ZOOM_PAD_RATIO = 0.15;++const BACKDROP = '#1E1B4B';+const MUTED = '#9CA3AF';+const ON_DARK = '#FFFFFF';++const TOOLTIP_BG = 'rgba(17, 15, 43, 0.92)';+const TOOLTIP_FONT_SIZE = 20;+const TOOLTIP_LINE_HEIGHT = 27;+const TOOLTIP_PADDING_X = 16;+const TOOLTIP_PADDING_Y = 12;+const TOOLTIP_RADIUS = 10;+const TOOLTIP_GAP = 14;+const TOOLTIP_MAX_LINES = 3;+const TOOLTIP_MAX_WIDTH_RATIO = 0.45;+const FRAME_PADDING = 20;++const COVER_MARGIN = 96;+const COVER_CELL_WIDTH = 300;++export const STEP_SECONDS = STEP_ZOOMED_OUT_SEC + STEP_ZOOM_TRANSITION_SEC + STEP_ZOOMED_IN_SEC;++export function toFrames(seconds: number, fps = FPS): number {+ return Math.round(seconds * fps);+}++export function stepFrames(fps = FPS): number {+ return toFrames(STEP_SECONDS, fps);+}++export function overlapFrames(fps = FPS): number {+ return toFrames(TRANSITION_DURATION_SEC, fps);+}++export function totalStepFrames(stepCount: number, fps = FPS): number {+ if (stepCount <= 0) return 0;+ return stepCount * stepFrames(fps) - (stepCount - 1) * overlapFrames(fps);+}++export function zoomProgress(frame: number, fps = FPS): number {+ const held = toFrames(STEP_ZOOMED_OUT_SEC, fps);+ const moving = toFrames(STEP_ZOOM_TRANSITION_SEC, fps);+ if (frame <= held) return 0;+ if (frame >= held + moving) return 1;+ return (frame - held) / moving;+}++export function easeInOut(t: number): number {+ const x = clamp(t, 0, 1);+ return x < 0.5 ? 4 * x ** 3 : 1 - (-2 * x + 2) ** 3 / 2;+}++export interface Rect {+ x: number;+ y: number;+ width: number;+ height: number;+}++interface Size {+ width: number;+ height: number;+}++export function findIdealZoomLevel(+ target: Rect,+ imgWidth: number,+ imgHeight: number,+ viewWidth: number,+ viewHeight: number,+): number {+ const nx = target.x / imgWidth;+ const ny = target.y / imgHeight;+ const needWidth = Math.min(target.width / imgWidth + 2 * ZOOM_PAD_RATIO, 1 - nx) * viewWidth;+ const needHeight = Math.min(target.height / imgHeight + 2 * ZOOM_PAD_RATIO, 1 - ny) * viewHeight;+ const zoom = Math.min(viewWidth / needWidth, viewHeight / needHeight);+ return Number.isFinite(zoom) ? clamp(zoom, ZOOM_MIN, ZOOM_MAX) : ZOOM_MIN;+}++export function zoomCrop(+ image: Size,+ target: Rect | null,+ eased: number,+ viewWidth = FRAME_WIDTH,+ viewHeight = FRAME_HEIGHT,+): Rect {+ const full = { x: 0, y: 0, width: image.width, height: image.height };+ if (!target) return full;++ const zoom = findIdealZoomLevel(target, image.width, image.height, viewWidth, viewHeight);+ if (zoom <= ZOOM_MIN) return full;++ const width = image.width / zoom;+ const height = image.height / zoom;+ const x = clamp(target.x + target.width / 2 - width / 2, 0, image.width - width);+ const y = clamp(target.y + target.height / 2 - height / 2, 0, image.height - height);+ const t = clamp(eased, 0, 1);++ return {+ x: x * t,+ y: y * t,+ width: image.width + (width - image.width) * t,+ height: image.height + (height - image.height) * t,+ };+}++export function letterbox(srcWidth: number, srcHeight: number, dstWidth: number, dstHeight: number) {+ const scale = Math.min(dstWidth / srcWidth, dstHeight / srcHeight);+ const width = srcWidth * scale;+ const height = srcHeight * scale;+ return { scale, width, height, x: (dstWidth - width) / 2, y: (dstHeight - height) / 2 };+}++export function wrapLines(+ text: string,+ maxWidth: number,+ measure: (line: string) => number,+ maxLines = TOOLTIP_MAX_LINES,+): string[] {+ const words = text.trim().split(/\s+/).filter(Boolean);+ if (words.length === 0) return [];++ const lines: string[] = [];+ let current = '';++ for (const word of words) {+ const candidate = current ? `${current} ${word}` : word;+ if (current && measure(candidate) > maxWidth) {+ lines.push(current);+ current = word;+ if (lines.length === maxLines) {+ lines[maxLines - 1] = `${lines[maxLines - 1]}β¦`;+ return lines;+ }+ } else {+ current = candidate;+ }+ }++ if (current) lines.push(current);+ return lines;+}++export function tooltipPlacement(+ target: Rect,+ tooltip: { width: number; height: number },+ frameWidth = FRAME_WIDTH,+ frameHeight = FRAME_HEIGHT,+) {+ const below = target.y + target.height + TOOLTIP_GAP;+ const fitsBelow = below + tooltip.height <= frameHeight - FRAME_PADDING;+ const rawY = fitsBelow ? below : target.y - TOOLTIP_GAP - tooltip.height;+ const rawX = target.x + target.width / 2 - tooltip.width / 2;+ return {+ x: clamp(rawX, FRAME_PADDING, Math.max(FRAME_PADDING, frameWidth - tooltip.width - FRAME_PADDING)),+ y: clamp(rawY, FRAME_PADDING, Math.max(FRAME_PADDING, frameHeight - tooltip.height - FRAME_PADDING)),+ below: fitsBelow,+ };+}++function logoBitmap(logo: NonNullable<Branding['logo']>): Promise<ImageBitmap> {+ const bytes = dataUrlToBytes(logo.dataUrl);+ return createImageBitmap(new Blob([bytes as BlobPart]));+}++function drawTooltip(ctx: Ctx, text: string, target: Rect) {+ ctx.font = `500 ${TOOLTIP_FONT_SIZE}px Poppins, sans-serif`;+ const lines = wrapLines(text, FRAME_WIDTH * TOOLTIP_MAX_WIDTH_RATIO, (line) => ctx.measureText(line).width);+ if (lines.length === 0) return;++ const textWidth = Math.max(...lines.map((line) => ctx.measureText(line).width));+ const width = textWidth + TOOLTIP_PADDING_X * 2;+ const height = lines.length * TOOLTIP_LINE_HEIGHT + TOOLTIP_PADDING_Y * 2;+ const at = tooltipPlacement(target, { width, height });++ ctx.fillStyle = TOOLTIP_BG;+ drawRoundedRect(ctx, at.x, at.y, width, height, TOOLTIP_RADIUS);+ ctx.fill();++ ctx.fillStyle = ON_DARK;+ ctx.textBaseline = 'top';+ lines.forEach((line, i) => {+ ctx.fillText(line, at.x + TOOLTIP_PADDING_X, at.y + TOOLTIP_PADDING_Y + i * TOOLTIP_LINE_HEIGHT);+ });+}++interface StepLayer {+ bitmap: ImageBitmap;+ fit: ReturnType<typeof letterbox>;+ target: Rect | null;+ description: string;+}++async function loadStepLayer(step: Step, screenshot: Screenshot): Promise<StepLayer> {+ const rendered = await renderScreenshot(screenshot, { format: 'image/webp', quality: 0.9 });+ const bitmap = await createImageBitmap(rendered);+ const viewport = resolveViewport(screenshot);+ const target = resolveTarget(screenshot);+ const sx = bitmap.width / viewport.width;+ const sy = bitmap.height / viewport.height;++ return {+ bitmap,+ fit: letterbox(bitmap.width, bitmap.height, FRAME_WIDTH, FRAME_HEIGHT),+ target: target+ ? {+ x: (target.x - viewport.x) * sx,+ y: (target.y - viewport.y) * sy,+ width: target.width * sx,+ height: target.height * sy,+ }+ : null,+ description: step.description,+ };+}++function drawStepFrame(ctx: Ctx, layer: StepLayer, frame: number) {+ const crop = zoomCrop(layer.bitmap, layer.target, easeInOut(zoomProgress(frame)));+ const { fit } = layer;+ ctx.drawImage(layer.bitmap, crop.x, crop.y, crop.width, crop.height, fit.x, fit.y, fit.width, fit.height);++ if (!layer.description) return;++ const scale = fit.width / crop.width;+ const anchor: Rect = layer.target+ ? {+ x: fit.x + (layer.target.x - crop.x) * scale,+ y: fit.y + (layer.target.y - crop.y) * scale,+ width: layer.target.width * scale,+ height: layer.target.height * scale,+ }+ : { x: FRAME_WIDTH / 2, y: FRAME_HEIGHT, width: 0, height: 0 };++ drawTooltip(ctx, layer.description, anchor);+}++async function drawCoverFrame(ctx: Ctx, guide: Guide, steps: Step[], brand: Branding) {+ ctx.fillStyle = BACKDROP;+ ctx.fillRect(0, 0, FRAME_WIDTH, FRAME_HEIGHT);+ ctx.textBaseline = 'top';++ let y = 150;+ ctx.fillStyle = MUTED;+ ctx.font = '700 14px Poppins, sans-serif';+ ctx.fillText(i18n.t('export.guideLabel').toUpperCase(), COVER_MARGIN, y);+ y += 34;++ ctx.fillStyle = ON_DARK;+ ctx.font = '700 52px Poppins, sans-serif';+ const titleWidth = FRAME_WIDTH - COVER_MARGIN * 2 - (brand.logo ? 240 : 0);+ for (const line of wrapLines(guide.title, titleWidth, (l) => ctx.measureText(l).width, 2)) {+ ctx.fillText(line, COVER_MARGIN, y);+ y += 64;+ }++ y += 26;+ ctx.strokeStyle = brand.accent;+ ctx.lineWidth = 2;+ ctx.beginPath();+ ctx.moveTo(COVER_MARGIN, y);+ ctx.lineTo(FRAME_WIDTH - COVER_MARGIN, y);+ ctx.stroke();+ y += 26;++ const domain = extractDomain(steps);+ const cells: Array<[string, string]> = [+ [i18n.t('export.steps').toUpperCase(), String(steps.length).padStart(2, '0')],+ [i18n.t('export.created').toUpperCase(), formatDate(guide.createdAt)],+ ];+ if (domain) cells.push([i18n.t('export.source').toUpperCase(), domain]);++ cells.forEach(([label, value], index) => {+ const x = COVER_MARGIN + index * COVER_CELL_WIDTH;+ ctx.fillStyle = MUTED;+ ctx.font = '700 12px Poppins, sans-serif';+ ctx.fillText(label, x, y);+ ctx.fillStyle = index === 0 ? brand.accent : ON_DARK;+ ctx.font = '700 30px Poppins, sans-serif';+ ctx.fillText(value, x, y + 20);+ });++ if (brand.logo) {+ const size = fitLogo(brand.logo, 200, 64);+ const bitmap = await logoBitmap(brand.logo);+ ctx.drawImage(bitmap, FRAME_WIDTH - COVER_MARGIN - size.width, 132, size.width, size.height);+ bitmap.close();+ }++ const footer = [brand.footer, brand.attribution ? i18n.t('export.madeWith') : ''].filter(Boolean).join(' Β· ');+ if (footer) {+ ctx.fillStyle = MUTED;+ ctx.font = '500 15px Poppins, sans-serif';+ ctx.fillText(footer, COVER_MARGIN, FRAME_HEIGHT - 96);+ }+}++export type VideoOptions = Pick<ExportOptions, 'cover'>;++export interface VideoExportControls {+ onProgress?: (done: number, total: number) => void;+ signal?: AbortSignal;+}++export interface VideoExportResult {+ blob: Blob;+ extension: string;+}++export async function exportGuideAsVideo(+ guide: Guide,+ steps: Step[],+ screenshots: Map<string, Screenshot>,+ exportOptions?: VideoOptions,+ controls: VideoExportControls = {},+): Promise<VideoExportResult> {+ const frames = steps.filter((step) => screenshots.has(step.id));+ if (frames.length === 0) throw new Error('This guide has no screenshots to turn into a video');++ const { BufferTarget, CanvasSource, Mp4OutputFormat, Output, QUALITY_HIGH, WebMOutputFormat } = await import(+ 'mediabunny'+ );++ const container = await pickContainer();+ if (!container) throw new Error('This browser cannot encode video');+ const mp4 = container === 'mp4';++ const [brand, options] = await Promise.all([+ loadBranding(),+ exportOptions ? Promise.resolve(exportOptions) : loadExportOptions(),+ ]);++ const canvas = document.createElement('canvas');+ canvas.width = FRAME_WIDTH;+ canvas.height = FRAME_HEIGHT;+ const ctx = canvas.getContext('2d');+ if (!ctx) throw new Error('Canvas 2D context unavailable');++ const output = new Output({+ format: mp4 ? new Mp4OutputFormat() : new WebMOutputFormat(),+ target: new BufferTarget(),+ });+ const source = new CanvasSource(canvas, {+ codec: mp4 ? 'avc' : 'vp9',+ quality: QUALITY_HIGH,+ keyFrameInterval: KEY_FRAME_INTERVAL_SEC,+ });+ output.addVideoTrack(source);+ await output.start();++ const span = stepFrames();+ const overlap = overlapFrames();+ const stride = span - overlap;+ const stepTotal = totalStepFrames(frames.length);+ const total = stepTotal + (options.cover ? 1 : 0);+ const loaded = new Map<number, StepLayer>();+ const { onProgress, signal } = controls;+ let done = 0;++ const layerAt = async (index: number) => {+ const cached = loaded.get(index);+ if (cached) return cached;+ const layer = await loadStepLayer(frames[index], screenshots.get(frames[index].id) as Screenshot);+ loaded.set(index, layer);+ return layer;+ };++ const releaseBefore = (index: number) => {+ for (const [key, layer] of loaded) {+ if (key < index) {+ layer.bitmap.close();+ loaded.delete(key);+ }+ }+ };++ const abortIfRequested = () => {+ if (signal?.aborted) throw new DOMException('Video export was aborted', 'AbortError');+ };++ try {+ const offset = options.cover ? COVER_SECONDS : 0;++ if (options.cover) {+ abortIfRequested();+ await drawCoverFrame(ctx, guide, frames, brand);+ await source.add(0, COVER_SECONDS);+ done += 1;+ onProgress?.(done, total);+ }++ for (let frame = 0; frame < stepTotal; frame++) {+ abortIfRequested();++ const index = Math.min(Math.floor(frame / stride), frames.length - 1);+ const local = frame - index * stride;+ const outgoing = index > 0 && local < overlap ? index - 1 : -1;++ const current = await layerAt(index);+ const previous = outgoing >= 0 ? await layerAt(outgoing) : null;+ releaseBefore(outgoing >= 0 ? outgoing : index);++ ctx.globalAlpha = 1;+ ctx.fillStyle = BACKDROP;+ ctx.fillRect(0, 0, FRAME_WIDTH, FRAME_HEIGHT);++ if (previous) {+ drawStepFrame(ctx, previous, local + stride);+ ctx.globalAlpha = (local + 1) / overlap;+ drawStepFrame(ctx, current, local);+ ctx.globalAlpha = 1;+ } else {+ drawStepFrame(ctx, current, local);+ }++ await source.add(offset + frame / FPS, 1 / FPS);+ done += 1;+ onProgress?.(done, total);+ }++ await output.finalize();+ } catch (error) {+ await output.cancel();+ throw error;+ } finally {+ for (const layer of loaded.values()) layer.bitmap.close();+ loaded.clear();+ }++ const buffer = output.target.buffer;+ if (!buffer) throw new Error('Video encoding produced no output');++ return {+ blob: new Blob([buffer], { type: mp4 ? 'video/mp4' : 'video/webm' }),+ extension: mp4 ? 'mp4' : 'webm',+ };+}diff --git a/src/core/export/video-support.ts b/src/core/export/video-support.tsnew file mode 100644index 0000000..becad2c--- /dev/null+++ b/src/core/export/video-support.ts@@ -0,0 +1,37 @@+export const FRAME_WIDTH = 1280;+export const FRAME_HEIGHT = 720;++export const AVC_CODEC = 'avc1.64001f';+export const VP9_CODEC = 'vp09.00.31.08';++export type VideoContainer = 'mp4' | 'webm';++async function encodes(codec: string): Promise<boolean> {+ try {+ const { supported } = await VideoEncoder.isConfigSupported({+ codec,+ width: FRAME_WIDTH,+ height: FRAME_HEIGHT,+ });+ return Boolean(supported);+ } catch {+ return false;+ }+}++async function probe(): Promise<VideoContainer | null> {+ if (typeof VideoEncoder === 'undefined') return null;+ if (await encodes(AVC_CODEC)) return 'mp4';+ return (await encodes(VP9_CODEC)) ? 'webm' : null;+}++let pending: Promise<VideoContainer | null> | undefined;++export function pickContainer(): Promise<VideoContainer | null> {+ pending ??= probe();+ return pending;+}++export async function canExportVideo(): Promise<boolean> {+ return (await pickContainer()) !== null;+}