# @fave1/kit

Your app made a photo or a clip. One call gives people the sheet Fave1’s own apps use — save, share, download, post it — on every site and in app mode.

npm package · card mode · app mode · no permission of its own

```bash
$ npm install @fave1/kit
```

It’s plain TypeScript with no dependencies. Your build already bundles it — the template’s `npm run build` is esbuild — and only what you import ends up in your `index.js`.

| import | What you get | gzip |
| --- | --- | --- |
| `openExport` | The export sheet — preview, Save, Share, Download, Copy, Post it | ~17 KB |
| `photoEditor · videoEditor · liveEditor` | Inside the sheet: words, stickers, filters and your own looks on the photo or clip before it goes out — or on a live scene before you film it | ~24 KB |
| `Recorder` | A canvas you draw on becomes an MP4 (WebM where the browser can’t) | ~1 KB |
| `shareFiles · download · copyImage · copyText · fileName` | The same three ways out, for when you build your own buttons | <1 KB |
| `busyOn` | Three dots on the button someone just pressed — and no double tap | ~1 KB |

## A photo

Hand it a canvas (or a `Blob`). The sheet makes the file, names it, and shows the buttons this browser can really do — Share only where the share sheet takes files, Copy only where the clipboard takes images.

`src/share.ts`

```ts
import { openExport } from '@fave1/kit';

export function showPhoto(ctx: Ctx, card: HTMLCanvasElement) {
  const page = ctx.page;
  // card mode · app mode
  const where = ctx.surface === 'card' && page.document ? page.layer() : ctx.ui.host();
  // Fave1 steps aside while the sheet is up
  if (ctx.surface === 'card') ctx.ui.hide();

  openExport(where, { image: card }, {
    app: 'my-app',  // → fave1.com-my-app-2026-11-24.jpg
    sub: page.title,
    save: ctx.can('storage')
      ? async (file, name, progress) => { await ctx.files.put(file, { name, onProgress: progress }); }
      : undefined,  // no save → no Save button
    onClose: () => ctx.ui.show(),
  });
}
```

