# AppFile: a guide for AI assistants

You're building (or editing) a single-file HTML tool for someone, and you've been pointed at `appfile.js`. This guide covers what the script does, how to write tool code that works with it, what tends to go wrong, and how to extend it.

**In short:** AppFile makes an HTML file save itself. When the person clicks Save, it writes the page *as it currently looks* (current input values, plus any data the tool stored with `AppFile.set`) to a standalone HTML file, with the script inlined. When that file is opened again, the tool's code runs again on top of that saved page. Almost every problem comes from forgetting that second part.

---

## 1. Adding it to a tool

Put the script in `<head>`, **before** the tool's own scripts, with no `async` or `defer`:

```html
<head>
  <meta charset="utf-8">
  <title>Freelance Rate Calculator</title>   <!-- used as the file name when there isn't one yet -->
  <script src="appfile.js"></script>
  ...
</head>
```

Two ways to ship it:

- **Linked** (`<script src="appfile.js">`) is good while developing next to a copy of the script. The first Save inlines it, so the saved file stands alone.
- **Inlined** (paste the whole of `appfile.js` into a `<script>` in `<head>`) is better when you hand the person a single file, since it works before the first Save too. Paste it unchanged.

The script defines `window.AppFile` right away, so tool code can call `AppFile.get` at the top level. The toolbar mounts at `DOMContentLoaded`.

Give the page a good `<title>` and, if it has a key color, a `<meta name="theme-color">`. The toolbar takes its name from the title (until the file has its own name) and its color from the theme color or page background.

---

## 2. How saving works (what you have to design for)

On Save, AppFile:

1. Clones the whole document as it is right now, including everything your code has drawn.
2. Writes each saved input's current value into the clone's HTML (`value`, `checked`, `selected`, textarea text).
3. Writes `AppFile.set` data to `<script type="application/json" id="appfile-data">` and file info (ID, timestamps, an encryption key for drafts) to `#appfile-manifest`.
4. Removes its toolbar, inlines itself as `<script id="appfile-script">`, and writes the file.

When the saved file opens, **your scripts run again from the top**, on a page that already contains the last render.

Where it saves:

- **Chrome / Edge:** the first Save asks for a location. After that, changes autosave to that file (about 0.7s after the last change) until the tab closes.
- **Safari / Firefox:** Save downloads an updated copy.
- **Everywhere:** once the file has been saved at least once, unsaved changes are also kept in the browser (encrypted) and restored the next time the same file is opened. When that happens, AppFile fires `restore`.

---

## 3. Where state goes

There are two places to put state. Choose for each piece of state:

| State | Put it in | Why |
|---|---|---|
| A fixed form field the person fills in (rate, name, notes, a checkbox) | A plain `<input>`/`<select>`/`<textarea>` with an `id` | Saved automatically. Nothing else to do. |
| Lists, records, trees, anything you render from data | `AppFile.set(key, value)` / `AppFile.get(key, fallback)` | Stored once, as JSON, in the file's data block |
| Inputs your code generates from that data (row editors, etc.) | Mark the container `data-nosave` | Otherwise the values are stored twice, and the copy baked into the HTML gets out of sync |
| UI state you *don't* want saved (search box, filters, a half-typed "new entry" form) | `data-nosave` on the element or a container | Otherwise it's in the saved file |
| Rich text (`contenteditable`) | `data-save` on the element | Opts it in. Its HTML is sanitized (scripts, `on*` handlers and `javascript:` links removed). |

Never saved: password and file inputs, buttons.

**Give every saved input an `id`** (or a `name`). Inputs without one are still written into the saved HTML, but their unsaved changes can't be restored from the browser draft.

### The data API

```js
let expenses = AppFile.get('expenses', []);   // returns a deep copy; mutating it changes nothing

function addExpense(e) {
  expenses.push(e);
  AppFile.set('expenses', expenses);           // stores a copy and marks the file changed
  renderExpenses();
}

AppFile.on('restore', () => {                  // a browser draft replaced inputs and data
  expenses = AppFile.get('expenses', []);
  renderExpenses();
  recalc();
});
```

- Values must be JSON. `Date`s become strings, `Map`/`Set`/class instances lose their shape, `undefined` becomes `null`. Store ISO date strings and plain objects.
- Use one key per logical document (e.g. `'ledger'`) rather than many small keys. It keeps loading, migrating and restoring simple.

### Full API

