Something went wrong. Try again.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241// The documents of one folder (or the trash), as a grid of cards or a list,// with selection, drag and drop between folders, and files dropped from the// desktop.import { LitElement, html, nothing } from 'lit';import { repeat } from 'lit/directives/repeat.js';import { api } from '../api.ts';import { childrenOf, fmtDate, fmtSize, kindIcon, kindLabel, TRASH, type DocJson } from '../model.ts';
const DND_TYPE = 'application/x-notable-ids';
/** Thumbnails by document and hash, as object URLs; fetched once, kept for the session. */class ThumbCache { private urls = new Map<string, string | null>(); private pending = new Map<string, Promise<void>>();
key(doc: DocJson) { return `${doc.id}:${doc.hash}`; }
get(doc: DocJson): string | null | undefined { return this.urls.get(this.key(doc)); }
load(doc: DocJson, done: () => void): void { const key = this.key(doc); if (this.urls.has(key) || this.pending.has(key) || !doc.cover) return; const p = api .thumbnail(doc.id, doc.cover) .then((bytes) => { this.urls.set(key, bytes ? URL.createObjectURL(new Blob([bytes as BlobPart], { type: 'image/png' })) : null); }) .catch(() => { this.urls.set(key, null); }) .finally(() => { this.pending.delete(key); done(); }); this.pending.set(key, p); }
forget(id: string) { for (const [k, url] of this.urls) { if (k.startsWith(`${id}:`)) { if (url) URL.revokeObjectURL(url); this.urls.delete(k); } } }}export const thumbs = new ThumbCache();
export function dragIds(e: DragEvent): string[] | null { const raw = e.dataTransfer?.getData(DND_TYPE); if (!raw) return null; try { return JSON.parse(raw) as string[]; } catch { return null; }}
export function acceptsDrop(e: DragEvent): boolean { const types = e.dataTransfer?.types ?? []; return types.includes(DND_TYPE) || types.includes('Files');}
export class NbLibrary extends LitElement { static properties = { docs: { attribute: false }, folder: { attribute: false }, selection: { attribute: false }, view: { attribute: false }, query: { attribute: false }, dropping: { state: true } }; declare docs: DocJson[]; declare folder: string; declare selection: Set<string>; declare view: 'grid' | 'list'; declare query: string; declare dropping: string | null;
constructor() { super(); this.docs = []; this.folder = ''; this.selection = new Set(); this.view = 'grid'; this.query = ''; this.dropping = null; }
protected override createRenderRoot() { return this; }
/** What is shown: the folder's children, or every match when searching. */ get shown(): DocJson[] { const q = this.query.trim().toLowerCase(); if (q) { const inTrash = this.folder === TRASH; return this.docs .filter((d) => !d.deleted && d.trashed === inTrash && d.name.toLowerCase().includes(q)) .sort((a, b) => Number(b.isFolder) - Number(a.isFolder) || a.path.localeCompare(b.path)); } return childrenOf(this.docs, this.folder); }
private emit<T>(name: string, detail: T) { this.dispatchEvent(new CustomEvent(name, { detail, bubbles: true, composed: true })); }
private select(doc: DocJson, e: MouseEvent) { const next = new Set(e.metaKey || e.ctrlKey ? this.selection : []); if (e.shiftKey && this.selection.size) { const shown = this.shown; const last = shown.findIndex((d) => this.selection.has(d.id)); const here = shown.findIndex((d) => d.id === doc.id); const [a, b] = last < here ? [last, here] : [here, last]; for (const d of shown.slice(Math.max(0, a), b + 1)) next.add(d.id); } else if (next.has(doc.id) && (e.metaKey || e.ctrlKey)) { next.delete(doc.id); } else { next.add(doc.id); } this.emit('select', next); }
private open(doc: DocJson) { if (doc.isFolder) this.emit('navigate', doc.id); else this.emit('open', doc); }
private dragStart(doc: DocJson, e: DragEvent) { const ids = this.selection.has(doc.id) ? [...this.selection] : [doc.id]; e.dataTransfer?.setData(DND_TYPE, JSON.stringify(ids)); e.dataTransfer?.setData('text/plain', doc.name); if (e.dataTransfer) e.dataTransfer.effectAllowed = 'move'; }
private dragOver(target: string | null, e: DragEvent) { if (!acceptsDrop(e)) return; e.preventDefault(); if (e.dataTransfer) e.dataTransfer.dropEffect = e.dataTransfer.types.includes('Files') ? 'copy' : 'move'; this.dropping = target ?? this.folder; }
private async drop(target: string | null, e: DragEvent) { e.preventDefault(); e.stopPropagation(); this.dropping = null; const parent = target ?? this.folder; const ids = dragIds(e); if (ids?.length) { if (ids.includes(parent)) return; // a folder onto itself this.emit('move', { ids, parent }); return; } const files = e.dataTransfer?.files; if (files?.length) this.emit('upload-files', { files, parent }); }
private thumb(doc: DocJson) { const url = thumbs.get(doc); if (url === undefined && doc.cover) thumbs.load(doc, () => this.requestUpdate()); return url ?? null; }
private card(doc: DocJson) { const selected = this.selection.has(doc.id); const url = doc.isFolder ? null : this.thumb(doc); return html`<article class="card doc ${doc.isFolder ? 'folder' : 'file'} ${selected ? 'selected' : ''} ${this.dropping === doc.id ? 'dropping' : ''}" draggable="true" tabindex="0" role="option" aria-selected=${selected} title=${doc.name} @click=${(e: MouseEvent) => this.select(doc, e)} @dblclick=${() => this.open(doc)} @keydown=${(e: KeyboardEvent) => { if (e.key === 'Enter' && !e.metaKey) { e.preventDefault(); this.open(doc); } }} @dragstart=${(e: DragEvent) => this.dragStart(doc, e)} @dragover=${doc.isFolder ? (e: DragEvent) => this.dragOver(doc.id, e) : nothing} @dragleave=${doc.isFolder ? () => { if (this.dropping === doc.id) this.dropping = null; } : nothing} @drop=${doc.isFolder ? (e: DragEvent) => this.drop(doc.id, e) : nothing} > <div class="cover"> ${doc.isFolder ? html`<i class="icon icon-folder icon-lg" aria-hidden="true"></i>` : url ? html`<img src=${url} alt="" loading="lazy" />` : html`<i class="icon ${kindIcon(doc)} icon-lg" aria-hidden="true"></i>`} </div> <div class="meta"> <strong class="name">${doc.name}</strong> <span class="sub">${kindLabel(doc)}${doc.pageCount ? ` · ${doc.pageCount} ${doc.pageCount === 1 ? 'page' : 'pages'}` : ''}${this.query ? ` · ${doc.path}` : ''}</span> <span class="sub">${fmtDate(doc.lastModified)}</span> </div> </article>`; }
private row(doc: DocJson) { const selected = this.selection.has(doc.id); return html`<tr class="${selected ? 'selected' : ''} ${this.dropping === doc.id ? 'dropping' : ''}" draggable="true" tabindex="0" aria-selected=${selected} @click=${(e: MouseEvent) => this.select(doc, e)} @dblclick=${() => this.open(doc)} @keydown=${(e: KeyboardEvent) => { if (e.key === 'Enter' && !e.metaKey) { e.preventDefault(); this.open(doc); } }} @dragstart=${(e: DragEvent) => this.dragStart(doc, e)} @dragover=${doc.isFolder ? (e: DragEvent) => this.dragOver(doc.id, e) : nothing} @drop=${doc.isFolder ? (e: DragEvent) => this.drop(doc.id, e) : nothing} > <td class="name"><i class="icon ${kindIcon(doc)}" aria-hidden="true"></i> ${doc.name}${this.query ? html`<span class="sub">${doc.path}</span>` : nothing}</td> <td>${kindLabel(doc)}</td> <td class="num">${doc.isFolder ? '' : (doc.pageCount ?? '')}</td> <td class="num">${fmtSize(doc.size)}</td> <td class="num">${fmtDate(doc.lastModified)}</td> </tr>`; }
override render() { const shown = this.shown; const empty = this.folder === TRASH ? 'The trash is empty.' : this.query ? 'Nothing matches.' : 'This folder is empty. Make a notebook, or drop a PDF here.'; return html`<div class="library ${this.dropping === this.folder ? 'dropping' : ''}" role="listbox" aria-multiselectable="true" @click=${(e: MouseEvent) => { if (e.target === e.currentTarget) this.emit('select', new Set<string>()); }} @dragover=${(e: DragEvent) => this.dragOver(null, e)} @dragleave=${(e: DragEvent) => { if (e.target === e.currentTarget) this.dropping = null; }} @drop=${(e: DragEvent) => this.drop(null, e)} > ${!shown.length ? html`<p class="empty fg-muted">${empty}</p>` : this.view === 'grid' ? html`<div class="cards">${repeat(shown, (d) => d.id, (d) => this.card(d))}</div>` : html`<table class="data"> <thead><tr><th>Name</th><th>Kind</th><th class="num">Pages</th><th class="num">Size</th><th class="num">Modified</th></tr></thead> <tbody>${repeat(shown, (d) => d.id, (d) => this.row(d))}</tbody> </table>`} </div>`; }}
customElements.define('nb-library', NbLibrary);