bloggie 0.4.2 → 0.4.4

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/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 {} },
@@ -1,34 +1,40 @@
1
1
  ---
2
2
  // Layout of a post: src/pages/posts/<slug>/index.mdx sets `layout: ../../../layouts/Post.astro`.
3
+ // A subpage (lib/pages.js: any other .mdx page under src/pages/posts/) uses the same layout.
3
4
  // Front matter: title, date, edited (the date of the last edit, shown after the date when it is later),
4
5
  // description, eyebrow, lede, author, slides (false hides a deck that exists),
6
+ // downloads (whether the byline offers the two downloads; true for a post, false for a subpage, by default),
5
7
  // equationNumbers (false turns numbering off), toc (false hides the table of contents),
6
8
  // agentSummary (a short statement of the post's question, placed at the top of the agent download).
7
9
  // `roles` is set by remarkRoles (bloggie/lib/roles.js): the symbol roles the post's math uses, shown as a key.
8
10
  import { existsSync } from 'node:fs'
9
- import { dirname, join } from 'node:path'
11
+ import { basename, dirname, join } from 'node:path'
10
12
  import { createMarkdownProcessor } from '@astrojs/markdown-remark'
11
13
  import Base from './Base.astro'
12
14
  import { site, longDate, isoDate } from '@/site.js'
13
15
  import { siteUrl } from '../lib/site-url.js'
14
16
  import { roles } from '../lib/roles.js'
17
+ import { pagePath, offersDownloads, downloadNames } from '../lib/pages.js'
15
18
 
16
19
  const { frontmatter, file } = Astro.props
17
20
  // The lede is Markdown (links, emphasis, code): front matter is plain data, so render it here, and
18
21
  // strip the <p> the processor wraps it in.
19
22
  const markdown = await createMarkdownProcessor()
20
23
  const lede = frontmatter.lede && (await markdown.render(frontmatter.lede)).code.replace(/^\s*<p>|<\/p>\s*$/g, '')
21
- // A post has a deck when slides.mdx sits beside its index.mdx; the byline then links to it and
22
- // the S key opens it. Without one, neither appears.
23
- const hasSlides = frontmatter.slides !== false && !!file && existsSync(join(dirname(file), 'slides.mdx'))
24
+ // A page has a deck when it is an index.mdx with slides.mdx beside it, at any depth; the byline then links to it
25
+ // and the S key opens it. Without one, neither appears. A file subpage (<name>.mdx) shares its folder with its post's
26
+ // index.mdx, so slides.mdx there is the post's deck, not the subpage's; a subpage with a deck is a folder,
27
+ // <name>/index.mdx and <name>/slides.mdx.
28
+ const hasSlides = frontmatter.slides !== false && !!file && basename(file) === 'index.mdx' && existsSync(join(dirname(file), 'slides.mdx'))
24
29
  // Absolute, so the link works whether or not the post's URL ends in a slash.
25
30
  const postHref = Astro.url.pathname.replace(/\/?$/, '/')
26
31
  const slidesHref = `${postHref}slides/`
27
- // bloggie/scripts/export-posts.js writes both files beside the post after `astro build`.
28
- const slug = postHref.split('/').filter(Boolean).at(-1)
29
- const downloads = { page: `${slug}.html`, agent: `${slug}-agent.html` }
30
- // A heading's anchor copies a link to the deployed post, even from a downloaded copy.
31
- const shareUrl = new URL(`posts/${slug}/`, siteUrl).href
32
+ const path = pagePath(postHref, import.meta.env.BASE_URL) ?? postHref.split('/').filter(Boolean).at(-1)
33
+ // bloggie/scripts/export-posts.js writes both files beside the page after `astro build`, for each page whose byline
34
+ // offers them (the [data-download] control).
35
+ const downloads = offersDownloads(frontmatter, path) ? downloadNames(path) : null
36
+ // A heading's anchor copies a link to the deployed page, even from a downloaded copy.
37
+ const shareUrl = new URL(`posts/${path}/`, siteUrl).href
32
38
  const keyRoles = roles.filter((role) => frontmatter.roles?.includes(role.name))
33
39
  ---
34
40
  <Base title={frontmatter.title} description={frontmatter.description}>
