oficina / slides Public

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

Plain git — no account needed to clone.

Download

Download this file

1// fixtures/box-menu.mjs — the menu on a selected box (the quieter
2// editor, spec §4): arranging a box moved out of the card and onto the
3// box. The round button ([slides-box-more]) sits on the selected box's
4// outline, at its top end corner where there is room, never over a
5// resize handle and never outside the stage; it opens the menu
6// ([slides-box-menu]), estilo's panel and rows as a manual popover. So
7// do the context-menu key and Shift+F10 with a box selected, and a
8// right-click on a box, unless the pointer is in text being edited:
9// there the browser's own menu opens, because spelling and paste live
10// in it.
11//
12// The menu's markup is the server's, every row drawn; open() hides the
13// rows that do not apply (rowsFor: layers and Position and size on a
14// canvas slide, the region rows on a flow one). A row is the command
15// its card button was, run through run(name) (commands.mjs); a region
16// row is setRegion(id, region). The arrows move through the rows,
17// Enter and Space press one, and Esc (or Tab) closes the menu and puts
18// focus back on the box, the selection kept.
19//
20// The box's keys are here too (boxKey): bring forward and send back,
21// move up and down, Delete, and Shift+F10 for the menu. They are heard
22// only while a box is selected and focus is on the stage: never in the
23// bar, the notes, the strip (whose Delete asks about a slide, head.mjs)
24// or a dialog. Delete and Mod+Shift+arrows are the box's only when the
25// box itself has focus (its canvas overlay, or its own tab stop): in
26// text they delete and select text.
27//
28// mountBoxMenu({root, stageEl, getSelected, getSlide, run, setRegion,
29// focusBox, select, after}) → {open('button' | {x, y}), close({restore}),
30// place(), sync(), isOpen(), destroy()}. getSlide() is the slide's JSON;
31// focusBox(id) puts focus on a box and select(id) selects one
32// (stage-focus.mjs); after(name, id) hears each row or key run on box id
33// ('region' for a region row), for where focus goes next. place() runs
34// wherever the canvas overlay is placed; sync() after every change to
35// the document, closing the open menu when its box or the slide's
36// layout changed under it. Where the button and the menu go is
37// box-spot.mjs; with no room on the stage the button docks beside the
38// view switch (data-docked).
39import { defaultRegion } from './layout.mjs'
40import { buttonSpot, menuSpot, clip, overlaps } from './box-spot.mjs'
41
42export { buttonSpot, menuSpot }
43
44const ROWS = {
45 canvas: ['block-format', 'block-forward', 'block-back', 'block-move-up', 'block-move-down', 'block-place', 'block-delete'],
46 flow: ['block-format', 'block-move-up', 'block-move-down', 'region', 'block-delete']
47}
48const EDITABLE = '[contenteditable="true"]'
49
50/** The menu's rows for a box, in order: what decides is the slide's layout. */
51export function rowsFor ({ layout }) {
52 return [...(layout === 'canvas' ? ROWS.canvas : ROWS.flow)]
53}
54
55/** Whether a right-click on target is the box menu's: not in text being edited. */
56export function canOwnContextMenu (target) {
57 if (!target || typeof target.closest !== 'function') return false
58 const editable = target.closest(EDITABLE)
59 if (!editable) return true
60 const active = globalThis.document ? globalThis.document.activeElement : null
61 return !(active && editable.contains(active))
62}
63
64/**
65 * The box's command for a keydown, 'menu', or null. onBox: the box
66 * itself has focus, no text is being edited.
67 */
68export function boxKey (e, { onBox = false } = {}) {
69 const mod = !!(e.ctrlKey || e.metaKey)
70 if (e.key === 'F10' && e.shiftKey && !mod && !e.altKey) return 'menu'
71 if (mod && !e.shiftKey && !e.altKey) {
72 if (e.key === ']' || e.code === 'BracketRight') return 'block-forward'
73 if (e.key === '[' || e.code === 'BracketLeft') return 'block-back'
74 }
75 if (!onBox) return null
76 if (mod && e.shiftKey && !e.altKey && e.key === 'ArrowUp') return 'block-move-up'
77 if (mod && e.shiftKey && !e.altKey && e.key === 'ArrowDown') return 'block-move-down'
78 if ((e.key === 'Delete' || e.key === 'Backspace') && !mod && !e.altKey && !e.shiftKey) return 'block-delete'
79 return null
80}
81
82const rectOf = el => (el && typeof el.getBoundingClientRect === 'function' ? el.getBoundingClientRect() : null)
83
84export function mountBoxMenu ({ root, stageEl, getSelected, getSlide, run, setRegion, focusBox = () => {}, select = () => {}, after = () => {} }) {
85 const button = root.querySelector('[slides-box-more]')
86 const menu = root.querySelector('[slides-box-menu]')
87 const doc = globalThis.document
88 // In Phone view the stage's frame is the phone's screen, and it is
89 // what scrolls; elsewhere it is nothing (display: contents, no box).
90 const frame = typeof stageEl.closest === 'function' ? stageEl.closest('[slides-stage-frame]') : null
91 const abort = new AbortController()
92 const { signal } = abort
93 let shown = false
94 let boxId = ''
95 // The slide's layout when the menu opened: its rows are that layout's.
96 let openLayout = ''
97
98 const boxEl = id => (id ? [...stageEl.querySelectorAll('[slides-block]')].find(b => b.getAttribute('data-id') === id) || null : null)
99 function selected () {
100 const id = getSelected()
101 const slide = id ? getSlide() : null
102 const block = slide && Array.isArray(slide.blocks) ? slide.blocks.find(b => b.id === id) : null
103 return block ? { slide, block } : null
104 }
105 // The rows drawn: the row itself, or its group, not hidden.
106 const drawn = () => [...menu.querySelectorAll('[estilo-menu-item]')].filter(i => !i.hidden && !(i.closest('[data-row]') || i).hidden)
107
108 // The round button over the selected box, in the stage pane's
109 // pixels; hidden with nothing selected, and the menu closed then.
110 function place () {
111 const id = getSelected()
112 const el = boxEl(id)
113 if (shown && (!el || id !== boxId)) close()
114 sync()
115 if (!button) return
116 button.hidden = !el
117 if (!el || !button.style) return
118 const box = rectOf(el)
119 const pane = rectOf(button.offsetParent || button.parentNode)
120 if (!box || !pane) return
121 // What can be seen of the stage: in Phone view, what the screen shows.
122 const bound = clip(rectOf(stageEl), rectOf(frame))
123 if (bound && !overlaps(box, bound)) return void (button.hidden = true)
124 const handles = [...stageEl.querySelectorAll('[slides-handle]')].map(rectOf).filter(h => h && h.width > 0)
125 const avoid = [...stageEl.querySelectorAll('[slides-block]')].filter(b => !b.contains(el) && !el.contains(b)).map(rectOf).filter(r => r && r.width > 0)
126 const rtl = typeof getComputedStyle === 'function' && getComputedStyle(stageEl).direction === 'rtl'
127 const size = button.offsetWidth || 28
128 let spot = buttonSpot({ box, handles, avoid, bound, size, rtl })
129 // A stage too small for it anywhere clear of the handles: docked in
130 // the stage bar beside the view switch, off the slide.
131 const docked = !spot
132 const sw = docked ? rectOf(root.querySelector('[slides-switcher]')) : null
133 if (docked && !sw) return
134 if (docked) spot = { left: rtl ? sw.left - 8 - size : sw.right + 8, top: sw.top + (sw.height - size) / 2 }
135 if (docked) button.setAttribute('data-docked', '')
136 else button.removeAttribute('data-docked')
137 button.style.left = `${spot.left - pane.left}px`
138 button.style.top = `${spot.top - pane.top}px`
139 }
140
141 function position (at) {
142 if (!menu.style || typeof menu.getBoundingClientRect !== 'function') return
143 const anchor = at && typeof at === 'object'
144 ? { left: at.x, right: at.x, top: at.y, bottom: at.y }
145 : (button && !button.hidden && rectOf(button)) || rectOf(boxEl(boxId))
146 if (!anchor) return
147 menu.style.maxBlockSize = ''
148 const { width, height } = menu.getBoundingClientRect()
149 const spot = menuSpot({ anchor, width, height, vw: globalThis.innerWidth, vh: globalThis.innerHeight })
150 menu.style.left = `${spot.left}px`
151 menu.style.top = `${spot.top}px`
152 menu.style.maxBlockSize = `${spot.maxHeight}px`
153 }
154
155 // The selected box's menu, its rows those that apply, the box's
156 // region checked; at the button, or at the pointer ({x, y}).
157 function open (at = 'button') {
158 const sel = selected()
159 if (!sel || !menu) return false
160 const rows = rowsFor({ layout: sel.slide.layout, type: sel.block.type })
161 for (const r of menu.querySelectorAll('[data-row]')) r.hidden = !rows.includes(r.dataset.row)
162 checkRegion(sel.block)
163 boxId = sel.block.id
164 openLayout = sel.slide.layout
165 if (!shown && typeof menu.showPopover === 'function') menu.showPopover()
166 shown = true
167 if (button) button.setAttribute('aria-expanded', 'true')
168 position(at)
169 const first = drawn()[0]
170 if (first) first.focus()
171 return true
172 }
173
174 function checkRegion (block) {
175 const region = block.region || defaultRegion(block.type)
176 for (const b of menu.querySelectorAll('[data-region]')) b.setAttribute('aria-checked', String(b.dataset.region === region))
177 }
178
179 // The open menu against the document as it is now (a colleague's
180 // change, an undo): closed when its box is gone or no longer the
181 // selection, or the slide's layout is not the one its rows were drawn
182 // for; otherwise its region checks follow the box.
183 function sync () {
184 if (!shown) return
185 const sel = selected()
186 if (sel && sel.block.id === boxId && sel.slide.layout === openLayout) return checkRegion(sel.block)
187 close({ restore: !!sel && sel.block.id === boxId && menu.contains(doc.activeElement) })
188 }
189
190 // restore: focus back on the box (Esc, a row that leaves it there).
191 function close ({ restore = false } = {}) {
192 const id = boxId
193 if (shown) {
194 shown = false
195 try { if (typeof menu.hidePopover === 'function') menu.hidePopover() } catch { /* closed already */ }
196 }
197 if (button) button.setAttribute('aria-expanded', 'false')
198 if (restore && id) focusBox(id)
199 }
200
201 menu.addEventListener('click', e => {
202 const row = e.target && typeof e.target.closest === 'function' ? e.target.closest('[estilo-menu-item]') : null
203 if (!row || !shown) return
204 const id = boxId
205 // A row runs only while it still applies to the box as it is now.
206 const sel = selected()
207 if (!sel || sel.block.id !== id || !rowsFor({ layout: sel.slide.layout }).includes((row.closest('[data-row]') || row).dataset.row)) {
208 close({ restore: !!sel && sel.block.id === id })
209 return
210 }
211 if (row.dataset.region) {
212 close({ restore: true })
213 setRegion(id, row.dataset.region)
214 after('region', id)
215 return
216 }
217 const name = row.dataset.command
218 if (!name) return
219 // The box is still there afterwards, but for Delete.
220 close({ restore: name !== 'block-delete' })
221 run(name)
222 after(name, id)
223 }, { signal })
224
225 menu.addEventListener('keydown', e => {
226 if (e.isComposing) return
227 if (e.key === 'Escape' || e.key === 'Tab') {
228 e.preventDefault()
229 e.stopPropagation()
230 close({ restore: true })
231 return
232 }
233 const rows = drawn()
234 if (!rows.length) return
235 const at = rows.indexOf(doc.activeElement)
236 const next = { ArrowDown: rows[(at + 1) % rows.length], ArrowUp: rows[(at - 1 + rows.length) % rows.length], Home: rows[0], End: rows[rows.length - 1] }[e.key]
237 if (!next) return
238 e.preventDefault()
239 next.focus()
240 }, { signal })
241
242 if (button) button.addEventListener('click', () => (shown ? close({ restore: true }) : open('button')), { signal })
243
244 // A press anywhere else closes it (a manual popover has no light dismiss).
245 doc.addEventListener('pointerdown', e => {
246 if (!shown || !e.target) return
247 if (menu.contains(e.target) || (button && button.contains(e.target))) return
248 close()
249 }, { signal, capture: true })
250
251 // A right-click on a box (or on the overlay over the selected one),
252 // outside text being edited; from the keyboard (no pointer), at the
253 // round button. A box not yet selected is selected first.
254 stageEl.addEventListener('contextmenu', e => {
255 const t = e.target
256 if (!canOwnContextMenu(t)) return
257 const box = t.closest('[slides-canvas-overlay]') ? boxEl(getSelected()) : t.closest('[slides-block]')
258 const id = box ? box.getAttribute('data-id') : ''
259 if (!id) return
260 e.preventDefault()
261 if (id !== getSelected()) select(id)
262 open(e.clientX || e.clientY ? { x: e.clientX, y: e.clientY } : 'button')
263 }, { signal })
264
265 for (const el of [stageEl, frame]) if (el) el.addEventListener('scroll', () => place(), { signal, passive: true })
266
267 doc.addEventListener('keydown', e => {
268 if (e.defaultPrevented || e.isComposing || shown) return
269 const a = doc.activeElement
270 if (!a || !stageEl.contains(a) || !getSelected()) return
271 const inText = typeof a.closest === 'function' && !!a.closest(EDITABLE)
272 const onBox = !inText && typeof a.matches === 'function' && (a.matches('[slides-canvas-overlay]') || a.matches('[slides-block]'))
273 const name = boxKey(e, { onBox })
274 if (!name) return
275 // Held from the browser (Mod+[ and Mod+] go back and forward in
276 // history in some) even where the box has no such row.
277 e.preventDefault()
278 if (name === 'menu') {
279 open('button')
280 return
281 }
282 const sel = selected()
283 if (!sel || !rowsFor({ layout: sel.slide.layout, type: sel.block.type }).includes(name)) return
284 run(name)
285 after(name, sel.block.id)
286 }, { signal })
287
288 return {
289 open,
290 close,
291 place,
292 sync,
293 isOpen: () => shown,
294 destroy () {
295 close()
296 abort.abort()
297 }
298 }
299}
300