Skip to content

armgit / bento

Public Imported from GitHub
0

Bento, the office suite that fits in a file

tray/ios: support single-file apps that are not Bento

nyblnetb8e94942bda0
diff --git a/tray/README.md b/tray/README.md
index 168b21f2..0349a18e 100644
--- a/tray/README.md
+++ b/tray/README.md
@@ -55,6 +55,30 @@ methods. Two consequences:
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.
+### Saving from apps that are not Bento
+
+Two idioms, both supported, because "any self-contained HTML document" has to
+mean more than "any document that saves the way Bento does":
+
+- **File System Access.** The handle implements `kind`, `name`, `isSameEntry`,
+ `queryPermission`, `requestPermission`, `getFile` and `createWritable`; the
+ writable implements `write` (raw data AND the `{type:'write'|'seek'|'truncate'}`
+ params form), `seek`, `truncate`, `abort` and `close`. Bento only ever calls
+ `createWritable`/`write`/`close`, but a third-party page may reasonably call
+ `queryPermission()` before saving or `truncate()` to overwrite in place — a
+ live probe page reported those as `undefined` before this existed.
+ `getFile()` and `keepExistingData` need the bytes on disk, so the bridge has a
+ `read` op; only the OPEN document is readable, since an export target is
+ somewhere we were handed once and do not hold.
+
+- **`<a download>`.** The older and commoner idiom — TiddlyWiki, and most
+ "export this page" tools. WKWebView DROPS these silently without a download
+ delegate, so the button appears to do nothing, which is the worst possible
+ failure for a save. Downloads land in the app's Documents folder (visible in
+ Files under Bento Tray) with a collision-safe name and a confirmation. A
+ picker per save would punish an app that saves often, and a download cannot
+ overwrite the user's original anyway — that is what the FSA path is for.
+
### Which file a save targets
Bento only reaches a picker when it holds **no handle**; afterwards ⌘S, autosave
diff --git a/tray/ios/EditorViewController.swift b/tray/ios/EditorViewController.swift
index 7b5180a4..2373e0a3 100644
--- a/tray/ios/EditorViewController.swift
+++ b/tray/ios/EditorViewController.swift
@@ -34,7 +34,8 @@ import CryptoKit
/// 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 {
+final class EditorViewController: UIViewController, WKScriptMessageHandler, WKURLSchemeHandler,
+ WKNavigationDelegate, WKDownloadDelegate {
private let document: BentoDocument
private var webView: WKWebView!
@@ -157,6 +158,7 @@ final class EditorViewController: UIViewController, WKScriptMessageHandler, WKUR
webView = WKWebView(frame: view.bounds, configuration: cfg)
webView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
webView.allowsBackForwardNavigationGestures = false
+ webView.navigationDelegate = self
// The page must reach every physical edge. Left at .automatic, UIKit
// insets the scroll view by the safe area, so in landscape the deck
// stopped short of the left, right and bottom edges — visible as bands
@@ -199,6 +201,69 @@ final class EditorViewController: UIViewController, WKScriptMessageHandler, WKUR
}
func webView(_ webView: WKWebView, stop task: WKURLSchemeTask) {}
+ // MARK: - downloads
+ //
+ // Not every self-contained HTML app saves through the File System Access
+ // API. The older and still commonest idiom is a Blob plus `<a download>` —
+ // TiddlyWiki, and most "export this page" tools. WKWebView DROPS those
+ // silently unless a download delegate exists, so the button appears to do
+ // nothing at all, which is the worst possible failure for a save.
+ //
+ // Downloads land in the app's Documents folder, which is visible in Files
+ // under Bento Tray. A picker per save would be punishing for an app that
+ // saves often, and a download cannot overwrite the user's original anyway —
+ // that is what the FSA path is for.
+
+ func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction,
+ decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
+ decisionHandler(navigationAction.shouldPerformDownload ? .download : .allow)
+ }
+
+ func webView(_ webView: WKWebView, decidePolicyFor navigationResponse: WKNavigationResponse,
+ decisionHandler: @escaping (WKNavigationResponsePolicy) -> Void) {
+ decisionHandler(navigationResponse.canShowMIMEType ? .allow : .download)
+ }
+
+ func webView(_ webView: WKWebView, navigationAction: WKNavigationAction,
+ didBecome download: WKDownload) { download.delegate = self }
+
+ func webView(_ webView: WKWebView, navigationResponse: WKNavigationResponse,
+ didBecome download: WKDownload) { download.delegate = self }
+
+ func download(_ download: WKDownload, decideDestinationUsing response: URLResponse,
+ suggestedFilename: String, completionHandler: @escaping (URL?) -> Void) {
+ guard let docs = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first
+ else { completionHandler(nil); return }
+ var dest = docs.appendingPathComponent(suggestedFilename)
+ // never clobber: downloads are new files by definition
+ var n = 2
+ let ext = dest.pathExtension
+ let stem = dest.deletingPathExtension().lastPathComponent
+ while FileManager.default.fileExists(atPath: dest.path) {
+ dest = docs.appendingPathComponent(ext.isEmpty ? "\(stem) \(n)" : "\(stem) \(n).\(ext)")
+ n += 1
+ }
+ lastDownloadName = dest.lastPathComponent
+ completionHandler(dest)
+ }
+
+ func downloadDidFinish(_ download: WKDownload) {
+ notify(String(format: NSLocalizedString("Saved “%@” to this app’s folder in Files.",
+ comment: "download finished"), lastDownloadName ?? "file"))
+ }
+
+ func download(_ download: WKDownload, didFailWithError error: Error, resumeData: Data?) {
+ notify(NSLocalizedString("That download could not be saved.", comment: "download failed"))
+ }
+
+ private var lastDownloadName: String?
+
+ private func notify(_ message: String) {
+ let a = UIAlertController(title: nil, message: message, preferredStyle: .alert)
+ a.addAction(UIAlertAction(title: NSLocalizedString("OK", comment: ""), style: .default))
+ present(a, animated: true)
+ }
+
// MARK: - the save bridge
func userContentController(_ c: WKUserContentController, didReceive message: WKScriptMessage) {
@@ -217,6 +282,17 @@ final class EditorViewController: UIViewController, WKScriptMessageHandler, WKUR
reply(id, ok: true, value: pendingExportName!)
}
+ case "read":
+ // getFile() and createWritable({keepExistingData}) need the bytes
+ // currently on disk. Only the OPEN document is readable — an export
+ // target is somewhere we were handed once and do not hold.
+ let want = (m["name"] as? String) ?? ""
+ if want == document.fileURL.lastPathComponent {
+ reply(id, ok: true, value: String(data: document.html, encoding: .utf8) ?? "")
+ } else {
+ reply(id, ok: true, value: nil)
+ }
+
case "write":
let text = (m["text"] as? String) ?? ""
let name = (m["name"] as? String) ?? ""
diff --git a/tray/ios/Resources/bridge.js b/tray/ios/Resources/bridge.js
index bc7a927c..3e7d9808 100644
--- a/tray/ios/Resources/bridge.js
+++ b/tray/ios/Resources/bridge.js
@@ -47,22 +47,66 @@
// 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.
+ // Bento derives that name from the DECK TITLE, so it rarely matches and
+ // every save would wrongly prompt.
const name = await call('begin', { suggestedName: want })
+ return makeHandle(name)
+ }
+
+ // A FileSystemFileHandle faithful enough for apps that are not Bento.
+ // Bento itself only ever touches createWritable/write/close, but this host
+ // opens ANY self-contained HTML document, and a real app may well call
+ // queryPermission() before saving or truncate() to overwrite in place. Those
+ // returned `undefined` and threw — measured against a live third-party page,
+ // not guessed.
+ function makeHandle(name) {
return {
- name,
- createWritable: async () => {
- const parts = []
+ kind: 'file',
+ name: name,
+ isSameEntry: (other) => Promise.resolve(!!other && other.name === name),
+ // Permissions are meaningless here: the user already granted access by
+ // opening the document. Always-granted is the truthful answer.
+ queryPermission: () => Promise.resolve('granted'),
+ requestPermission: () => Promise.resolve('granted'),
+ getFile: async () => {
+ const text = await call('read', { name })
+ return new File([text == null ? '' : text], name, { type: 'text/html' })
+ },
+ createWritable: async (o) => {
+ // keepExistingData means "start from what is on disk", which requires
+ // reading it back — the spec default is an empty file.
+ let buf = (o && o.keepExistingData) ? (await call('read', { name })) || '' : ''
+ let pos = buf.length
+ const asText = async (d) => {
+ if (d == null) return ''
+ if (typeof d === 'string') return d
+ if (d instanceof Blob) return await d.text()
+ if (d instanceof ArrayBuffer || ArrayBuffer.isView(d)) return new TextDecoder().decode(d)
+ return String(d)
+ }
+ const put = (text) => {
+ if (pos > buf.length) buf = buf + '\0'.repeat(pos - buf.length)
+ buf = buf.slice(0, pos) + text + buf.slice(pos + text.length)
+ pos += text.length
+ }
return {
async write(data) {
- parts.push(typeof data === 'string' ? data : await data.text())
- },
- async close() {
- await call('write', { name, text: parts.join('') })
+ // the params form: {type:'write'|'seek'|'truncate', data, position, size}
+ if (data && typeof data === 'object' && typeof data.type === 'string') {
+ if (data.type === 'seek') { pos = data.position || 0; return }
+ if (data.type === 'truncate') { buf = buf.slice(0, data.size || 0); if (pos > buf.length) pos = buf.length; return }
+ if (typeof data.position === 'number') pos = data.position
+ put(await asText(data.data))
+ return
+ }
+ put(await asText(data))
},
+ async seek(p) { pos = p || 0 },
+ async truncate(size) { buf = buf.slice(0, size || 0); if (pos > buf.length) pos = buf.length },
+ async abort() { buf = ''; pos = 0 },
+ async close() { await call('write', { name, text: buf }) },
}
},
}
}
-})()
+})();