Something went wrong. Try again.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179// The folder the person picks, mirrored as plain markdown.//// Chrome's File System Access API only — `showDirectoryPicker` does not exist in// Firefox or Safari, and a fallback that silently downloads files instead would// be a worse lie than an honest "this needs Chrome". The handle is persisted in// IndexedDB so the permission prompt is a click, not a re-pick, on the next// visit.
import { filenameOf, toMarkdown, type SceneNote } from "./notes.ts";
const HANDLE_KEY = "scn-local:public-dir";
export class FolderError extends Error { constructor(message: string) { super(message); this.name = "FolderError"; }}
export type Permission = "granted" | "denied" | "prompt";
// TypeScript's DOM lib has the File System Access handles but not the permission// methods on them yet, so say what we use rather than casting to `any`. These// are in the spec and in Chrome.interface Entries { values(): AsyncIterableIterator<FileSystemHandle>;}
interface Permissible { queryPermission(options?: { mode?: "read" | "readwrite" }): Promise<Permission>; requestPermission(options?: { mode?: "read" | "readwrite" }): Promise<Permission>;}
function permissible(handle: FileSystemDirectoryHandle): FileSystemDirectoryHandle & Permissible { return handle as FileSystemDirectoryHandle & Permissible;}
/** * Whether we may write into the folder right now. * * **A stored handle does not carry its permission across a reload.** It is * restored from IndexedDB with `prompt`, and every write against it throws * `NotAllowedError` from `getFileHandle` — which reads as a broken file system * rather than as a permission that has to be granted again, in a user gesture, * on this page. `requestPermission` needs that gesture, so the folder control * calls this on click. */export async function permissionOf(handle: FileSystemDirectoryHandle): Promise<Permission> { const state = await permissible(handle).queryPermission({ mode: "readwrite" }); if (state === "granted") return "granted"; if (state === "denied") return "denied"; return "prompt";}
/** Ask for write permission. Only works inside a click or other gesture. */export async function requestPermission(handle: FileSystemDirectoryHandle): Promise<Permission> { const target = permissible(handle); if ((await target.queryPermission({ mode: "readwrite" })) === "granted") return "granted"; return await target.requestPermission({ mode: "readwrite" });}
export function supported(): boolean { return typeof (window as unknown as { showDirectoryPicker?: unknown }).showDirectoryPicker === "function";}
export async function chooseFolder(): Promise<FileSystemDirectoryHandle> { if (!supported()) throw new Error("this browser has no File System Access API — Chrome or Edge only"); const handle = await (window as unknown as { showDirectoryPicker: (options?: { mode?: "read" | "readwrite" }) => Promise<FileSystemDirectoryHandle>; }).showDirectoryPicker({ mode: "readwrite" }); await storeHandle(handle); return handle;}
async function storeHandle(handle: FileSystemDirectoryHandle): Promise<void> { const db = await openDb(); await new Promise<void>((resolve, reject) => { const tx = db.transaction("handles", "readwrite"); tx.objectStore("handles").put(handle, HANDLE_KEY); tx.oncomplete = () => resolve(); tx.onerror = () => reject(tx.error); });}
export async function storedFolder(): Promise<FileSystemDirectoryHandle | null> { const db = await openDb(); return new Promise((resolve, reject) => { const tx = db.transaction("handles", "readonly"); const request = tx.objectStore("handles").get(HANDLE_KEY); request.onsuccess = () => resolve((request.result as FileSystemDirectoryHandle) ?? null); request.onerror = () => reject(request.error); });}
function openDb(): Promise<IDBDatabase> { return new Promise((resolve, reject) => { const request = indexedDB.open("scn-local-fs", 1); request.onupgradeneeded = () => request.result.createObjectStore("handles"); request.onsuccess = () => resolve(request.result); request.onerror = () => reject(request.error); });}
/** Write one note to the chosen folder: `<slug>.md`, front matter and all. */export async function writeNote(folder: FileSystemDirectoryHandle, note: SceneNote): Promise<void> { if ((await permissionOf(folder)) !== "granted") { // Explicit, because the raw failure is `getFileHandle` throwing NotAllowed // and that says nothing about what to do next. throw new FolderError("the folder needs write permission again — click the folder to grant it"); }
const name = filenameOf(note); if (!name || name.includes("/") || name === "." || name === "..") { throw new FolderError(`not a usable filename: ${JSON.stringify(name)}`); }
const file = await folder.getFileHandle(name, { create: true }); const writable = await file.createWritable(); await writable.write(toMarkdown(note)); await writable.close();}
export interface LocalFile { name: string; /** * Modified time from the File API. * * **There is no creation time.** `FileSystemFileHandle.getFile()` returns a * `File`, and a `File` carries `lastModified` and nothing else — the File * System Access API does not expose birth time, and `lastModifiedDate` is * deprecated. So a note's creation date has to come from the note, i.e. from * its front matter, which the caller reads out of `text`. */ modified: number; /** The file's markdown, so the caller can read front matter without a second read. */ text: string;}
/** * The markdown already in the folder. * * The mirror was one-way for too long: a file dropped in by hand was invisible, * which made the folder look like an export rather than a copy. This is the * other direction — not a sync, just a listing, so the app can show what is on * disk and offer to publish it. */export async function listMarkdown(folder: FileSystemDirectoryHandle): Promise<LocalFile[]> { if ((await permissionOf(folder)) !== "granted") { throw new FolderError("the folder needs permission before it can be read — click the folder"); } const files: LocalFile[] = []; for await (const handle of (folder as FileSystemDirectoryHandle & Entries).values()) { if (handle.kind !== "file") continue; if (!handle.name.toLowerCase().endsWith(".md")) continue; const file = await (handle as FileSystemFileHandle).getFile(); files.push({ name: handle.name, modified: file.lastModified, text: await file.text() }); } return files.sort((a, b) => b.modified - a.modified);}
export async function readMarkdown(folder: FileSystemDirectoryHandle, name: string): Promise<string> { const handle = await folder.getFileHandle(name); const file = await handle.getFile(); return file.text();}
/** The whole set, for the first mirror after a folder is picked. */export async function writeAll(folder: FileSystemDirectoryHandle, notes: SceneNote[]): Promise<number> { if ((await permissionOf(folder)) !== "granted") { throw new FolderError("the folder needs write permission again — click the folder to grant it"); } let written = 0; for (const note of notes) { await writeNote(folder, note); written += 1; } return written;}