oficina / mapa Public

Clone
git clone https://amadan.net/oficina/mapa

Plain git — no account needed to clone.

Download

Download this file

1// title.mjs — a team page's title, renamed in place (level-up §4.1,
2// build note 78). The H1's text and the header's title field rename
3// through the same POST /p/{id}/rename, asking for JSON, with one
4// pending state between them (mock-up risk 9): while one is out, both
5// show the title on its way and neither can send another. When it
6// lands the header, the H1, the tab's title, the sidebar's entry, the
7// kicker's old titles and the editor's name all take it, with no
8// reload, and the page offers "Update links to the new title" with the
9// confirm page's honest count (base §3.4), posting the same POST
10// /p/{id}/links. Without script the H1 is the plain heading it always
11// was, and the header's form posts and lands on the confirm page.
12//
13// Why the H1's own text, made contenteditable, and not an input styled
14// as the H1: a title wraps, an input does not, so an input would shift
15// the page whenever a title is longer than a line, and its caret could
16// not land where a click on the second line fell. The editable text is
17// a span inside the heading with role textbox and its own name ("Title,
18// renames the page"), so the heading keeps its name (the title, read
19// from the textbox's value) for heading navigation, and the field says
20// what it does. contenteditable takes IME composition natively; Enter
21// is never acted on while composing. Blur renames only when focus moves
22// within the page, never when the window or tab loses it; closing the
23// page with an edited title renames it (build note 79). It is contenteditable="true", not
24// "plaintext-only": Chromium forces plaintext-only text to pre-wrap,
25// which keeps and measures a line's end space, so a wrapped title's box
26// changed at mount. Plain text is held instead by refusing breaks and
27// formatting (beforeinput) and pasting text only.
28
29import { HOLD_MS, held } from './busy.mjs'
30
31export const NAME = 'Title, renames the page'
32
33// clean is CleanTitle's whitespace rule: runs of space are one, and the
34// ends are trimmed. The server is the authority; this only spares a
35// POST for a title that would not change.
36export function clean (text) {
37 return text.split(/\s+/u).filter(Boolean).join(' ')
38}
39
40// Renamer is the one pending state (§4.1). rename answers what became
41// of the title it was given; listeners hear pending, renamed, refused
42// and failed, each with the source that sent it (h1 or header).
43export class Renamer {
44 constructor (title, action, deps) {
45 this.title = title
46 this.action = action
47 this.deps = deps
48 this.pending = null
49 this.listeners = []
50 }
51
52 on (listener) { this.listeners.push(listener) }
53
54 emit (event) {
55 for (const listener of this.listeners) listener(event)
56 }
57
58 async rename (typed, source) {
59 const title = clean(typed)
60 if (this.pending !== null) return 'busy'
61 if (title === '') return 'empty'
62 if (title === this.title) return 'unchanged'
63 this.pending = title
64 this.emit({ kind: 'pending', title, source })
65 // The busy rule: the pending state shows for HOLD_MS at least.
66 const hold = this.deps.wait(HOLD_MS)
67 let reply = null
68 try { reply = await this.deps.post(this.action, { title }) } catch {}
69 await hold
70 this.pending = null
71 if (reply?.status === 200 && reply.json?.title) {
72 this.title = reply.json.title
73 this.emit({ kind: 'renamed', source, ...reply.json })
74 return 'renamed'
75 }
76 if (reply?.status === 422 && reply.json?.error) {
77 this.emit({ kind: 'refused', source, typed, error: reply.json.error, taken: reply.json.taken ?? '' })
78 return 'refused'
79 }
80 this.emit({ kind: 'failed', source, typed })
81 return 'failed'
82 }
83
84 // closing is the page closing with title typed and not yet renamed:
85 // one keepalive POST, whose answer nobody is left to read.
86 closing (title) {
87 try {
88 this.deps.post(this.action, { title }, { keepalive: true })?.catch?.(() => {})
89 } catch {}
90 }
91
92 // updateLinks is "Update links to the new title": the confirm page's
93 // POST, answered as JSON. It answers the server's sentence, or null.
94 async updateLinks () {
95 const action = this.action.replace(/\/rename$/u, '/links')
96 let reply = null
97 try { reply = await this.deps.post(action, {}) } catch {}
98 return reply?.status === 200 ? reply.json?.notice ?? null : null
99 }
100}
101
102function element (tag, attrs = {}, ...children) {
103 const node = document.createElement(tag)
104 for (const [name, value] of Object.entries(attrs)) node.setAttribute(name, value)
105 node.append(...children)
106 return node
107}
108
109// caretAtEnd puts the caret after the text's last character.
110function caretAtEnd (node) {
111 node.focus()
112 const range = document.createRange()
113 range.selectNodeContents(node)
114 range.collapse(false)
115 const selection = getSelection()
116 selection.removeAllRanges()
117 selection.addRange(range)
118}
119
120// startTitle makes the page's title editable, if the server marked it
121// renamable (h1[mapa-rename]): a team page the editor mounts on, never
122// a daily note, a scratch page, History or a deleted page. hooks are
123// the editor's: renamed({from, to, title}) and refresh().
124export function startTitle ({ post, hooks = {} }) {
125 const heading = document.querySelector('h1[mapa-title][mapa-rename]')
126 const text = heading?.querySelector('[mapa-title-text]')
127 if (!text) return null
128 const renamer = new Renamer(text.textContent, heading.getAttribute('mapa-rename'),
129 { post, wait: ms => new Promise(resolve => setTimeout(resolve, ms)) })
130 const note = element('div', { 'mapa-title-note': '', id: 'mapa-title-note', role: 'status' })
131 heading.after(note)
132 const field = headerField(renamer.action)
133 editable(heading, text, renamer)
134 if (field) headerForm(field, renamer)
135 renamer.on(event => show(event, { heading, text, field, note, renamer, hooks }))
136 return renamer
137}
138
139// headerField is the bar's title field, if it renames this page.
140function headerField (action) {
141 const form = document.querySelector('form[estilo-bar-title]')
142 const input = form?.querySelector('[estilo-bar-title-input]')
143 if (!input || new URL(form.action, location.href).pathname !== action) return null
144 return { form, input, button: form.querySelector('[estilo-bar-title-submit]') }
145}
146
147function editable (heading, text, renamer) {
148 text.setAttribute('contenteditable', 'true')
149 text.setAttribute('role', 'textbox')
150 text.setAttribute('aria-label', NAME)
151 text.setAttribute('aria-describedby', 'mapa-title-note')
152 text.setAttribute('spellcheck', 'false')
153 // The heading's room past the text's end is the title's too: a click
154 // there edits it, with the caret at the end.
155 heading.addEventListener('mousedown', event => {
156 if (event.target !== heading || event.button !== 0) return
157 event.preventDefault()
158 caretAtEnd(text)
159 })
160 let reverting = false
161 let refused = null
162 const commit = async how => {
163 const typed = text.textContent
164 const title = clean(typed)
165 if (renamer.pending !== null) return
166 if (title === '' || title === renamer.title) {
167 if (how === 'enter' && title === '') return
168 text.removeAttribute('aria-invalid')
169 if (text.textContent !== renamer.title) text.textContent = renamer.title
170 if (how === 'enter') text.blur()
171 return
172 }
173 // Leaving a refused title as it was does not send it again.
174 if (how === 'blur' && title === refused) return
175 const outcome = await renamer.rename(typed, 'h1')
176 refused = outcome === 'refused' ? title : null
177 if (outcome === 'renamed' && document.activeElement === text) {
178 reverting = true
179 text.blur()
180 reverting = false
181 }
182 }
183 text.addEventListener('keydown', event => {
184 if (event.isComposing || event.keyCode === 229) return
185 const save = event.key === 's' && (event.metaKey || event.ctrlKey)
186 if (event.key === 'Enter' || save) {
187 event.preventDefault()
188 commit('enter')
189 } else if (event.key === 'Escape') {
190 event.preventDefault()
191 if (renamer.pending !== null) return
192 reverting = true
193 refused = null
194 text.textContent = renamer.title
195 text.removeAttribute('aria-invalid')
196 text.blur()
197 reverting = false
198 clearRefusal(heading)
199 }
200 })
201 // Leaving the field renames; the window or the tab losing focus is not
202 // leaving it (Cmd-Tab mid-typing must not rename to half a title). The
203 // edit stays open: it renames when the person comes back and leaves
204 // the field, or presses Enter, or when the page closes (below).
205 let away = false
206 text.addEventListener('blur', () => {
207 if (reverting) return
208 if (!document.hasFocus() || document.visibilityState === 'hidden') {
209 away = true
210 return
211 }
212 commit('blur')
213 })
214 text.addEventListener('focus', () => { away = false })
215 // Browsers give a window's focused element its focus back; where one
216 // does not, the field takes it back, so leaving it still renames.
217 window.addEventListener('focus', () => {
218 if (away && document.activeElement === document.body) caretAtEnd(text)
219 })
220 // Closing the page with the title edited renames, as closing commits
221 // the page's text (§6.5): one keepalive POST, the same rename. A
222 // rename still out is sent again, since leaving may cancel it; a title
223 // already in place is no change, and writes nothing.
224 window.addEventListener('pagehide', () => {
225 const title = renamer.pending ?? clean(text.textContent)
226 if (title === '' || title === renamer.title) return
227 if (renamer.pending === null && title === refused) return
228 renamer.closing(title)
229 })
230 // One line of plain text: no breaks, no formatting, and nothing typed
231 // while a rename is out.
232 text.addEventListener('beforeinput', event => {
233 const lineBreak = /^(insertParagraph|insertLineBreak)$/u.test(event.inputType)
234 if (renamer.pending !== null || lineBreak || /^format/u.test(event.inputType)) {
235 event.preventDefault()
236 }
237 // A break typed outside a composition is Enter: Android's keyboard
238 // sends its Enter as keyCode 229, which keydown leaves alone, and
239 // the break arrives here. It renames as Enter does; a break inside a
240 // composition still does nothing.
241 if (lineBreak && !event.isComposing && renamer.pending === null) commit('enter')
242 })
243 text.addEventListener('paste', event => {
244 event.preventDefault()
245 if (renamer.pending !== null) return
246 const pasted = clean(event.clipboardData?.getData('text/plain') ?? '')
247 document.execCommand('insertText', false, pasted)
248 })
249 text.addEventListener('drop', event => event.preventDefault())
250}
251
252function headerForm ({ form, input, button }, renamer) {
253 form.addEventListener('submit', async event => {
254 event.preventDefault()
255 if (renamer.pending !== null) return
256 const title = clean(input.value)
257 if (title === '' || title === renamer.title) {
258 input.value = renamer.title
259 input.removeAttribute('aria-invalid')
260 input.blur()
261 return
262 }
263 const run = () => renamer.rename(input.value, 'header')
264 const outcome = button ? await held(button, run) : await run()
265 if (outcome === 'renamed') input.blur()
266 })
267}
268
269function clearRefusal (heading) {
270 const note = heading.nextElementSibling
271 if (note?.querySelector('[role="alert"]')) note.replaceChildren()
272}
273
274// show draws one event of the shared state on both fields and the note.
275function show (event, parts) {
276 const { text, field, note } = parts
277 const fromH1 = event.source === 'h1'
278 if (event.kind === 'pending') {
279 text.setAttribute('aria-readonly', 'true')
280 text.setAttribute('aria-busy', 'true')
281 if (!fromH1) text.textContent = event.title
282 if (field) {
283 field.input.readOnly = true
284 if (fromH1) field.input.value = event.title
285 }
286 note.replaceChildren(element('p', {}, element('span', { 'rst-spin': '', 'aria-hidden': 'true' }), 'Renaming…'))
287 return
288 }
289 text.removeAttribute('aria-readonly')
290 text.removeAttribute('aria-busy')
291 if (field) field.input.readOnly = false
292 if (event.kind === 'renamed') return renamed(event, parts)
293 // Refused or failed: the field it was typed in keeps the text; the
294 // other goes back to the title the page has.
295 const keeper = fromH1 ? text : field?.input
296 if (fromH1 && field) field.input.value = parts.renamer.title
297 if (!fromH1 && text.textContent !== parts.renamer.title) text.textContent = parts.renamer.title
298 keeper?.setAttribute('aria-invalid', 'true')
299 const sentence = event.kind === 'refused'
300 ? event.error
301 : 'Not renamed: the title could not be saved. Check your connection and try again.'
302 const line = element('p', { role: 'alert' }, sentence)
303 if (event.taken) line.append(' ', element('a', { href: event.taken }, 'Open the page with that title'))
304 note.replaceChildren(line)
305}
306
307function renamed (event, { text, field, note, renamer, hooks }) {
308 const title = event.title
309 text.removeAttribute('aria-invalid')
310 if (text.textContent !== title) text.textContent = title
311 if (field) {
312 field.input.removeAttribute('aria-invalid')
313 field.input.value = title
314 field.input.defaultValue = title
315 // estilo's chrome.js fits the stacked field to its title on input.
316 field.input.dispatchEvent(new Event('input', { bubbles: true }))
317 }
318 document.title = `${title} · Mapa`
319 for (const link of document.querySelectorAll('[mapa-side] a[mapa-side-page]')) {
320 if (new URL(link.href).pathname !== event.href) continue
321 const label = link.querySelector('[mapa-side-label]')
322 if (!label) continue
323 renameMore(link.closest('[mapa-side-row]')?.querySelector('[mapa-row-more]'), label.textContent, title)
324 label.textContent = title
325 }
326 alsoCalled(event.aliases ?? [])
327 hooks.renamed?.({ title, from: event.from, to: event.to })
328 hooks.refresh?.()
329 note.replaceChildren(...offer(event, note, renamer, hooks))
330}
331
332// renameMore renames a sidebar row's ⋯ with its row (build note 88):
333// the server wrote its name as words, then the title, so the title at
334// its end is the old one.
335function renameMore (more, was, title) {
336 const name = more?.getAttribute('aria-label')
337 if (!name?.endsWith(was)) return
338 more.setAttribute('aria-label', name.slice(0, name.length - was.length) + title)
339}
340
341// alsoCalled redraws the kicker's old titles.
342function alsoCalled (aliases) {
343 const kicker = document.querySelector('[mapa-doc-kicker]')
344 if (!kicker) return
345 let span = kicker.querySelector('[mapa-also]')
346 if (aliases.length === 0) {
347 span?.remove()
348 return
349 }
350 if (!span) {
351 span = element('span', { 'mapa-also': '' })
352 kicker.insertBefore(span, kicker.querySelector('[mapa-actions]'))
353 }
354 span.textContent = `Also called ${aliases.join(', ')}`
355}
356
357// offer is the notice after a rename: with links to update, the choice
358// (base §3.4: an explicit, attributed edit, never silent), with the
359// confirm page's count and words; with none, the form's own sentence.
360function offer (event, note, renamer, hooks) {
361 if (!(event.links > 0)) return [element('p', {}, 'Renamed. The old title still leads here.')]
362 const update = element('button', { 'rst-btn': 'primary', type: 'button' }, 'Update links')
363 const later = element('button', { 'rst-btn': '', type: 'button' }, 'Not now')
364 update.addEventListener('click', async () => {
365 const said = await held(update, () => renamer.updateLinks())
366 if (said === null) {
367 note.querySelector('[mapa-title-links-failed]')?.remove()
368 note.append(element('p', { role: 'alert', 'mapa-title-links-failed': '' },
369 'Links not updated. Check your connection and try again.'))
370 return
371 }
372 note.replaceChildren(element('p', {}, said))
373 hooks.refresh?.()
374 })
375 later.addEventListener('click', () => note.replaceChildren())
376 return [
377 element('p', {}, `Renamed. ${event.count} you can edit link here by an old title. ` +
378 `Update them to "${event.title}"? It's an edit by you; other people's private notes keep working.`),
379 update, later
380 ]
381}
382