// Notable: the reMarkable cloud as a library of folders and documents, with // an editor for notebooks (strokes, in the tablet's format) and one for PDFs // (pdf.js annotations), uploads, exports, and a mirror of everything to a // folder on disk. The sidecar (app/sidecar/server.js) holds the credentials // and talks to the cloud; this page is the room. import { LitElement, html, nothing, type TemplateResult } from 'lit'; import { repeat } from 'lit/directives/repeat.js'; import { api, ApiError } from './api.ts'; import { confirm, droppedPaths, installMenu, isDesktop, isMac, mollusc, onCloseRequested, openExternal, pickDirectory, pickFiles, pickSave, showInFolder } from './desktop.ts'; import { DEFAULT_PEN } from './ink.ts'; import { ancestorsOf, childrenOf, descendantsOf, fmtDate, kindLabel, msg, ROOT, TRASH, type DocInfo, type DocJson, type PenPrefs, type Status } from './model.ts'; import { acceptsDrop, dragIds, thumbs } from './components/nb-library.ts'; import { CONNECT_URL } from './components/nb-login.ts'; import type { NbNotebook } from './components/nb-notebook.ts'; import type { NbPdf } from './components/nb-pdf.ts'; import type { NbSync } from './components/nb-sync.ts'; import './components/nb-login.ts'; import './components/nb-library.ts'; import './components/nb-notebook.ts'; import './components/nb-pdf.ts'; import './components/nb-sync.ts'; import logoUrl from '../icons/icon.svg'; type Open = { info: DocInfo; kind: 'notebook' | 'pdf' }; type Toast = { text: string; kind: 'ok' | 'bad' | 'info' }; type Prompt = { title: string; label?: string; value: string; ok: string; folders?: DocJson[]; resolve: (v: string | null) => void }; type Format = 'markdown' | 'svg' | 'pdf'; const POLL_MS = 60_000; const UPLOAD_FILTER = [{ name: 'Documents', extensions: ['pdf', 'epub', 'rm', 'md', 'markdown', 'txt'] }]; export class NotableApp extends LitElement { static properties = { status: { state: true }, docs: { state: true }, folder: { state: true }, selection: { state: true }, view: { state: true }, query: { state: true }, open: { state: true }, loading: { state: true }, toast: { state: true }, prompt: { state: true }, expanded: { state: true }, accountOpen: { state: true }, reason: { state: true }, prefs: { state: true }, dropTarget: { state: true }, }; declare status: Status | null; declare docs: DocJson[]; declare folder: string; declare selection: Set; declare view: 'grid' | 'list'; declare query: string; declare open: Open | null; declare loading: boolean; declare toast: Toast | null; declare prompt: Prompt | null; declare expanded: Set; declare accountOpen: boolean; /** Why the login screen shows for someone who was paired (a token the cloud no longer takes). */ declare reason: string | null; declare prefs: PenPrefs; declare dropTarget: string | null; private poll: ReturnType | null = null; private toastTimer: ReturnType | null = null; private onKey = (e: KeyboardEvent) => this.keydown(e); constructor() { super(); this.status = null; this.docs = []; this.folder = ROOT; this.selection = new Set(); this.view = 'grid'; this.query = ''; this.open = null; this.loading = false; this.toast = null; this.prompt = null; this.expanded = new Set(); this.accountOpen = false; this.reason = null; this.prefs = { ...DEFAULT_PEN }; this.dropTarget = null; } protected override createRenderRoot() { return this; } override connectedCallback() { super.connectedCallback(); document.body.dataset.shell = isDesktop ? 'desktop' : 'web'; if (isMac) document.body.dataset.platform = 'mac'; window.addEventListener('keydown', this.onKey); installMenu({ account: () => { this.accountOpen = true; }, newNotebook: () => void this.newNotebook(), newFolder: () => void this.newFolder(), upload: () => void this.upload(), save: () => void this.editor?.save(), export: () => void this.exportCurrent(), download: () => void this.downloadCurrent(), sync: () => this.syncDialog?.open(), close: () => void this.closeDoc(), undo: () => this.editor?.undo(), redo: () => this.editor?.redo(), rename: () => void this.renameSelected(), trash: () => void this.trashSelected(), refresh: () => void this.refresh(true), grid: () => this.setView('grid'), list: () => this.setView('list'), zoomIn: () => this.editor?.zoomIn(), zoomOut: () => this.editor?.zoomOut(), zoomFit: () => this.editor?.zoomFit(), nextPage: () => this.editor?.nextPage(), prevPage: () => this.editor?.prevPage(), }); onCloseRequested(async () => { await this.editor?.flush(); }); void this.boot(); this.poll = setInterval(() => { if (this.status?.loggedIn && !this.open && !document.hidden) void this.refresh(); }, POLL_MS); } override disconnectedCallback() { super.disconnectedCallback(); window.removeEventListener('keydown', this.onKey); if (this.poll) clearInterval(this.poll); } override updated(changed: Map) { if (changed.has('prompt')) { const dialog = this.querySelector('dialog.prompt') as HTMLDialogElement | null; if (this.prompt && dialog && !dialog.open) { dialog.showModal(); (dialog.querySelector('input, select') as HTMLElement | null)?.focus(); (dialog.querySelector('input') as HTMLInputElement | null)?.select(); } else if (!this.prompt && dialog?.open) dialog.close(); } if (changed.has('accountOpen')) { const dialog = this.querySelector('dialog.account') as HTMLDialogElement | null; if (this.accountOpen && dialog && !dialog.open) dialog.showModal(); else if (!this.accountOpen && dialog?.open) dialog.close(); } } get editor(): NbNotebook | NbPdf | null { return this.querySelector('nb-notebook, nb-pdf') as NbNotebook | NbPdf | null; } get syncDialog(): NbSync | null { return this.querySelector('nb-sync') as NbSync | null; } // ---- the cloud --------------------------------------------------------------- private async boot() { if (!api.available()) return; this.loading = true; try { this.status = await api.status(); const s = this.status.settings; if (s.view === 'grid' || s.view === 'list') this.view = s.view; if (s.pen) this.prefs = { ...DEFAULT_PEN, ...s.pen }; if (this.status.loggedIn) await this.refresh(true); else if (this.status.error) this.reason = this.status.error; } catch (err) { this.say(msg(err), 'bad'); } finally { this.loading = false; } } async refresh(force = false) { if (!this.status?.loggedIn) return; this.loading = true; try { const tree = await api.tree(force); this.docs = tree.docs; if (this.folder !== ROOT && this.folder !== TRASH && !this.docs.some((d) => d.id === this.folder && !d.deleted)) this.navigate(ROOT); } catch (err) { if (err instanceof ApiError && err.status === 401) { this.reason = `The cloud no longer accepts this pairing: ${err.message}`; this.status = { ...this.status, loggedIn: false, user: null }; } else this.say(msg(err), 'bad'); } finally { this.loading = false; } } private say(text: string, kind: Toast['kind'] = 'info') { this.toast = { text, kind }; if (this.toastTimer) clearTimeout(this.toastTimer); this.toastTimer = setTimeout(() => { this.toast = null; }, kind === 'bad' ? 8000 : 4000); } private async run(work: () => Promise, done?: string): Promise { this.loading = true; try { const out = await work(); if (done) this.say(done, 'ok'); return out; } catch (err) { this.say(msg(err), 'bad'); return undefined; } finally { this.loading = false; } } /** A document changed on the cloud through us: keep the library's picture current. */ private updateDoc(doc: DocJson) { thumbs.forget(doc.id); const i = this.docs.findIndex((d) => d.id === doc.id); const prev = this.docs[i]; const next = prev ? { ...prev, ...doc } : doc; this.docs = i >= 0 ? this.docs.map((d, j) => (j === i ? next : d)) : [...this.docs, next]; // the open editor keeps its own picture of the document; only its name in the title bar comes from here if (this.open && this.open.info.doc.id === doc.id && this.open.info.doc.name !== next.name) { this.open = { ...this.open, info: { ...this.open.info, doc: next } }; } } // ---- navigation, selection ------------------------------------------------------ navigate(folder: string) { this.folder = folder; this.selection = new Set(); this.query = ''; for (const a of ancestorsOf(this.docs, folder)) this.expanded.add(a.id); this.expanded = new Set(this.expanded); } private setView(view: 'grid' | 'list') { this.view = view; void api.settings({ view }).catch(() => {}); } get selectedDocs(): DocJson[] { return this.docs.filter((d) => this.selection.has(d.id)); } get singleDoc(): DocJson | null { const sel = this.selectedDocs; return sel.length === 1 && !sel[0]!.isFolder ? sel[0]! : null; } private get allFolders(): DocJson[] { return descendantsOf(this.docs, ROOT).filter((d) => d.isFolder); } // ---- asking --------------------------------------------------------------------- private ask(opts: Omit): Promise { return new Promise((resolve) => { this.prompt = { ...opts, resolve }; }); } private answer(value: string | null) { const p = this.prompt; this.prompt = null; p?.resolve(value); } private async chooseFormat(): Promise { if (mollusc) { const { response } = await mollusc.dialog.message({ type: 'question', message: 'Export as…', detail: 'Markdown keeps typed text; SVG and PDF keep the handwriting.', buttons: ['PDF', 'SVG', 'Markdown', 'Cancel'], defaultId: 0, cancelId: 3 }); return ([ 'pdf', 'svg', 'markdown' ] as Format[])[response] ?? null; } const v = window.prompt('Export as: pdf, svg or markdown', 'pdf'); return v === 'pdf' || v === 'svg' || v === 'markdown' ? v : null; } // ---- actions -------------------------------------------------------------------- async newNotebook() { if (this.open) return; const name = await this.ask({ title: 'New notebook', label: 'Name', value: 'Untitled', ok: 'Create' }); if (!name?.trim()) return; const parent = this.folder === TRASH ? ROOT : this.folder; const out = await this.run(() => api.newNotebook(name.trim(), parent), `Made “${name.trim()}”`); if (!out) return; await this.refresh(); const doc = this.docs.find((d) => d.id === out.doc.id); if (doc) void this.openDoc(doc); } async newFolder() { if (this.open) return; const name = await this.ask({ title: 'New folder', label: 'Name', value: 'New folder', ok: 'Create' }); if (!name?.trim()) return; const parent = this.folder === TRASH ? ROOT : this.folder; const out = await this.run(() => api.newFolder(name.trim(), parent), `Made “${name.trim()}”`); if (out) await this.refresh(); } async upload(paths?: string[], parent = this.folder) { if (!paths) paths = await pickFiles(UPLOAD_FILTER); if (!paths.length) return; const target = parent === TRASH ? ROOT : parent; const out = await this.run(() => api.upload(paths, target), paths.length === 1 ? 'Uploaded' : `Uploaded ${paths.length} files`); if (out) await this.refresh(); } private async uploadDropped(files: FileList, parent: string) { const paths = await droppedPaths(files); if (!paths.length) { this.say(isDesktop ? 'Those files could not be read; use Upload… instead.' : 'Dropping files works in the desktop app; use Upload… here.', 'bad'); return; } await this.upload(paths, parent); } async renameSelected() { const target = this.open ? this.open.info.doc : this.selectedDocs.length === 1 ? this.selectedDocs[0]! : null; if (!target) return; const name = await this.ask({ title: `Rename “${target.name}”`, label: 'Name', value: target.name, ok: 'Rename' }); if (!name?.trim() || name.trim() === target.name) return; const out = await this.run(() => api.rename(target.id, name.trim()), 'Renamed'); if (out) { this.updateDoc(out.doc); if (this.open) document.title = `${out.doc.name} — Notable`; } } async moveSelected() { const ids = [...this.selection]; if (!ids.length) return; const excluded = new Set(ids.flatMap((id) => [id, ...descendantsOf(this.docs, id).map((d) => d.id)])); const folders = this.allFolders.filter((f) => !excluded.has(f.id)); const parent = await this.ask({ title: `Move ${ids.length === 1 ? 'to' : `${ids.length} items to`}`, value: this.folder === TRASH ? ROOT : this.folder, ok: 'Move', folders }); if (parent === null) return; await this.move(ids, parent); } private async move(ids: string[], parent: string) { const out = await this.run(() => api.move(ids, parent), ids.length === 1 ? 'Moved' : `Moved ${ids.length} items`); if (out) { this.selection = new Set(); await this.refresh(); } } async trashSelected() { const ids = this.open ? [this.open.info.doc.id] : [...this.selection]; if (!ids.length || this.folder === TRASH) return; if (this.open) await this.closeDoc(); const out = await this.run(() => api.trash(ids), ids.length === 1 ? 'Moved to the trash' : `Moved ${ids.length} items to the trash`); if (out) { this.selection = new Set(); await this.refresh(); } } async restoreSelected() { const ids = [...this.selection]; if (!ids.length) return; const out = await this.run(() => api.restore(ids, ROOT), ids.length === 1 ? 'Restored' : `Restored ${ids.length} items`); if (out) { this.selection = new Set(); await this.refresh(); } } async purgeSelected() { const docs = this.selectedDocs; if (!docs.length) return; const what = docs.length === 1 ? `“${docs[0]!.name}”` : `${docs.length} items`; if (!(await confirm(`Delete ${what} for good?`, 'This removes them from the cloud and every device. It cannot be undone.', 'Delete', 'warning'))) return; const out = await this.run(() => api.purge(docs.map((d) => d.id)), 'Deleted'); if (out) { this.selection = new Set(); await this.refresh(); } } async exportDoc(doc: DocJson) { const format = await this.chooseFormat(); if (!format) return; const ext = format === 'markdown' ? 'md' : format; const path = await pickSave(`${doc.name}.${ext}`, [{ name: format.toUpperCase(), extensions: [ext] }]); if (!path) return; const out = await this.run(() => api.exportDoc(doc.id, format, path)); if (out) { this.say(out.files.length === 1 ? `Exported to ${out.files[0]}` : `Exported ${out.files.length} files`, 'ok'); showInFolder(out.files[0]!); } } async downloadDoc(doc: DocJson) { const dir = await pickDirectory(`Download the raw files of “${doc.name}” into…`); if (!dir) return; const out = await this.run(() => api.download(doc.id, dir)); if (out) { this.say(`Downloaded ${out.files.length} files`, 'ok'); showInFolder(out.files[0] ?? dir); } } private exportCurrent() { const doc = this.open?.info.doc ?? this.singleDoc; if (doc) void this.exportDoc(doc); } private downloadCurrent() { const doc = this.open?.info.doc ?? this.singleDoc; if (doc) void this.downloadDoc(doc); } async openDoc(doc: DocJson) { if (doc.isFolder) { this.navigate(doc.id); return; } const info = await this.run(() => api.doc(doc.id)); if (!info) return; this.open = { info, kind: info.fileType === 'pdf' ? 'pdf' : 'notebook' }; this.selection = new Set(); document.title = `${doc.name} — Notable`; } async closeDoc() { if (!this.open) return; await this.editor?.flush(); this.open = null; document.title = 'Notable'; void this.refresh(); } private async logout() { if (!(await confirm('Disconnect from the reMarkable cloud?', 'The pairing is removed from this machine; the tablet and other apps are not affected.', 'Disconnect'))) return; this.accountOpen = false; this.open = null; this.docs = []; this.status = await api.logout(); this.reason = null; } private async dropOn(target: string, e: DragEvent) { e.preventDefault(); e.stopPropagation(); this.dropTarget = null; const ids = dragIds(e); if (ids?.length) { if (ids.includes(target)) return; await this.move(ids, target); return; } const files = e.dataTransfer?.files; if (files?.length) await this.uploadDropped(files, target); } private keydown(e: KeyboardEvent) { const t = e.target as HTMLElement | null; const typing = t && (/^(INPUT|TEXTAREA|SELECT)$/.test(t.tagName) || t.isContentEditable); const meta = e.metaKey || e.ctrlKey; if (this.prompt || this.accountOpen) return; if (meta && e.key.toLowerCase() === 'f' && !this.open) { e.preventDefault(); (this.querySelector('input.search') as HTMLInputElement | null)?.focus(); } else if (!typing && !this.open && meta && e.key === 'Backspace' && this.selection.size) { e.preventDefault(); void this.trashSelected(); } else if (!typing && e.key === 'Escape') { if (this.selection.size) this.selection = new Set(); } else if (!typing && !this.open && !meta && e.key === 'Enter' && this.selectedDocs.length === 1) { e.preventDefault(); void this.openDoc(this.selectedDocs[0]!); } } // ---- render --------------------------------------------------------------------------- private folderTree(parent: string, depth: number): TemplateResult[] { return childrenOf(this.docs, parent) .filter((d) => d.isFolder) .map((d) => { const kids = childrenOf(this.docs, d.id).some((k) => k.isFolder); const open = this.expanded.has(d.id); return html`
{ if (acceptsDrop(e)) { e.preventDefault(); this.dropTarget = d.id; } }} @dragleave=${() => { if (this.dropTarget === d.id) this.dropTarget = null; }} @drop=${(e: DragEvent) => void this.dropOn(d.id, e)}>
${open ? this.folderTree(d.id, depth + 1) : nothing}
`; }); } private sidebar() { const user = this.status?.user; const trashed = this.docs.filter((d) => !d.deleted && d.parent === TRASH).length; return html``; } private breadcrumb() { const trail = this.folder === TRASH ? [] : ancestorsOf(this.docs, this.folder); const crumb = (id: string, label: string, last: boolean) => html``; return html``; } private topbar() { if (this.open) { const doc = this.open.info.doc; return html`

