bloggie 0.4.2 → 0.4.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/e2e/editor.js CHANGED
@@ -124,6 +124,31 @@ export async function editorChecks({ check, launch, root }) {
124
124
  return observed
125
125
  })
126
126
 
127
+ // Every slide of every deck, moved to the start, the end and one place each way: every slide keeps its
128
+ // kind (a `#` that moves past the title is given its kind in a tag), and the moved slide keeps its text.
129
+ await check(LABEL, 'every slide of every deck moves, and every slide keeps its kind', () => {
130
+ const observed = {}
131
+ for (const slug of decksIn(root)) {
132
+ const source = readFileSync(join(root, 'src/pages/posts', slug, 'slides.mdx'), 'utf8')
133
+ const before = outline(source).slides
134
+ const n = before.length
135
+ let moves = 0
136
+ for (let from = 0; from < n; from++) {
137
+ for (const to of new Set([0, n - 1, from - 1, from + 1].filter((t) => t >= 0 && t < n && t !== from))) {
138
+ const order = before.map((s, i) => i)
139
+ order.splice(to, 0, ...order.splice(from, 1))
140
+ const after = outline(applyEdit(source, { type: 'move-slide', slide: from, to }).source).slides
141
+ const kinds = after.map((s) => s.kind).join()
142
+ if (kinds !== order.map((i) => before[i].kind).join()) throw new Error(`${slug}: moving slide ${from + 1} to ${to + 1} gives the kinds ${kinds}`)
143
+ if (after[to].opaque !== before[from].opaque || after[to].hashes.join() !== before[from].hashes.join()) throw new Error(`${slug}: slide ${from + 1}, moved to ${to + 1}, changed its blocks`)
144
+ moves++
145
+ }
146
+ }
147
+ observed[slug] = `${moves} moves`
148
+ }
149
+ return observed
150
+ })
151
+
127
152
  const copy = copyProject(root)
128
153
  let dev = null
129
154
  let browser = null
@@ -398,6 +423,30 @@ export async function editorChecks({ check, launch, root }) {
398
423
  return `"${value}" written, rendered as ${shown}, and undone, in place`
399
424
  })
400
425
 
