notes
All repositories: gitoria
18.7 KB
// components/notes.hl — THE NOTES PAGE, `/` and `/note/:id` (tickets notes#1, notes#2, notes#4): the sidebar (subject =// first line, last edited first), the open note in <md-editor>, New note, Delete. Plain Hybriel: project.hl lists this// page in `offline`, so hl:web keeps it — its service worker, the page's state in the browser (per user, forgotten at a// log-out) and a queue for the saves made without a network (replayed when it is back). No JavaScript of our own.//// notes what the server says: every live note of the user, with its text (lib/notes.hl notesFor). Kept offline.// __hlQueue the saves / deletes waiting for the network (hl:web keeps it across a reload)// edits what THIS tab typed: [{ key, text, sent, base, when }] — `sent` = the text last emitted// rows = notes, then the queue, then this tab's edits laid over (rowsOf) — the sidebar and the open note// A note made here has the key `l…` until the server gives it its id; the address follows (settle).// A save names `base` (the version the tab started from); the server continues a run of saves of one login, and the// later edit wins a conflict, the other becomes a copy (lib/notes.hl pushNote). Every save goes through the face// notesPut (statement form: queued offline), every change of a user's notes is pushed (notesChanged) to their tabs.// Input enqueues each edit before a history departure; the 1 s notesTick retries pending edits and pulls every 10 s.// The helper statics below must stay in THIS file: a braced import would make `rows` a server-only value.parent './main.hl'import { siteName } from '../project.hl'import { userIdOfSession, tagOf } from '../lib/users.hl'import { draftsFor } from '../lib/drafts.hl'import { notesFor, pushNote, removeNote } from '../lib/notes.hl'import { isText, isTime } from '../lib/api-helpers.hl'import { messageLook } from '../lib/looks.hl'import { navigate } from 'hl:web'import MdEditor from './md-editor/md-editor.hl'import ListFirst from '../theme/shell/list-first.hl'import ContentFirst from '../theme/shell/content-first.hl'// ---- the list: notes, then the queue, then this tab's edits ------------------------------------------------------------// does row `r` stand for key `k` (its server id, or the id the creating tab gave it)?static isKey = (Hybrid r, String k) => { return k != null && k != '' && (r.key == k || r.sid == k || (r.local != '' && r.local == k)) }static rowOf = (Hybrid list, String k) => {for (r of list) { if (isKey(r, k)) { return r } }return null}// a save laid over the list: the row it names gets the text (and moves up only when the text changed), or it is newstatic putRow = (Hybrid list, String sid, String local, String text, Number when, Number base, Boolean restoreBase = false) => {out = []let found = falsek = sid != null && sid != '' ? sid : localfor (r of list) {if (!found && (isKey(r, k) || (local != null && local != '' && isKey(r, local)))) {found = trueout.push({ key = r.key sid = r.sid local = r.local text = text edited = text == r.text ? r.edited : when base = restoreBase ? base : r.base })} else { out.push(r) }}if (!found) { out.push({ key = k sid = sid == null ? '' : sid local = local == null ? '' : local text = text edited = when base = base }) }return out}static dropRow = (Hybrid list, String k) => {out = []for (r of list) { if (!isKey(r, k)) { out.push(r) } }return out}// the language has no escapes: a newline is written as itselfstatic newline = ''// the words of a table row: its cells, trimmed, empty ones left out, joined by one spacestatic tableWords = (String row) => {out = []for (c of row.split('|')) {w = c.trim()if (w != '') { out.push(w) }}return out.join(' ')}// the SUBJECT: the first non-empty line without leading `#` (a table's header row as its words), at most 80 charactersstatic subjectOf = (String text) => {for (raw of text.split(newline)) {let line = raw.trim()while (line.length > 0 && line.slice(0, 1) == '#') { line = line.slice(1) }line = line.trim()// a note that starts with a table: the header cells as words, not the pipes (`| Item | Qty |` -> `Item Qty`)if (line.startsWith('|')) { line = tableWords(line) }if (line != '') { return line.length > 80 ? line.slice(0, 80) : line }}return 'Untitled note'}// last edited first (by hand: hybriel#1): each row goes in before the first one older than itstatic newestFirst = (Hybrid list) => {let out = []for (r of list) {next = []let placed = falsefor (x of out) {if (!placed && r.edited > x.edited) {next.push(r)placed = true}next.push(x)}if (!placed) { next.push(r) }out = next}return out}static rowsOf = (Hybrid notes, Hybrid queue, Hybrid drafts, Hybrid edits, Hybrid dropped, String sel) => {let list = []for (n of notes) { list.push({ key = n.id sid = n.id local = n.local text = n.text edited = n.edited base = n.edited }) }for (d of drafts) {r = rowOf(list, d.key)// A later accepted version (or deletion) wins over an older kept draft.if (r != null && r.edited < d.when) { list = putRow(list, r.sid, r.local, d.text, d.when, d.base, true) }}for (q of queue) {if (q.event == 'notesPut') { list = putRow(list, q.id, q.local, q.text, q.when, q.base) }if (q.event == 'notesDrop') { list = dropRow(list, q.id != '' ? q.id : q.local) }}for (e of edits) { list = putRow(list, rowOf(list, e.key) != null ? rowOf(list, e.key).sid : '', e.key, e.text, e.when, e.base) }for (k of dropped) { list = dropRow(list, k) }out = []for (r of newestFirst(list)) {out.push({ id = r.key key = r.key sid = r.sid local = r.local text = r.text edited = r.edited base = r.base subject = subjectOf(r.text) href = '/note/' + r.key current = isKey(r, sel) ? 'page' : null })}return out}static editOf = (Hybrid edits, String k) => {for (e of edits) { if (e.key == k) { return e } }return null}static withEdit = (Hybrid edits, Hybrid e) => {out = []for (x of edits) { if (x.key != e.key) { out.push(x) } }out.push(e)return out}static withKey = (Hybrid list, String k) => {out = []for (x of list) { out.push(x) }out.push(k)return out}static withoutEdit = (Hybrid edits, String k) => {out = []for (e of edits) { if (e.key != k) { out.push(e) } }return out}// A provisional address becoming a server address must carry any edit the server did not accept.static rekeyEdits = (Hybrid list, String local, String sid) => {out = []for (e of list) {if (e.key == local) {out.push({ key = sid text = e.text sent = e.sent base = e.base when = e.when })} else { out.push(e) }}return out}// ---- the page's state ---------------------------------------------------------------------------------------------------session = nullid = nullroute = nullsignedIn = userIdOfSession(session) != nullsignedOut = userIdOfSession(session) == null__title = siteNamenotes = notesFor(userIdOfSession(session))drafts = draftsFor(userIdOfSession(session), tagOf(session))__hlQueue = []__hlOnline = trueedits = []lastInput = nullinputVersion = 0dropped = []sel = route != null && route.params.id != null ? route.params.id : ''reachable = trueloginGone = falsesaveError = ''asking = falseticks = 0pulling = falserows = rowsOf(notes, __hlQueue, drafts, edits, dropped, sel)openRow = rowOf(rows, sel)openList = openRow == null ? [] : [{ id = openRow.key }]shownText = openRow == null ? '' : openRow.textnoneOpen = sel == ''openMissing = sel != '' && openRow == nullnoNotes = rows.length == 0bookView = sel != '' ? 'detail' : 'list'syncState = loginGone ? 'Your login has expired — log in again to sync your notes.' : (!__hlOnline || !reachable ? 'Offline — your changes are kept in this browser and sent when you are back online.' : '')Style {pMessage = messageLook + { }noteList { display = 'grid' gap = '.6rem' alignContent = 'start'// the aside has only 4 px of side padding (the rows carry their own 12 px, so their text stands on the 16 px gutter): the header// takes the same 12 px, so "Notes" and "New note" stand on the gutter too instead of touching the screen edge'> header' { display = 'flex' alignItems = 'center' justifyContent = 'space-between' gap = '1rem' padding = '0 .75rem' }h1 { margin = '0' }p { margin = '0' }}'#notes' { margin = '0' padding = '0' listStyle = 'none' }noteReader { display = 'block' minWidth = '0' }noteEditor { display = 'grid' gridTemplateColumns = 'minmax(0, 1fr)' gap = '.8rem''> footer' { display = 'flex' flexWrap = 'wrap' alignItems = 'center' gap = '.6rem' padding = '.3rem 0' }}// the editor's wrapper: a block that may shrink (a wide table scrolls inside the editor, it does not widen the page)noteText { display = 'block' minWidth = '0' }'list-first note-editor a.back' { marginBottom = '0' }// the delete confirmation: the question on its own line, then Delete and Keep as two equal buttons (a phone shows them side by side// on the full width; they used to wrap into a ragged line with "Keep" alone below)pAsk { display = 'none' alignItems = 'center' gap = '.6rem' margin = '0'button { flex = '1 1 0' maxWidth = '12rem' background = 'var(--color-surface)' }}// the open state: the question follows its own `open` attribute (the View binds it to `asking`)'p.ask[open]' { display = 'flex' flexWrap = 'wrap' flex = '1 0 100%' padding = '0' }askText { display = 'block' flex = '1 0 100%' }// the page's clock (components/notes.hl): an invisible endless 1 s animation, each round is a ticknotesTick { position = 'fixed' left = '0' top = '0' width = '1px' height = '1px' opacity = '0' pointerEvents = 'none' animation = 'notes-tick 1s linear infinite' }'@keyframes notes-tick' = {'from' = { opacity = '0' }to = { opacity = '0' }}}View {if (signedOut) {ContentFirst {main { p { id = "loginhint" class = "muted" "Log in with ident (top right) to see your notes." } }}}if (signedIn) {// THE LAYOUTS LIST-FIRST SHELL (mission 011): a notes app is a list and one note. Phone: the list, a tap opens the note alone// (`a.back` returns); from 60rem the list (aside) and the note (main) side by side, each scrolling on its own.ListFirst { view = bookViewaside {noteList {header {h1 { "Notes" }button { id = "newnote" type = "button" class = "primary" "New note" on click(e) { emit create(e) } }}p { id = "syncstate" class = "muted" syncState }if (noNotes) { p { id = "empty" class = "empty" "No notes yet." } }ol { id = "notes"for (r of rows) { li { a { href = r.href "aria-current" = r.current on click(e) { emit pick(e, r.key) } r.subject } } }}}}main {noteReader {if (noneOpen) { p { id = "pick" class = "empty" "Select a note or create a new one." } }if (openMissing) {p { id = "missing" class = "empty" "This note does not exist any more. "a { href = "/" on click(e) { emit pick(e, "") } "Back to your notes" }}}for (o of openList) {noteEditor {a { class = "back" href = "/" on click(e) { emit pick(e, "") } "All notes" }noteText { id = "notetext" on input(e) { emit typed(e) }on beforeinput(Hybrid e) { markInput(e) }on keydown(Hybrid e) { markInput(e) }on pointerdown(Hybrid e) { markInput(e) }MdEditor { name = "text" value = shownText rows = 16 files = "off" placeholder = "" }}p { id = "saveerror" Style.pMessage saveError }footer {button { id = "delete" type = "button" "Delete note" on click(e) { emit askDelete(e) } }p { id = "deleteask" Style.pAsk open = askingaskText { "Delete this note for good?" }button { id = "deleteyes" type = "button" class = "danger" "Delete" on click(e) { emit dropOpen(e) } }button { id = "deleteno" type = "button" "Keep" on click(e) { emit keepOpen(e) } }}}}}}}}notesTick { "aria-hidden" = "true" on animationiteration(e) { emit tick(e) } }}}// ---- what the person does ----------------------------------------------------------------------------------------------// a link of the list (or "All notes", "Back"): opens the note in place — the address follows, no page loadon pick(Hybrid e, String k) {if (e.button != 0 || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) { return null }e.preventDefault()open(k)}on create(Hybrid e) {flush(0)k = 'l' + window.crypto.randomUUID().replaceAll('-', '').slice(0, 16)t = Date.now()edits = withEdit(edits, { key = k text = '' sent = '' base = 0 when = t })emit server notesPut({ key = k id = '' local = k text = '' base = 0 when = t })open(k)}markInput = (Hybrid e) => {if (e.isTrusted) { inputVersion = inputVersion + 1 }}// the MdEditor announces its Markdown with an `input` event on its hidden field (named `text`); its other inputs are not iton typed(Hybrid e) {if (e.target.name != 'text') { return null }v = e.target.valuer = rowOf(rows, sel)if (r == null) { return null }// Suppress a repeated announcement within one gesture; a new real gesture may repeat earlier text.if (lastInput != null && isKey(r, lastInput.key) && lastInput.text == v && lastInput.version == inputVersion) { return null }had = editOf(edits, sel)if (had == null && v == r.text) { return null }if (had != null && had.text == v) { return null }lastInput = { key = r.key text = v version = inputVersion }edits = withEdit(edits, { key = sel text = v sent = had != null ? had.sent : r.text base = had != null ? had.base : r.base when = Date.now() })// Back can detach this page before its next tick. Enqueue the edit while input owns it.flush(0)}on askDelete(Hybrid e) { asking = true }on keepOpen(Hybrid e) { asking = false }on dropOpen(Hybrid e) {r = rowOf(rows, sel)asking = falseif (r != null) {emit server notesDrop({ key = r.key id = r.sid local = r.local base = r.base when = Date.now() })dropped = withKey(dropped, r.key)// this tab's edit of the note may be keyed by the id the tab gave it (`local`) or by the server id: remove it under every name the row has,// or it is laid over the list again (putRow) once the server's list no longer holds the note (notes#15)edits = withoutEdit(withoutEdit(withoutEdit(edits, r.key), r.local), r.sid)}open('')}// the tick: what was typed 0.6 s ago goes to the server; every 10 s the server is asked for the other devices' changeson tick(Hybrid e) {flush(600)ticks = ticks + 1if (ticks % 10 == 0) { pull() }}on client reconnected(Hybrid r) { pull() }on client notesChanged(String user, Hybrid list) {notes = listsettle(list)}on client notesSaveError(String key, String why) { saveError = why }open = (String k) => {// hybriel#196: close the delete question BEFORE flush(0): its awaited emit would otherwise set asking=false after the ack, closing a question opened meanwhileasking = falseflush(0)saveError = ''navigate(k == null || k == '' ? '/' : '/note/' + k)}// send this tab's typed text that is older than `waitMs` and not sent yetflush = (Number waitMs) => {t = Date.now()pending = []next = []for (e of edits) {if (e.text != e.sent && t - e.when >= waitMs) {r = rowOf(rows, e.key)pending.push({ key = e.key id = r != null ? r.sid : '' local = r != null && r.local != '' ? r.local : (e.key.slice(0, 1) == 'l' ? e.key : '') text = e.text base = e.base when = e.when })next.push({ key = e.key text = e.text sent = e.text base = e.base when = e.when })} else { next.push(e) }}if (pending.length == 0) { return null }// Mark these texts sent before emitting: the push can settle them while the emit waits.// Writing the old snapshot afterwards would put acknowledged edits back over a later delete.edits = nextfor (n of pending) { emit server notesPut(n) }}pull = () => {if (pulling) { return null }pulling = truegot = emit server notesPull()pulling = falseif (got == null) {reachable = falsereturn null}reachable = trueloginGone = got.login == trueif (got.notes != null) {notes = got.notesdrafts = got.draftssettle(got.notes)}}// THE SERVER'S LIST ARRIVED: an edit the server now has (or kept as this tab's conflict copy) is done; the open note// that got its server id takes it (and the address follows); a delete that went through is forgottensettle = (Hybrid list) => {next = []for (e of edits) {let done = falsefor (n of list) {mine = n.id == e.key || (n.local != '' && n.local == e.key)if (mine && n.text == e.text && e.sent == e.text) { done = true }// sent, and the server has moved on since (its version is not older than this edit): the server's text is the truth now —// a later save of ANOTHER tab must show here, not stay hidden under this tab's old edit (a lost conflict became a copy)if (mine && e.sent == e.text && n.edited >= e.when) { done = true }if (n.copyOf != '' && e.sent == e.text && n.text.startsWith(e.text) && rowOf(rows, e.key) != null && n.copyOf == rowOf(rows, e.key).sid) { done = true }}if (!done) { next.push(e) }}if (next.length != edits.length) { edits = next }still = []for (k of dropped) {let there = falsefor (n of list) { if (n.id == k || n.local == k) { there = true } }if (there) { still.push(k) }}if (still.length != dropped.length) { dropped = still }if (sel != '' && sel.slice(0, 1) == 'l') {for (n of list) {if (n.local == sel) {// Accepted edits were removed above; preserve the remaining draft under its new id.edits = rekeyEdits(edits, sel, n.id)// Retained pages resolve their state, but only the matching visible entry may move.visible = location.pathname == '/note/' + selsel = n.idif (visible) { navigate('/note/' + n.id, replace = true) }}}}}// ---- the faces (thin: lib/notes.hl decides; the trailing `session` is always the server's, hybriel #16) ----------------on server notesPut(n, session) {u = userIdOfSession(session)if (u == null || n == null || hlTypeName(n) != 'Hybrid' || !isText(n.id) || !isText(n.local) || !isText(n.text) || !isTime(n.base) || !isTime(n.when)) { return null }if (n.local.length > 64 || n.id.length > 64) { return null }r = pushNote(u, n.id, n.local, n.text, n.base, n.when, tagOf(session))if (r.error != null) { emit client notesSaveError(n.key, r.error) }emit client notesChanged(u, notesFor(u))}on server notesDrop(n, session) {u = userIdOfSession(session)if (u == null || n == null || hlTypeName(n) != 'Hybrid' || !isText(n.id) || !isText(n.local) || !isTime(n.base)) { return null }removeNote(u, n.id, n.base, n.local, tagOf(session))emit client notesChanged(u, notesFor(u))}on server notesPull(session) {u = userIdOfSession(session)if (u == null) { return { login = true } }return { notes = notesFor(u) drafts = draftsFor(u, tagOf(session)) }}
Branches
Latest commits
- a5c27cb6Allow real edits back to earlier text and honor configured identAtlas
- 15c46ced|||PR Preserve note edits, conflict bases and visible historyAtlas
- 4c6e0bf6Merge branch 'notes13-day61' into mainAtlas
- eb51864f|||PR Back/Forward via navigate, server drafts, Hybriel day61Atlas
- 3537cf7eMerge branch 'vendor-day59' into mainAtlas
- c13d188b|||PR Vendor Hybriel day59Atlas
- 24c95433Merge branch 'notes17-ghost-note' into mainAtlas
- ae1075b2Preserve rejected drafts during note ID adoptionAtlas
- 383cce23|||PR Prevent saved local edits from restoring deleted notesAtlas
- 99ca1cf6Merge branch 'vendor-day56' into mainAtlas
- 649cef37|||PR Vendor Hybriel day56Atlas
- aadd0abcMerge branch 'hl-standard-2' into mainAtlas
- 52ffac9f|||PR Keyboard and reload checks for the notes gate (HL-STANDARD F21, F5)Atlas
- 617ee8c0Merge branch 'hl-standard' into mainAtlas
- 452458ee|||PR Type the function parameters of notes' own .hl files (HL-STANDARD L10)Atlas
- 23758cd6Re-vendor complete Hybriel plugins and runtime to day44mre
- 5d7cc700Backup tar: --hard-dereference, so mpackdb sidecars are never stored as hard links (Tracker's finding)mre
- 3e07b1cfVendor complete Hybriel day39 plugin sources and librariesmre
- d7366702Check session cookie flags after login and assert anonymous GET stays cookielessmre
- 16bc8fd8Re-vendor Hybriel day38b with the mpackdb store-open race fixmre