${doc.name} ${kindLabel(doc)}

`; } const n = this.selection.size; const inTrash = this.folder === TRASH; const single = this.selectedDocs.length === 1 ? this.selectedDocs[0]! : null; return html`
${this.breadcrumb()} ${n ? html` ${n} selected ${single && !single.isFolder ? html`` : nothing} ${single ? html`` : nothing} ${!inTrash ? html`` : nothing} ${single && !single.isFolder ? html`` : nothing} ${inTrash ? html` ` : html``} ` : nothing} { this.query = (e.target as HTMLInputElement).value; }} aria-label="Search" /> ${!inTrash ? html` ` : nothing}
`; } private main() { if (!api.available()) { return html``; } if (!this.status) return html`

${this.loading ? 'Starting…' : 'The sidecar did not answer.'}

`; if (!this.status.loggedIn) { return html`) => { this.status = e.detail; this.reason = null; void this.refresh(true); }}>`; } if (this.open) { const { info, kind } = this.open; return kind === 'pdf' ? html`) => this.updateDoc(e.detail)}>` : html`) => this.updateDoc(e.detail)} @prefs-changed=${(e: CustomEvent) => { this.prefs = e.detail; void api.settings({ pen: e.detail }).catch(() => {}); }}>`; } return html`) => this.navigate(e.detail)} @open=${(e: CustomEvent) => void this.openDoc(e.detail)} @select=${(e: CustomEvent>) => { this.selection = e.detail; }} @move=${(e: CustomEvent<{ ids: string[]; parent: string }>) => void this.move(e.detail.ids, e.detail.parent)} @upload-files=${(e: CustomEvent<{ files: FileList; parent: string }>) => void this.uploadDropped(e.detail.files, e.detail.parent)}>`; } private promptDialog() { const p = this.prompt; return html` { e.preventDefault(); this.answer(null); }}> ${p ? html`
{ e.preventDefault(); const f = e.target as HTMLFormElement; const v = (f.elements.namedItem('value') as HTMLInputElement | HTMLSelectElement).value; this.answer(v); }}>

${p.title}

${p.folders ? html`` : html``}
` : nothing}
`; } private accountDialog() { const s = this.status; const u = s?.user; return html``; } override render() { const loggedIn = Boolean(this.status?.loggedIn); return html`
${loggedIn ? this.sidebar() : nothing}
${loggedIn ? this.topbar() : html`
Notable
`}
${this.main()}
${this.toast ? html`
${this.toast.text}
` : nothing} ${this.promptDialog()} ${this.accountDialog()} this.say('Mirror up to date', 'ok')}>
`; } } customElements.define('notable-app', NotableApp);