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): rebuild the pdf, docx and html layout with switchable sections

Luis Ortiz38e060095e65
diff --git a/src/core/export/__tests__/docx-export.test.ts b/src/core/export/__tests__/docx-export.test.ts
index c43002c..cd42be5 100644
--- a/src/core/export/__tests__/docx-export.test.ts
+++ b/src/core/export/__tests__/docx-export.test.ts
@@ -62,7 +62,8 @@ describe('exportGuideAsDOCX', () => {
const xml = await readDocumentXml(blob);
expect(xml).toContain('My Guide');
- expect(xml).toContain('export.stepsCount[1]');
+ expect(xml).toContain('EXPORT.STEPS');
+ expect(xml).toContain('>01</w:t>');
expect(xml).toContain('EXPORT.CREATED');
expect(xml).toContain('EXPORT.SOURCE');
expect(xml).toContain('example.com');
@@ -75,7 +76,8 @@ describe('exportGuideAsDOCX', () => {
const xml = await readDocumentXml(blob);
expect(xml).toContain('Test Guide');
- expect(xml).toContain('export.stepsCount[0]');
+ expect(xml).toContain('EXPORT.STEPS');
+ expect(xml).toContain('>00</w:t>');
expect(xml).not.toContain('Click the button');
});
diff --git a/src/core/export/__tests__/options.test.ts b/src/core/export/__tests__/options.test.ts
new file mode 100644
index 0000000..96e5f28
--- /dev/null
+++ b/src/core/export/__tests__/options.test.ts
@@ -0,0 +1,59 @@
+import { beforeEach, describe, expect, it } from 'vitest';
+import { fakeBrowser } from 'wxt/testing';
+import {
+ DEFAULT_EXPORT_OPTIONS,
+ IMAGE_SCALE_FACTORS,
+ loadExportOptions,
+ normaliseExportOptions,
+ saveExportOptions,
+} from '@/core/export/options';
+
+describe('normaliseExportOptions', () => {
+ it('returns the defaults for anything that is not an options object', () => {
+ for (const value of [undefined, null, 'nope', 42, []]) {
+ expect(normaliseExportOptions(value)).toEqual(DEFAULT_EXPORT_OPTIONS);
+ }
+ });
+
+ it('keeps valid values and replaces invalid ones field by field', () => {
+ const result = normaliseExportOptions({
+ cover: false,
+ screenshots: 'yes',
+ stepUrls: null,
+ imageScale: 'small',
+ });
+ expect(result).toEqual({
+ cover: false,
+ screenshots: DEFAULT_EXPORT_OPTIONS.screenshots,
+ stepUrls: DEFAULT_EXPORT_OPTIONS.stepUrls,
+ imageScale: 'small',
+ });
+ });
+
+ it('rejects an unknown image scale so no exporter can derive a NaN width', () => {
+ const result = normaliseExportOptions({ imageScale: 'enormous' });
+ expect(result.imageScale).toBe(DEFAULT_EXPORT_OPTIONS.imageScale);
+ expect(IMAGE_SCALE_FACTORS[result.imageScale]).toBeGreaterThan(0);
+ });
+});
+
+describe('export option persistence', () => {
+ beforeEach(() => {
+ fakeBrowser.reset();
+ });
+
+ it('defaults when nothing has been saved', async () => {
+ expect(await loadExportOptions()).toEqual(DEFAULT_EXPORT_OPTIONS);
+ });
+
+ it('round-trips a saved selection', async () => {
+ const options = { ...DEFAULT_EXPORT_OPTIONS, cover: false, imageScale: 'large' as const };
+ await saveExportOptions(options);
+ expect(await loadExportOptions()).toEqual(options);
+ });
+
+ it('survives a corrupted stored value', async () => {
+ await fakeBrowser.storage.local.set({ exportOptions: 'corrupted' });
+ expect(await loadExportOptions()).toEqual(DEFAULT_EXPORT_OPTIONS);
+ });
+});
diff --git a/src/core/export/docx-export.ts b/src/core/export/docx-export.ts
index 85a8dce..26be447 100644
--- a/src/core/export/docx-export.ts
+++ b/src/core/export/docx-export.ts
@@ -2,16 +2,25 @@ import {
AlignmentType,
BorderStyle,
Document,
+ ExternalHyperlink,
+ Footer,
+ Header,
ImageRun,
Packer,
+ PageNumber,
Paragraph,
Table,
TableCell,
+ TableLayoutType,
TableRow,
TextRun,
+ UnderlineType,
+ VerticalAlign,
WidthType,
} from 'docx';
import { i18n } from '#imports';
+import { type Branding, dataUrlToBytes, fitLogo, loadBranding } from '@/core/export/branding';
+import { type ExportOptions, IMAGE_SCALE_FACTORS, loadExportOptions } from '@/core/export/options';
import { blobToArrayBuffer, extractDomain, formatDate } from '@/core/export/utils';
import type { Guide, Screenshot, Step } from '@/core/guides/types';
import { logger } from '@/lib/logger';
@@ -23,6 +32,28 @@ const DOCX_MAX_IMAGE_HEIGHT = 640; // px @ 96dpi, fits one page after margins
const DOCX_STEP_INDENT = 900;
const DOCX_FONT_FAMILY = 'Helvetica';
+const MM = 56.7;
+const dxa = (mm: number) => Math.round(mm * MM);
+const px = (mm: number) => Math.round((mm / 25.4) * 96);
+
+const MARGIN_MM = 18.5;
+const CONTENT_MM = 210 - MARGIN_MM * 2;
+const NUM_COL_MM = 22;
+const COL_GAP_MM = 8;
+const TEXT_COL_MM = CONTENT_MM - NUM_COL_MM - COL_GAP_MM;
+const META_COL_MM = 43;
+const LOGO_MAX_W = px(34);
+const LOGO_MAX_H = px(15);
+
+const INK = '1E1B4B';
+const MUTED = '6B7280';
+const HAIR = 'E5E7EB';
+
+const NONE = { style: BorderStyle.NONE, size: 0, color: 'FFFFFF' };
+const NO_BORDERS = { top: NONE, right: NONE, bottom: NONE, left: NONE };
+
+const bare = (hex: string) => hex.slice(1).toUpperCase();
+
/** Scale screenshot to fit page bounds without upscaling or distorting. */
export function fitDocxImageSize(
screenshotWidth: number,
@@ -37,98 +68,146 @@ export function fitDocxImageSize(
};
}
-function buildGradientDividerParagraph(): Paragraph {
- const gradientSegments = ['4F46E5', '635BED', '8178F4', 'A4A1F9', 'C7D2FE', '9BD2FE', '60C8FB', '38BDF8'];
+function stepUrlLabel(url: string): string {
+ try {
+ const parsed = new URL(url);
+ const label = `${parsed.hostname.replace(/^www\./, '')}${parsed.pathname === '/' ? '' : parsed.pathname}`;
+ return label.length > 64 ? `${label.slice(0, 63)}…` : label;
+ } catch {
+ return url;
+ }
+}
+function plainCell(children: Paragraph[], widthMm: number, rightGapMm = 0, bottom = false): TableCell {
+ return new TableCell({
+ borders: NO_BORDERS,
+ width: { size: dxa(widthMm), type: WidthType.DXA },
+ margins: { top: 0, bottom: 0, left: 0, right: dxa(rightGapMm) },
+ ...(bottom ? { verticalAlign: VerticalAlign.BOTTOM } : {}),
+ children,
+ });
+}
+
+function label(text: string): Paragraph {
return new Paragraph({
- alignment: AlignmentType.CENTER,
- spacing: { after: 260 },
- children: gradientSegments.map(
- (color) =>
- new TextRun({
- text: '--------',
- font: DOCX_FONT_FAMILY,
- color,
- bold: true,
- size: 16,
- }),
- ),
+ children: [new TextRun({ text, bold: true, color: MUTED, size: 15, font: DOCX_FONT_FAMILY })],
});
}
-function buildMetaTable(guide: Guide, domain: string | null): Table {
- const baseCell = {
- borders: {
- top: { style: BorderStyle.NONE, size: 0, color: 'FFFFFF' },
- right: { style: BorderStyle.NONE, size: 0, color: 'FFFFFF' },
- bottom: { style: BorderStyle.NONE, size: 0, color: 'FFFFFF' },
- left: { style: BorderStyle.NONE, size: 0, color: 'FFFFFF' },
- },
- margins: { top: 0, bottom: 0, left: 80, right: 80 },
- };
+function buildLogoCell(brand: Branding): TableCell {
+ const children: Paragraph[] = [];
+ if (brand.logo) {
+ try {
+ const { width, height } = fitLogo(brand.logo, LOGO_MAX_W, LOGO_MAX_H);
+ children.push(
+ new Paragraph({
+ alignment: AlignmentType.RIGHT,
+ children: [
+ new ImageRun({ type: 'png', data: dataUrlToBytes(brand.logo.dataUrl), transformation: { width, height } }),
+ ],
+ }),
+ );
+ } catch (err) {
+ logger.warn('DOCX: failed to embed brand logo', err);
+ }
+ }
+ if (!children.length) children.push(new Paragraph({ children: [] }));
+ return plainCell(children, 40);
+}
- return new Table({
- width: { size: 70, type: WidthType.PERCENTAGE },
- alignment: AlignmentType.CENTER,
+function buildCover(guide: Guide, steps: Step[], domain: string | null, brand: Branding): Array<Paragraph | Table> {
+ const accent = bare(brand.accent);
+
+ const head = new Table({
+ width: { size: dxa(CONTENT_MM), type: WidthType.DXA },
+ layout: TableLayoutType.FIXED,
+ columnWidths: [dxa(CONTENT_MM - 40), dxa(40)],
rows: [
new TableRow({
+ cantSplit: true,
children: [
- new TableCell({
- ...baseCell,
- width: { size: domain ? 50 : 100, type: WidthType.PERCENTAGE },
- children: [
+ plainCell(
+ [
new Paragraph({
- alignment: AlignmentType.LEFT,
- spacing: { after: 40 },
+ spacing: { after: 360 },
children: [
new TextRun({
- text: i18n.t('export.created').toUpperCase(),
- font: DOCX_FONT_FAMILY,
+ text: i18n.t('export.guideLabel'),
bold: true,
- color: '6B7280',
- size: 14,
+ color: MUTED,
+ size: 16,
+ font: DOCX_FONT_FAMILY,
}),
],
}),
new Paragraph({
- alignment: AlignmentType.LEFT,
children: [
- new TextRun({ text: formatDate(guide.createdAt), font: DOCX_FONT_FAMILY, color: '1E1B4B', size: 24 }),
+ new TextRun({ text: guide.title, bold: true, color: INK, size: 60, font: DOCX_FONT_FAMILY }),
],
}),
],
+ CONTENT_MM - 40,
+ ),
+ buildLogoCell(brand),
+ ],
+ }),
+ ],
+ });
+
+ const rule = new Paragraph({
+ spacing: { before: 200, after: 280 },
+ border: { bottom: { style: BorderStyle.SINGLE, size: 10, color: INK, space: 4 } },
+ children: [],
+ });
+
+ const metaKeys = [i18n.t('export.steps').toUpperCase(), i18n.t('export.created').toUpperCase()];
+ const metaValues: Paragraph[][] = [
+ [
+ new Paragraph({
+ children: [
+ new TextRun({
+ text: String(steps.length).padStart(2, '0'),
+ bold: true,
+ color: accent,
+ size: 60,
+ font: DOCX_FONT_FAMILY,
}),
- ...(domain
- ? [
- new TableCell({
- ...baseCell,
- width: { size: 50, type: WidthType.PERCENTAGE },
- children: [
- new Paragraph({
- alignment: AlignmentType.LEFT,
- spacing: { after: 40 },
- children: [
- new TextRun({
- text: i18n.t('export.source').toUpperCase(),
- font: DOCX_FONT_FAMILY,
- bold: true,
- color: '6B7280',
- size: 14,
- }),
- ],
- }),
- new Paragraph({
- alignment: AlignmentType.LEFT,
- children: [new TextRun({ text: domain, font: DOCX_FONT_FAMILY, color: '4F46E5', size: 24 })],
- }),
- ],
- }),
- ]
- : []),
],
}),
],
+ [
+ new Paragraph({
+ children: [new TextRun({ text: formatDate(guide.createdAt), color: INK, size: 22, font: DOCX_FONT_FAMILY })],
+ }),
+ ],
+ ];
+
+ if (domain) {
+ metaKeys.push(i18n.t('export.source').toUpperCase());
+ metaValues.push([
+ new Paragraph({
+ children: [
+ new ExternalHyperlink({
+ link: `https://${domain}`,
+ children: [new TextRun({ text: domain, color: accent, size: 22, font: DOCX_FONT_FAMILY })],
+ }),
+ ],
+ }),
+ ]);
+ }
+
+ const widths = metaKeys.map(() => META_COL_MM);
+ const meta = new Table({
+ width: { size: dxa(CONTENT_MM), type: WidthType.DXA },
+ layout: TableLayoutType.FIXED,
+ columnWidths: widths.map((w) => dxa(w)),
+ rows: [
+ new TableRow({ cantSplit: true, children: metaKeys.map((k) => plainCell([label(k)], META_COL_MM, 4, true)) }),
+ new TableRow({ cantSplit: true, children: metaValues.map((v) => plainCell(v, META_COL_MM, 4, true)) }),
+ ],
});
+
+ return [head, rule, meta];
}
function getDocxImageType(mimeType: string): SupportedDocxImageType | null {
@@ -150,7 +229,7 @@ function getDocxImageType(mimeType: string): SupportedDocxImageType | null {
async function buildImageParagraph(
screenshot: Screenshot,
stepIndex: number,
- leftIndent = 0,
+ scale: number,
): Promise<Paragraph | null> {
const imageType = getDocxImageType(screenshot.mimeType);
if (!imageType) {
@@ -160,18 +239,14 @@ async function buildImageParagraph(
try {
const arrayBuffer = await blobToArrayBuffer(screenshot.blob);
- const { width, height } = fitDocxImageSize(screenshot.width, screenshot.height, leftIndent);
+ const fitted = fitDocxImageSize(screenshot.width, screenshot.height, DOCX_STEP_INDENT / 2);
+ const width = Math.max(1, Math.round(fitted.width * scale));
+ const height = Math.max(1, Math.round(fitted.height * scale));
return new Paragraph({
alignment: AlignmentType.LEFT,
- indent: { left: leftIndent },
- spacing: { after: 280 },
children: [
- new ImageRun({
- type: imageType,
- data: new Uint8Array(arrayBuffer),
- transformation: { width, height },
- }),
+ new ImageRun({ type: imageType, data: new Uint8Array(arrayBuffer), transformation: { width, height } }),
],
});
} catch (err) {
@@ -180,95 +255,207 @@ async function buildImageParagraph(
}
}
-export async function exportGuideAsDOCX(
- guide: Guide,
- steps: Step[],
- screenshots: Map<string, Screenshot>,
-): Promise<Blob> {
- const domain = extractDomain(steps);
- const coverChildren: Array<Paragraph | Table> = [
+async function buildStepTable(
+ step: Step,
+ screenshot: Screenshot | undefined,
+ brand: Branding,
+ opts: ExportOptions,
+): Promise<Table> {
+ const accent = bare(brand.accent);
+ const stepNumber = String(step.index + 1).padStart(2, '0');
+
+ const textChildren: Paragraph[] = [
new Paragraph({
- alignment: AlignmentType.CENTER,
- spacing: { before: 3300, after: 200 },
+ spacing: { after: 140 },
children: [
- new TextRun({
- text: i18n.t('export.stepsCount', [String(steps.length)]),
- font: DOCX_FONT_FAMILY,
- bold: true,
- color: '4F46E5',
- size: 20,
- }),
+ new TextRun({ text: step.description, bold: true, color: INK, size: 22, font: DOCX_FONT_FAMILY }),
+ ...(step.url && opts.stepUrls
+ ? [
+ new TextRun({ text: ' · ', color: MUTED, size: 18, font: DOCX_FONT_FAMILY }),
+ new ExternalHyperlink({
+ link: step.url,
+ children: [
+ new TextRun({
+ text: stepUrlLabel(step.url),
+ color: accent,
+ underline: { type: UnderlineType.SINGLE, color: accent },
+ size: 18,
+ font: DOCX_FONT_FAMILY,
+ }),
+ ],
+ }),
+ ]
+ : []),
],
}),
- buildGradientDividerParagraph(),
- new Paragraph({
- alignment: AlignmentType.CENTER,
- spacing: { after: 280 },
- children: [new TextRun({ text: guide.title, font: DOCX_FONT_FAMILY, bold: true, size: 44, color: '1E1B4B' })],
- }),
- buildMetaTable(guide, domain),
- new Paragraph({ spacing: { after: 420 } }),
];
- const children: Array<Paragraph | Table> = [...coverChildren];
+ if (screenshot) {
+ const imageParagraph = await buildImageParagraph(screenshot, step.index, IMAGE_SCALE_FACTORS[opts.imageScale]);
+ if (imageParagraph) textChildren.push(imageParagraph);
+ }
- if (steps.length > 0) {
- children.push(
- new Paragraph({
- pageBreakBefore: true,
+ return new Table({
+ width: { size: dxa(CONTENT_MM), type: WidthType.DXA },
+ layout: TableLayoutType.FIXED,
+ columnWidths: [dxa(NUM_COL_MM + COL_GAP_MM), dxa(TEXT_COL_MM)],
+ rows: [
+ new TableRow({
+ cantSplit: true,
+ children: [
+ plainCell(
+ [
+ new Paragraph({
+ children: [
+ new TextRun({ text: stepNumber, bold: true, color: accent, size: 60, font: DOCX_FONT_FAMILY }),
+ ],
+ }),
+ ],
+ NUM_COL_MM + COL_GAP_MM,
+ ),
+ new TableCell({
+ borders: { ...NO_BORDERS, top: { style: BorderStyle.SINGLE, size: 6, color: INK } },
+ width: { size: dxa(TEXT_COL_MM), type: WidthType.DXA },
+ margins: { top: dxa(2), bottom: 0, left: 0, right: 0 },
+ children: textChildren,
+ }),
+ ],
}),
- );
- }
+ ],
+ });
+}
- for (const step of steps) {
- const stepNumber = String(step.index + 1).padStart(2, '0');
+function buildFooter(brand: Branding): Footer {
+ const children: TextRun[] = [
+ new TextRun({ text: brand.footer, color: MUTED, size: 16, font: DOCX_FONT_FAMILY }),
+ new TextRun({
+ text: `\t${brand.attribution ? i18n.t('export.madeWith') : ''}\t`,
+ color: MUTED,
+ size: 16,
+ font: DOCX_FONT_FAMILY,
+ }),
+ new TextRun({
+ children: [PageNumber.CURRENT, ' / ', PageNumber.TOTAL_PAGES],
+ color: MUTED,
+ size: 16,
+ font: DOCX_FONT_FAMILY,
+ }),
+ ];
- children.push(
+ return new Footer({
+ children: [
new Paragraph({
- border: {
- top: {
- color: 'C7D2FE',
- size: 6,
- space: 1,
- style: BorderStyle.SINGLE,
- },
- },
- spacing: { before: 240, after: 120 },
- children: [new TextRun({ text: '', font: DOCX_FONT_FAMILY })],
+ border: { top: { style: BorderStyle.SINGLE, size: 4, color: HAIR, space: 6 } },
+ tabStops: [
+ { type: 'center', position: dxa(CONTENT_MM / 2) },
+ { type: 'right', position: dxa(CONTENT_MM) },
+ ],
+ children,
}),
- new Paragraph({
- indent: { left: DOCX_STEP_INDENT / 2 },
- spacing: { after: 180 },
- children: [
- new TextRun({ text: stepNumber, font: DOCX_FONT_FAMILY, bold: true, color: '818CF8', size: 32 }),
- new TextRun({ text: ' ', font: DOCX_FONT_FAMILY }),
- new TextRun({ text: step.description, font: DOCX_FONT_FAMILY, color: '1E1B4B', size: 24 }),
+ ],
+ });
+}
+
+function buildHeader(guide: Guide, brand: Branding, withLogo: boolean): Header {
+ const titleRun = new TextRun({ text: guide.title, bold: true, color: INK, size: 16, font: DOCX_FONT_FAMILY });
+
+ if (!withLogo || !brand.logo) {
+ return new Header({
+ children: [
+ new Paragraph({
+ border: { bottom: { style: BorderStyle.SINGLE, size: 4, color: HAIR, space: 4 } },
+ children: [titleRun],
+ }),
+ ],
+ });
+ }
+
+ const { width, height } = fitLogo(brand.logo, px(18), px(7));
+ return new Header({
+ children: [
+ new Table({
+ width: { size: dxa(CONTENT_MM), type: WidthType.DXA },
+ layout: TableLayoutType.FIXED,
+ columnWidths: [dxa(CONTENT_MM - 22), dxa(22)],
+ borders: {
+ top: NONE,
+ right: NONE,
+ left: NONE,
+ insideHorizontal: NONE,
+ insideVertical: NONE,
+ bottom: { style: BorderStyle.SINGLE, size: 4, color: HAIR },
+ },
+ rows: [
+ new TableRow({
+ cantSplit: true,
+ children: [
+ plainCell([new Paragraph({ children: [titleRun] })], CONTENT_MM - 22),
+ plainCell(
+ [
+ new Paragraph({
+ alignment: AlignmentType.RIGHT,
+ children: [
+ new ImageRun({
+ type: 'png',
+ data: dataUrlToBytes(brand.logo.dataUrl),
+ transformation: { width, height },
+ }),
+ ],
+ }),
+ ],
+ 22,
+ ),
+ ],
+ }),
],
}),
- );
-
- const screenshot = screenshots.get(step.id);
- if (screenshot) {
- const imageParagraph = await buildImageParagraph(screenshot, step.index, DOCX_STEP_INDENT / 2);
- if (imageParagraph) {
- children.push(imageParagraph);
- }
+ ],
+ });
+}
+
+export async function exportGuideAsDOCX(
+ guide: Guide,
+ steps: Step[],
+ screenshots: Map<string, Screenshot>,
+ options?: ExportOptions,
+): Promise<Blob> {
+ const opts = options ?? (await loadExportOptions());
+ const domain = extractDomain(steps);
+ const brand = await loadBranding();
+
+ const children: Array<Paragraph | Table> = opts.cover ? buildCover(guide, steps, domain, brand) : [];
+
+ for (const [i, step] of steps.entries()) {
+ if (i === 0 && opts.cover) {
+ children.push(new Paragraph({ pageBreakBefore: true, spacing: { after: 120 }, children: [] }));
}
+ children.push(await buildStepTable(step, opts.screenshots ? screenshots.get(step.id) : undefined, brand, opts));
+ children.push(new Paragraph({ spacing: { after: 300 }, children: [] }));
}
const doc = new Document({
- styles: {
- default: {
- document: {
- run: {
- font: DOCX_FONT_FAMILY,
- },
- },
- },
- },
+ styles: { default: { document: { run: { font: DOCX_FONT_FAMILY } } } },
sections: [
{
- properties: {},
+ properties: {
+ page: {
+ margin: {
+ top: dxa(MARGIN_MM),
+ bottom: dxa(MARGIN_MM),
+ left: dxa(MARGIN_MM),
+ right: dxa(MARGIN_MM),
+ },
+ },
+ titlePage: opts.cover,
+ },
+ headers: {
+ default: buildHeader(guide, brand, !opts.cover),
+ ...(opts.cover ? { first: new Header({ children: [new Paragraph({ children: [] })] }) } : {}),
+ },
+ footers: {
+ default: buildFooter(brand),
+ ...(opts.cover ? { first: buildFooter(brand) } : {}),
+ },
children,
},
],
diff --git a/src/core/export/html-export.ts b/src/core/export/html-export.ts
index 8f6528c..3ecc1d9 100644
--- a/src/core/export/html-export.ts
+++ b/src/core/export/html-export.ts
@@ -1,40 +1,113 @@
import { i18n } from '#imports';
-import { blobToBase64, escapeHtml, extractDomain, fetchFaviconBase64, formatDate } from '@/core/export/utils';
+import { fitLogo, loadBranding } from '@/core/export/branding';
+import { type ExportOptions, IMAGE_SCALE_FACTORS, loadExportOptions } from '@/core/export/options';
+import { blobToBase64, escapeHtml, extractDomain, formatDate } from '@/core/export/utils';
import type { Guide, Screenshot, Step } from '@/core/guides/types';
import { renderScreenshot } from '@/core/screenshot/render';
+const LOGO_MAX_WIDTH = 148;
+const LOGO_MAX_HEIGHT = 56;
+
+function stepUrlLabel(url: string): string {
+ try {
+ const parsed = new URL(url);
+ const label = `${parsed.hostname.replace(/^www\./, '')}${parsed.pathname === '/' ? '' : parsed.pathname}`;
+ return label.length > 72 ? `${label.slice(0, 71)}…` : label;
+ } catch {
+ return url;
+ }
+}
+
export async function exportGuideAsHTML(
guide: Guide,
steps: Step[],
screenshots: Map<string, Screenshot>,
+ options?: ExportOptions,
): Promise<string> {
+ const opts = options ?? (await loadExportOptions());
+ const brand = await loadBranding();
+ const accent = brand.accent;
+ const imgWidthPct = Math.round(IMAGE_SCALE_FACTORS[opts.imageScale] * 100);
+ const domain = extractDomain(steps);
const stepSections: string[] = [];
for (const step of steps) {
- const screenshot = screenshots.get(step.id);
+ const screenshot = opts.screenshots ? screenshots.get(step.id) : undefined;
let imgHtml = '';
if (screenshot) {
const b64 = await blobToBase64(await renderScreenshot(screenshot));
const altText = screenshot.edits?.alt || i18n.t('export.stepLabel', [String(step.index + 1)]);
- imgHtml = `<img src="data:${screenshot.mimeType};base64,${b64}" alt="${escapeHtml(altText)}" style="max-width:100%;border-radius:8px;box-shadow:0 1px 4px rgba(30,27,75,0.06);margin-top:16px;" />`;
+ imgHtml = `<img src="data:${screenshot.mimeType};base64,${b64}" alt="${escapeHtml(altText)}" style="display:block;width:${imgWidthPct}%;margin-top:14px;border:1px solid #CBD5E1;" />`;
}
const stepNumber = String(step.index + 1).padStart(2, '0');
+ const urlHtml =
+ step.url && opts.stepUrls
+ ? `<a href="${escapeHtml(step.url)}" target="_blank" rel="noopener" style="font-size:14px;font-weight:400;color:${accent};">${escapeHtml(stepUrlLabel(step.url))}</a>`
+ : '';
stepSections.push(`
- <div style="border-top:2px solid #C7D2FE;padding-top:24px;margin-bottom:40px;">
- <div style="display:flex;gap:16px;align-items:flex-start;">
- <span style="font-size:32px;font-weight:700;color:#818CF8;line-height:1;flex-shrink:0;min-width:48px;">${stepNumber}</span>
- <div style="flex:1;min-width:0;">
- <p style="margin:0;font-size:16px;line-height:1.6;color:#1E1B4B;">${escapeHtml(step.description)}</p>
- ${imgHtml}
- </div>
+ <section data-step="${step.index + 1}" style="display:flex;gap:26px;margin-bottom:52px;">
+ <div style="flex:0 0 76px;font-size:34px;font-weight:700;color:${accent};line-height:.9;">${stepNumber}</div>
+ <div style="flex:1;min-width:0;border-top:1px solid #1E1B4B;padding-top:12px;">
+ <p style="margin:0;font-size:17px;font-weight:700;line-height:1.45;color:#1E1B4B;">${escapeHtml(step.description)}${
+ urlHtml ? `<span style="color:#6B7280;font-weight:400;"> &nbsp;·&nbsp; </span>${urlHtml}` : ''
+ }</p>
+ ${imgHtml}
</div>
- </div>`);
+ </section>`);
}
- const domain = extractDomain(steps);
- const favicon = domain ? await fetchFaviconBase64(domain) : null;
+ let logoHtml = '';
+ if (brand.logo) {
+ const { width, height } = fitLogo(brand.logo, LOGO_MAX_WIDTH, LOGO_MAX_HEIGHT);
+ logoHtml = `<img src="${brand.logo.dataUrl}" width="${width}" height="${height}" alt="" style="flex-shrink:0;" />`;
+ }
+
+ const footerParts: string[] = [];
+ footerParts.push(brand.footer ? escapeHtml(brand.footer) : '');
+ footerParts.push(brand.attribution ? i18n.t('export.madeWith') : '');
+ const footerHtml = footerParts.some(Boolean)
+ ? `<footer data-doc-footer="true" style="margin-top:16px;padding-top:20px;border-top:1px solid #E5E7EB;display:flex;justify-content:space-between;gap:16px;font-size:13px;color:#6B7280;">
+ <span>${footerParts[0]}</span><span>${footerParts[1]}</span>
+ </footer>`
+ : '';
+
+ const metaCell = (label: string, value: string) => `
+ <div style="flex:0 0 190px;">
+ <div style="font-size:11px;font-weight:700;color:#6B7280;letter-spacing:0.06em;">${label}</div>
+ <div style="font-size:17px;color:#1E1B4B;margin-top:4px;">${value}</div>
+ </div>`;
+
+ const headerHtml = opts.cover
+ ? `<header data-cover="true" style="margin-bottom:56px;">
+ <div style="display:flex;align-items:flex-start;gap:24px;margin-bottom:26px;">
+ <div style="flex:1;">
+ <div style="font-size:11px;font-weight:700;color:#6B7280;letter-spacing:0.08em;">${i18n.t('export.guideLabel')}</div>
+ <h1 style="font-size:38px;font-weight:700;line-height:1.15;margin-top:18px;">${escapeHtml(guide.title)}</h1>
+ </div>
+ ${logoHtml}
+ </div>
+ <div style="border-top:2px solid #1E1B4B;padding-top:18px;display:flex;align-items:baseline;">
+ <div style="flex:0 0 190px;">
+ <div style="font-size:11px;font-weight:700;color:#6B7280;letter-spacing:0.06em;">${i18n.t('export.steps').toUpperCase()}</div>
+ <div style="font-size:38px;font-weight:700;color:${accent};line-height:1;margin-top:2px;">${String(steps.length).padStart(2, '0')}</div>
+ </div>
+ ${metaCell(i18n.t('export.created').toUpperCase(), formatDate(guide.createdAt))}
+ ${
+ domain
+ ? metaCell(
+ i18n.t('export.source').toUpperCase(),
+ `<a href="https://${escapeHtml(domain)}" target="_blank" rel="noopener" style="color:${accent};">${escapeHtml(domain)}</a>`,
+ )
+ : ''
+ }
+ </div>
+ </header>`
+ : `<header style="display:flex;align-items:center;gap:16px;margin-bottom:40px;padding-bottom:14px;border-bottom:1px solid #E5E7EB;">
+ <h1 style="flex:1;font-size:20px;font-weight:700;line-height:1.2;">${escapeHtml(guide.title)}</h1>
+ ${logoHtml}
+ </header>`;
return `<!DOCTYPE html>
<html lang="en">
@@ -47,31 +120,15 @@ export async function exportGuideAsHTML(
<link href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;600;700&display=swap" rel="stylesheet">
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
- body { font-family: 'Poppins', sans-serif; max-width: 800px; margin: 0 auto; padding: 48px 24px; color: #1E1B4B; background: #fff; }
+ body { font-family: 'Poppins', sans-serif; max-width: 860px; margin: 0 auto; padding: 56px 28px; color: #1E1B4B; background: #fff; }
+ a { text-decoration: none; }
</style>
</head>
<body>
- <div style="margin-bottom:48px;text-align:center;display:flex;flex-direction:column;align-items:center;">
- <span style="display:inline-block;background:#EEF2FF;color:#4F46E5;font-size:13px;font-weight:600;padding:5px 16px;border-radius:999px;">${i18n.t('export.stepsCount', [String(steps.length)])}</span>
- <div style="height:3px;width:60%;background:linear-gradient(to right,#4F46E5,#C7D2FE,#818CF8);border-radius:3px;margin:20px auto;"></div>
- <h1 style="font-size:28px;font-weight:800;color:#1E1B4B;line-height:1.2;margin-bottom:24px;max-width:80%;">${escapeHtml(guide.title)}</h1>
- <div style="display:flex;gap:32px;justify-content:center;">
- <div style="text-align:left;">
- <div style="font-size:10px;font-weight:600;color:#6B7280;text-transform:uppercase;letter-spacing:0.06em;">${i18n.t('export.created')}</div>
- <div style="font-size:14px;font-weight:600;color:#1E1B4B;">${formatDate(guide.createdAt)}</div>
- </div>
- ${
- domain
- ? `<div style="text-align:left;">
- <div style="font-size:10px;font-weight:600;color:#6B7280;text-transform:uppercase;letter-spacing:0.06em;">${i18n.t('export.source')}</div>
- <a href="https://${escapeHtml(domain)}" target="_blank" rel="noopener" style="font-size:14px;font-weight:600;color:#4F46E5;display:flex;align-items:center;gap:6px;text-decoration:none;">${favicon ? `<img src="${favicon}" width="18" height="18" style="border-radius:4px;" />` : ''}${escapeHtml(domain)}</a>
- </div>`
- : ''
- }
- </div>
- </div>
+ ${headerHtml}
${stepSections.join('\n')}
+ ${footerHtml}
</body>
</html>`;
}
diff --git a/src/core/export/options.ts b/src/core/export/options.ts
new file mode 100644
index 0000000..6b4254e
--- /dev/null
+++ b/src/core/export/options.ts
@@ -0,0 +1,46 @@
+import { localStorage } from '@/lib/browser-api';
+
+export type ImageScale = 'small' | 'medium' | 'large';
+
+export const IMAGE_SCALE_FACTORS: Record<ImageScale, number> = {
+ small: 0.55,
+ medium: 0.78,
+ large: 1,
+};
+
+export interface ExportOptions {
+ cover: boolean;
+ screenshots: boolean;
+ stepUrls: boolean;
+ imageScale: ImageScale;
+}
+
+export const DEFAULT_EXPORT_OPTIONS: ExportOptions = {
+ cover: true,
+ screenshots: true,
+ stepUrls: true,
+ imageScale: 'medium',
+};
+
+const bool = (value: unknown, fallback: boolean) => (typeof value === 'boolean' ? value : fallback);
+
+export function normaliseExportOptions(value: unknown): ExportOptions {
+ if (!value || typeof value !== 'object') return { ...DEFAULT_EXPORT_OPTIONS };
+ const raw = value as Partial<ExportOptions>;
+ return {
+ cover: bool(raw.cover, DEFAULT_EXPORT_OPTIONS.cover),
+ screenshots: bool(raw.screenshots, DEFAULT_EXPORT_OPTIONS.screenshots),
+ stepUrls: bool(raw.stepUrls, DEFAULT_EXPORT_OPTIONS.stepUrls),
+ imageScale:
+ raw.imageScale && raw.imageScale in IMAGE_SCALE_FACTORS ? raw.imageScale : DEFAULT_EXPORT_OPTIONS.imageScale,
+ };
+}
+
+export async function loadExportOptions(): Promise<ExportOptions> {
+ const stored = await localStorage.get(['exportOptions']);
+ return normaliseExportOptions(stored.exportOptions);
+}
+
+export async function saveExportOptions(options: ExportOptions): Promise<void> {
+ await localStorage.set({ exportOptions: options });
+}
diff --git a/src/core/export/pdf-export.ts b/src/core/export/pdf-export.ts
index 99fa2d9..6a558fc 100644
--- a/src/core/export/pdf-export.ts
+++ b/src/core/export/pdf-export.ts
@@ -1,195 +1,251 @@
import { jsPDF } from 'jspdf';
import { i18n } from '#imports';
-import { blobToDataUrl, extractDomain, fetchFaviconBase64, formatDate } from '@/core/export/utils';
+import { fitLogo, loadBranding } from '@/core/export/branding';
+import { type ExportOptions, IMAGE_SCALE_FACTORS, loadExportOptions } from '@/core/export/options';
+import { blobToDataUrl, extractDomain, formatDate } from '@/core/export/utils';
import type { Guide, Screenshot, Step } from '@/core/guides/types';
+import { hexToRgb } from '@/core/screenshot/color';
import { resolveViewport } from '@/core/screenshot/geometry';
import { renderScreenshot } from '@/core/screenshot/render';
import { logger } from '@/lib/logger';
const JPEG_QUALITY = 0.85;
+const PAGE_W = 210;
+const PAGE_H = 297;
+const MARGIN = 18.5;
+const CONTENT_W = PAGE_W - MARGIN * 2;
+const NUM_COL = 22;
+const COL_GAP = 8;
+const TEXT_COL = CONTENT_W - NUM_COL - COL_GAP;
+const TEXT_X = MARGIN + NUM_COL + COL_GAP;
+const RIGHT = PAGE_W - MARGIN;
+const FOOTER_Y = PAGE_H - 24;
+const HEAD_BOTTOM = MARGIN + 6;
+const STEP_TOP = MARGIN + 20;
+const STEP_GAP = 13;
+const LOGO_MAX_W = 34;
+const LOGO_MAX_H = 15;
+const HEAD_LOGO_W = 18;
+const HEAD_LOGO_H = 7;
+const META_COL_W = 43;
+const META_DROP = 9;
+
+const INK: [number, number, number] = [30, 27, 75];
+const MUTED: [number, number, number] = [107, 114, 128];
+const HAIR: [number, number, number] = [229, 231, 235];
+
export async function exportGuideAsPDF(
guide: Guide,
steps: Step[],
screenshots: Map<string, Screenshot>,
+ options?: ExportOptions,
): Promise<Blob> {
+ const opts = options ?? (await loadExportOptions());
const doc = new jsPDF({ orientation: 'portrait', unit: 'mm', format: 'a4' });
- const pageWidth = doc.internal.pageSize.getWidth();
- const pageHeight = doc.internal.pageSize.getHeight();
- const margin = 20;
- const contentWidth = pageWidth - margin * 2;
-
- const centerX = pageWidth / 2;
const domain = extractDomain(steps);
- const dateStr = formatDate(guide.createdAt);
- const faviconDataUrl = domain ? await fetchFaviconBase64(domain) : null;
-
- const badgeText = i18n.t('export.stepsCount', [String(steps.length)]);
- doc.setFontSize(10);
- doc.setFont('helvetica', 'bold');
- const badgeTextWidth = doc.getTextWidth(badgeText);
- const badgePadH = 5;
- const badgeW = badgeTextWidth + badgePadH * 2;
- const badgeH = 7;
-
- doc.setFontSize(22);
- doc.setFont('helvetica', 'bold');
- const titleLines = doc.splitTextToSize(guide.title, contentWidth * 0.8);
- const titleBlockH = titleLines.length * 9;
-
- const gradLineW = contentWidth * 0.6;
- const totalBlockH = badgeH + 8 + 1.5 + 10 + titleBlockH + 16 + 12;
- let y = (pageHeight - totalBlockH) / 2;
-
- doc.setFillColor(238, 242, 255);
- doc.roundedRect(centerX - badgeW / 2, y, badgeW, badgeH, 3.5, 3.5, 'F');
- doc.setFontSize(10);
- doc.setTextColor(79, 70, 229);
- doc.text(badgeText, centerX, y + 5, { align: 'center' });
- y += badgeH + 8;
-
- const gradX = centerX - gradLineW / 2;
- const gradStops = [
- [79, 70, 229],
- [99, 91, 237],
- [129, 120, 244],
- [164, 161, 249],
- [199, 210, 254],
- [155, 210, 254],
- [96, 200, 251],
- [56, 189, 248],
- ] as const;
- const segW = gradLineW / gradStops.length;
- for (let i = 0; i < gradStops.length; i++) {
- const [r, g, b] = gradStops[i];
- doc.setFillColor(r, g, b);
- doc.rect(gradX + segW * i, y, segW + 0.2, 1.5, 'F');
- }
- y += 10;
-
- doc.setFontSize(22);
- doc.setFont('helvetica', 'bold');
- doc.setTextColor(30, 27, 75);
- doc.text(titleLines, centerX, y, { align: 'center' });
- y += titleBlockH + 16;
-
- const metaColW = 40;
- const metaGap = 16;
- const numCols = domain ? 2 : 1;
- const metaTotalW = numCols * metaColW + (numCols - 1) * metaGap;
- let metaX = centerX - metaTotalW / 2;
-
- doc.setFontSize(7);
- doc.setFont('helvetica', 'bold');
- doc.setTextColor(107, 114, 128);
- doc.text(i18n.t('export.created').toUpperCase(), metaX, y);
- doc.setFontSize(12);
- doc.setFont('helvetica', 'normal');
- doc.setTextColor(30, 27, 75);
- doc.text(dateStr, metaX, y + 6);
-
- if (domain) {
- metaX += metaColW + metaGap;
- doc.setFontSize(7);
- doc.setFont('helvetica', 'bold');
- doc.setTextColor(107, 114, 128);
- doc.text(i18n.t('export.source').toUpperCase(), metaX, y);
- const faviconSize = 4;
- let domainTextX = metaX;
- if (faviconDataUrl) {
+ const brand = await loadBranding();
+ const accent = hexToRgb(brand.accent) ?? [79, 70, 229];
+ const logo = brand.logo ? fitLogo(brand.logo, LOGO_MAX_W, LOGO_MAX_H) : null;
+ const headLogo = !opts.cover && brand.logo ? fitLogo(brand.logo, HEAD_LOGO_W, HEAD_LOGO_H) : null;
+ const headRight = headLogo ? RIGHT - headLogo.width - 4 : RIGHT;
+ const imgWidth = TEXT_COL * IMAGE_SCALE_FACTORS[opts.imageScale];
+ if (opts.cover) {
+ if (brand.logo && logo) {
try {
- doc.addImage(faviconDataUrl, 'PNG', metaX, y + 2.5, faviconSize, faviconSize);
- domainTextX = metaX + faviconSize + 2;
- } catch {
- domainTextX = metaX;
+ doc.addImage(brand.logo.dataUrl, 'PNG', RIGHT - logo.width, MARGIN, logo.width, logo.height);
+ } catch (err) {
+ logger.warn('PDF: failed to draw brand logo', err);
}
}
- doc.setFontSize(12);
+
+ doc.setFontSize(8);
+ doc.setFont('helvetica', 'bold');
+ doc.setTextColor(...MUTED);
+ doc.text(i18n.t('export.guideLabel'), MARGIN, MARGIN + 4, { charSpace: 0.6 });
+
+ doc.setFontSize(30);
+ doc.setTextColor(...INK);
+ const titleLines = doc.splitTextToSize(guide.title, CONTENT_W * 0.82);
+ doc.text(titleLines, MARGIN, MARGIN + 26);
+
+ const y = MARGIN + 26 + (titleLines.length - 1) * 11 + 8;
+ doc.setDrawColor(...INK);
+ doc.setLineWidth(0.4);
+ doc.line(MARGIN, y, RIGHT, y);
+
+ const yLabel = y + 12;
+ const yValue = yLabel + META_DROP;
+ const drawLabel = (text: string, x: number) => {
+ doc.setFontSize(7.5);
+ doc.setFont('helvetica', 'bold');
+ doc.setTextColor(...MUTED);
+ doc.text(text, x, yLabel, { charSpace: 0.4 });
+ };
+
+ drawLabel(i18n.t('export.steps').toUpperCase(), MARGIN);
+ doc.setFontSize(30);
+ doc.setFont('helvetica', 'bold');
+ doc.setTextColor(...accent);
+ doc.text(String(steps.length).padStart(2, '0'), MARGIN, yValue);
+
+ drawLabel(i18n.t('export.created').toUpperCase(), MARGIN + META_COL_W);
+ doc.setFontSize(11);
doc.setFont('helvetica', 'normal');
- doc.setTextColor(79, 70, 229);
- doc.textWithLink(domain, domainTextX, y + 6, { url: `https://${domain}` });
+ doc.setTextColor(...INK);
+ doc.text(formatDate(guide.createdAt), MARGIN + META_COL_W, yValue);
+
+ if (domain) {
+ const x = MARGIN + META_COL_W * 2;
+ drawLabel(i18n.t('export.source').toUpperCase(), x);
+ doc.setFontSize(11);
+ doc.setFont('helvetica', 'normal');
+ doc.setTextColor(...accent);
+ doc.textWithLink(domain, x, yValue, { url: `https://${domain}` });
+ }
}
+ const pageSteps: number[][] = [];
+ const coverPages = opts.cover ? 1 : 0;
- const stepIndent = 16;
- const maxImgHeight = 90;
- const stepSpacing = 6;
+ const startStepPage = () => {
+ if (coverPages > 0 || pageSteps.length > 0) doc.addPage();
+ pageSteps.push([]);
+ doc.setFontSize(8);
+ doc.setFont('helvetica', 'bold');
+ doc.setTextColor(...INK);
+ doc.text(doc.splitTextToSize(guide.title, CONTENT_W * 0.7)[0], MARGIN, MARGIN + 3);
+ if (brand.logo && headLogo) {
+ try {
+ doc.addImage(
+ brand.logo.dataUrl,
+ 'PNG',
+ RIGHT - headLogo.width,
+ HEAD_BOTTOM - 1.5 - headLogo.height,
+ headLogo.width,
+ headLogo.height,
+ );
+ } catch (err) {
+ logger.warn('PDF: failed to draw brand logo in running head', err);
+ }
+ }
+ doc.setDrawColor(...HAIR);
+ doc.setLineWidth(0.3);
+ doc.line(MARGIN, HEAD_BOTTOM, RIGHT, HEAD_BOTTOM);
+ return STEP_TOP;
+ };
- doc.addPage();
- y = margin;
+ let sy = startStepPage();
- for (let i = 0; i < steps.length; i++) {
- const step = steps[i];
+ for (const step of steps) {
+ const stepNum = String(step.index + 1).padStart(2, '0');
- const descWidth = contentWidth - stepIndent;
doc.setFontSize(11);
- doc.setFont('helvetica', 'normal');
- const descLines = doc.splitTextToSize(step.description, descWidth);
- const descHeight = descLines.length * 5;
+ doc.setFont('helvetica', 'bold');
+ const descLines = doc.splitTextToSize(step.description, TEXT_COL);
- const screenshot = screenshots.get(step.id);
+ const screenshot = opts.screenshots ? screenshots.get(step.id) : undefined;
let imgDataUrl: string | null = null;
- const imgWidth = contentWidth - stepIndent;
let imgHeight = 0;
-
if (screenshot) {
try {
const rendered = await renderScreenshot(screenshot, { format: 'image/jpeg', quality: JPEG_QUALITY });
imgDataUrl = await blobToDataUrl(rendered);
const viewport = resolveViewport(screenshot);
- imgHeight = Math.min((viewport.height / viewport.width) * imgWidth, maxImgHeight);
+ imgHeight = (viewport.height / viewport.width) * imgWidth;
} catch (err) {
logger.warn('PDF: failed to load screenshot for step', step.index, err);
}
}
- const stepBlockHeight = 6 + descHeight + 6 + imgHeight + stepSpacing;
-
- if (y + stepBlockHeight > pageHeight - margin && y > margin) {
- doc.addPage();
- y = margin;
+ const blockH = 6 + descLines.length * 5 + 4 + imgHeight;
+ if (sy + blockH > FOOTER_Y - 8 && sy > STEP_TOP) {
+ sy = startStepPage();
}
+ pageSteps[pageSteps.length - 1].push(step.index + 1);
- doc.setDrawColor(199, 210, 254);
- doc.setLineWidth(0.3);
- doc.line(margin, y, margin + contentWidth, y);
- y += 6;
-
- const stepNum = String(step.index + 1).padStart(2, '0');
- doc.setFontSize(12);
+ doc.setFontSize(30);
doc.setFont('helvetica', 'bold');
- doc.setTextColor(129, 140, 248);
- doc.text(stepNum, margin, y + 4);
+ doc.setTextColor(...accent);
+ doc.text(stepNum, MARGIN, sy + 8);
- doc.setFontSize(11);
- doc.setFont('helvetica', 'normal');
- doc.setTextColor(30, 27, 75);
- doc.text(descLines, margin + stepIndent, y + 4);
- y += descHeight + 6;
+ doc.setDrawColor(...INK);
+ doc.setLineWidth(0.3);
+ doc.line(TEXT_X, sy, RIGHT, sy);
- if (imgDataUrl) {
- if (y + imgHeight > pageHeight - margin) {
- doc.addPage();
- y = margin;
+ doc.setFontSize(11);
+ doc.setFont('helvetica', 'bold');
+ doc.setTextColor(...INK);
+ doc.text(descLines, TEXT_X, sy + 6);
+
+ let ux = TEXT_X + doc.getTextWidth(descLines[descLines.length - 1]);
+ let uy = sy + 6 + (descLines.length - 1) * 5;
+
+ if (step.url && opts.stepUrls) {
+ const label = stepUrlLabel(step.url);
+ doc.setFontSize(9);
+ doc.setFont('helvetica', 'normal');
+ const sep = ' · ';
+ const sepW = doc.getTextWidth(sep);
+ const urlW = doc.getTextWidth(label);
+ if (ux + sepW + urlW > RIGHT) {
+ ux = TEXT_X;
+ uy += 5;
+ } else {
+ doc.setTextColor(...MUTED);
+ doc.text(sep, ux, uy);
+ ux += sepW;
}
+ doc.setTextColor(...accent);
+ doc.textWithLink(label, ux, uy, { url: step.url });
+ doc.setDrawColor(...accent);
+ doc.setLineWidth(0.2);
+ doc.line(ux, uy + 0.9, ux + urlW, uy + 0.9);
+ }
- doc.addImage(imgDataUrl, 'JPEG', margin + stepIndent, y, imgWidth, imgHeight);
+ let iy = uy + 4;
+ if (imgDataUrl) {
+ doc.addImage(imgDataUrl, 'JPEG', TEXT_X, iy, imgWidth, imgHeight);
const altText = screenshot?.edits?.alt || i18n.t('export.stepLabel', [stepNum]);
- doc.text(doc.splitTextToSize(altText, imgWidth), margin + stepIndent, y + 4, { renderingMode: 'invisible' });
- y += imgHeight + stepSpacing;
- } else {
- y += stepSpacing;
+ doc.text(doc.splitTextToSize(altText, imgWidth), TEXT_X, iy + 4, { renderingMode: 'invisible' });
+ iy += imgHeight;
}
+ sy = iy + STEP_GAP;
}
-
const totalPages = doc.getNumberOfPages();
- const stepPages = totalPages - 1;
- for (let p = 2; p <= totalPages; p++) {
+ const attribution = brand.attribution ? i18n.t('export.madeWith') : '';
+ for (let p = 1; p <= totalPages; p++) {
doc.setPage(p);
doc.setFontSize(8);
doc.setFont('helvetica', 'normal');
- doc.setTextColor(107, 114, 128);
- doc.text(`${p - 1} of ${stepPages}`, pageWidth - margin, pageHeight - margin, { align: 'right' });
+ doc.setTextColor(...MUTED);
+
+ const onPage = pageSteps[p - 1 - coverPages];
+ if (onPage?.length) {
+ const range =
+ onPage.length > 1
+ ? i18n.t('export.stepsRange', [String(onPage[0]), String(onPage[onPage.length - 1]), String(steps.length)])
+ : i18n.t('export.stepOf', [String(onPage[0]), String(steps.length)]);
+ doc.text(range, headRight, MARGIN + 3, { align: 'right' });
+ }
+
+ doc.setDrawColor(...HAIR);
+ doc.setLineWidth(0.3);
+ doc.line(MARGIN, FOOTER_Y, RIGHT, FOOTER_Y);
+ const fy = FOOTER_Y + 4;
+ if (brand.footer) doc.text(brand.footer, MARGIN, fy);
+ if (attribution) doc.text(attribution, PAGE_W / 2, fy, { align: 'center' });
+ doc.text(`${p} / ${totalPages}`, RIGHT, fy, { align: 'right' });
}
return doc.output('blob');
}
+
+function stepUrlLabel(url: string): string {
+ try {
+ const parsed = new URL(url);
+ const label = `${parsed.hostname.replace(/^www\./, '')}${parsed.pathname === '/' ? '' : parsed.pathname}`;
+ return label.length > 64 ? `${label.slice(0, 63)}…` : label;
+ } catch {
+ return url;
+ }
+}
diff --git a/src/locales/de.yml b/src/locales/de.yml
index 1dca2b0..d00702f 100644
--- a/src/locales/de.yml
+++ b/src/locales/de.yml
@@ -46,6 +46,7 @@ guideme:
manualStep: "Dieser Schritt wurde bearbeitet und kann nicht automatisch erkannt werden. Nutze Weiter, wenn du fertig bist."
roadblock: "Wir kommen nicht weiter. Führe die Aktion auf dem Bildschirm aus, um fortzufahren."
live: Live
+ stepOf: "Schritt $1 von $2"
noDescription: Keine Beschreibung
prev: Zurück
next: Weiter
@@ -227,6 +228,9 @@ steps:
defaultAction: "$1 $2"
export:
+ guideLabel: "ANLEITUNG"
+ stepsRange: "Schritte $1–$2 von $3"
+ stepOf: "Schritt $1 von $2"
madeWith: "Made with Mimik"
created: Erstellt
source: Quelle
diff --git a/src/locales/en.yml b/src/locales/en.yml
index 10c1f59..4933075 100644
--- a/src/locales/en.yml
+++ b/src/locales/en.yml
@@ -46,6 +46,7 @@ guideme:
live: Live
roadblock: "We hit a roadblock. Try taking action on the screen to move forward."
manualStep: "This step was edited, so it can't be detected automatically. Use Next once you've done it."
+ stepOf: "Step $1 of $2"
noDescription: No description
prev: Prev
next: Next
@@ -295,6 +296,9 @@ steps:
defaultAction: "$1 $2"
export:
+ guideLabel: "GUIDE"
+ stepsRange: "Steps $1–$2 of $3"
+ stepOf: "Step $1 of $2"
madeWith: "Made with Mimik"
created: Created
source: Source
diff --git a/src/locales/es.yml b/src/locales/es.yml
index 60e187f..1ea7a8d 100644
--- a/src/locales/es.yml
+++ b/src/locales/es.yml
@@ -46,6 +46,7 @@ guideme:
live: En vivo
roadblock: "Nos encontramos con un obstáculo. Actúa en la pantalla para avanzar."
manualStep: "Este paso fue editado, así que no se puede detectar automáticamente. Usa Siguiente cuando lo hayas hecho."
+ stepOf: "Paso $1 de $2"
noDescription: Sin descripción
prev: Anterior
next: Siguiente
@@ -295,6 +296,9 @@ steps:
defaultAction: "$1 $2"
export:
+ guideLabel: "GUÍA"
+ stepsRange: "Pasos $1–$2 de $3"
+ stepOf: "Paso $1 de $2"
madeWith: "Made with Mimik"
created: Creado
source: Fuente
diff --git a/src/locales/fr.yml b/src/locales/fr.yml
index aa2ef00..cf5196b 100644
--- a/src/locales/fr.yml
+++ b/src/locales/fr.yml
@@ -46,6 +46,7 @@ guideme:
live: En direct
roadblock: "Nous avons rencontré un obstacle. Agissez à l'écran pour continuer."
manualStep: "Cette étape a été modifiée, elle ne peut donc pas être détectée automatiquement. Utilisez Suivant une fois faite."
+ stepOf: "Étape $1 sur $2"
noDescription: Aucune description
prev: "Préc."
next: Suiv.
@@ -295,6 +296,9 @@ steps:
defaultAction: "$1 $2"
export:
+ guideLabel: "GUIDE"
+ stepsRange: "Étapes $1–$2 sur $3"
+ stepOf: "Étape $1 sur $2"
madeWith: "Made with Mimik"
created: "Créé"
source: Source
diff --git a/src/locales/pt-BR.yml b/src/locales/pt-BR.yml
index e0b7489..c6d6c2f 100644
--- a/src/locales/pt-BR.yml
+++ b/src/locales/pt-BR.yml
@@ -46,6 +46,7 @@ guideme:
live: Ao vivo
roadblock: "Encontramos um obstáculo. Aja na tela para avançar."
manualStep: "Esta etapa foi editada, então não pode ser detectada automaticamente. Use Próximo quando terminar."
+ stepOf: "Passo $1 de $2"
noDescription: Sem descrição
prev: Anterior
next: Próximo
@@ -295,6 +296,9 @@ steps:
defaultAction: "$1 $2"
export:
+ guideLabel: "GUIA"
+ stepsRange: "Etapas $1–$2 de $3"
+ stepOf: "Etapa $1 de $2"
madeWith: "Made with Mimik"
created: Criado
source: Origem