426
+ await step('⌘S saves the Markdown being edited and a size step before its pause, and the browser does not save the page', async () => {
427
+ const prevented = await ev(`(() => { const e = new KeyboardEvent('keydown', { key: 's', code: 'KeyS', metaKey: true, ctrlKey: true, bubbles: true, cancelable: true }); document.body.dispatchEvent(e); return e.defaultPrevented })()`)
428
+ if (!prevented) throw new Error('⌘S was not prevented: the browser would save the page')
429
+ const p = await center(paragraph)
430
+ await click(p.x, p.y)
431
+ await key('Enter')
432
+ await page.waitFor(`document.querySelector('.se-source textarea')`, { timeout: 5000, what: 'the Markdown editor' })
433
+ await ev(`document.querySelector('.se-source textarea').value = 'Saved with ⌘S.'`)
434
+ await drawn(() => key('s', ['meta']))
435
+ if (!read().includes('Saved with ⌘S.') || (await ev(`!!document.querySelector('.se-source')`))) throw new Error('⌘S did not save and close the Markdown editor')
436
+ await drawn(() => key('z', ['meta']))
437
+ // A size step waits 450 ms before it is written; ⌘S writes it at once.
438
+ await click(p.x, p.y)
439
+ await key('.', ['meta', 'shift'])
440
+ const start = Date.now()
441
+ await key('s', ['meta'])
442
+ await page.waitFor(`document.querySelector('.se-status')?.textContent === 'Saving…' || document.querySelector('.se-status')?.textContent === 'Saved'`, { timeout: 2000, what: 'the size step to be sent' })
443
+ const sent = Date.now() - start
444
+ await saved()
445
+ if (!/font-size: \d+px/.test(readBlock(read(), target.id).style) || sent > 300) throw new Error(`after ⌘S the style is "${readBlock(read(), target.id).style}", sent after ${sent} ms`)
446
+ await undoAll()
447
+ return `⌘S prevented; the Markdown saved and the size step sent ${sent} ms after ⌘S`
448
+ })
449
+
401
450
  await step('⌘D copies a list as a list of its own, and undo removes the copy', async () => {
402
451
  const index = await ev(`[...document.querySelectorAll('.deck > .slide')].findIndex((s) => s.querySelector('.slide-body > ul[data-edit]'))`)
403
452
  await ev(`location.hash = '#${index + 1}'`)
@@ -474,6 +523,29 @@ export async function editorChecks({ check, launch, root }) {
474
523
  return `${count} → ${copied} → ${count} slides; the copy was shown as slide ${now}`
475
524
  })
476
525
 
526
+ await step('a dragged thumbnail moves its slide, ⌘↑ moves it back one, and undo brings slides.mdx back; nothing reloads', async () => {
527
+ const hashes = (text) => outline(text).slides.map((s) => s.hash)
528
+ const was = hashes(original)
529
+ await ev(`document.querySelector('.se-panel').scrollTop = 0`)
530
+ await sleep(200)
531
+ // From thumbnail 2 to the lower half of thumbnail 4: slide 2 becomes slide 4.
532
+ const from = await center('.se-slide[data-index="1"] .se-slide-frame')
533
+ const below = await ev(`(() => { const r = document.querySelector('.se-slide[data-index="3"]').getBoundingClientRect(); return { x: r.left + r.width / 2, y: r.top + r.height * 0.75 } })()`)
534
+ await drawn(() => drag(from.x, from.y, below.x, below.y))
535
+ const dragged = hashes(read())
536
+ const state = await ev(`({ thumbs: document.querySelectorAll('.se-panel .se-slide').length, current: document.querySelector('.se-slide.se-current')?.dataset.index, ghost: !!document.querySelector('.se-ghost') })`)
537
+ if (dragged[3] !== was[1] || dragged[1] !== was[2] || dragged[2] !== was[3]) throw new Error('slides.mdx does not have slide 2 as slide 4')
538
+ if (state.thumbs !== was.length || (await at()) !== 4 || state.current !== '3' || state.ghost) throw new Error(`after the drag: ${JSON.stringify(state)}, on slide ${await at()}`)
539
+ await drawn(() => key('ArrowUp', ['meta']))
540
+ const keyed = hashes(read())
541
+ if (keyed[2] !== was[1] || (await at()) !== 3) throw new Error(`after ⌘↑ the slide is not slide 3 (on slide ${await at()})`)
542
+ await drawn(() => key('z', ['meta']))
543
+ await drawn(() => key('z', ['meta']))
544
+ if (read() !== original) throw new Error('undo did not bring slides.mdx back')
545
+ if ((await ev(`document.querySelectorAll('.se-panel .se-slide').length`)) !== was.length) throw new Error('the slide list lost a thumbnail')
546
+ return 'slide 2 → 4 by a drag, → 3 by ⌘↑, and back by two undos'
547
+ })
548
+
477
549
  await step('Delete and its undo are drawn in place, and a figure on another slide keeps running', async () => {
478
550
  const demo = await ev(`[...document.querySelectorAll('.deck > .slide')].findIndex((s) => s.querySelector('astro-island[data-edit] .fig-play'))`)
479
551
  const figure = `.deck > .slide:nth-child(${demo + 1}) astro-island`
package/e2e/jump.js CHANGED
@@ -64,6 +64,7 @@ title: Jump to source check (slides)
64
64
  ---
65
65
 
66
66
  import RoleKey from '@bloggie/components/RoleKey.astro'
67
+ import Dots from '@/figures/e2e-jump/Dots.svelte'
67
68
 
68
69
  # Jump Check Deck
69
70
 
@@ -76,6 +77,10 @@ Slide text names Aberdeen.
76
77
  ## Second Slide Shows Roles
77
78
 
78
79
  <RoleKey />
80
+
81
+ ## Third Slide Shows Dots
82
+
83
+ <Dots client:load />
79
84
  `
80
85
 
81
86
  const DOTS = `<script>
@@ -239,7 +244,7 @@ export async function jumpChecks({ check, launch, root }) {
239
244
  }
240
245
  })
241
246
 
242
- await check(LABEL, 'on a deck: a slide\'s title, its text, and a component after the notes of the slide before', async () => {
247
+ await check(LABEL, 'on a deck: a slide\'s title, its text, and a component after the notes of the slide before; in the slide editor, Enter on a part of a figure', async () => {
243
248
  const show = async (text) => {
244
249
  const n = await page.evaluate(`[...document.querySelectorAll('.deck > section.slide')].findIndex((s) => s.textContent.includes(${JSON.stringify(text)})) + 1`)
245
250
  await page.evaluate(`location.hash = '#${n}'`)
@@ -254,7 +259,29 @@ export async function jumpChecks({ check, launch, root }) {
254
259
  const text = opens(await jump(await page.evaluate(wordPoint('Aberdeen', active))), DECK_FILE, 'Aberdeen')
255
260
  await show('Second Slide')
256
261
  const roles = opens(await jump(await page.evaluate(boxPoint('.deck > section.slide.active .role-list li'))), DECK_FILE, '<RoleKey')
257
- return { title, text, roles }
262
+ // In the slide editor, Enter on an element inside a figure (selected with a double-click) opens it, as a
263
+ // Cmd+Shift+click does.
264
+ await show('Third Slide')
265
+ await page.waitFor(`${active}.querySelector('.e2e-dots circle')?.__svelte_meta`, { what: 'the figure on the deck to hydrate' })
266
+ const press = async (key, code, vk, text) => {
267
+ await page.cdp('Input.dispatchKeyEvent', { type: 'keyDown', key, code, windowsVirtualKeyCode: vk, text })
268
+ await page.cdp('Input.dispatchKeyEvent', { type: 'keyUp', key, code, windowsVirtualKeyCode: vk })
269
+ }
270
+ await press('e', 'KeyE', 69, 'e')
271
+ await page.waitFor(`document.body.classList.contains('se-on') && document.querySelector('.se-toolbar')`, { what: 'edit mode' })
272
+ const c = await page.evaluate(boxPoint('.deck > section.slide.active .e2e-dots circle', 8))
273
+ for (const clickCount of [1, 2]) {
274
+ await page.cdp('Input.dispatchMouseEvent', { type: 'mousePressed', x: c.x, y: c.y, button: 'left', buttons: 1, clickCount })
275
+ await page.cdp('Input.dispatchMouseEvent', { type: 'mouseReleased', x: c.x, y: c.y, button: 'left', clickCount })
276
+ }
277
+ await page.waitFor(`document.querySelector('.se-what')?.textContent.includes('› circle')`, { what: 'the circle selected inside the figure' })
278
+ const before = await page.evaluate('window.__jumps.length')
279
+ await press('Enter', 'Enter', 13, '\r')
280
+ const answer = await page.waitFor(`window.__jumps.length > ${before} && window.__jumps.at(-1)`, { what: 'the dev server to answer the editor' })
281
+ const editor = opens(answer, 'src/figures/e2e-jump/Dots.svelte', '<circle')
282
+ await press('Escape', 'Escape', 27)
283
+ await press('e', 'KeyE', 69, 'e')
284
+ return { title, text, roles, editor }
258
285
  })
259
286
 
260
287
  if (existsSync(join(copy, 'src/pages/posts/how-this-blog-works/index.mdx'))) {
package/editor/client.js CHANGED
@@ -7,7 +7,8 @@
7
7
  // a figure, a demo note), add one to the selection, draw a box
8
8
  // around several on the slide's background
9
9
  // ⌘+click, double-click a figure select an element inside a block, such as a figure's label;
10
- // Esc (or Shift+Enter) goes back out to the block
10
+ // Esc (or Shift+Enter) goes back out to the block, and Enter opens
11
+ // its source, as ⌘⇧+click does (bloggie/jump/)
11
12
  // Option+click use the figure under the pointer as a reader does
12
13
  // drag move; it snaps to where it started and to the stage's center
13
14
  // lines (hold ⌘ to place it freely)
@@ -29,9 +30,12 @@
29
30
  // ⌘D, Delete, ⌘A duplicate, delete, select every block of the slide
30
31
  // Tab, Shift+Tab next, previous block
31
32
  // ⌘Z, ⌘⇧Z undo, redo (the dev server keeps the steps, across reloads)
33
+ // ⌘S save now: the Markdown being edited, a typed size, and a change of
34
+ // CSS still in its pause; the browser does not save the page
32
35
  //
33
- // The column on the left shows every slide (panel.js): click one to show it; there ⌘D duplicates
34
- // the slide and Delete deletes it, as do the buttons at its top for the slide on the stage.
36
+ // The column on the left shows every slide (panel.js): click one to show it, drag one to move its
37
+ // slide. There ⌘↑ ⌘↓ move the slide, and ⌘D duplicates it and Delete deletes it, as do the buttons
38
+ // at the column's top for the slide on the stage.
35
39
  //
36
40
  // A change of CSS is sent to the dev server (integration.js), which writes it to slides.mdx; the
37
41
  // page shows it already. A change of text, or of the blocks or slides, the page draws from the
@@ -45,7 +49,7 @@ import { fetchRender, reconcile } from './patch.js'
45
49
  import { hex, pickColor } from './eyedropper.js'
46
50
 
47
51
  const STAGE = { width: 1600, height: 900 }
48
- const PROTOCOL = 3 // integration.js's: the dev server's half must be as new as this file
52
+ const PROTOCOL = 4 // integration.js's: the dev server's half must be as new as this file
49
53
  const ENDPOINT = `${import.meta.env.BASE_URL.replace(/\/?$/, '/')}__slide-editor`
50
54
  const MANAGED = ['translate', 'width', 'max-width', 'font-family', 'font-size', 'font-weight', 'font-style', 'text-align', 'color', 'fill', 'z-index', 'position', 'display']
51
55
  const COLORS = [
@@ -479,10 +483,14 @@ export function initEditor(deck) {
479
483
  onPick: (i) => { select([]); location.hash = `#${i + 1}` },
480
484
  onDuplicate: (i) => slideEdit('duplicate-slide', i),
481
485
  onDelete: (i) => slideEdit('delete-slide', i),
486
+ onMove: (from, to) => {
487
+ select([])
488
+ structural({ type: 'move-slide', slide: from, to }, (data) => panel.focus(data.slide), rebuildPanel)
489
+ },
482
490
  current: activeIndex,
483
491
  })
484
492
  let panel = makePanel()
485
- // After slides were added or removed: a new list, shown if editing is on.
493
+ // After slides were added, removed or moved: a new list, shown if editing is on.
486
494
  function rebuildPanel() {
487
495
  panel.hide()
488
496
  panel = makePanel()
@@ -636,13 +644,15 @@ export function initEditor(deck) {
636
644
  styleWords({ color: withAlpha(base, Number(opacityInput.value)) }, range)
637
645
  }, COMMIT_DELAY)
638
646
  })
647
+ function commitSize() {
648
+ const value = clamp(round(Number(sizeInput.value)), 6, 400)
649
+ if (value) setEach(() => ({ 'font-size': `${value}px` }), true)
650
+ sizeInput.blur()
651
+ }
639
652
  sizeInput.addEventListener('keydown', (event) => {
640
653
  event.stopPropagation()
641
- if (event.key === 'Enter' && targets().length) {
642
- const value = clamp(round(Number(sizeInput.value)), 6, 400)
643
- if (value) setEach(() => ({ 'font-size': `${value}px` }), true)
644
- sizeInput.blur()
645
- } else if (event.key === 'Escape') sizeInput.blur()
654
+ if (event.key === 'Enter' && targets().length) commitSize()
655
+ else if (event.key === 'Escape') sizeInput.blur()
646
656
  })
647
657
 
648
658
  // --- selection ---------------------------------------------------------------------------------
@@ -1201,6 +1211,22 @@ export function initEditor(deck) {
1201
1211
  box.querySelector('[data-act="save"]').addEventListener('click', saveText)
1202
1212
  }
1203
1213
 
1214
+ // ⌘S: save what is not in slides.mdx yet. Every other edit was written when it was made.
1215
+ function saveNow(target) {
1216
+ if (editor) return saveText()
1217
+ if (target === sizeInput && targets().length) commitSize()
1218
+ if (pending.size) return flush()
1219
+ if (statusEl.dataset.kind !== 'busy') setStatus('Saved: every edit is in slides.mdx', 'ok')
1220
+ }
1221
+
1222
+ // Enter on an element inside a block: open the line that writes it (a figure's .svelte, or the
1223
+ // deck's Markdown), through jump to source.
1224
+ function jumpToSource(el) {
1225
+ const r = el.getBoundingClientRect()
1226
+ const ask = new CustomEvent('bloggie:jump', { cancelable: true, detail: { target: el, x: r.left + r.width / 2, y: r.top + r.height / 2 } })
1227
+ if (window.dispatchEvent(ask)) setStatus('Jump to source is not on in this dev server', 'error')
1228
+ }
1229
+
1204
1230
  function closeEditor() {
1205
1231
  editor?.panel.remove()
1206
1232
  editor = null
@@ -1440,6 +1466,11 @@ export function initEditor(deck) {
1440
1466
  const code = event.code
1441
1467
  const mod = event.metaKey || event.ctrlKey
1442
1468
  const alt = event.altKey
1469
+ if (on && mod && !alt && code === 'KeyS') {
1470
+ event.preventDefault()
1471
+ event.stopPropagation()
1472
+ return saveNow(event.target)
1473
+ }
1443
1474
  if (picking || editor || typing(event.target)) return
1444
1475
  // The palette's opacity slider keeps its arrow keys; Esc still closes the palette.
1445
1476
  if (event.target instanceof Element && event.target.closest('.se-palette') && event.key !== 'Escape') return
@@ -1476,6 +1507,7 @@ export function initEditor(deck) {
1476
1507
  const moves = { ArrowLeft: [-step, 0], ArrowRight: [step, 0], ArrowUp: [0, -step], ArrowDown: [0, step] }
1477
1508
  if (moves[key] && !mod && !alt) { handled(); return nudge(...moves[key]) }
1478
1509
  if (key === 'Enter' && event.shiftKey && inner) { handled(); return select([inner.block]) }
1510
+ if (key === 'Enter' && !mod && inner) { handled(); return jumpToSource(inner.el) }
1479
1511
  if (key === 'Enter' && !mod && !inner && selection.length === 1) { handled(); return openEditor(primary()) }
1480
1512
  if ((key === 'Delete' || key === 'Backspace') && !mod) { handled(); return removeSelection() }
1481
1513
  if (mod && !alt && code === 'KeyD') { handled(); return inner ? undefined : duplicateSelection() }
package/editor/editor.css CHANGED
@@ -401,6 +401,44 @@
401
401
  border-right: 1px solid var(--rule);
402
402
  font: 12px/1 var(--sans);
403
403
  color: var(--text-muted);
404
+ user-select: none;
405
+ }
406
+
407
+ .se-panel.se-dragging,
408
+ .se-panel.se-dragging .se-slide {
409
+ cursor: grabbing;
410
+ }
411
+
412
+ .se-panel.se-dragging .se-slide .se-slide-tools {
413
+ display: none;
414
+ }
415
+
416
+ /* A dragged thumbnail: its place in the list is dimmed, a copy follows the pointer, and a line
417
+ shows where the slide goes, above the copy; the list's head stays above both. */
418
+ .se-slide.se-dragged {
419
+ opacity: 0.35;
420
+ }
421
+
422
+ .se-slide-frame.se-ghost {
423
+ position: fixed;
424
+ left: 0;
425
+ top: 0;
426
+ z-index: 2;
427
+ pointer-events: none;
428
+ opacity: 0.75;
429
+ box-shadow: 0 0 0 2px var(--series-1), 0 6px 18px rgb(0 0 0 / 25%);
430
+ }
431
+
432
+ .se-drop {
433
+ position: absolute;
434
+ left: 26px;
435
+ right: 8px;
436
+ height: 3px;
437
+ margin-top: -1.5px;
438
+ z-index: 3;
439
+ border-radius: 2px;
440
+ background: var(--series-1);
441
+ pointer-events: none;
404
442
  }
405
443
 
406
444
  .se-slide {
@@ -494,7 +532,7 @@
494
532
  .se-panel-head {
495
533
  position: sticky;
496
534
  top: 0;
497
- z-index: 1;
535
+ z-index: 4;
498
536
  display: flex;
499
537
  align-items: center;
500
538
  gap: 4px;
@@ -19,7 +19,7 @@ const ENDPOINT = '/__slide-editor'
19
19
  // The version of the requests and answers between the page (client.js) and this server. The dev
20
20
  // server loads this file when it starts, but the page's code is new on every load: after a change
21
21
  // here, the page tells the author to restart `npm run dev` rather than work with an older server.
22
- export const PROTOCOL = 3
22
+ export const PROTOCOL = 4
23
23
  const HISTORY = 200 // undo steps kept per file
24
24
 
25
25
  const version = (text) => createHash('sha256').update(text).digest('hex').slice(0, 16)
package/editor/panel.js CHANGED
@@ -1,6 +1,9 @@
1
1
  // The slide editor's overview (client.js): every slide of the deck as a thumbnail in a column on the
2
- // left, as in a slide editor. Click one to show it. With a thumbnail focused, ↑ ↓ move between
3
- // slides, ⌘D duplicates the slide and Delete deletes it; each thumbnail also has buttons for both.
2
+ // left, as in a slide editor. Click one to show it. Drag one to move its slide: a line shows where it
3
+ // goes, the list scrolls when the pointer is near its top or bottom, and Esc cancels. With a
4
+ // thumbnail focused, ↑ ↓ move between slides, ⌘↑ ⌘↓ move the slide up or down, ⌘⇧↑ ⌘⇧↓ to the
5
+ // start or the end, ⌘D duplicates the slide and Delete deletes it; each thumbnail also has buttons
6
+ // for the last two.
4
7
  //
5
8
  // A thumbnail is a copy of the slide's elements, scaled down: it is drawn once when it scrolls into
6
9
  // view, and again when the editor changes the slide. It is a picture only. Its figures are copies of
@@ -9,6 +12,8 @@
9
12
 
10
13
  const STAGE_WIDTH = 1600
11
14
  const THUMB_WIDTH = 176 // px on screen
15
+ const DRAG_START = 5 // px the pointer moves before a press on a thumbnail becomes a drag
16
+ const SCROLL_EDGE = 48 // px from the list's top or bottom where a drag scrolls it
12
17
 
13
18
  // A copy of a slide that shows it and runs nothing.
14
19
  function snapshot(slide) {
@@ -49,7 +54,7 @@ export function stillCopy(element) {
49
54
  return copy
50
55
  }
51
56
 
52
- export function createPanel({ deck, slides, onPick, onDuplicate, onDelete, current: shown }) {
57
+ export function createPanel({ deck, slides, onPick, onDuplicate, onDelete, onMove, current: shown }) {
53
58
  const panel = document.createElement('aside')
54
59
  panel.className = 'se-panel'
55
60
  panel.setAttribute('aria-label', 'Slides')
@@ -87,10 +92,102 @@ export function createPanel({ deck, slides, onPick, onDuplicate, onDelete, curre
87
92
  for (const entry of entries) if (entry.isIntersecting && !drawn.has(Number(entry.target.dataset.index))) draw(Number(entry.target.dataset.index))
88
93
  }, { root: panel, rootMargin: '200px 0px' })
89
94
 
95
+ // Drag a thumbnail to move its slide. `gap` is where it would go: before thumbnail `gap`, or after
96
+ // the last one. A drop sends one move; the list is drawn again after it, so this list takes no
97
+ // second drag.
98
+ const line = document.createElement('div')
99
+ line.className = 'se-drop'
100
+ let drag = null // { from, pointerId, x, y (where it started), clientY, moving, ghost, offset, scrolling }
101
+ let moved = false
102
+ let dropped = false // a drag just ended: the click that follows it picks no slide
103
+ const gapAt = (clientY) => {
104
+ const i = items.findIndex((item) => { const r = item.getBoundingClientRect(); return clientY < r.top + r.height / 2 })
105
+ return i < 0 ? items.length : i
106
+ }
107
+ // The move a drop at `gap` makes, or null where the slide would stay.
108
+ const target = (gap) => (gap === drag.from || gap === drag.from + 1 ? null : gap > drag.from ? gap - 1 : gap)
109
+ const place = () => {
110
+ const gap = gapAt(drag.clientY)
111
+ if (target(gap) === null) return line.remove()
112
+ const below = items[gap]
113
+ const above = items[gap - 1]
114
+ line.style.top = `${below ? below.offsetTop : above.offsetTop + above.offsetHeight}px`
115
+ if (!line.isConnected) panel.append(line)
116
+ }
117
+ const autoscroll = () => {
118
+ if (!drag?.moving) return
119
+ const r = panel.getBoundingClientRect()
120
+ const top = head.getBoundingClientRect().bottom
121
+ const dy = drag.clientY < top + SCROLL_EDGE ? -(top + SCROLL_EDGE - drag.clientY) : drag.clientY > r.bottom - SCROLL_EDGE ? drag.clientY - (r.bottom - SCROLL_EDGE) : 0
122
+ if (dy) { panel.scrollTop += dy / 3; place() }
123
+ drag.scrolling = requestAnimationFrame(autoscroll)
124
+ }
125
+ const endDrag = () => {
126
+ if (!drag) return
127
+ cancelAnimationFrame(drag.scrolling)
128
+ drag.ghost?.remove()
129
+ line.remove()
130
+ items[drag.from].classList.remove('se-dragged')
131
+ panel.classList.remove('se-dragging')
132
+ window.removeEventListener('keydown', onEscape, true)
133
+ drag = null
134
+ }
135
+ const onEscape = (event) => {
136
+ if (event.key !== 'Escape') return
137
+ event.preventDefault()
138
+ event.stopPropagation()
139
+ endDrag()
140
+ }
141
+ panel.addEventListener('pointerdown', (event) => {
142
+ const item = event.target.closest('.se-slide')
143
+ if (!item || event.button !== 0 || event.target.closest('button') || moved) return
144
+ drag = { from: Number(item.dataset.index), pointerId: event.pointerId, x: event.clientX, y: event.clientY, moving: false }
145
+ })
146
+ panel.addEventListener('pointermove', (event) => {
147
+ if (!drag || event.pointerId !== drag.pointerId) return
148
+ drag.clientY = event.clientY
149
+ if (!drag.moving) {
150
+ if (Math.hypot(event.clientX - drag.x, event.clientY - drag.y) < DRAG_START) return
151
+ drag.moving = true
152
+ panel.setPointerCapture(event.pointerId)
153
+ const item = items[drag.from]
154
+ item.classList.add('se-dragged')
155
+ panel.classList.add('se-dragging')
156
+ const frame = item.querySelector('.se-slide-frame')
157
+ const r = frame.getBoundingClientRect()
158
+ drag.ghost = frame.cloneNode(true)
159
+ drag.ghost.classList.add('se-ghost')
160
+ drag.offset = [drag.x - r.left, drag.y - r.top]
161
+ panel.append(drag.ghost)
162
+ window.addEventListener('keydown', onEscape, true)
163
+ drag.scrolling = requestAnimationFrame(autoscroll)
164
+ }
165
+ drag.ghost.style.translate = `${event.clientX - drag.offset[0]}px ${event.clientY - drag.offset[1]}px`
166
+ place()
167
+ })
168
+ panel.addEventListener('pointerup', (event) => {
169
+ if (!drag || event.pointerId !== drag.pointerId) return
170
+ const to = drag.moving ? target(gapAt(event.clientY)) : null
171
+ const { from, moving } = drag
172
+ endDrag()
173
+ if (!moving) return
174
+ dropped = true
175
+ setTimeout(() => { dropped = false })
176
+ if (to === null) return
177
+ moved = true
178
+ // Show the order at once; the editor draws the list again from the new render.
179
+ const item = items[from]
180
+ const others = items.filter((x) => x !== item)
181
+ if (to < others.length) others[to].before(item)
182
+ else others.at(-1).after(item)
183
+ onMove(from, to)
184
+ })
185
+ panel.addEventListener('pointercancel', endDrag)
186
+
90
187
  let current = -1
91
188
  panel.addEventListener('click', (event) => {
92
189
  const item = event.target.closest('.se-slide')
93
- if (!item) return
190
+ if (!item || dropped) return
94
191
  const i = Number(item.dataset.index)
95
192
  const act = event.target.closest('button[data-act]')?.dataset.act
96
193
  if (act === 'duplicate') return onDuplicate(i)
@@ -101,8 +198,14 @@ export function createPanel({ deck, slides, onPick, onDuplicate, onDelete, curre
101
198
  panel.addEventListener('keydown', (event) => {
102
199
  const mod = event.metaKey || event.ctrlKey
103
200
  const handled = () => { event.preventDefault(); event.stopPropagation() }
104
- if (['ArrowUp', 'ArrowLeft'].includes(event.key) && current > 0) { handled(); onPick(current - 1); items[current - 1].focus() }
105
- else if (['ArrowDown', 'ArrowRight'].includes(event.key) && current < items.length - 1) { handled(); onPick(current + 1); items[current + 1].focus() }
201
+ const up = ['ArrowUp', 'ArrowLeft'].includes(event.key)
202
+ const down = ['ArrowDown', 'ArrowRight'].includes(event.key)
203
+ if (mod && (up || down)) {
204
+ handled()
205
+ const to = event.shiftKey ? (up ? 0 : items.length - 1) : current + (up ? -1 : 1)
206
+ if (!moved && current >= 0 && to >= 0 && to < items.length && to !== current) { moved = true; onMove(current, to) }
207
+ } else if (up && current > 0) { handled(); onPick(current - 1); items[current - 1].focus() }
208
+ else if (down && current < items.length - 1) { handled(); onPick(current + 1); items[current + 1].focus() }
106
209
  else if ((event.key === 'Delete' || event.key === 'Backspace') && !mod) { handled(); onDelete(current) }
107
210
  else if (mod && event.code === 'KeyD') { handled(); onDuplicate(current) }
108
211
  else if (event.key.startsWith('Arrow')) handled()
@@ -115,6 +218,7 @@ export function createPanel({ deck, slides, onPick, onDuplicate, onDelete, curre
115
218
  items.forEach((item) => seen.observe(item))
116
219
  },
117
220
  hide() {
221
+ endDrag()
118
222
  seen.disconnect()
119
223
  panel.remove()
120
224
  },
package/editor/patch.js CHANGED
@@ -175,7 +175,7 @@ function renumber(slide, to, ids) {
175
175
  }
176
176
 
177
177
  // Swap the new render's changes into the deck. Returns each kept element's old id → new id, the new
178
- // indexes of the slides drawn again, and whether the number of slides changed.
178
+ // indexes of the slides drawn again, and whether slides were added, removed or moved.
179
179
  export function reconcile(deck, was, is, doc) {
180
180
  const freshDeck = doc.querySelector('.deck')
181
181
  if (!freshDeck) throw new Error('the new render has no deck')
@@ -188,7 +188,8 @@ export function reconcile(deck, was, is, doc) {
188
188
  const ids = new Map()
189
189
  const drawn = []
190
190
  let previous = null
191
- for (const { op, a, b } of align(was.slides.map((s) => s.hash), is.slides.map((s) => s.hash))) {
191
+ const ops = align(was.slides.map((s) => s.hash), is.slides.map((s) => s.hash))
192
+ for (const { op, a, b } of ops) {
192
193
  if (op === 'keep') {
193
194
  renumber(live[a], b, ids)
194
195
  previous = live[a]
@@ -211,5 +212,5 @@ export function reconcile(deck, was, is, doc) {
211
212
  previous = slide
212
213
  } else live[a].remove()
213
214
  }
214
- return { ids, drawn, recount: was.slides.length !== is.slides.length }
215
+ return { ids, drawn, recount: ops.some(({ op }) => op === 'insert' || op === 'remove') }
215
216
  }
package/editor/source.js CHANGED
@@ -1,9 +1,9 @@
1
1
  // Source edits for the slide editor: find a block of a deck in its slides.mdx, and rewrite the
2
- // block's CSS or its text, or copy or delete a block or a whole slide. Each edit takes the file's
3
- // text and returns the new text; the dev server (integration.js) writes it. A block is named as in
4
- // the page, "<slide>/<block>" ("3/1"), or "<slide>/t" for the slide's title, with the indexes of
5
- // slidesFromHeadings and slideBlocks (bloggie/lib/slide-headings.js), which the page's markers come
6
- // from too.
2
+ // block's CSS or its text, copy or delete a block, or copy, move or delete a whole slide. Each edit
3
+ // takes the file's text and returns the new text; the dev server (integration.js) writes it. A block
4
+ // is named as in the page, "<slide>/<block>" ("3/1"), or "<slide>/t" for the slide's title, with the
5
+ // indexes of slidesFromHeadings and slideBlocks (bloggie/lib/slide-headings.js), which the page's
6
+ // markers come from too.
7
7
  //
8
8
  // Where the CSS goes:
9
9
  // a Markdown block or a figure tag <Box style="…"> around it (a new Box when it has none)
@@ -628,12 +628,59 @@ function removeSlide(source, index) {
628
628
  return { source: next, reload: true, slide: Math.min(index, slides.length - 2) }
629
629
  }
630
630
 
631
+ // Slide `from` moved so that it becomes slide `to`. The first `#` is the title and every later one a
632
+ // divider, so a move can change the kind of a `#` slide whose tag names none: such a slide is given
633
+ // its kind in a tag first, and every slide keeps the kind it had.
634
+ function moveSlide(source, from, to) {
635
+ from = Number(from)
636
+ to = Number(to)
637
+ let slides = parse(source)
638
+ findSlide(slides, from)
639
+ findSlide(slides, to)
640
+ if (from === to) return { source, unchanged: true }
641
+ const order = slides.map((s) => s.index)
642
+ order.splice(to, 0, ...order.splice(from, 1))
643
+ let sawTitle = false
644
+ const named = []
645
+ for (const i of order) {
646
+ const { heading, implied } = slides[i]
647
+ const now = heading?.depth === 1 ? (sawTitle ? 'divider' : 'title') : implied
648
+ if (!heading || heading.depth === 1) sawTitle = true
649
+ if (now !== implied && !readHeading(source, slides[i]).kind) named.push(slides[i])
650
+ }
651
+ let next = source
652
+ for (const slide of named.sort((a, b) => b.index - a.index)) {
653
+ const h = readHeading(next, slide)
654
+ next = splice(next, h.start, h.titleStart, `${h.hashes}[${slide.implied}] `)
655
+ }
656
+ slides = parse(next)
657
+ const { start, end } = slideSpan(next, slides, from)
658
+ const text = next.slice(start, end)
659
+ const before = next.slice(0, start).replace(/\s+$/, '')
660
+ const after = next.slice(end).replace(/^\s+/, '')
661
+ next = after ? `${before}\n\n${after}` : `${before}\n`
662
+ const rest = parse(next)
663
+ if (to < rest.length) {
664
+ const at = slideSpan(next, rest, to, { imports: false }).start
665
+ next = splice(next, at, at, `${text}\n\n`)
666
+ } else {
667
+ const at = slideSpan(next, rest, rest.length - 1, { imports: false }).end
668
+ next = splice(next, at, at, `\n\n${text}`)
669
+ }
670
+ const moved = parse(next)
671
+ const placed = moved.length === slides.length ? slideSpan(next, moved, to, { imports: false }) : null
672
+ if (!placed || next.slice(placed.start, placed.end) !== text) throw new EditError('the slide could not be moved on its own; move it in slides.mdx')
673
+ if (moved.map((s) => s.kind).join() !== order.map((i) => slides[i].kind).join()) throw new EditError('the move would change the kind of a slide; move it in slides.mdx')
674
+ return { source: next, reload: true, slide: to }
675
+ }
676
+
631
677
  // One edit, or a batch of them applied in order as one step:
632
678
  // { type: 'style', id, set } { type: 'inner', id, selector, set }
633
679
  // { type: 'text', id, text } { type: 'insert', after: id, text }
634
680
  // { type: 'delete', id } { type: 'duplicate', id }
635
681
  // { type: 'words', id, plain, start, end, color | mark } words selected on the page
636
682
  // { type: 'duplicate-slide', slide } { type: 'delete-slide', slide }
683
+ // { type: 'move-slide', slide, to }
637
684
  // { type: 'batch', edits: [...] }
638
685
  // A change of CSS also returns `inverse`, the edit that undoes it (for a batch, a batch).
639
686
  export function applyEdit(source, edit) {
@@ -647,6 +694,7 @@ export function applyEdit(source, edit) {
647
694
  case 'words': return formatWords(source, edit.id, edit)
648
695
  case 'duplicate-slide': return duplicateSlide(source, edit.slide)
649
696
  case 'delete-slide': return removeSlide(source, edit.slide)
697
+ case 'move-slide': return moveSlide(source, edit.slide, edit.to)
650
698
  case 'batch': {
651
699
  if (!Array.isArray(edit.edits) || !edit.edits.length) throw new EditError('an empty batch')
652
700
  let text = source
package/jump/client.js CHANGED
@@ -24,6 +24,15 @@ for (const type of ['pointerdown', 'mousedown', 'pointerup', 'mouseup', 'click']
24
24
  }, { capture: true, passive: false })
25
25
  }
26
26
 
27
+ // The slide editor (bloggie/editor/) asks for the source of an element it has selected (Enter on an element inside a
28
+ // block, such as a part of a figure): a bloggie:jump event with the element and a point on it. Cancelling the event
29
+ // tells the editor that this page can jump.
30
+ window.addEventListener('bloggie:jump', (event) => {
31
+ event.preventDefault()
32
+ const { target, x, y } = event.detail
33
+ jump({ target, clientX: x, clientY: y, altKey: false }).catch((error) => toast(`Jump to source: ${error.message}`))
34
+ })
35
+
27
36
  const storage = {
28
37
  get(key) { try { return localStorage.getItem(key) } catch { return null } },
29
38
  set(key, value) { try { localStorage.setItem(key, value) } catch {} },
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "bloggie",
3
- "version": "0.4.2",
3
+ "version": "0.4.3",
4
4
  "description": "Write one story with your AI agent. Publish it as an interactive blog post that ports to slides when you need them.",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -11,7 +11,7 @@
11
11
  "bloggie:update": "npm install bloggie@latest"
12
12
  },
13
13
  "dependencies": {
14
- "bloggie": "^0.4.2",
14
+ "bloggie": "^0.4.3",
15
15
  "d3": "^7.9.0"
16
16
  },
17
17
  "overrides": {