`save` is yours — usually [ctx.files](https://developers.fave1.com/docs/ctx-files.md). Pass its third argument on as `onProgress` and the Save button fills up as the file goes out and says how big it is (`Saving 4.2 MB · 63%`); without it a sliver sweeps across under `Saving 4.2 MB…`. Share and Download still work meanwhile. What happened shows on the button itself — **✓ Downloaded**, **✓ Saved to Fave1** (a link to your `href`, if you return one) — and there’s no status line under the buttons. If `save` throws, your error’s `message` opens in a small dialog over the sheet, with your link or button, and Save comes back; write messages a person can read.

## A clip

You draw, the `Recorder` listens. Open the sheet first with nothing in it — it says what’s happening — then `set()` the clip when it’s done.

`src/clip.ts`

```ts
import { Recorder, openExport } from '@fave1/kit';

export function makeClip(
  ctx: Ctx,
  stage: HTMLCanvasElement,
  draw: (seconds: number) => void,
) {
  const page = ctx.page;
  if (ctx.surface === 'card') ctx.ui.hide();
  const rec = new Recorder(stage);  // 30 fps · MP4 where the browser can
  const where = ctx.surface === 'card' && page.document ? page.layer() : ctx.ui.host();
  const sheet = openExport(where, null, {
    app: 'my-app',
    pending: 'Recording…',
    save: async (file, name) => { await ctx.files.put(file, { name }); },
    onClose: () => { rec.cancel(); ctx.ui.show(); },
  });
  if (!rec.start()) {
    sheet.fail('This browser can’t record video.');
    return;
  }

  const t0 = performance.now();
  const frame = () => {
    if (sheet.closed) return;
    const t = (performance.now() - t0) / 1000;
    draw(t);  // you paint the canvas
    rec.drew();  // lets it grab a cover frame
    if (t < 6) { requestAnimationFrame(frame); return; }
    rec.stop().then((take) => {
      if (take) sheet.set({ video: take });
      else sheet.fail('That didn’t record — try again.');
    });
  };
  frame();
}
```

Sound? Pass a `MediaStream` to `rec.start(stream)` — a Web Audio `MediaStreamAudioDestinationNode`’s `stream`, or [ctx.mic](https://developers.fave1.com/docs/ctx-mic.md)’s — and hand the take over as `sheet.set({ video: { ...take, sound: true } })`, so the preview gets a sound button (it starts muted). A clip gets TikTok and Instagram tiles: on a phone TikTok and Instagram open the share sheet with the file in it (the only way the web can hand an app a file); on a computer the upload page opens in a new tab and the file is downloaded for them to drop in.

## Let them edit it

Give the sheet the photo as an editor instead of a file and the preview becomes the canvas: they type words in eight styles, drop stickers, drag and pinch them, pick a filter and its strength, undo, and hit **Surprise me**. Save, Share and Download send what they made.

`src/snap.ts`

```ts
import { openExport } from '@fave1/kit';
import { photoEditor } from '@fave1/kit/editor';

export function editPhoto(ctx: Ctx, photo: HTMLCanvasElement) {
  const where = ctx.surface === 'card' && ctx.page.document ? ctx.page.layer() : ctx.ui.host();
  if (ctx.surface === 'card') ctx.ui.hide();
  openExport(where, { edit: photoEditor({ base: photo }) }, {
    app: 'my-app',
    title: 'Make it yours.',
    save: async (file, name) => { await ctx.files.put(file, { name }); },
    onClose: () => ctx.ui.show(),
  });
}
```

The file comes out the size of `base`, any shape — the canvas keeps its proportions. Still making the photo? Open the sheet with `pending` and `editing: true`, and call `sheet.edit(photoEditor({ base }))` when it’s ready. The stickers, badge words and quick phrases come from `setupLayers` in `@fave1/kit/layers`, once when your app starts.

| photoEditor | What it does | default |
| --- | --- | --- |
| `base` | The photo without anything on it. The export is this size | required |
| `tabs` | Which of `text` · `stickers` · `filters` to show | all three |
| `looks` | Your own frames: `{ items, value, hint, locked(id), lockedHint, onPick(id), title }`. Adds a Look tab; you draw them in `paint`. `title: { value, max }` puts a title field on top of it — `paint` gets `s.title` | — |
| `panels` | Tabs of your own after ours — `{ id, name, el }`. Use the `kx-eseg` · `kx-elab` · `kx-ehint` classes and they match | — |
| `open` | The tab it opens on | the first |
| `paint(g, s)` | Draws over the filtered photo — `s` has `look`, `layers`, `width`, `height`, and on a clip `time`. Leave it out and only the words and stickers are drawn | layers only |
| `layers` | Words and stickers to open with — the ones they added before filming | none |
| `style · onStyle` | The text style and color to start with, and a callback to remember the last one | Neon · pink |
| `filter · strength` | A filter that’s already on when it opens (`'golden'`, …) and how strong, 0–1 | none · 1 |
| `surprise` | The Surprise me button | true |
| `type · quality` | The file it makes | image/jpeg · 0.92 |
| `words` | Every label, by key | English |

Undo and redo sit next to ×, and ⌘Z · ⇧⌘Z work too. Escape first leaves the text field, then lets go of the selected sticker, and only then closes. If they change it while Save is still going, the sheet says so and lets them save again.

Switching a theme or background under their edits? Don’t build a new editor — `ed.setBase(canvas)` swaps the picture and keeps the words, stickers, undo, filter, open tab and scroll (a different shape resizes the canvas). Call it from `looks.onPick` and undo brings the old background back too.

## Let them edit the clip

Record the plain scene, then give the sheet a `videoEditor`: the clip loops under the canvas with a sound button, and the same four tabs work on it — words and stickers drag on the moving picture, the filter runs on every frame. Your `paint` gets `s.time`, so a frame or a sticker can keep the beat.

`src/clip.ts`

```ts
import { openExport, Recorder } from '@fave1/kit';
import { videoEditable, videoEditor } from '@fave1/kit/editor';

export async function filmIt(ctx: Ctx, stage: HTMLCanvasElement, draw: (g: CanvasRenderingContext2D, t: number) => void) {
  const editable = await videoEditable(document);
  const rec = new Recorder(stage);
  const where = ctx.surface === 'card' && ctx.page.document ? ctx.page.layer() : ctx.ui.host();
  if (ctx.surface === 'card') ctx.ui.hide();
  const sheet = openExport(where, null, { app: 'my-app', pending: 'Recording…', editing: editable, onClose: () => { rec.cancel(); ctx.ui.show(); } });
  if (!rec.start()) { sheet.fail('This browser can’t record video.'); return; }
  const g = stage.getContext('2d')!;
  const t0 = performance.now();
  const tick = () => {
    if (!rec.recording) return;
    const t = (performance.now() - t0) / 1000;
    draw(g, t);
    if (!editable) g.fillText('my-app', 40, 80);   // no editor here: bake the frame in
    rec.drew();
    if (t < 6) requestAnimationFrame(tick); else void done();
  };
  const done = async () => {
    const take = await rec.stop();
    if (!take) return sheet.fail('That didn’t record.');
    if (editable) sheet.edit(videoEditor({ base: take, paint: (c, s) => { c.font = '700 64px system-ui'; c.fillStyle = '#fff'; c.fillText('my-app', 40, 80 + Math.sin(s.time * 6) * 8); } }));
    else sheet.set({ video: take });
  };
  requestAnimationFrame(tick);
}
```

Until they change something, Save, Share and Download hand over the clip you recorded right away. Once they do, those buttons make the clip again in real time, sound and all, and the button you pressed fills up as it goes (`Making… 42%`). About a second after they stop editing it starts on its own, so it’s often done by the time they tap. The tab has to stay open while it’s made — if they switch away it stops and says so. Change anything and the made clip is thrown out.

| videoEditor | What it does | default |
| --- | --- | --- |
| `base` | The take from `Recorder.stop()` — `{ blob, mime, sec, poster }` | required |
| `aspect` | Width ÷ height of the canvas. The clip comes out the size of the take (1080 wide only if that can’t be read) | 9:16 |
| `sound` | The sound button on the preview | true |
| `videoBits` | Bitrate of the clip it makes | 6 Mbps |
| `keepOriginal` | Hand over the recorded clip as is while nothing’s changed. Off by default when you pass `paint` — your frame isn’t in the take yet. Turn it on if it already is | true without `paint` |
| `tabs · looks · paint · layers · style · filter · words` | Same as `photoEditor` | — |

`videoEditable(document)` resolves `false` where the browser can’t record or the site’s CSP blocks `blob:` video — there, record with your frame on and use `sheet.set({ video: take })`.

## Let them dress it before filming

Got a scene you draw every frame — a 3D stage, a game? `liveEditor` puts the same tabs and handles over it before you record, so words and stickers land where they’ll be in the clip. Open it in the share sheet and it’s one screen from start to finish: while it’s up the sheet hides Save · Share · Download and shows only your `when: 'before'` button. When the take is in, put `videoEditor` in the same sheet with what they placed — they keep tweaking, add a filter, and save.

`src/film.ts`

```ts
import { openExport, type ExportSheet } from '@fave1/kit/export';
import { liveEditor, videoEditor, type EditorPaint } from '@fave1/kit/editor';
import { drawLayers } from '@fave1/kit/layers';

type RecordFn = (stop: AbortSignal, progress: (p: number) => void) => Promise<Blob>;

export function film(where: HTMLElement, scene: HTMLCanvasElement, record: RecordFn): ExportSheet {
  const t0 = performance.now();
  const looks = [{ id: 'clean', name: 'Clean' }];
  const paint = (g: CanvasRenderingContext2D, s: EditorPaint) => {
    const k = s.width / 1080;
    g.save(); g.scale(k, k);
    g.font = '800 72px system-ui'; g.fillStyle = '#fff'; g.fillText(s.title, 60, 1800);
    drawLayers(g, s.layers, { beat: s.time * 2, anim: true, px: k });
    g.restore();
  };
  let stop: AbortController | null = null, gone = false;
  const sheet = openExport(where, null, {
    app: 'my-app',
    onClose: () => { gone = true; stop?.abort(); },   // closed mid-take — stop recording
    actions: [{ id: 'rec', label: 'Record', primary: true, when: 'before', run: () => { void shoot(); } }],
  });
  const pre = sheet.edit(liveEditor({
    draw: (g, w, h) => { g.drawImage(scene, 0, 0, w, h); return (performance.now() - t0) / 1000; },
    looks: { items: looks, value: 'clean', title: { value: 'My clip', max: 40 } },
    paint,
  }));
  sheet.head({ title: 'Make a clip' });

  async function shoot() {
    if (stop) { stop.abort(); return; }
    if (!pre) return;
    const layers = pre.layers.map((l) => ({ ...l })), look = pre.look, title = pre.title;
    stop = new AbortController();
    let blob: Blob;
    try {
      blob = await record(stop.signal, (p) => sheet.mark('rec', { p, label: `Stop · ${Math.round(p * 100)}%`, live: true }));
    } catch {
      return;   // stopped or failed — the button is back to Record
    } finally {
      stop = null;
      sheet.unmark('rec');
    }
    if (gone) return;
    sheet.head({ title: null });
    sheet.edit(videoEditor({ base: { blob, mime: blob.type, sec: 6 }, layers, looks: { items: looks, value: look, title: { value: title, max: 40 } }, paint }));
  }
  return sheet;
}
```

`sheet.mark(id, { p, label, live })` fills your button as a progress bar — with `live` it stays tappable, so the same button stops the take — and `unmark(id)` puts it back. `head({ title, sub, note })` swaps the heading and the small print (`null` goes back to what you opened with). Want to let them film again? Add a `when: 'after'` button that calls `sheet.edit(liveEditor(…))` with the layers from `sheet.editor`. Building your own sheet instead: `liveEditor` also mounts on any `EditHost` — the preview box, a spot for the tools, one for undo, the box that takes keys and `say(text, bad)`. Tabs default to Text and Stickers; add `looks` and your own `panels`.

## Options

| option | What it does | default |
| --- | --- | --- |
| `app` | Your app ID. Files are named `fave1.com-<app>-<date>.<ext>` so people know where a file came from | required |
| `save(file, name)` | Keep it on their account. Leave it out and there’s no Save button. May return `{ message, href, hrefLabel, link }` — `href` makes ✓ Saved to Fave1 a link (on a site only — in app mode, `<id>.fave1.app`, it stays a plain ✓ Saved), `link` goes in the QR, `message` is read to screen readers. Throw `{ message, href, hrefLabel, actionLabel, action, soft }` to open the error dialog with your link or button (`soft` — not red, they stopped it themselves) | — |
| `appName` | The name that goes along to the share sheet | `app` |
| `shareText` | A line that goes along to the share sheet | — |
| `signIn` | A URL, used when you leave out `save` — say `ctx.can('storage')` is false. The main button becomes “Sign in to keep it” and goes there | — |
| `saved · remove()` | Reopening something they already kept: no Save, and a trash button in the header that asks before it deletes | — |
| `title · sub` | The heading and the small line under it (a clip’s length is added for you) | Your clip is ready |
| `at · tag` | The date in the file name (when it was made, not when it’s downloaded) and an extra word — `fave1.com-my-app-cover-…` | now · none |
| `post` | The TikTok · Instagram row | clips yes · photos no |
| `link` | A URL that opens this on their phone — shown as a QR on a computer. `true` waits for the `link` your `save` returns | — |
| `copy` | Copy the photo to the clipboard | photos yes |
| `imageType · imageQuality` | What a canvas is exported as | image/jpeg · 0.92 |
| `aspect` | The preview’s width ÷ height — while it’s `pending` too. Once an editor is in, the editor’s own shape wins | from the file · clips 9:16 |
| `actions` | Your own buttons — `{ id, label, icon, run(sheet) }`. They join the row of round tiles after Share, Download and Copy (give them an `icon`, a 24×24 line SVG). Return a string and it shows on the button for a moment; reject (or throw from an `async` `run`) and the message opens in a small dialog — a plain synchronous throw is ignored. `primary` makes it the big gradient button on top instead; `when: 'before'` shows it only while a `liveEditor` is up (nothing to export yet — Record), `'after'` only once there is | — |
| `above` | An element of yours under the heading — a score, a caption field | — |
| `accent` | Two colors for the main button’s gradient | Fave1 violet → sky |
| `pending · kind` | Open before the file exists. `pending` is the line in the preview; `kind` picks the heading (`video` or `image`) | video |
| `editing` | An editor is coming (`sheet.edit()`). The sheet waits in the editing layout, so the preview doesn’t change size when the editor arrives. If it ends without one, it goes back to the plain layout | false |
| `inline` | Cover the element you passed instead of the whole screen | false |
| `note` | The small print at the bottom. `''` removes it | a posting reminder |
| `words` | Every string in the sheet, by key — for another language or your own voice | English |
| `onClose` | Called once, however it closes | — |

`openExport` returns the sheet: `set(input)` puts a file in (or swaps it — Save resets), `edit(photoEditor(…))` or `edit(videoEditor(…))` opens the editor, `editor` is the one that’s open, `fail(text)` says it couldn’t be made, `say(text, true)` opens a small dialog (without `true` it’s only read to screen readers), `close()`, `closed`, `esc()` if you route the Escape key yourself, `mark(id, { p, label, live })` · `unmark(id)` for progress on one of your buttons, and `head({ title, sub, note })` to change the heading as you go.

## Where it goes

The first argument is where the sheet lives. On a site that’s [ctx.page.layer()](https://developers.fave1.com/docs/ctx-page.md#layer) (it needs `page`); in app mode it’s `ctx.ui.host()`. Calling `host()` clears what your panel was showing, so on a site with a block UI use the layer — it leaves your panel as it was. If that element isn’t inside a shadow root of yours, the sheet makes one for itself — the site’s CSS can’t restyle it and its CSS can’t leak onto the site.

- **Hide Fave1 first** (card mode) — The card sits above your layer. Call `ctx.ui.hide()` before you open and `ctx.ui.show()` in `onClose`.
- **Nothing leaks** (keys) — Keys typed in the sheet don’t reach the site’s shortcuts, Tab stays inside it, and closing drops the video, object URLs and listeners.
- **× or Escape** (closing) — Tapping outside doesn’t close it — the × bounces instead. For its first 0.6 s buttons and Escape are ignored, so a hand that was still tapping your app can’t hit Post by accident.
- **A bottom sheet** (small screens) — Under 640 px it rises from the bottom and scrolls inside itself; the preview keeps its shape. With the editor, the canvas stays put and only the tools scroll.

## Your own buttons

Not using the sheet? The same ways out are there one by one. They tell you what happened instead of failing quietly — a blocked share is not the same as a closed one.

`src/out.ts`

```ts
import {
  busyOn, copyText, download, fileName, shareFiles, toFile,
} from '@fave1/kit';

export async function sendList(button: HTMLButtonElement, csv: string) {
  const done = busyOn(button);  // three dots, no double tap
  const blob = new Blob([csv], { type: 'text/csv' });
  // fave1.com-my-app-2026-11-24.csv
  const name = fileName('my-app', 'csv');
  const file = toFile(blob, name);
  const how = file ? await shareFiles(file) : 'unsupported';
  if (how === 'failed' || how === 'unsupported') {
    download(blob, name, button.parentNode);
  }
  done();
}

export async function copyLink(url: string) {
  const ok = await copyText(url);
  return ok ? 'Link copied.' : 'Couldn’t copy — copy it by hand.';
}
```

| shareFiles returns | What happened · what to do | then |
| --- | --- | --- |
| `shared` | It went to the share sheet | — |
| `closed` | They closed the share sheet. Nothing to fix | — |
| `busy` | A share sheet is already open (a second tap). Ignore it | — |
| `failed` | The browser refused — the tap went stale, or the page doesn’t allow sharing | download |
| `unsupported` | This browser can’t share that kind of file. Check first with `canShareFiles(type)` and don’t show the button | download |

Call `shareFiles` and `copyImage` from the tap itself — make the file before, not after. `copyImage` takes a promise, so Safari still counts it as the tap. Give `download` an element inside your own root as its third argument and the site’s link handlers never see the click.

## More in the box

| name | What it does | from |
| --- | --- | --- |
| `new Recorder(canvas, opts)` | `opts`: `fps` (30), `videoBits` (6 Mbps), `audioBits` (160 kbps), `posterAt` — when the cover frame is taken, in seconds (0.9). `rec.recording` and `rec.elapsed` (seconds) tell you where it is | `@fave1/kit` |
| `canRecord() · pickType()` | Whether this browser can record a canvas, and the type it would use — check before you show a Record button | `@fave1/kit` |
| `shareLink(url, data)` | A link to the share sheet — the same answers as `shareFiles` | `@fave1/kit` |
| `canShareFiles(type) · canCopyImage()` | Ask before you draw a Share or Copy button of your own | `@fave1/kit` |
| `makeQr(text) · qrSvg(qr, ink)` | A QR code as an SVG string — `makeQr` answers `null` when the text is too long | `@fave1/kit/qr` |
| `FILTERS · applyFilter()` | The eight filters the editor uses — `club` · `velvet` · `neon` · `sparkle` · `golden` · `flash` · `haze` · `noir` (and `none`) — for a canvas of your own. `releaseFilters()` frees their memory | `@fave1/kit/filters` |
| `setupLayers(opts)` | Once, when your app starts: `emojis` (the sticker tray), `badges` (new words for the badge stickers), `captions` (one-tap lines), and for the words panel `firstText` · `placeholder` · `hint` · `panelEmojis` · `panelBadges` | `@fave1/kit/layers` |

`editing` needs `@fave1/kit` 0.8.3 or later; `setBase`, `filter` · `strength` and `keepOriginal` need 0.8.2.

## In their language

Everything the kit puts on screen — the sheet, the editor, the text and sticker tray — comes in English. Call `useKitLocale(ctx)` once at the top of `onLaunch` and it follows the person’s language through your [ctx.t](https://developers.fave1.com/docs/ctx-locale.md).

`src/index.ts`

```ts
import { useKitLocale } from '@fave1/kit/i18n';

Fave1.defineApp({
  onLaunch(ctx) {
    useKitLocale(ctx);
    // the rest of your app
  },
});
```

Then translate the kit’s lines in your own `locales/<lang>.json`, next to yours. The keys all start with `kit.` and `KIT_EN` lists every one with its English. Leave them out of `en.json` — the kit carries its English, and any key a language file doesn’t have shows in English. The upload check knows these keys and doesn’t list them as missing from `en.json` (`@fave1/cli` 0.1.10 and later do the same on your machine). If you pass `onProgress` to Save, translate `kit.export.savingSize` and `savingSizeWait` too — that’s the line people see then.

`locales/es.json`

```json
{
  "kit.export.share": "Compartir",
  "kit.export.download": "Descargar",
  "kit.export.savingPct": "Guardando… {n}%",
  "kit.export.savingSize": "Guardando {size} · {n}%",
  "kit.editor.text": "Texto"
}
```

What you pass still wins: `title`, `actions`, the `words` option, and the emoji, badges and quick lines you give `setupLayers` stay exactly as you wrote them. Translate those with your own keys. Badge words fit their shape in any language — they get smaller, the stamp and the bubble go to two lines, the pills and the tape grow wider, and only a very long word ends in “…”.

## The rules

> **The file is theirs.** The sheet only hands it to the person — their share sheet, their downloads, their Fave1 storage. Don’t upload what you made anywhere else, and don’t open it at launch: it’s the answer to something they just did. Screens of someone else’s site go out with the small print left on (“make sure you’re allowed to share what’s in it”).
