// title.mjs — a team page's title, renamed in place (level-up §4.1, // build note 78). The H1's text and the header's title field rename // through the same POST /p/{id}/rename, asking for JSON, with one // pending state between them (mock-up risk 9): while one is out, both // show the title on its way and neither can send another. When it // lands the header, the H1, the tab's title, the sidebar's entry, the // kicker's old titles and the editor's name all take it, with no // reload, and the page offers "Update links to the new title" with the // confirm page's honest count (base §3.4), posting the same POST // /p/{id}/links. Without script the H1 is the plain heading it always // was, and the header's form posts and lands on the confirm page. // // Why the H1's own text, made contenteditable, and not an input styled // as the H1: a title wraps, an input does not, so an input would shift // the page whenever a title is longer than a line, and its caret could // not land where a click on the second line fell. The editable text is // a span inside the heading with role textbox and its own name ("Title, // renames the page"), so the heading keeps its name (the title, read // from the textbox's value) for heading navigation, and the field says // what it does. contenteditable takes IME composition natively; Enter // is never acted on while composing. Blur renames only when focus moves // within the page, never when the window or tab loses it; closing the // page with an edited title renames it (build note 79). It is contenteditable="true", not // "plaintext-only": Chromium forces plaintext-only text to pre-wrap, // which keeps and measures a line's end space, so a wrapped title's box // changed at mount. Plain text is held instead by refusing breaks and // formatting (beforeinput) and pasting text only. import { HOLD_MS, held } from './busy.mjs' export const NAME = 'Title, renames the page' // clean is CleanTitle's whitespace rule: runs of space are one, and the // ends are trimmed. The server is the authority; this only spares a // POST for a title that would not change. export function clean (text) { return text.split(/\s+/u).filter(Boolean).join(' ') } // Renamer is the one pending state (§4.1). rename answers what became // of the title it was given; listeners hear pending, renamed, refused // and failed, each with the source that sent it (h1 or header). export class Renamer { constructor (title, action, deps) { this.title = title this.action = action this.deps = deps this.pending = null this.listeners = [] } on (listener) { this.listeners.push(listener) } emit (event) { for (const listener of this.listeners) listener(event) } async rename (typed, source) { const title = clean(typed) if (this.pending !== null) return 'busy' if (title === '') return 'empty' if (title === this.title) return 'unchanged' this.pending = title this.emit({ kind: 'pending', title, source }) // The busy rule: the pending state shows for HOLD_MS at least. const hold = this.deps.wait(HOLD_MS) let reply = null try { reply = await this.deps.post(this.action, { title }) } catch {} await hold this.pending = null if (reply?.status === 200 && reply.json?.title) { this.title = reply.json.title this.emit({ kind: 'renamed', source, ...reply.json }) return 'renamed' } if (reply?.status === 422 && reply.json?.error) { this.emit({ kind: 'refused', source, typed, error: reply.json.error, taken: reply.json.taken ?? '' }) return 'refused' } this.emit({ kind: 'failed', source, typed }) return 'failed' } // closing is the page closing with title typed and not yet renamed: // one keepalive POST, whose answer nobody is left to read. closing (title) { try { this.deps.post(this.action, { title }, { keepalive: true })?.catch?.(() => {}) } catch {} } // updateLinks is "Update links to the new title": the confirm page's // POST, answered as JSON. It answers the server's sentence, or null. async updateLinks () { const action = this.action.replace(/\/rename$/u, '/links') let reply = null try { reply = await this.deps.post(action, {}) } catch {} return reply?.status === 200 ? reply.json?.notice ?? null : null } } function element (tag, attrs = {}, ...children) { const node = document.createElement(tag) for (const [name, value] of Object.entries(attrs)) node.setAttribute(name, value) node.append(...children) return node } // caretAtEnd puts the caret after the text's last character. function caretAtEnd (node) { node.focus() const range = document.createRange() range.selectNodeContents(node) range.collapse(false) const selection = getSelection() selection.removeAllRanges() selection.addRange(range) } // startTitle makes the page's title editable, if the server marked it // renamable (h1[mapa-rename]): a team page the editor mounts on, never // a daily note, a scratch page, History or a deleted page. hooks are // the editor's: renamed({from, to, title}) and refresh(). export function startTitle ({ post, hooks = {} }) { const heading = document.querySelector('h1[mapa-title][mapa-rename]') const text = heading?.querySelector('[mapa-title-text]') if (!text) return null const renamer = new Renamer(text.textContent, heading.getAttribute('mapa-rename'), { post, wait: ms => new Promise(resolve => setTimeout(resolve, ms)) }) const note = element('div', { 'mapa-title-note': '', id: 'mapa-title-note', role: 'status' }) heading.after(note) const field = headerField(renamer.action) editable(heading, text, renamer) if (field) headerForm(field, renamer) renamer.on(event => show(event, { heading, text, field, note, renamer, hooks })) return renamer } // headerField is the bar's title field, if it renames this page. function headerField (action) { const form = document.querySelector('form[estilo-bar-title]') const input = form?.querySelector('[estilo-bar-title-input]') if (!input || new URL(form.action, location.href).pathname !== action) return null return { form, input, button: form.querySelector('[estilo-bar-title-submit]') } } function editable (heading, text, renamer) { text.setAttribute('contenteditable', 'true') text.setAttribute('role', 'textbox') text.setAttribute('aria-label', NAME) text.setAttribute('aria-describedby', 'mapa-title-note') text.setAttribute('spellcheck', 'false') // The heading's room past the text's end is the title's too: a click // there edits it, with the caret at the end. heading.addEventListener('mousedown', event => { if (event.target !== heading || event.button !== 0) return event.preventDefault() caretAtEnd(text) }) let reverting = false let refused = null const commit = async how => { const typed = text.textContent const title = clean(typed) if (renamer.pending !== null) return if (title === '' || title === renamer.title) { if (how === 'enter' && title === '') return text.removeAttribute('aria-invalid') if (text.textContent !== renamer.title) text.textContent = renamer.title if (how === 'enter') text.blur() return } // Leaving a refused title as it was does not send it again. if (how === 'blur' && title === refused) return const outcome = await renamer.rename(typed, 'h1') refused = outcome === 'refused' ? title : null if (outcome === 'renamed' && document.activeElement === text) { reverting = true text.blur() reverting = false } } text.addEventListener('keydown', event => { if (event.isComposing || event.keyCode === 229) return const save = event.key === 's' && (event.metaKey || event.ctrlKey) if (event.key === 'Enter' || save) { event.preventDefault() commit('enter') } else if (event.key === 'Escape') { event.preventDefault() if (renamer.pending !== null) return reverting = true refused = null text.textContent = renamer.title text.removeAttribute('aria-invalid') text.blur() reverting = false clearRefusal(heading) } }) // Leaving the field renames; the window or the tab losing focus is not // leaving it (Cmd-Tab mid-typing must not rename to half a title). The // edit stays open: it renames when the person comes back and leaves // the field, or presses Enter, or when the page closes (below). let away = false text.addEventListener('blur', () => { if (reverting) return if (!document.hasFocus() || document.visibilityState === 'hidden') { away = true return } commit('blur') }) text.addEventListener('focus', () => { away = false }) // Browsers give a window's focused element its focus back; where one // does not, the field takes it back, so leaving it still renames. window.addEventListener('focus', () => { if (away && document.activeElement === document.body) caretAtEnd(text) }) // Closing the page with the title edited renames, as closing commits // the page's text (§6.5): one keepalive POST, the same rename. A // rename still out is sent again, since leaving may cancel it; a title // already in place is no change, and writes nothing. window.addEventListener('pagehide', () => { const title = renamer.pending ?? clean(text.textContent) if (title === '' || title === renamer.title) return if (renamer.pending === null && title === refused) return renamer.closing(title) }) // One line of plain text: no breaks, no formatting, and nothing typed // while a rename is out. text.addEventListener('beforeinput', event => { const lineBreak = /^(insertParagraph|insertLineBreak)$/u.test(event.inputType) if (renamer.pending !== null || lineBreak || /^format/u.test(event.inputType)) { event.preventDefault() } // A break typed outside a composition is Enter: Android's keyboard // sends its Enter as keyCode 229, which keydown leaves alone, and // the break arrives here. It renames as Enter does; a break inside a // composition still does nothing. if (lineBreak && !event.isComposing && renamer.pending === null) commit('enter') }) text.addEventListener('paste', event => { event.preventDefault() if (renamer.pending !== null) return const pasted = clean(event.clipboardData?.getData('text/plain') ?? '') document.execCommand('insertText', false, pasted) }) text.addEventListener('drop', event => event.preventDefault()) } function headerForm ({ form, input, button }, renamer) { form.addEventListener('submit', async event => { event.preventDefault() if (renamer.pending !== null) return const title = clean(input.value) if (title === '' || title === renamer.title) { input.value = renamer.title input.removeAttribute('aria-invalid') input.blur() return } const run = () => renamer.rename(input.value, 'header') const outcome = button ? await held(button, run) : await run() if (outcome === 'renamed') input.blur() }) } function clearRefusal (heading) { const note = heading.nextElementSibling if (note?.querySelector('[role="alert"]')) note.replaceChildren() } // show draws one event of the shared state on both fields and the note. function show (event, parts) { const { text, field, note } = parts const fromH1 = event.source === 'h1' if (event.kind === 'pending') { text.setAttribute('aria-readonly', 'true') text.setAttribute('aria-busy', 'true') if (!fromH1) text.textContent = event.title if (field) { field.input.readOnly = true if (fromH1) field.input.value = event.title } note.replaceChildren(element('p', {}, element('span', { 'rst-spin': '', 'aria-hidden': 'true' }), 'Renaming…')) return } text.removeAttribute('aria-readonly') text.removeAttribute('aria-busy') if (field) field.input.readOnly = false if (event.kind === 'renamed') return renamed(event, parts) // Refused or failed: the field it was typed in keeps the text; the // other goes back to the title the page has. const keeper = fromH1 ? text : field?.input if (fromH1 && field) field.input.value = parts.renamer.title if (!fromH1 && text.textContent !== parts.renamer.title) text.textContent = parts.renamer.title keeper?.setAttribute('aria-invalid', 'true') const sentence = event.kind === 'refused' ? event.error : 'Not renamed: the title could not be saved. Check your connection and try again.' const line = element('p', { role: 'alert' }, sentence) if (event.taken) line.append(' ', element('a', { href: event.taken }, 'Open the page with that title')) note.replaceChildren(line) } function renamed (event, { text, field, note, renamer, hooks }) { const title = event.title text.removeAttribute('aria-invalid') if (text.textContent !== title) text.textContent = title if (field) { field.input.removeAttribute('aria-invalid') field.input.value = title field.input.defaultValue = title // estilo's chrome.js fits the stacked field to its title on input. field.input.dispatchEvent(new Event('input', { bubbles: true })) } document.title = `${title} · Mapa` for (const link of document.querySelectorAll('[mapa-side] a[mapa-side-page]')) { if (new URL(link.href).pathname !== event.href) continue const label = link.querySelector('[mapa-side-label]') if (!label) continue renameMore(link.closest('[mapa-side-row]')?.querySelector('[mapa-row-more]'), label.textContent, title) label.textContent = title } alsoCalled(event.aliases ?? []) hooks.renamed?.({ title, from: event.from, to: event.to }) hooks.refresh?.() note.replaceChildren(...offer(event, note, renamer, hooks)) } // renameMore renames a sidebar row's ⋯ with its row (build note 88): // the server wrote its name as words, then the title, so the title at // its end is the old one. function renameMore (more, was, title) { const name = more?.getAttribute('aria-label') if (!name?.endsWith(was)) return more.setAttribute('aria-label', name.slice(0, name.length - was.length) + title) } // alsoCalled redraws the kicker's old titles. function alsoCalled (aliases) { const kicker = document.querySelector('[mapa-doc-kicker]') if (!kicker) return let span = kicker.querySelector('[mapa-also]') if (aliases.length === 0) { span?.remove() return } if (!span) { span = element('span', { 'mapa-also': '' }) kicker.insertBefore(span, kicker.querySelector('[mapa-actions]')) } span.textContent = `Also called ${aliases.join(', ')}` } // offer is the notice after a rename: with links to update, the choice // (base §3.4: an explicit, attributed edit, never silent), with the // confirm page's count and words; with none, the form's own sentence. function offer (event, note, renamer, hooks) { if (!(event.links > 0)) return [element('p', {}, 'Renamed. The old title still leads here.')] const update = element('button', { 'rst-btn': 'primary', type: 'button' }, 'Update links') const later = element('button', { 'rst-btn': '', type: 'button' }, 'Not now') update.addEventListener('click', async () => { const said = await held(update, () => renamer.updateLinks()) if (said === null) { note.querySelector('[mapa-title-links-failed]')?.remove() note.append(element('p', { role: 'alert', 'mapa-title-links-failed': '' }, 'Links not updated. Check your connection and try again.')) return } note.replaceChildren(element('p', {}, said)) hooks.refresh?.() }) later.addEventListener('click', () => note.replaceChildren()) return [ element('p', {}, `Renamed. ${event.count} you can edit link here by an old title. ` + `Update them to "${event.title}"? It's an edit by you; other people's private notes keep working.`), update, later ] }