| Call | |
|---|---|
| `AppFile.get(key, fallback)` | Read saved data (a copy) |
| `AppFile.set(key, value)` | Save data with the file, and mark it changed |
| `AppFile.on('restore', fn)` | Inputs/data were replaced from a browser draft; re-read and re-render |
| `AppFile.on('beforesave', fn)` | Runs just before every serialize |
| `AppFile.changed()` | Mark the file changed when AppFile can't see it |
| `AppFile.save()` / `AppFile.saveAs()` | Same as the toolbar buttons |
| `AppFile.serialize()` | The HTML Save would write, as a string |
| `AppFile.version` | Script version |

---

## 4. Rules for tool code

**1. Render by replacing, not appending.** The saved page already contains the last render. This is the most common bug.

```js
// Right: the same result however many times it runs
list.innerHTML = items.map(rowHTML).join('');
// or: list.replaceChildren(...items.map(makeRow));

// Wrong: shows every row twice after reopening, three times after the next save
items.forEach(it => list.append(makeRow(it)));
```

The same goes for anything that mounts into the page: clear the container before drawing a chart or mounting a component into it. Don't render into `document.body` directly; render into a container. (Replacing `body`'s contents also removes the toolbar.)

**2. Compute derived output on startup.** Read the input values (they're already filled in from the saved file), compute, and render. Don't rely on the HTML's last render being current.

**3. Call `AppFile.set` only for real edits**, not on every render or on startup. `set` marks the file as changed, so calling it while loading makes a freshly opened file show "Unsaved changes" and warn on close.

**4. Handle `restore`.** Register the handler at startup (not after an `await`). Restoring sets input values and fires `input` and `change` events on them, so listeners on those inputs run. Anything read from `AppFile.get` has to be read again.

**5. Programmatic changes need a signal.** Setting `el.value = x` in code doesn't fire an event, so AppFile doesn't know the file changed (no autosave, no draft). Dispatch an event or call `AppFile.changed()`:

```js
input.value = defaults.rate;
input.dispatchEvent(new Event('input', { bubbles: true }));
```

Do the same for anything AppFile can't see: drawing on a canvas, dragging an SVG, and so on, ideally storing the underlying data with `AppFile.set` as well.

**6. Clear temporary UI on startup.** A toast, "Copied!", an open dialog, a spinner or a selected tab is saved exactly as it was shown, but the timer or handler that would have cleared it doesn't come back. Reset these when the page starts, or keep them outside what gets saved.

**7. Rebuilding a `<select>`'s options loses the saved choice.** The saved file has `selected` on the right `<option>`. If your code then rebuilds the options from data, read `select.value` first and put it back after.

**8. Don't use `⌘S` / `Ctrl+S`** for anything else. AppFile uses them for Save and Save As.

**9. Don't use the reserved names:** the IDs `appfile-script`, `appfile-data` and `appfile-manifest`, and the attribute `data-appfile-ui`.

**10. Keep `beforesave` fast.** It runs on every Save, every autosave and every Share. A `AppFile.set` made there goes straight into the file being written and doesn't mark the file changed again. Calling `set` as edits happen is still better, because that's what keeps browser drafts and autosave current.

---

## 5. Things that cause trouble

**Layout**

- The toolbar is a `position: sticky` bar prepended to `<body>` (about 50px tall, a little less on phones). Plan for it:
  - If `body` is `display: flex` or `grid`, the toolbar becomes a flex/grid item. Put the app's layout on a wrapper (`<main>`), not on `body`.
  - `height: 100vh` layouts overflow by the toolbar's height. Use flex on a wrapper, or `calc(100vh - 50px)` if necessary.
  - Your own `position: sticky; top: 0` or `fixed` header ends up under the toolbar. Offset it.
  - Broad selectors like `body > div` or `body > *:first-child` match the toolbar's host element.
- The toolbar is hidden when printing.

**What isn't captured**

- `<canvas>` pixels, `<iframe>` contents, and anything inside a Web Component's shadow DOM. Store the underlying data with `AppFile.set` and redraw.
- Uploaded files (`<input type="file">`). To keep an image, read it as a data URL and `AppFile.set` it. Watch the size: it makes the file bigger, and browser drafts (in `localStorage`, usually about 5 MB) stop working past that.
- State that lives only in JavaScript variables or a framework's component state. On reopen it starts from scratch unless it came from an input or `AppFile.get`.

**Frameworks** (React, Vue, Preact, Alpine, etc.): treat `AppFile` as the store. Initialize state from `AppFile.get`, call `AppFile.set` when it changes, re-read on `restore`, and put `data-nosave` on the framework's root so the inputs it renders aren't baked in too. Make sure mounting replaces the root's existing content (the last render, saved in the file). Plain DOM code is often simpler for tools this size.

**Dependencies.** Only `appfile.js` is inlined. Other `<script src>`, stylesheets, fonts and images stay as references: relative paths break when the file is moved or emailed, and CDN links need a network connection. Inline what you can. Anything a library adds to the DOM at runtime (a `<style>` it injects, for instance) is saved with the page and is there on reopen alongside whatever the library adds next time, so prefer libraries that render into a container you control.

**Previews and sandboxes.** Embedded previews (chat artifact panes, sandboxed iframes, code playgrounds) often block the file picker, downloads or `localStorage`, so saving may fail there even when the tool is fine. Test by opening the actual `.html` file in a browser.

**Drafts begin after the first Save.** A fresh file that has never been saved has no file identity yet, so unsaved changes aren't kept in the browser until it's saved once. Tell the person to save early.

**Numbers.** Input values are strings. `parseFloat(el.value) || 0`.

---

## 6. Editing a file that has already been saved

People will send you a saved AppFile and ask for changes. You'll recognize one by `<script id="appfile-script">` (the inlined script), `#appfile-manifest` and `#appfile-data`.

- **The data block is the person's data.** Keep it. If you change the shape of what the tool stores, write the migration in the tool's code (read the old shape from `AppFile.get`, normalize it, keep going) rather than hand-editing the JSON. Then the next Save writes the new shape.
- **Don't edit `#appfile-manifest`.** It holds the file's ID and the key for its browser drafts. Removing it makes the file a new document, which is what you want only for a blank template (below).
- **The HTML inside generated regions is a snapshot of the last render.** It will be replaced when the tool runs, so edit the code that renders it, not the snapshot.
- **Input values are in the HTML** as `value`/`checked`/`selected`/textarea text. These are also the person's data.
- **Renaming or removing an input** discards what it held. Keep `id`s stable.
- **Upgrading the script:** replace the *contents* of `<script id="appfile-script">` with the new `appfile.js`, and keep the tag and its `id`.
- **To make a blank template** from a filled-in file: remove `#appfile-manifest` and `#appfile-data`, and reset the input values in the HTML to their defaults.

---

## 7. Extending it

**Start with the tool's code, not the script.** Most extra features can be built on the public API:

- *Export / import:* `JSON.stringify(AppFile.get('ledger'))` to a download; on import, `AppFile.set('ledger', parsed)` and re-render.
- *Reset to defaults:* set inputs back (dispatching `input` events), `AppFile.set` the default data, re-render.
- *A custom Save button or shortcut:* call `AppFile.save()`.
- *Undo:* keep a history of your own state in the tool and `AppFile.set` the current entry.
- *Copy for another app:* `AppFile.serialize()` gives you the complete file as a string.

Don't reach into the toolbar's shadow DOM or restyle it. `window.AppFile` is frozen; wrap its functions instead of trying to patch them.

**If you do need to change `appfile.js`:**

- **Everything has to stay inside the one `function appfile() { ... }`.** Saved files carry the script by inlining `appfile.toString()`. Code outside that function (including the header comment), `import`s and extra files are not carried into saved files.
- **Never write the characters `</script` anywhere in it**, not even in a string or comment. The script is inlined into a `<script>` tag, and that would end the tag early. Write `'<\/script'` if you need it. (The script logs an error at startup if its source contains it.)
- **Keep it free of network requests and external dependencies.** People are told their data stays on their device.
- **Keep reading old files.** Files already in the wild have `format: 1` manifests and a `#appfile-data` block. If you change the format, bump `format` and keep loading the old one.
- **Change `VERSION`** (e.g. `0.1.0-ledger.1`) so a modified copy is distinguishable from the original.
- Leave the safety pieces in place: `safeJSON` (so data can't close its `<script>`), `sanitize` for `data-save` content, and encrypted drafts.

---

## 8. Testing checklist

Before handing the tool over, open the actual file in Chrome (and Safari or Firefox if you can):

1. Change some inputs and add some data. The status should say "Unsaved changes".
2. Open the file fresh. It should *not* say "Unsaved changes" before you touch anything.
3. Save, close, reopen. Everything is there, **nothing appears twice**, and computed values are right.
4. Change something, save again, reopen again. A second round trip catches append-instead-of-replace bugs the first one misses.
5. Make a change, close *without* saving, reopen. It should restore ("Restored unsaved changes") and the whole UI should reflect the restored data.
6. Check that filters, search boxes and temporary messages don't come back in the saved file.

If you can't open a browser, you can still check the output: run `AppFile.serialize()` in the console (or a headless browser) and read the HTML it would save. Look for the data block, the baked values, and any temporary UI that shouldn't be there. For an automated round trip: load the page, set values, take `serialize()`, load that HTML as a new page, and compare.
