Skip to content

armgit / bento

Public Imported from GitHub
0

Bento, the office suite that fits in a file

iOS host: scaffold a native wrapper so decks save in place

nyblnet61637c8ad10f
diff --git a/.gitignore b/.gitignore
index d7194101..9e3857f6 100644
--- a/.gitignore
+++ b/.gitignore
@@ -26,3 +26,7 @@ working/
# make-og.mjs intermediate (the SVG rasterised into site-src/og.png)
scripts/.cache/
+
+# generated Xcode project — regenerate with `cd ios && xcodegen`
+ios/*.xcodeproj/
+ios/BentoHost/Resources/starter.bento.html
diff --git a/ios/BentoHost/AppDelegate.swift b/ios/BentoHost/AppDelegate.swift
new file mode 100644
index 00000000..24b48ada
--- /dev/null
+++ b/ios/BentoHost/AppDelegate.swift
@@ -0,0 +1,15 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+
+import UIKit
+
+@main
+final class AppDelegate: UIResponder, UIApplicationDelegate {
+ func application(_ app: UIApplication,
+ configurationForConnecting session: UISceneSession,
+ options: UIScene.ConnectionOptions) -> UISceneConfiguration {
+ let cfg = UISceneConfiguration(name: "Default", sessionRole: session.role)
+ cfg.delegateClass = SceneDelegate.self
+ return cfg
+ }
+}
diff --git a/ios/BentoHost/BentoDocument.swift b/ios/BentoHost/BentoDocument.swift
new file mode 100644
index 00000000..4a53b095
--- /dev/null
+++ b/ios/BentoHost/BentoDocument.swift
@@ -0,0 +1,27 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+
+import UIKit
+
+/// A `.bento.html` opened IN PLACE from Files/iCloud/Dropbox.
+///
+/// UIDocument is what makes the whole app worth building: it is the only way to
+/// write back to the user's actual file on iOS. Every browser there is WebKit,
+/// so the File System Access API does not exist and the web app can only ever
+/// hand back downloaded copies.
+///
+/// The bytes are kept as Data and handed to the web view untouched. The app
+/// never parses, rewrites or "understands" the document — it is a courier. That
+/// is deliberate: the file carries its own runtime, so a deck saved by any past
+/// or future version of Bento opens correctly without this app knowing anything
+/// about the format.
+final class BentoDocument: UIDocument {
+ var html: Data = Data()
+
+ override func contents(forType typeName: String) throws -> Any { html }
+
+ override func load(fromContents contents: Any, ofType typeName: String?) throws {
+ guard let data = contents as? Data else { return }
+ html = data
+ }
+}
diff --git a/ios/BentoHost/DocumentBrowserViewController.swift b/ios/BentoHost/DocumentBrowserViewController.swift
new file mode 100644
index 00000000..70045268
--- /dev/null
+++ b/ios/BentoHost/DocumentBrowserViewController.swift
@@ -0,0 +1,60 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+
+import UIKit
+
+/// The app's root: the system document browser. Opening IN PLACE is the whole
+/// point — the user picks a deck wherever it already lives (Files, iCloud,
+/// Dropbox, a Downloads folder) and edits travel back to that same file.
+final class DocumentBrowserViewController: UIDocumentBrowserViewController,
+ UIDocumentBrowserViewControllerDelegate {
+ override func viewDidLoad() {
+ super.viewDidLoad()
+ delegate = self
+ allowsDocumentCreation = true
+ allowsPickingMultipleItems = false
+ }
+
+ /// A new deck is seeded from a bundled starter shell. That bundled copy is
+ /// the ONLY Bento version the app ships, and it ages harmlessly: a new deck
+ /// self-updates through the normal signed channel the first time it checks,
+ /// so the seed drifting behind a release does not strand anyone.
+ func documentBrowser(_ c: UIDocumentBrowserViewController,
+ didRequestDocumentCreationWithHandler handler:
+ @escaping (URL?, UIDocumentBrowserViewController.ImportMode) -> Void) {
+ guard let seed = Bundle.main.url(forResource: "starter", withExtension: "bento.html") else {
+ handler(nil, .none); return
+ }
+ let tmp = FileManager.default.temporaryDirectory.appendingPathComponent("Untitled.bento.html")
+ try? FileManager.default.removeItem(at: tmp)
+ do { try FileManager.default.copyItem(at: seed, to: tmp) } catch { handler(nil, .none); return }
+ handler(tmp, .move)
+ }
+
+ func documentBrowser(_ c: UIDocumentBrowserViewController, didPickDocumentsAt urls: [URL]) {
+ guard let url = urls.first else { return }
+ present(url)
+ }
+
+ func documentBrowser(_ c: UIDocumentBrowserViewController, didImportDocumentAt sourceURL: URL,
+ toDestinationURL destinationURL: URL) {
+ present(destinationURL)
+ }
+
+ private func present(_ url: URL) {
+ // Security-scoped access: a document opened in place lives outside the
+ // app container, so the URL must be scoped for the whole editing
+ // session and released when the editor closes.
+ let scoped = url.startAccessingSecurityScopedResource()
+ let doc = BentoDocument(fileURL: url)
+ doc.open { [weak self] ok in
+ guard let self, ok else {
+ if scoped { url.stopAccessingSecurityScopedResource() }
+ return
+ }
+ let editor = EditorViewController(document: doc)
+ editor.modalPresentationStyle = .fullScreen
+ self.present(editor, animated: true)
+ }
+ }
+}
diff --git a/ios/BentoHost/EditorViewController.swift b/ios/BentoHost/EditorViewController.swift
new file mode 100644
index 00000000..d288bdba
--- /dev/null
+++ b/ios/BentoHost/EditorViewController.swift
@@ -0,0 +1,134 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+
+import UIKit
+import WebKit
+import UniformTypeIdentifiers
+
+/// Hosts one open deck in a WKWebView and bridges saving to UIDocument.
+///
+/// TWO decisions here carry the design:
+///
+/// 1. The deck is served through a CUSTOM SCHEME, never `loadFileURL`. A
+/// file:// page in WKWebView gets an opaque, unstable origin, which makes
+/// localStorage and IndexedDB unreliable — that would silently break the
+/// autosave backstop, the per-device collab member key, and the language and
+/// reduce-motion preferences. A custom scheme is a stable secure origin, and
+/// it keeps cross-origin fetches to the sync relay well-defined rather than
+/// arriving as `Origin: null`.
+///
+/// 2. The web content is the DOCUMENT'S OWN runtime. The app bundles no shell
+/// for rendering and has no opinion about which version a deck carries, so a
+/// deck self-updates through Bento's normal signed channel and iOS users get
+/// the same release as everyone else on the same day — no App Store
+/// submission per release, no drift. What the app ships is file access.
+final class EditorViewController: UIViewController, WKScriptMessageHandler, WKURLSchemeHandler {
+ private let document: BentoDocument
+ private var webView: WKWebView!
+
+ /// Has the open document been handed to the web app yet? Bento only reaches
+ /// a picker when it holds no handle — afterwards ⌘S, autosave write-back and
+ /// in-place update all reuse it. So the FIRST request targets this document
+ /// and needs no UI; any later one is a genuine Save-As or export and must
+ /// not overwrite it. Comparing filenames instead would fail: Bento derives
+ /// its suggested name from the deck TITLE, so it rarely matches.
+ private var openDocumentVended = false
+ private var pendingExportName: String?
+
+ init(document: BentoDocument) {
+ self.document = document
+ super.init(nibName: nil, bundle: nil)
+ }
+ required init?(coder: NSCoder) { fatalError("not used") }
+
+ override func viewDidLoad() {
+ super.viewDidLoad()
+ let cfg = WKWebViewConfiguration()
+ cfg.setURLSchemeHandler(self, forURLScheme: "bento-app")
+ cfg.userContentController.add(self, name: "bentoFile")
+
+ // .atDocumentStart is required, not stylistic: Bento decides whether it
+ // can save during boot, so a bridge injected later arrives after the
+ // editor has already concluded it cannot.
+ if let js = Bundle.main.url(forResource: "bridge", withExtension: "js"),
+ let src = try? String(contentsOf: js, encoding: .utf8) {
+ cfg.userContentController.addUserScript(
+ WKUserScript(source: src, injectionTime: .atDocumentStart, forMainFrameOnly: true))
+ }
+
+ webView = WKWebView(frame: view.bounds, configuration: cfg)
+ webView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
+ webView.allowsBackForwardNavigationGestures = false
+ view.addSubview(webView)
+ webView.load(URLRequest(url: URL(string: "bento-app://deck/index.html")!))
+ }
+
+ // MARK: - serving the deck
+
+ func webView(_ webView: WKWebView, start task: WKURLSchemeTask) {
+ let resp = HTTPURLResponse(url: task.request.url!, statusCode: 200, httpVersion: "HTTP/1.1",
+ headerFields: ["Content-Type": "text/html; charset=utf-8",
+ "Content-Length": String(document.html.count)])!
+ task.didReceive(resp)
+ task.didReceive(document.html)
+ task.didFinish()
+ }
+ func webView(_ webView: WKWebView, stop task: WKURLSchemeTask) {}
+
+ // MARK: - the save bridge
+
+ func userContentController(_ c: WKUserContentController, didReceive message: WKScriptMessage) {
+ guard let m = message.body as? [String: Any],
+ let id = m["id"] as? Int, let op = m["op"] as? String else { return }
+
+ switch op {
+ case "begin":
+ if !openDocumentVended {
+ openDocumentVended = true
+ reply(id, ok: true, value: document.fileURL.lastPathComponent)
+ } else {
+ // A copy/template/read-only export. Ask where it goes; it must
+ // never land on the open document.
+ pendingExportName = (m["suggestedName"] as? String) ?? "deck.bento.html"
+ reply(id, ok: true, value: pendingExportName!)
+ }
+
+ case "write":
+ let text = (m["text"] as? String) ?? ""
+ let name = (m["name"] as? String) ?? ""
+ if name == document.fileURL.lastPathComponent {
+ document.html = Data(text.utf8)
+ // updateChangeCount + autosave is the sanctioned path: it
+ // coordinates with iCloud and file coordination rather than
+ // writing behind UIDocument's back.
+ document.updateChangeCount(.done)
+ document.save(to: document.fileURL, for: .forOverwriting) { [weak self] ok in
+ self?.reply(id, ok: ok, value: ok ? nil : "write failed")
+ }
+ } else {
+ exportCopy(named: name, text: text) { [weak self] ok, err in
+ self?.reply(id, ok: ok, value: err)
+ }
+ }
+
+ default:
+ reply(id, ok: false, value: "unknown op")
+ }
+ }
+
+ private func reply(_ id: Int, ok: Bool, value: String?) {
+ let arg = value.map { "\"\($0.replacingOccurrences(of: "\"", with: "\\\""))\"" } ?? "null"
+ webView.evaluateJavaScript("window.__bentoNativeReply(\(id), \(ok), \(arg))")
+ }
+
+ /// Write an exported copy to a temp file and let the user place it. Kept
+ /// separate from the open document on purpose — a share export carries
+ /// different credentials (a read-only copy has the owner keys stripped), so
+ /// overwriting the original with one would be a real data loss.
+ private func exportCopy(named name: String, text: String, done: @escaping (Bool, String?) -> Void) {
+ let tmp = FileManager.default.temporaryDirectory.appendingPathComponent(name)
+ do { try Data(text.utf8).write(to: tmp) } catch { done(false, "\(error)"); return }
+ let picker = UIDocumentPickerViewController(forExporting: [tmp], asCopy: true)
+ present(picker, animated: true) { done(true, nil) }
+ }
+}
diff --git a/ios/BentoHost/Info.plist b/ios/BentoHost/Info.plist
new file mode 100644
index 00000000..06103748
--- /dev/null
+++ b/ios/BentoHost/Info.plist
@@ -0,0 +1,34 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict>
+ <key>CFBundleDisplayName</key><string>Bento</string>
+ <key>CFBundlePackageType</key><string>APPL</string>
+ <key>LSSupportsOpeningDocumentsInPlace</key><true/>
+ <key>UISupportsDocumentBrowser</key><true/>
+ <key>UIFileSharingEnabled</key><true/>
+ <key>UILaunchScreen</key><dict/>
+ <key>CFBundleDocumentTypes</key>
+ <array>
+ <dict>
+ <key>CFBundleTypeName</key><string>Bento document</string>
+ <key>CFBundleTypeRole</key><string>Editor</string>
+ <key>LSHandlerRank</key><string>Alternate</string>
+ <key>LSItemContentTypes</key>
+ <array><string>public.html</string></array>
+ </dict>
+ </array>
+ <key>UIApplicationSceneManifest</key>
+ <dict>
+ <key>UIApplicationSupportsMultipleScenes</key><true/>
+ <key>UISceneConfigurations</key>
+ <dict>
+ <key>UIWindowSceneSessionRoleApplication</key>
+ <array><dict>
+ <key>UISceneConfigurationName</key><string>Default</string>
+ <key>UISceneDelegateClassName</key><string>$(PRODUCT_MODULE_NAME).SceneDelegate</string>
+ </dict></array>
+ </dict>
+ </dict>
+</dict>
+</plist>
diff --git a/ios/BentoHost/Resources/bridge.js b/ios/BentoHost/Resources/bridge.js
new file mode 100644
index 00000000..bc7a927c
--- /dev/null
+++ b/ios/BentoHost/Resources/bridge.js
@@ -0,0 +1,68 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+//
+// The ENTIRE web-side surface of the iOS host: a polyfill of the one File
+// System Access call Bento tests for. Injected at .atDocumentStart, because
+// capability is read during boot — inject it later and the editor has already
+// decided it cannot save.
+//
+// Bento needs exactly this much of the API (kernel/src/save.ts):
+// showSaveFilePicker({suggestedName}) -> { name, createWritable() }
+// createWritable() -> { write(Blob|string), close() }
+// ...and hasFsAccess() is just `typeof window.showSaveFilePicker === 'function'`.
+//
+// That is why the app needs NO changes to Bento and works with decks saved by
+// any past version: every in-place path (⌘S, autosave write-back, self-update)
+// already routes through this one function. A bespoke `window.__bentoHost`
+// bridge would only have helped decks re-saved after it shipped.
+(function () {
+ const bridge = window.webkit && window.webkit.messageHandlers
+ && window.webkit.messageHandlers.bentoFile
+ if (!bridge) return // plain browser: leave the real API (or its absence) alone
+
+ let seq = 0
+ const pending = new Map()
+
+ // native calls back into this
+ window.__bentoNativeReply = (id, ok, value) => {
+ const p = pending.get(id)
+ if (!p) return
+ pending.delete(id)
+ ok ? p.resolve(value) : p.reject(new Error(value || 'cancelled'))
+ }
+
+ const call = (op, payload) => new Promise((resolve, reject) => {
+ const id = ++seq
+ pending.set(id, { resolve, reject })
+ bridge.postMessage(Object.assign({ id, op }, payload))
+ })
+
+ window.showSaveFilePicker = async (opts) => {
+ const want = (opts && opts.suggestedName) || ''
+ // Native decides what this call targets; the rule is DETERMINISTIC and lives
+ // there, not here. Bento only reaches a picker when it holds no handle —
+ // once it has one, ⌘S, autosave write-back and in-place update all reuse it
+ // (kernel/src/save.ts). So the FIRST call is "the document already open in
+ // the app" and resolves with no UI, and any LATER call is a genuine Save-As
+ // or export (read-only copy, invite, template) that must not overwrite it.
+ //
+ // Do NOT try to infer this by comparing suggestedName to the open file:
+ // Bento derives that name from the DECK TITLE, so it rarely matches the
+ // filename and every save would wrongly prompt.
+ const name = await call('begin', { suggestedName: want })
+ return {
+ name,
+ createWritable: async () => {
+ const parts = []
+ return {
+ async write(data) {
+ parts.push(typeof data === 'string' ? data : await data.text())
+ },
+ async close() {
+ await call('write', { name, text: parts.join('') })
+ },
+ }
+ },
+ }
+ }
+})()
diff --git a/ios/BentoHost/SceneDelegate.swift b/ios/BentoHost/SceneDelegate.swift
new file mode 100644
index 00000000..409d927d
--- /dev/null
+++ b/ios/BentoHost/SceneDelegate.swift
@@ -0,0 +1,17 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+
+import UIKit
+
+final class SceneDelegate: UIResponder, UIWindowSceneDelegate {
+ var window: UIWindow?
+
+ func scene(_ scene: UIScene, willConnectTo session: UISceneSession,
+ options: UIScene.ConnectionOptions) {
+ guard let ws = scene as? UIWindowScene else { return }
+ let w = UIWindow(windowScene: ws)
+ w.rootViewController = DocumentBrowserViewController()
+ w.makeKeyAndVisible()
+ window = w
+ }
+}
diff --git a/ios/README.md b/ios/README.md
new file mode 100644
index 00000000..5bba12ef
--- /dev/null
+++ b/ios/README.md
@@ -0,0 +1,107 @@
+# bento/host — iOS
+
+A thin native host so decks can be **saved in place** on iOS.
+
+## Why this exists
+
+Every browser on iOS is WebKit, so the File System Access API does not exist
+there — not in Safari, not in Chrome or Firefox, which are WKWebView underneath.
+Without it Bento can only hand back downloaded copies: no in-place save, no
+silent autosave write-back, no in-place self-update. `UIDocument` is the only
+way to write back to the user's actual file, and only a native app can use it.
+
+## What it is, and what it deliberately is not
+
+The app supplies **file access and nothing else**. It bundles no runtime for
+rendering and has no opinion about which version of Bento a deck carries.
+
+That is the decision everything else follows from. The deck runs **its own
+embedded runtime**, exactly as it would in Safari, so it self-updates through
+Bento's normal signed channel — iOS users get the same release as everyone else,
+the same day, with no App Store submission per release and no second release
+train to keep in step.
+
+The alternative (bundling a shell and rendering every deck with it) would have
+put iOS behind an App Store review queue forever and made the bundled copy drift
+from the current release. It is not needed: Apple's rule is about downloading
+code that changes the features **of the app**, and the app here behaves
+identically whatever a document contains. What updates is user content, the same
+as any page a browser renders.
+
+## How saving works — no changes to Bento
+
+`kernel/src/save.ts` tests exactly one thing: `typeof
+window.showSaveFilePicker === 'function'`, and needs only
+
+```
+showSaveFilePicker({suggestedName}) -> { name, createWritable() }
+createWritable() -> { write(Blob|string), close() }
+```
+
+So `Resources/bridge.js` polyfills that over a `UIDocument` bridge — three
+methods. Two consequences:
+
+- **No web-side changes at all.** Every in-place path (⌘S, autosave write-back,
+ self-update, the capability-aware messaging) already routes through that one
+ function.
+- **Every deck ever saved works**, including files whose embedded runtime
+ predates this app. A bespoke `window.__bentoHost` bridge would only have helped
+ decks re-saved after it shipped — which is to say, none of the existing ones.
+
+### Which file a save targets
+
+Bento only reaches a picker when it holds **no handle**; afterwards ⌘S, autosave
+and in-place update all reuse it. So the rule is deterministic:
+
+- **first** `begin` → the document already open in the app, resolved with no UI
+- **any later** `begin` → a genuine Save-As or export (read-only copy, invite,
+ template), which gets a real picker and must never overwrite the open file
+
+Do **not** infer this by comparing `suggestedName` to the open filename. Bento
+derives that name from the deck TITLE, so it rarely matches — an early version
+of this bridge did exactly that and prompted on every single save.
+
+## Two implementation details that carry weight
+
+- **The deck is served through a custom scheme** (`bento-app://`), never
+ `loadFileURL`. A `file://` page in WKWebView gets an opaque, unstable origin,
+ which makes `localStorage` and IndexedDB unreliable — silently breaking the
+ autosave backstop, the per-device collab member key, and language/motion
+ preferences. It also keeps relay fetches from arriving as `Origin: null`.
+- **`bridge.js` is injected `.atDocumentStart`.** Bento decides whether it can
+ save during boot; injected later, the editor has already concluded it cannot.
+
+## Building
+
+Needs **full Xcode** (Command Line Tools alone is not enough) and XcodeGen:
+
+```sh
+brew install xcodegen
+cd ios && xcodegen && open BentoHost.xcodeproj
+```
+
+`BentoHost.xcodeproj` is generated, never committed — a `.pbxproj` in git is a
+merge-conflict magnet.
+
+## State: scaffold, not shippable
+
+Verified — the save contract, exercised against the **real** Bento build in a
+browser with the native side emulated (`begin`/`write` over the same protocol):
+
+- ⌘S writes the open document, no export prompt, 899KB of valid HTML with the
+ `#bento-doc` block intact and no stray script-close
+- autosave write-back reuses the handle and writes again silently
+- "Save a copy…" prompts for a destination and leaves the open document
+ untouched
+
+Not verified — **none of the Swift has been compiled or run.** It was written on
+a machine without Xcode; `swiftc -parse` checks syntax only and cannot resolve
+UIKit or WebKit. Treat every Swift file as unreviewed until it builds.
+
+Still to do:
+
+- `Resources/starter.bento.html` — the seed for new documents. Not committed;
+ wire a build step that copies `slides/dist-single/Bento_Slides.bento.html`.
+ Until then, document creation fails.
+- App icon, launch screen, signing, an Apple Developer account ($99/yr).
+- Decide whether a `.bento.html` UTI is worth declaring over plain `public.html`.
diff --git a/ios/project.yml b/ios/project.yml
new file mode 100644
index 00000000..f5bcd2a0
--- /dev/null
+++ b/ios/project.yml
@@ -0,0 +1,20 @@
+# XcodeGen spec — `brew install xcodegen && cd ios && xcodegen` produces
+# BentoHost.xcodeproj. The project file is generated, never committed, so it
+# can't rot into a merge-conflict magnet the way .pbxproj does.
+name: BentoHost
+options:
+ bundleIdPrefix: page.bento
+ deploymentTarget:
+ iOS: "16.0" # WKURLSchemeHandler + modern UIDocumentBrowser behaviour
+targets:
+ BentoHost:
+ type: application
+ platform: iOS
+ sources:
+ - path: BentoHost
+ settings:
+ base:
+ INFOPLIST_FILE: BentoHost/Info.plist
+ PRODUCT_BUNDLE_IDENTIFIER: page.bento.host
+ TARGETED_DEVICE_FAMILY: "1,2" # iPhone and iPad
+ SWIFT_VERSION: "5.0"