@@ -45,7 +51,7 @@ const keyRoles = roles.filter((role) => frontmatter.roles?.includes(role.name))
45
51
  <time datetime={isoDate(frontmatter.date)}>{longDate(frontmatter.date)}</time>
46
52
  {frontmatter.edited && isoDate(frontmatter.edited) > isoDate(frontmatter.date) && <>{' '}(edited <time datetime={isoDate(frontmatter.edited)}>{longDate(frontmatter.edited)}</time>)</>}
47
53
  {hasSlides && <><span aria-hidden="true">/</span> <a href={slidesHref} data-slides-link title="Slides (S)">Slides</a></>}
48
- <span aria-hidden="true">/</span>
54
+ {downloads && <><span aria-hidden="true">/</span>
49
55
  <span class="download" data-download>
50
56
  <a class="download-main" href={`${postHref}${downloads.page}`} download={downloads.page}
51
57
  title="Download this post as one HTML file with working figures" aria-label="Download this post as one HTML file with working figures">
@@ -64,7 +70,7 @@ const keyRoles = roles.filter((role) => frontmatter.roles?.includes(role.name))
64
70
  </a>
65
71
  </div>
66
72
  </details>
67
- </span>
73
+ </span></>}
68
74
  </div>
69
75
  {keyRoles.length > 0 && (
70
76
  <p class="role-key">
package/lib/pages.js ADDED
@@ -0,0 +1,29 @@
1
+ // Where a page sits among the posts, for the features that depend on it: the deck link, the downloads and the share
2
+ // link (layouts/Post.astro, scripts/export-posts.js, scripts/export/).
3
+ //
4
+ // A post is src/pages/posts/<slug>/index.mdx, at /posts/<slug>/; the home page lists it. Every other page under
5
+ // src/pages/posts/ is a subpage, which the home page does not list:
6
+ // a file beside a post's index.mdx posts/<slug>/<name>.mdx -> /posts/<slug>/<name>/
7
+ // a folder inside a post posts/<slug>/<name>/index.mdx -> /posts/<slug>/<name>/
8
+ // A page's path is its URL under posts/, without slashes at either end: '<slug>' for a post, '<slug>/<name>' (or
9
+ // deeper) for a subpage.
10
+
11
+ // The page's path from its URL path (`base` is the site's base path, import.meta.env.BASE_URL); null outside posts/.
12
+ export function pagePath(pathname, base = '/') {
13
+ const prefix = `${base.replace(/\/?$/, '/')}posts/`
14
+ if (!pathname.startsWith(prefix)) return null
15
+ return pathname.slice(prefix.length).replace(/\/+$/, '') || null
16
+ }
17
+
18
+ export const isSubpage = (path) => path.includes('/')
19
+
20
+ // A page offers the two downloads unless its front matter says otherwise (`downloads: false` on a post,
21
+ // `downloads: true` on a subpage). Subpages default to none: each download costs build time (see
22
+ // scripts/export-posts.js), and a subpage is usually reached from its post.
23
+ export const offersDownloads = (frontmatter, path) => frontmatter.downloads ?? !isSubpage(path)
24
+
25
+ // The downloads' file names, beside the page: named after the last part of its path.
26
+ export function downloadNames(path) {
27
+ const name = path.split('/').at(-1)
28
+ return { page: `${name}.html`, agent: `${name}-agent.html` }
29
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "bloggie",
3
- "version": "0.4.2",
3
+ "version": "0.4.4",
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": {
package/pages/index.astro CHANGED
@@ -2,61 +2,88 @@
2
2
  // The home page: every post under the blog's src/pages/posts/<slug>/index.mdx, newest first. The engine adds it as
3
3
  // the route / (astro.config.js), unless the blog has a src/pages/index.astro of its own. A folder whose
4
4
  // name starts with "_" is not a page (Astro skips it), so it is not listed either.
5
- // A post with no tags is part of the main story. Front matter `tags: [wip]` or `tags: [archived]` sets a post apart:
6
- // the reader shows or hides each tag with a checkbox above the list, and a post shows when none of its tags is off.
7
- // Front matter `edited:` is the date of the post's last edit. When the reader checks "Last edited", the list shows it
8
- // after the publication date (for a post edited after the day it was published) and orders the posts by it, most
9
- // recently edited first; a post with no `edited:` counts as last edited on its publication date.
5
+ //
6
+ // Tags. Front matter `tags: [wip]` or `tags: [archived]` marks a post; a post with no tags is part of the main story.
7
+ // One tag is computed, not written: `slides`, for a post with a deck (slides.mdx beside it, unless its front matter
8
+ // sets `slides: false`, as for its byline in layouts/Post.astro). Such a post has the slides icon to the left of its
9
+ // title, a link to the deck.
10
+ //
11
+ // Above the list, a chip per tag in use filters the list, one at a time: "All" shows every post but those with a
12
+ // hidden tag (archived), a tag's chip shows only the posts with that tag (and none with a hidden tag, unless the chip
13
+ // is that tag), and a click on the chosen chip goes back to All. A menu sorts the list: newest first, recently
14
+ // updated first (front matter `edited:`, else the publication date), or oldest first. A post edited after the day it
15
+ // was published shows "updated <date>". The chip and the sort are in the URL (?tag=slides&sort=updated), so a view can
16
+ // be linked to, and Back comes back to it.
17
+ import { existsSync } from 'node:fs'
18
+ import { join } from 'node:path'
10
19
  import Base from '../layouts/Base.astro'
11
20
  import { parseFrontmatter } from '@astrojs/markdown-remark'
12
21
  import { site, longDate, isoDate } from '@/site.js'
13
22
 
14
- // Each tag's name, its mark after a post's title (an icon, else the name), and whether it starts hidden.
15
- // A tag not listed here is shown, with its own word as its name.
23
+ const SLIDES_ICON = '<svg class="slides-icon" viewBox="0 0 16 16" width="16" height="16" aria-hidden="true"><path d="M1 2.5h14M2.5 2.5v8h11v-8M8 10.5V13M8 13l-2.5 2.5M8 13l2.5 2.5M5 8.5l2-2 1.5 1.5L11 5" /></svg>'
24
+
25
+ // Each tag's name, its mark after a post's title (an icon, else the name; `svg` is drawn in the chip only), and
26
+ // whether it is left out of All. A tag not listed here is shown, with its own word as its name.
16
27
  const TAGS = {
28
+ slides: { name: 'Slides', svg: SLIDES_ICON, computed: true },
17
29
  wip: { name: 'Work in progress', icon: '🚧' },
18
30
  archived: { name: 'Archived', hidden: true },
19
31
  }
20
32
  const tag = (id) => TAGS[id] ?? { name: id }
33
+ const SORTS = [['newest', 'Newest'], ['updated', 'Recently updated'], ['oldest', 'Oldest']]
21
34
 
22
35
  // Each post is read as text, for its front matter only. Importing it would compile the post and every figure it uses,
23
36
  // so one post that does not compile (an agent in the middle of an edit) would take this page down with it.
24
37
  const posts = Object.entries(import.meta.glob(['/src/pages/posts/*/index.mdx', '!/src/pages/posts/_*/index.mdx'], { query: '?raw', import: 'default', eager: true }))
25
- .map(([path, text]) => ({ ...parseFrontmatter(text).frontmatter, url: import.meta.env.BASE_URL + path.slice('/src/pages/'.length, -'index.mdx'.length) }))
26
- .map((post) => ({ ...post, tags: [post.tags ?? []].flat().map(String) }))
38
+ .map(([path, text]) => ({ ...parseFrontmatter(text).frontmatter, path, url: import.meta.env.BASE_URL + path.slice('/src/pages/'.length, -'index.mdx'.length) }))
39
+ .map((post) => ({ ...post, deck: post.slides !== false && existsSync(join(process.cwd(), post.path.slice(1, -'index.mdx'.length), 'slides.mdx')) }))
40
+ .map((post) => ({ ...post, tags: [...(post.deck ? ['slides'] : []), ...[post.tags ?? []].flat().map(String).filter((id) => !tag(id).computed)] }))
27
41
  .sort((a, b) => new Date(b.date) - new Date(a.date))
28
42
 
29
- // The tags in use, those of TAGS first and in its order, each with its number of posts.
30
- const used = [...new Set([...Object.keys(TAGS), ...posts.flatMap((post) => post.tags)])]
31
- .map((id) => ({ id, ...tag(id), count: posts.filter((post) => post.tags.includes(id)).length }))
43
+ const hidden = (post) => post.tags.some((id) => tag(id).hidden)
44
+ // The posts a chip shows (the chip of `id`, or All for null), as the script below also decides.
45
+ const shows = (post, id) => (id ? post.tags.includes(id) && (tag(id).hidden || !hidden(post)) : !hidden(post))
46
+ // The tags in use, those of TAGS first and in its order, each with the number of posts its chip shows.
47
+ const chips = [...new Set([...Object.keys(TAGS), ...posts.flatMap((post) => post.tags)])]
48
+ .map((id) => ({ id, ...tag(id), count: posts.filter((post) => shows(post, id)).length }))
32
49
  .filter((t) => t.count)
33
- const hiddenAtFirst = (post) => post.tags.some((id) => tag(id).hidden)
34
50
  const wasEdited = (post) => post.edited && isoDate(post.edited) > isoDate(post.date)
35
51
  ---
36
52
  <Base title={site.title}>
37
53
  <main class="wrap">
38
54
  <h1>{site.title}</h1>
39
55
  <p class="lede">{site.lede}</p>
40
- <fieldset class="post-filter">
41
- <legend>Show</legend>
42
- {used.map((t) => (
43
- <label>
44
- <input type="checkbox" name="tag" value={t.id} checked={!t.hidden} />
45
- {t.icon && <span aria-hidden="true">{t.icon}</span>} {t.name} <span class="count">({t.count})</span>
46
- </label>
47
- ))}
48
- <label>
49
- <input type="checkbox" name="edited" /> Last edited
56
+ <div class="post-controls">
57
+ <fieldset class="post-filter" data-hidden={Object.keys(TAGS).filter((id) => TAGS[id].hidden).join(' ')}>
58
+ <legend>Tags</legend>
59
+ <label class="chip"><input type="radio" name="tag" value="" checked /> All <span class="count">{posts.filter((post) => shows(post, null)).length}</span></label>
60
+ {chips.map((t) => (
61
+ <label class="chip">
62
+ <input type="radio" name="tag" value={t.id} />
63
+ {t.svg ? <Fragment set:html={t.svg} /> : t.icon && <span aria-hidden="true">{t.icon}</span>} {t.name} <span class="count">{t.count}</span>
64
+ </label>
65
+ ))}
66
+ </fieldset>
67
+ <label class="post-sort">
68
+ Sort
69
+ <select name="sort">
70
+ {SORTS.map(([value, name]) => <option value={value}>{name}</option>)}
71
+ </select>
50
72
  </label>
51
- </fieldset>
52
- <ol class="post-list" reversed>
73
+ </div>
74
+ <ol class="post-list">
53
75
  {posts.map((post, n) => (
54
- <li data-order={n} data-tags={post.tags.join(' ')} data-date={isoDate(post.date)} data-edited={isoDate(post.edited ?? post.date)} hidden={hiddenAtFirst(post)}>
76
+ <li data-order={n} data-tags={post.tags.join(' ')} data-date={isoDate(post.date)} data-edited={isoDate(post.edited ?? post.date)} hidden={!shows(post, null)}>
55
77
  <time datetime={isoDate(post.date)}>{longDate(post.date)}</time>
56
- {wasEdited(post) && <span class="post-edited" hidden> · edited <time datetime={isoDate(post.edited)}>{longDate(post.edited)}</time></span>}
78
+ {wasEdited(post) && <span class="post-edited"> · updated <time datetime={isoDate(post.edited)}>{longDate(post.edited)}</time></span>}
57
79
  <h2>
80
+ {post.deck && (
81
+ <a class="post-deck" href={`${post.url}slides/`} title="Slides" aria-label={`Slides: ${post.title}`}>
82
+ <Fragment set:html={SLIDES_ICON} />
83
+ </a>
84
+ )}
58
85
  <a href={post.url}>{post.title}</a>
59
- {post.tags.map((id) => tag(id).icon
86
+ {post.tags.filter((id) => !tag(id).computed).map((id) => tag(id).icon
60
87
  ? <span class="post-icon" title={tag(id).name} role="img" aria-label={tag(id).name}>{tag(id).icon}</span>
61
88
  : <span class="post-tag">{tag(id).name}</span>)}
62
89
  </h2>
@@ -68,22 +95,47 @@ const wasEdited = (post) => post.edited && isoDate(post.edited) > isoDate(post.d
68
95
  </Base>
69
96
 
70
97
  <script>
71
- // A post shows when none of its tags is unchecked. "Last edited" shows each edit date and orders the posts by it;
72
- // unchecked, they are in publication order, newest first. The first render hides the tags that start hidden and every
73
- // edit date, in publication order, so the page is right before this runs; the browser may restore a checkbox on Back,
74
- // so this also runs once at load.
98
+ // The chip and the sort, from the URL and back into it (replaceState: no history entry per click). The first render
99
+ // is All and Newest, so the page is right before this runs.
75
100
  const filter = document.querySelector('.post-filter')
101
+ const sort = document.querySelector('.post-sort select')
76
102
  const list = document.querySelector('.post-list')
103
+ const hiddenTags = new Set(filter.dataset.hidden.split(' ').filter(Boolean))
104
+ const chip = () => filter.querySelector('input[name="tag"]:checked')?.value ?? ''
105
+
77
106
  const update = () => {
78
- const off = [...filter.querySelectorAll('input[name="tag"]:not(:checked)')].map((input) => input.value)
107
+ const id = chip()
79
108
  for (const li of list.children) {
80
- li.hidden = li.dataset.tags.split(' ').some((id) => off.includes(id))
109
+ const tags = li.dataset.tags.split(' ')
110
+ const isHidden = tags.some((t) => hiddenTags.has(t))
111
+ li.hidden = id ? !tags.includes(id) || (isHidden && !hiddenTags.has(id)) : isHidden
81
112
  }
82
- const edited = filter.querySelector('input[name="edited"]').checked
83
- for (const span of list.querySelectorAll('.post-edited')) span.hidden = !edited
84
- const key = (li) => (edited ? li.dataset.edited : '') + li.dataset.date
85
- list.append(...[...list.children].sort((a, b) => key(b).localeCompare(key(a)) || a.dataset.order - b.dataset.order))
113
+ const key = { newest: (li) => li.dataset.date, updated: (li) => li.dataset.edited + li.dataset.date, oldest: (li) => li.dataset.date }[sort.value]
114
+ const sign = sort.value === 'oldest' ? -1 : 1
115
+ list.append(...[...list.children].sort((a, b) => sign * key(b).localeCompare(key(a)) || a.dataset.order - b.dataset.order))
116
+ const params = new URLSearchParams(location.search)
117
+ id ? params.set('tag', id) : params.delete('tag')
118
+ sort.value !== 'newest' ? params.set('sort', sort.value) : params.delete('sort')
119
+ const query = params.toString()
120
+ history.replaceState(history.state, '', `${location.pathname}${query ? `?${query}` : ''}${location.hash}`)
86
121
  }
122
+
123
+ // A click on the chosen chip goes back to All.
124
+ let before = ''
125
+ filter.addEventListener('pointerdown', () => { before = chip() })
126
+ filter.addEventListener('keydown', () => { before = chip() })
127
+ filter.addEventListener('click', (event) => {
128
+ const input = event.target instanceof HTMLInputElement ? event.target : null
129
+ if (input?.value && input.value === before) filter.querySelector('input[value=""]').checked = true
130
+ before = chip()
131
+ update()
132
+ })
87
133
  filter.addEventListener('change', update)
134
+ sort.addEventListener('change', update)
135
+
136
+ const params = new URLSearchParams(location.search)
137
+ const chosen = filter.querySelector(`input[name="tag"][value="${CSS.escape(params.get('tag') ?? '')}"]`)
138
+ if (chosen) chosen.checked = true
139
+ if ([...sort.options].some((o) => o.value === params.get('sort'))) sort.value = params.get('sort')
88
140
  update()
89
141
  </script>
@@ -57,10 +57,10 @@ function keptText(island) {
57
57
  const box = (html) => raw(`<div class="fig-text">${html}</div>`)
58
58
 
59
59
  // `out` is the build's output directory; `site` the site's URL, for links back to it (see siteLinks).
60
- export async function agentPage(html, { references, out = dist, site, base }) {
60
+ export async function agentPage(html, { references, out = dist, site, base, pageUrl }) {
61
61
  const figures = await describers()
62
62
  const tree = fromHtml(html)
63
- siteLinks(tree, { site, base })
63
+ siteLinks(tree, { site, base, pageUrl })
64
64
  const meta = (name) => {
65
65
  let content = ''
66
66
  visit(tree, 'element', (node) => { if (node.tagName === 'meta' && node.properties.name === name) content = node.properties.content })
@@ -46,9 +46,10 @@ export const hasClass = (node, name) => (node.properties?.className || []).inclu
46
46
 
47
47
  // Links back to the site: each root-relative link (the blog index, the Slides link) becomes a link to
48
48
  // the deployed site, src/site.js `url`, so it works from a downloaded file when the reader is online.
49
- // `base` is the base path the page was built with (BASE_PATH, as in astro.config.mjs). The download
50
- // control is removed.
51
- export function siteLinks(tree, { site = siteUrl, base = process.env.BASE_PATH || '/' } = {}) {
49
+ // `base` is the base path the page was built with (BASE_PATH, as in astro.config.mjs). `pageUrl`, the page's own
50
+ // URL path under the base ('posts/<path>/'), makes a relative link (`../other-post/`, `./subpage/`) one to the
51
+ // deployed site too; without it, relative links stay as they are. The download control is removed.
52
+ export function siteLinks(tree, { site = siteUrl, base = process.env.BASE_PATH || '/', pageUrl = null } = {}) {
52
53
  visit(tree, 'element', (node, index, parent) => {
53
54
  if (node.properties?.dataDownload !== undefined) {
54
55
  parent.children.splice(index, 1)
@@ -56,7 +57,12 @@ export function siteLinks(tree, { site = siteUrl, base = process.env.BASE_PATH |
56
57
  }
57
58
  const href = node.tagName === 'a' ? node.properties.href : null
58
59
  // Built assets stay relative: each download inlines them (distAsset).
59
- if (typeof href !== 'string' || !href.startsWith(base) || href.startsWith('//') || distAsset(href)) return
60
+ if (typeof href !== 'string' || href.startsWith('//') || distAsset(href)) return
61
+ if (pageUrl && !href.startsWith('/') && !href.startsWith('#') && !/^[a-z][a-z0-9+.-]*:/i.test(href)) {
62
+ node.properties.href = new URL(href, new URL(pageUrl, site)).href
63
+ return
64
+ }
65
+ if (!href.startsWith(base)) return
60
66
  node.properties.href = new URL(href.slice(base.length), site).href
61
67
  })
62
68
  // The byline separators (" / ") left without anything after them.
@@ -26,19 +26,21 @@ export default function postDownloads() {
26
26
  const base = process.env.BASE_PATH || '/'
27
27
  const root = server.config.root
28
28
  const out = join(root, 'node_modules/.cache/post-downloads')
29
- const pattern = new RegExp(`^${base.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}posts/([^/]+)/([^/]+)\\.html$`)
29
+ // A page's downloads sit beside it, at any depth under posts/ (lib/pages.js), named after its last part.
30
+ const pattern = new RegExp(`^${base.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}posts/(.+)/([^/]+)\\.html$`)
30
31
  server.middlewares.use(async (req, res, next) => {
31
32
  const match = decodeURIComponent((req.url || '').split('?')[0]).match(pattern)
32
- const [, slug, name] = match ?? []
33
- if (!match || (name !== slug && name !== `${slug}-agent`)) return next()
33
+ const [, path, name] = match ?? []
34
+ const last = path?.split('/').at(-1)
35
+ if (!match || (name !== last && name !== `${last}-agent`)) return next()
34
36
  try {
35
37
  logger.info(`building the ${name}.html download`)
36
38
  await scratchBuild(root, out)
37
39
  const { exportPost } = await import('./index.js')
38
- const files = await exportPost({ out, slug, base })
40
+ const files = await exportPost({ out, path, base })
39
41
  res.setHeader('Content-Type', 'text/html; charset=utf-8')
40
42
  res.setHeader('Content-Disposition', `attachment; filename="${name}.html"`)
41
- res.end(name === slug ? files.page : files.agent)
43
+ res.end(name === last ? files.page : files.agent)
42
44
  } catch (error) {
43
45
  logger.error(String(error.stack || error))
44
46
  res.statusCode = 500
@@ -1,21 +1,25 @@
1
- // Both downloads of one built post. `out` is the build's output directory (dist/ after `npm run build`,
2
- // a scratch directory under the dev server); `slug` names the post folder in it.
1
+ // Both downloads of one built page. `out` is the build's output directory (dist/ after `npm run build`,
2
+ // a scratch directory under the dev server); `path` is the page's path under posts/ in it (lib/pages.js): a post's
3
+ // slug, or a subpage's '<slug>/<name>'. `slug`, the older name for it, still works.
3
4
  import { existsSync, readFileSync } from 'node:fs'
4
5
  import { join } from 'node:path'
5
6
  import { root } from './common.js'
6
7
  import { interactivePage } from './page.js'
7
8
  import { agentPage } from './agent.js'
8
9
 
9
- export async function exportPost({ out, slug, site, base }) {
10
- const html = readFileSync(join(out, 'posts', slug, 'index.html'), 'utf8')
10
+ export async function exportPost({ out, path, slug, site, base }) {
11
+ path ??= slug
12
+ const html = readFileSync(join(out, 'posts', path, 'index.html'), 'utf8')
11
13
  const references = JSON.parse(readFileSync(join(root, 'src/references.json'), 'utf8'))
12
- // The deck, when the post has one, travels inside the interactive page.
13
- const deckFile = join(out, 'posts', slug, 'slides', 'index.html')
14
- const deck = existsSync(deckFile) ? await interactivePage(readFileSync(deckFile, 'utf8'), { out, site, base, inFrame: true }) : null
14
+ // The page's own URL path, against which its relative links resolve (siteLinks).
15
+ const pageUrl = `posts/${path}/`
16
+ // The deck, when the page has one, travels inside the interactive page.
17
+ const deckFile = join(out, 'posts', path, 'slides', 'index.html')
18
+ const deck = existsSync(deckFile) ? await interactivePage(readFileSync(deckFile, 'utf8'), { out, site, base, pageUrl: `${pageUrl}slides/`, inFrame: true }) : null
15
19
  return {
16
- page: await interactivePage(html, { out, site, base, deck }),
17
- agent: await agentPage(html, { references, out, site, base }),
20
+ page: await interactivePage(html, { out, site, base, pageUrl, deck }),
21
+ agent: await agentPage(html, { references, out, site, base, pageUrl }),
18
22
  }
19
23
  }
20
24
 
21
- export const downloadNames = (slug) => ({ page: `${slug}.html`, agent: `${slug}-agent.html` })
25
+ export { downloadNames } from '../../lib/pages.js'
@@ -112,12 +112,13 @@ const DECK_IN_FRAME = `(() => {
112
112
  }, true)
113
113
  })()`
114
114
 
115
- // `out` is the build's output directory; `site` the site's URL, for links back to it (see siteLinks).
115
+ // `out` is the build's output directory; `site` the site's URL, for links back to it, and `pageUrl` the page's URL path
116
+ // under the base, against which its relative links resolve (see siteLinks).
116
117
  // `deck` is the post's deck, already exported with `inFrame: true`, to carry inside this page.
117
- export async function interactivePage(html, { out = defaultDist, site, base, deck, inFrame = false } = {}) {
118
+ export async function interactivePage(html, { out = defaultDist, site, base, pageUrl, deck, inFrame = false } = {}) {
118
119
  const asset = (url) => distAsset(url, out)
119
120
  const tree = fromHtml(html)
120
- siteLinks(tree, { site, base })
121
+ siteLinks(tree, { site, base, pageUrl })
121
122
  const modules = new Map() // file in dist -> key in the bundle's module table
122
123
  const sideEffects = [] // module scripts the page runs for their effects
123
124
  const element = (tagName, properties, value) => ({ type: 'element', tagName, properties, children: [{ type: 'text', value }] })
@@ -1,21 +1,36 @@
1
1
  // Run after `astro build` (part of `npm run build`): writes the two downloads that the byline's download
2
- // control links to, beside each built post in dist/posts/<slug>/:
3
- // <slug>.html the interactive page, one file that opens from disk with working figures
4
- // <slug>-agent.html a text export for language models (bloggie/scripts/export/agent.js)
2
+ // control links to, beside each built page under dist/posts/ that offers them (lib/pages.js: every post, and a
3
+ // subpage whose front matter sets `downloads: true`):
4
+ // <name>.html the interactive page, one file that opens from disk with working figures
5
+ // <name>-agent.html a text export for language models (bloggie/scripts/export/agent.js)
6
+ // <name> is the last part of the page's path: the post's slug, or the subpage's name.
7
+ // Each export inlines the page's scripts, styles, fonts and data into one file and bundles its figures, which takes
8
+ // time and space for every page; so a page without the control gets none.
5
9
  // Under `npm run dev`, bloggie/scripts/export/dev.js builds them on request instead.
6
- import { existsSync, readdirSync, writeFileSync } from 'node:fs'
10
+ import { existsSync, readdirSync, readFileSync, writeFileSync } from 'node:fs'
7
11
  import { join } from 'node:path'
8
12
  import { dist } from './export/common.js'
9
13
  import { downloadNames, exportPost } from './export/index.js'
10
14
 
11
15
  const kb = (text) => `${Math.round(Buffer.byteLength(text) / 1024)} KB`
16
+ // The byline's download control (layouts/Post.astro); a deck's page and a page that turns downloads off have none.
17
+ const OFFERS = /<[^>]*\sdata-download[\s>=]/
18
+
19
+ // The built pages under dist/posts/, by their paths there ('<slug>', '<slug>/<name>', ...).
20
+ function pages(dir, path = '') {
21
+ const found = path && existsSync(join(dir, 'index.html')) ? [path] : []
22
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
23
+ if (entry.isDirectory()) found.push(...pages(join(dir, entry.name), path ? `${path}/${entry.name}` : entry.name))
24
+ }
25
+ return found
26
+ }
12
27
 
13
28
  // A blog with no visible post (e.g. a new blog with the example hidden) has no dist/posts.
14
- const built = existsSync(join(dist, 'posts')) ? readdirSync(join(dist, 'posts')) : []
15
- for (const slug of built) {
16
- if (!existsSync(join(dist, 'posts', slug, 'index.html'))) continue
17
- const files = await exportPost({ out: dist, slug })
18
- const names = downloadNames(slug)
19
- for (const kind of ['page', 'agent']) writeFileSync(join(dist, 'posts', slug, names[kind]), files[kind])
20
- console.log(`export-posts: ${names.page} (${kb(files.page)}), ${names.agent} (${kb(files.agent)})`)
29
+ const built = existsSync(join(dist, 'posts')) ? pages(join(dist, 'posts')) : []
30
+ for (const path of built) {
31
+ if (!OFFERS.test(readFileSync(join(dist, 'posts', path, 'index.html'), 'utf8'))) continue
32
+ const files = await exportPost({ out: dist, path })
33
+ const names = downloadNames(path)
34
+ for (const kind of ['page', 'agent']) writeFileSync(join(dist, 'posts', path, names[kind]), files[kind])
35
+ console.log(`export-posts: ${path}/${names.page} (${kb(files.page)}), ${names.agent} (${kb(files.agent)})`)
21
36
  }
@@ -123,7 +123,8 @@ its figure components the same way: the deck must run the post's real interactiv
123
123
 
124
124
  - A deck is `slides.mdx` beside the post's `index.mdx` (`src/pages/posts/<slug>/slides.mdx`), with
125
125
  `layout: '@bloggie/layouts/Slides.astro'` in its front matter; Astro serves it at
126
- `/posts/<slug>/slides/`. The pairing is automatic: when `slides.mdx` exists, the post's byline
126
+ `/posts/<slug>/slides/`. A subpage has a deck only as a folder with its own `index.mdx`
127
+ (`posts/<slug>/<name>/slides.mdx`); a file subpage (`<name>.mdx`) shares its post's. The pairing is automatic: when `slides.mdx` exists, the post's byline
127
128
  links to the deck and S on the post opens it; Esc (or ✕) on the deck returns to the post, with
128
129
  its scroll position when the reader came from it. A post without a deck has neither, and
129
130
  `slides: false` in a post's front matter hides a deck that exists. `bloggie/lib/slides.js` is the