# HTML to App 1.1.1 project authoring guide

Use this guide to deliver an editable .htmltoapp document the user can open with HTML to App on macOS 12 or later. Build a complete working project, preserve user data, request only needed capabilities and name what you actually tested. The user reviews settings and exports the Mac app. No external service, compiler or installer is part of the project format.

This single document includes the package format, builder workflows, gallery index and public JavaScript bridge. [Read the human documentation](https://htmltoapp.app/documentation/).

## Choose the smallest useful package

Give the recipient an editable **project document** ending in `.htmltoapp`, not a prebuilt `.app`. Double-clicking the document opens the converter in HTML to App 1.1.0 or later. It does not run the page, install a Mac app, or add anything to the workspace library. Choose **Export with Defaults** or **Customize**, review access, then save the app on your Mac. The resulting export embeds its resources and no longer depends on the document.

- **One page with everything inline**. Save ordinary UTF-8 HTML, starting with `<!doctype html>`, with the extension `.htmltoapp`. Keep its CSS, JavaScript and artwork inside it. [Download Word Count](https://htmltoapp.app/downloads/Word-Count.htmltoapp) for a complete example. Open it in a text editor to read the entire tool. It requests no permissions.
- **A project with separate assets**. Put the static website in a standard ZIP named `My Tool.htmltoapp`. [Download Screen Ruler](https://htmltoapp.app/downloads/Screen-Ruler.htmltoapp) for an example from the gallery. Its HTML, CSS, JavaScript and PNG are separate files. Export it, choose a display, and place the ruler to try a shaped window. Choose **Edit** to return to setup.
- **To edit a received ZIP in the workspace**, make a copy, give that copy a `.zip` extension, extract it, then use **Add Project Folder** on the folder containing `index.html`. For plain HTML, make a copy named `index.html` in a folder. Use **Project > Share Project** to share your edits again.

## Work in the builder or convert from Finder

- **Convert without a project.** In Finder select one HTML file or website folder, then choose **Services > Convert HTML to App**. The workspace also has a **Convert HTML to App** button. Choose the whole folder if the HTML references neighboring files. Use **Customize** to choose a name and icon, style the icon label and its outline, set Dock effects, and review file associations and permissions. These export settings are separate from the JavaScript bridge.
- **Edit a project.** Use the **+** beside Projects to create a starter, add a folder in place or create an editable copy from the Example Gallery. Save text edits with Command-S. Select a PNG or SVG to preview it, replace it with the same format or show it in Finder. **Run** opens a WebKit preview. **Checks & Output** shows diagnostics. **Check Project** checks saved static HTML and CSS references, not every path generated by JavaScript.
- **Choose how an app loads its source.** Embedding includes a snapshot and needs no original folder. Linking loads the original location on each launch. Reload after editing the files. If the source moves, use **Locate Folder** or **Locate HTML File** in the export to reconnect it. The linked source is read-only to the exported app. Files separately opened with Editor access are a different permission. Opening a portable document always produces an embedded export.
- **Manage the source safely.** **Duplicate Project** copies a folder. **Remove from List** forgets the workspace entry without deleting files. **Move to Trash** moves the actual folder and its contents to Finder's Trash. Apps linked to that location can stop loading. Use **Reconnect Folder** for an existing project that has moved. In the Files list, the context menu also offers **Show in Finder**, **Copy Relative Path**, **Duplicate File** and **Move to Trash** where applicable.
- **Try the export.** Choose **Open App** or **Show in Finder** after saving. The result uses the fixed sandboxed launcher for local use, not a notarized distribution build. The Mac App Store edition offers optional, user-installed local approval automation. Setapp handles that step with its bundled helper. See the [first-launch instructions](https://htmltoapp.app/documentation/#first-launch). Right-click a running export's Dock icon for **Open HTML to App**, when the builder is installed, or **Visit HTML to App Website**.

## Lay out the source

For a multi-file tool, keep the lowercase `index.html` at the ZIP root like this. One enclosing project folder is also accepted. No manifest, build script, signing key or executable is required.

```text
index.html
style.css
app.js
ProjectIcon.png
data/sample.json
```

Use a real document title, UTF-8 and a viewport declaration. Load local CSS in the head. Use a deferred script or a JavaScript module. Relative URLs such as `./data/sample.json` and imports such as `./lib/format.js` work without starting an HTTP server. Match filename case. Use actual files or hash navigation, not a server route that rewrites to the entry page. Bundle fonts, images and libraries the tool needs offline. For a framework project, package the **output** of its static build, not its development server or dependency directory.

Use the following command from inside the example project folder above, with a new output name. It names the files explicitly so local credentials and unrelated files do not get swept into the archive. Adapt the list to the actual project. If your archiver produces a normal `.zip`, rename it to `.htmltoapp` without changing the bytes.

```sh
zip -X "../My Tool.htmltoapp" index.html style.css app.js ProjectIcon.png data/sample.json
unzip -t "../My Tool.htmltoapp"
```

Use stored or deflated, unencrypted ZIP entries. Include only regular files and directories with relative names. Do not include symlinks, absolute paths, parent components, conflicting names that differ only by case or Unicode normalization, or nested ZIPs in place of the site. Omit `.git`, `.env` files, build caches, credentials and personal data. The importer accepts up to 256 MiB of input, 512 MiB expanded, 4,096 entries, 32 path levels and a 32 MiB HTML entry. These are ceilings, not targets. Keep the entry small and put media in separate files.

## Supply editable artwork

For a folder, put a real square PNG named **ProjectIcon.png** beside `index.html`. This makes it easy to replace. Without a usable PNG, HTML to App checks `<meta name="htmltoapp:icon" ...>` in the head, then a supported favicon. Use simple static SVG or PNG. Inline icons are limited to 256 KiB decoded. Separate raster artwork may be up to 8 MiB. Remote or active SVG artwork is not supported.

Both the icon meta tag and `<link rel="icon" href="./art/icon.png">` can refer to a project-local file. For a single-file project, inline it instead. PNG is the most portable raster choice. The importer also recognizes JPEG, WebP, GIF, ICO, ICNS, TIFF, BMP, HEIC and AVIF if the system image decoder supports them. The result is static artwork, not an animated GIF. For SVG use paths, shapes, gradients or clip paths with presentation attributes. Avoid CSS styles, text elements, filters, embedded images and external references. A local SVG has the same 256 KiB limit as an inline one. These icon restrictions do not limit SVG drawn inside the project's own web page.

For a single-file tool, include the image in the HTML itself. Encode the hash in an SVG color as `%23`. The Word Count download shows a complete example.

```html
<meta name="htmltoapp:icon" content="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 64 64'%3E%3Ccircle cx='32' cy='32' r='29' fill='%23235455'/%3E%3C/svg%3E">
```

The workspace's **Set Project Icon** can override the default. When a ZIP needs separate document artwork without modifying the site's own artwork, put `ProjectIcon.png` and a directory named `Website/` side by side, with `Website/index.html` and its resources inside. In this layout, do not also put an `index.html` at the package root. Document artwork takes precedence over website artwork. The user can still choose different artwork in the export wizard.

## Start a menu bar app without a Dock icon

For a normal windowed app, no extra metadata is needed. For a menu bar utility, add this tag to the entry page's `<head>`, then export with HTML to App 1.1.1 or later.

```html
<meta name="htmltoapp:dock-visible" content="false">
```

This chooses the Dock icon's state **at launch**. It does not create a menu bar item or hide the window. Create the item with `HTMLtoApp.menuBar.setIcon()` and give its menu **Show Window** and **Quit** actions. To change the launch default of an existing app, re-export after editing the tag, even when the site is linked to its original folder.

To let the user change the icon while the app is running, see [show or hide the Dock icon](https://htmltoapp.app/documentation/bridge/#show-or-hide-the-dock-icon). Test this in the exported app. A project can [find the system Dock](https://htmltoapp.app/documentation/bridge/#find-the-system-dock) in Preview as well.

## Request only what the tool needs

Inside the document head, within the first 768 KiB, use `htmltoapp:open-with` to suggest export settings. The user reviews them. Metadata does not grant a permission. A tool without file associations or optional permissions needs no tag.

```html
<!-- A text viewer that reads opened documents and saves a separate copy. -->
<meta name="htmltoapp:open-with" content="role=viewer; files=txt,md; folders=false">
```

Use `role=editor` only for a tool that intentionally writes back to opened items. Give a comma-separated list of actual extensions, without dots or wildcards. Use `folders=true` only if the tool handles folders. For a camera tool use `camera=true`. Other independent options are `microphone=true`, `location=true`, `listInstalledApps=true` and `openInstalledApps=true`. A launcher that needs both app permissions can use `permissions=ListInstalledApps,OpenInstalledApps`. User choices, including previously disabling a suggestion, take precedence.

For Finder file registration, `files=true` alone is not enough. Use `files=txt,md` or provide a separate `extensions=txt,md` list. A folder-only viewer can use `role=viewer; folders=true` without file extensions. A permission-only tag such as `permissions=camera` does not register any file type.

When updating an older project, the builder also recognizes `mic` or `audio` for microphone and `geolocation` or `gps` for location. It accepts the legacy meta name `htmltoapp-open-with` and explicit head comments such as `<!-- htmltoapp:open-with: role=viewer; files=txt -->`. For a new project, use the meta tag shown above rather than maintaining two declarations.

## Keep project files separate from saved data

The project runs in system WebKit on a local origin. It cannot run Node.js, Python, PHP, shell scripts or a local HTTP service. Use relative fetch requests and ES modules for project resources. External services still need connectivity and must allow the request. A custom project origin does not bypass CORS or guarantee every HTTPS-only browser API.

Store preferences in localStorage and structured data in IndexedDB. That data belongs to the app identity and web origin. It is not written into the project or its portable document. Preview and the exported app have separate stores. Provide a real backup/import flow for valuable user records, especially when moving to another Mac. Preserve existing records during schema changes.

On repeat export, **Keep Existing Data** retains the identity and storage of a recognized replacement. **Create a Fresh Copy** uses an unused destination and an independent identity. **Reset Website Data** needs a matching export and an explicit confirmation. The updated app clears its own WebKit data once on launch, not project files or external documents. Replacing an unrecognized bundle via **Replace Anyway** is not a migration. The new app starts with empty website data. Use a different destination to preserve the old app.

## Find a working gallery example

In the workspace choose **+ > Example Gallery**, select an example and choose **Create Project**. You get editable source, so you can inspect a feature without changing the bundled original.

| What you want to build | Examples to open |
| --- | --- |
| A widget or a display-edge launcher | **Screen Ruler** for shaped hit regions, **Tracing Paper** for a floating reference, **Edge Shelf** for app icons and launch consent, and **Cue Cards** for presentation across displays. |
| A menu bar utility or live Dock icon | **Menu Bar Controls** for hiding and showing the Dock icon, **Focus Dial** for a countdown, **Desk Clock** for an analog clock, and **Notifications and Badge** for native alerts and counts. Test the app's own Dock icon after export. |
| A document or folder tool | **Text Editor** for writing back to an opened document, **Folder Board** for scoped browsing, **CSV Cleaner** and **Subtitle Repair** for saving a new copy, and **Contact Sheet** for processing a folder of images. |
| A viewer or drawing tool | **Image Viewer**, **Audio Player** and **Video Player** open local media. **Geometry Pad** draws and exports a PNG. **Camera Viewer** captures stills when camera access is available. |
| A local data or integration example | **Field Guide** loads local JSON. **Icon Pairs** uses sample artwork or installed app icons. **Native Integration Demo** combines files, menu bar actions, notifications and badges. |

<span id="delivery-checklist-for-an-ai-agent" aria-hidden="true"></span>

## Project delivery checklist

1. Build the working tool the person requested, not a description or a mockup. Start with a useful initial state, a clear primary action and an accessible result. Use real buttons and labels, keyboard focus, readable contrast and layouts that fit a narrow window. Keep system window decorations unless the project really needs a widget.
2. Use only the native APIs in the [bridge reference](https://htmltoapp.app/documentation/bridge/). A browser has no bridge. Detect each optional feature, explain unavailable actions, and keep ordinary web functions usable. Do not provide invented success responses. Show progress for slow file operations and handle cancellation or denial.
3. Test with the network off. Check relative fetches, imports, artwork, empty and error states, keyboard access and smaller window sizes. Register native event listeners before reading their initial snapshots. Never ask for privacy access until the relevant user action.
4. Inspect the delivered archive, not just the source tree. Test its ZIP integrity, extract into a fresh folder, and verify assets and filename case. For plain HTML, test with no neighboring files. Do not include a native launcher, a fake app bundle or any developer credentials.
5. Deliver the actual `.htmltoapp` file. State what it does, which permissions are needed and why, where user data lives, and what was actually tested. Give the recipient the converter steps above. Within the workspace use **Run** and **Check Project**. Test Finder delivery, Dock artwork, permissions and saved data in the exported app when those behaviors matter. A successful browser test alone does not verify macOS integration.

# Public JavaScript bridge in 1.1.1

## Detect the host and the permission

This reference describes HTML to App 1.1.1. Updating the builder does not update apps you already exported. Re-export with 1.1.1 or later to choose whether an app starts in the Dock, change its Dock icon visibility, or read the system Dock's position.

The namespace is exactly `window.HTMLtoApp`. Desktop APIs are provided to the local project's main document. Do not call private WebKit message handlers. A regular browser does not have this bridge. Feature-detect the specific method and handle rejected promises instead of assuming an installed app, a permission grant, or an OS version.

```js
const api = window.HTMLtoApp;
const preview = api?.isPreview === true;
const canPlaceWindow = typeof api?.window?.setBounds === "function";
const cameraPreview = preview && api?.previewCapabilities?.camera === true;
```

Preview uses the builder's identity. The Mac App Store edition does not offer camera, microphone or location in Preview. A Setapp Preview that advertises the corresponding `previewCapabilities.camera`, `.microphone` or `.location` can request it. Feature flags are not user consent. In an export, enable the selected capability and request it from a relevant user action with `navigator.mediaDevices.getUserMedia()` or `navigator.geolocation`. Handle missing hardware, denial and cancellation. Stop media tracks when finished.

The exported site normally loads from `htmltoapp://site/index.html`. A workspace project can have a different local scheme. Resolve resources relative to the document, never by hardcoding either scheme or a file path. Test Finder registration, the exported app's own permissions, its Dock artwork and its stored data in an actual export.

The bridge does not expose a shell, arbitrary filesystem paths, native Calendar or Contacts access, or a general way to call macOS APIs. Do not invent methods such as `HTMLtoApp.openExternal()` or `HTMLtoApp.showSaveDialog()`. Use ordinary links or a user-initiated download as described below.

## Links, navigation and recovery

Link to another project page with a relative URL. A top-level link to an external HTTP or HTTPS website opens in the Mac's default browser, not in the project window. A local link with `target="_blank"` loads in the existing project window. Do not use `window.open()` to create a second independent app window. Project links to `mailto:` or another app's custom URL scheme are blocked. To request that an installed app open, use the permission and user action described under [installed applications](https://htmltoapp.app/documentation/bridge/#installed-applications). Fetching data from a web service is a separate operation and still depends on connectivity and CORS.

In Preview and in an export, the **View** menu provides **Reload Page**, **Back**, **Forward**, **Home**, **Zoom In**, **Zoom Out** and **Actual Size**. Home returns to the project's entry page. Page zoom changes web content size, not the native window frame. If WebKit's renderer stops, the host attempts a reload. After repeated interruptions it offers a manual reload instead. Save important edits as they happen rather than relying on a page-close handler.

## Open files and folders

Finder Open With, Dock drops and later native opens deliver scoped items. On `window`, listen for `htmltoapp-open` and then read `api.launchItems` or `api.consumeLaunchItems()`. Despite its name, the latter returns a snapshot and does not drain the queue. Use `event.detail.items` and honor `replaceExisting`. Handle a cold start, later deliveries and a repeated item. For example, a viewer that keeps one row per document can use this pattern with its own `renderRows` function.

```js
const rows = new Map();
function receive(items, replace) {
  if (replace) rows.clear();
  for (const item of items) {
    rows.set(JSON.stringify([item.itemId ?? item.id, item.relativePath ?? ""]), item);
  }
  renderRows([...rows.values()]);
}
window.addEventListener("htmltoapp-open", ({detail}) =>
  receive(detail.items, detail.replaceExisting));
receive(window.HTMLtoApp?.launchItems ?? [], false);
```

Root items contain `id`, `itemId`, `name`, `path`, `relativePath`, `kind`, `isDirectory` and `writable`. Files have a loadable `url`; directories have `baseURL` and `listingURL`. An entry from a folder listing can be passed to the bridge by `itemId` and `relativePath`. Use `api.urlFor(item, relativePath)` for scoped media URLs. A displayed path or a cached ID is not a persistent grant. Never build a native URL from an arbitrary path.

`api.runtime` contains `enabled`, `role`, `allowFiles`, `allowFolders` and `canWriteBack`. Listen for `htmltoapp-runtime` for changes. A drop can provide read access even without Finder file registration. Viewer access does not permit writing back. Preview file operations can affect real files.

All `api.fs` methods return promises. Omit the relative path to use the item itself. On a folder, provide a relative child path. The following are the public methods.

| Method | Result and constraints |
| --- | --- |
| `stat(item, path?)` | File or folder metadata, including size for a regular file. |
| `list(item, path?)` | An object with `entries` and `truncated`, not an array. Handle a truncated listing explicitly. |
| `readText(item, path?, options?)` | Metadata plus `text` and detected `encoding`. |
| `readData(item, path?)` | Metadata plus `base64Data` and `mimeType`, not a Blob. |
| `writeText(item, text, path?, options?)` | Editor write-back. Options include `encoding`, `atomic` and `createIntermediates`. Preserves the detected encoding of an existing text file when possible. |
| `writeData(item, base64Data, path?, options?)` | Editor write-back with Base64 bytes, not a data URL. Supports `atomic` and `createIntermediates`. |
| `createDirectory(item, path, options?)` | Create a child of a writable folder. Supports `createIntermediates`. |
| `move(item, fromPath, toPath, options?)` | Move within the same writable folder. Supports `createIntermediates` and `overwrite`. Overwrite defaults to false. |
| `remove(item, path?, options?)` | Delete, not Move to Trash. Confirm with the user. Deleting a nonempty folder needs `recursive: true`. The opened root folder cannot be deleted. |

Read `(await api.fs.readText(item)).text`. Before modifying anything, check `api.runtime?.canWriteBack`, the item's writability, and the actual operation result. Atomic writes and intermediate directories default to enabled. Bridge file data is limited to 64 MiB per read or write, text writes to 16,777,216 UTF-16 units, a listing to 4,096 entries and opened items to 128. Relative paths are limited to 4,096 UTF-16 units and 256 components. Prefer a scoped URL for media playback instead of reading a video into Base64.

An HTML file input returns browser `File` objects, not native items. Use `file.text()`, object URLs or standard file APIs with those objects. A folder picker can use a separate `webkitdirectory` input when supported. To **save a copy** without Editor permission, create a Blob URL and activate an anchor with a suggested `download` filename. Release the URL after the download has started. The native save panel can be cancelled, so do not announce a successful disk write merely because the link was clicked. There is no public arbitrary-path or shell API.

### Text encodings and errors

`readText` detects the encoding. Passing an encoding option does not force decoding. For an explicit `writeText` encoding use `utf-8`, `utf-16`, `utf-16le`, `utf-16be`, `iso-8859-1` or `windows-1252`. When editing a file in place, omit the option to preserve its encoding when possible.

File operations reject with an `Error` that can carry `error.code`. For `opened_item_missing`, let the user reopen the document. For `write_back_not_allowed`, offer Save a Copy. For `file_too_large`, offer a smaller input or a scoped media URL. For `unsupported_encoding`, offer a supported output encoding without overwriting the original. These codes are not exhaustive. Show a useful fallback for other failures and report saved changes only after a successful write.

## Window placement, shape and displays

Use `api.setWindowTitle(title)`, `api.hideWindow()`, `api.showWindow()` and `api.quit()` for simple commands. They do not return confirmation promises. In Preview, quit closes the preview, not the builder. In an exported app it quits that app. The host also handles the standard `window.close()` request. Closing a window is not the same as quitting the app. For placement and desktop widgets, use `api.window`.

| Window method | Behavior |
| --- | --- |
| `getState()` | Resolves to the current options plus `bounds`, `displayId`, `minimized`, `zoomed`, `fullscreen` and `userRestored`. |
| `getDisplays()` | Resolves to entries with `id`, `name`, `bounds`, `visibleBounds`, `scale` and `primary`. |
| `configure(options)` | Merges the supplied options and resolves to the resulting state. Unknown keys or values reject. |
| `setBounds({x, y, width, height})` | Changes supplied fields in logical screen points. Use the returned state for the actual bounds after fitting or anchoring. |
| `moveToDisplay(id)` | Moves the one interactive window to a connected display. |
| `startDrag({snapToEdge: true})` | Starts a real user drag. Prefer an HTML grip with `data-htmltoapp-drag` or `data-htmltoapp-drag="snap"`. Buttons and fields are excluded. |
| `setShape(source)`, `setShape(null)` | Apply an alpha mask from a local image, canvas or PNG data URL, or return to tracking HTML regions. |
| `refreshShape()` | Schedules recalculation of tracked HTML regions after custom drawing or transforms. |
| `close()`, `minimize()`, `zoom()`, `toggleFullScreen()` | Native window actions. Zoom is not fullscreen. For fullscreen entry, use a titled window without all-Spaces mode. |
| `reset()` | Restore the standard frame, decoration, input policy and level. |
| `deferInitialPresentation()` | Synchronously returns a release function. Call before the first startup await and release in a finally block. It does not extend the export's roughly two-second first-window timeout. |

The origin is the **upper left of the primary display**, with positive y down. Displays to its left or above can have negative coordinates. `visibleBounds` excludes the Dock and menu bar. Display IDs are session values. Listen on `window` for `htmltoapp-displayschange` with `detail.displays` and `htmltoapp-windowchange` with the new state in `detail`.

| Configuration key | Supported values |
| --- | --- |
| `titleBar` | `standard`, `overlay` or `borderless`. Overlay keeps native buttons over the content. |
| `level` | `normal`, `floating` or `desktop`. Floating is above ordinary windows, not system security UI. |
| `transparent`, `allSpaces` | Booleans. Virtual Spaces are independent of physical displays. |
| `clickThrough` | `never`, `transparent` or `always`. Always makes the whole window ignore the mouse. |
| `anchor`, `inset` | `none`, `left`, `right`, `top`, `bottom`, `topLeft`, `topRight`, `bottomLeft`, `bottomRight`. Inset is 0 to 512 points. |
| `displayMode`, `mirrorInteraction` | `single` or `mirror`. Mirror interaction is `moveHere`, `activateHere` or `ignore`. |
| `missionControl` | `normal` or `stationary`. Stationary asks macOS to keep the widget in place. |

Enable `transparent: true` before setting a shape and leave the page background clear where the desktop should show. With `clickThrough: "transparent"`, mark the interactive surfaces with `data-htmltoapp-region` or `data-htmltoapp-region="ellipse"`. The renderer tracks up to 128 marked elements, or direct body children if none are marked. This is not pixel testing of every CSS effect. For an irregular silhouette or interior holes, pass a canvas or a local image to `setShape`. A direct PNG mask must be at most 1,024 by 1,024 pixels and its complete Base64 data URL must fit within 2,097,152 characters. If a manual mask changes, submit it again. Use `setShape(null)` to resume automatic region tracking.

Give a click-through widget a recovery action outside the window, such as a **Show Controls** item in its menu bar menu. **Window > Restore Standard Window** or **Option-Command-R** restores the normal window and locks customization for the current document. While `userRestored` is true, do not retry or immediately repin. Reloading the project unlocks customization. In contrast, the project's own `window.HTMLtoApp.window.reset()` restores the frame without imposing that user lock. Window changes can also reject while a sheet or fullscreen transition is active.

```js
// Call from a button. Place data-htmltoapp-region on the visible widget surface.
async function pinWidget() {
  const win = window.HTMLtoApp?.window;
  if (!win) return;
  await win.configure({titleBar: "borderless", level: "floating", transparent: true,
    clickThrough: "transparent", anchor: "right", inset: 8});
  await win.setBounds({width: 240, height: 160});
}
```

Mirrors are snapshots refreshed up to four times a second, not independent scripts or full-rate video windows. They pause when hidden, minimized, in native fullscreen or displaying a sheet. With `moveHere`, a click moves the interactive window to that display. With `activateHere`, it also delivers `htmltoapp-mirroractivate` with viewport `detail.x` and `detail.y`. Use `document.elementFromPoint` to identify the control. A real click on a mirror can authorize one `apps.open` request from that handler. Dispatching the same event yourself cannot create a launch gesture. Choose `ignore` for a display-only mirror.

## Find the system Dock

Use `await api.dock.getSystemPlacement()` to find which display edge to leave free for the macOS Dock. It works in Preview and in an exported app, even when the app has no Dock icon of its own. The query does not require permission to list apps, Accessibility access or Screen Recording.

| Field | What it tells you |
| --- | --- |
| `displayId` | The Dock's current display. Match it to an `id` from `api.window.getDisplays()`, not to a display name or the primary screen. |
| `edge` and `orientation` | A bottom Dock is `bottom` and `horizontal`. A side Dock is `left` or `right` and `vertical`. |
| `estimatedHeight` and `estimatedWidth` | The estimated thickness in screen points. Only height applies to a bottom Dock and only width to a side Dock. This is not the length of the Dock or the size of its icons. |
| `reservedArea` | When macOS reserves one identifiable strip, this is `{displayId, edge, thickness}`. After the Dock moves, the strip may still be on the previous display. |

Unknown fields are `null`, not zero. An auto-hidden Dock may have no detectable location. If the current Dock and the reserved strip disagree, both size estimates are `null`. For ordinary window placement use the target display's `visibleBounds`, which already accounts for reserved space. Do not subtract the Dock thickness again.

For example, a shelf that normally sits on the right can choose the left edge when the Dock occupies the right edge of that same display. Pass the shelf's target display ID, or `(await api.window.getState()).displayId` for its current display.

```js
async function chooseShelfEdge(displayId) {
  const dock = window.HTMLtoApp?.dock;
  if (typeof dock?.getSystemPlacement === "function") {
    try {
      const placement = await dock.getSystemPlacement();
      if (placement.displayId === displayId && placement.edge === "right") return "left";
    } catch {
      // Keep the default edge if the host cannot answer.
    }
  }
  return "right";
}
```

Read the placement when showing or repositioning the shelf and after `htmltoapp-displayschange`. Moving the Dock between connected displays does not always change the display arrangement. There is no Dock-moved event or background monitor.

## Installed applications

Use `await api.apps.permissions()` to read `{list, open, dockArtwork}`. Listing and opening are separate, optional user settings in Preview and export. `await api.apps.list()` returns eligible applications in accessible Applications folders as `{id, name}` records. `await api.apps.icon(id)` returns a small PNG data URL or null for an unavailable app. Both calls require listing access. Fetch icons for displayed rows rather than every app at once.

`await api.apps.open(id)` requests an installed **bundle identifier**, not a path, URL, command or argument list. Call it directly from a button activated by a real left click, Return or Space in the active project window. Each gesture can authorize one request and expires after one second. Load the list and icons before the click, not between the click and the launch. A timer or a synthetic DOM click cannot supply that gesture.

The native confirmation identifies the target. **Allow Once** permits that launch. **Allow Any App** skips more confirmations for the current document, not the gesture requirement. Reloading, navigating or closing ends that consent. **Cancel** resolves to false, success to true, and unavailable targets or disallowed requests reject. A tool that only opens a known app need not enumerate installed apps.

For example, give a real HTML button and a visible status element to this function. Supply an ID from the list or a known bundle identifier. A cancellation is not an error.

```js
async function wireLaunchButton(button, status, id) {
  const apps = window.HTMLtoApp?.apps;
  button.disabled = true;
  if (typeof apps?.permissions !== "function" || typeof apps.open !== "function") {
    status.textContent = "Open this project in HTML to App to launch apps.";
    return;
  }
  try {
    if (!(await apps.permissions()).open) {
      status.textContent = "Enable Open Installed Apps for this project.";
      return;
    }
  } catch {
    status.textContent = "App launch permission is unavailable.";
    return;
  }
  button.onclick = async () => {
    try {
      const opened = await apps.open(id);
      status.textContent = opened ? "App opened." : "Launch cancelled.";
    } catch (error) {
      status.textContent = error?.message || "Could not open the app.";
    }
  };
  button.disabled = false;
}
```

## Show or hide the Dock icon

An exported app normally starts with a Dock icon. For a menu bar utility, put the following in the entry page's `<head>`. Export reads it before the app launches, so the icon never has to appear just to be hidden. Omit the tag or use `content="true"` for the default. Re-export after changing it, even for a linked folder. The tag does not hide the window or create a menu bar item.

```html
<meta name="htmltoapp:dock-visible" content="false">
```

| Method | Behavior |
| --- | --- |
| `await api.dock.isVisible()` | Reports whether the running export shows its Dock icon. Always returns `false` in Preview. |
| `await api.dock.setVisible(true)` or `await api.dock.setVisible(false)` | Shows or hides the running app's icon without opening or hiding its window. Pass a boolean. Resolves to `true` on success, including when already in the requested state. Preview rejects the request and leaves the builder's icon alone. |

The choice lasts until the app quits, including across page reloads and window changes. The next launch uses the metadata again. Do not gate **Show Dock icon** on `dock.isAvailable()`. That checks whether artwork can be drawn on a *visible* icon. Hiding the running icon also takes the app out of the app switcher, but does not remove a shortcut the user pinned to the Dock. Give menu bar users **Show Window** and **Quit** actions.

To try it, create a fresh **Menu Bar Controls** project from the gallery and export it. Open the app, choose **Show Dock icon**, then click the icon to see the reopen event in the example's log. Choose **Hide Dock icon** and the window stays open. If a project instead calls `api.hideWindow()` on its only window, the export stays running. Reopen it in Finder or click its visible Dock icon to bring the window back.

## Live Dock artwork, badges and notifications

- `await api.dock.isAvailable()` checks for an exported app with a visible Dock icon. Preview does not change the builder's Dock artwork.
- `await api.dock.setIcon(source)` accepts a local project image, loaded image element, canvas or PNG data URL. A direct PNG must be at most 256 by 256 pixels. The 2,097,152-character limit is on the complete Base64 data URL, not the decoded file. Other supplied images are scaled to fit. Artwork is throttled to ten frames per second and a skipped frame returns false. A clock can update once per second.
- `await api.dock.resetIcon()` restores the original artwork. No on-disk bundle icon changes. `api.dock.onClick(handler)` returns an unsubscribe function. The handler receives a DOM event with `detail.hadVisibleWindows`. The equivalent `htmltoapp-dockclick` is a macOS reopen request. Opening the already running app from Finder can send it too. It is not the first launch, a right-click, or a Dock file drop.
- `api.setBadge(value)` and `api.clearBadge()` set a Dock badge, separate from artwork and from menu bar badges. Preview shares the builder's notification authorization and Dock badge. The gallery examples deliberately leave those alone in Preview. Test your project's own notification permission, badge and artwork in an export.
- For a local notification, check `Notification.permission`, call `Notification.requestPermission()` from a user action if it is still `"default"`, then use `new Notification(title, {body})` if granted. Only the title and body reach the native notification. The browser-style `tag`, `icon` and `silent` options do not replace a previous notification, provide a custom notification image, or mute its sound. Do not design a workflow around notification clicks. The bridge does not deliver a native click to `onclick`, and `close()` fires a JavaScript callback without removing the delivered macOS notification. The `onshow` and `onerror` callbacks reflect permission, not confirmed delivery. There is no Web Push or scheduling after the app quits.

Call this example from a **Notify Me** button. A result of `"requested"` is not proof that the person saw a notification.

```js
async function requestNotice(title, body) {
  if (!("Notification" in window)) return "unavailable";
  const permission = Notification.permission === "default"
    ? await Notification.requestPermission()
    : Notification.permission;
  if (permission !== "granted") return permission;
  new Notification(title, {body});
  return "requested";
}
```

## Menu bar

`api.menuBar.configure(options)` sets status item behavior. Use `setIcon(optionsOrImage)`, `setTitle(text)`, `setTooltip(text)`, `hideIcon()`, `setBadge(value)` and `clearBadge()` on that namespace. Icon options include `title`, `tooltip`, `image`, `imageVisible`, `imagePosition` (left or right) and `template`. Use a small local PNG encoded as a data URL for custom artwork.

Use `visible` to show or hide the item, `openMenuOn` to choose the mouse button and `showWindowOnClick` to control window activation. An exported app can include or omit its native menu actions with `defaultMenuItems`. Preview shows the project's menu items instead. The same options object can include `closeToMenuBarOnWindowClose`, `badge`, `menu`, `onClick` and `onItemClick`. A menu bar badge is drawn on the image. It does not add a count to a text-only title.

`setMenu(itemsOrProvider)` accepts an array or a provider function. The provider may return an array or an object with an `items` array, directly or as a promise. The host can ask for the menu when the provider is registered as well as when the menu opens, so keep the provider free of side effects. Give actions stable `id` and `title` values. Items support `enabled`, `hidden`, `checked` (or `state: "on"`), `toggle`, a single-character `keyEquivalent` (or `key`), nested `submenu` arrays (or `items`) and `{type: "separator"}`. Use `setOpenMenuOn("left" | "right" | "middle" | "other" | "any" | "none")` to choose the trigger and `closeMenu()` to dismiss it.

`onClick(handler)` and `onItemClick(handler)` return unsubscribe functions. The callbacks receive payloads directly. The DOM equivalents are `htmltoapp-menubar-click` and `htmltoapp-menubar-item-click`, with the payload in `event.detail`. Register one mechanism, not both for the same action. Menu item payloads include `id`, `title`, `checked`, `state`, `toggle` and `path`. Status clicks include `button`, `hasMenu` and `willOpenMenu`.

With a visible status item, `setCloseToMenuBarOnWindowClose(true)` lets an export stay in the menu bar when the user closes its window. Without an explicit `dock.setVisible()` choice, closing to the menu bar hides the Dock icon and showing the window restores the launch default. This is separate from a project hiding its own window. Neither mechanism installs a daemon or guarantees timers across sleep or after quitting.

