kinsite 0.3.0 → 0.5.0

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/lib/news.mjs ADDED
@@ -0,0 +1,175 @@
1
+ // What's new: the owner's narrative entries, and the change records stamped at each deploy.
2
+ import fs from 'node:fs'
3
+ import path from 'node:path'
4
+ import { restricted } from './gedcom.mjs'
5
+ import { diffTrees, describe, readGedcom } from './diff.mjs'
6
+ import { esc } from './html.mjs'
7
+ import { redact } from './redact.mjs'
8
+
9
+ export const count = (n, one, many = `${one}s`) => `${n} ${n === 1 ? one : many}`
10
+
11
+ const INLINE = /\*\*(?!\s)(.+?)(?<!\s)\*\*|\*(?!\s)(.+?)(?<!\s)\*|\[([^\]\n]+)\]\((https?:\/\/[^\s)]+)\)|(https?:\/\/\S*[^\s.,;:!?)'"\]])|@(\w+)@/g
12
+
13
+ function inline(s, mention) {
14
+ let html = '', at = 0
15
+ for (const m of s.matchAll(INLINE)) {
16
+ const [all, strong, em, text, href, url, xref] = m
17
+ html += esc(s.slice(at, m.index))
18
+ at = m.index + all.length
19
+ if (strong) html += `<strong>${inline(strong, mention)}</strong>`
20
+ else if (em) html += `<em>${inline(em, mention)}</em>`
21
+ else if (href) html += `<a href="${esc(href)}">${esc(text)}</a>`
22
+ else if (url) html += `<a href="${esc(url)}">${esc(url)}</a>`
23
+ else html += mention(xref) ?? esc(all)
24
+ }
25
+ return html + esc(s.slice(at))
26
+ }
27
+
28
+ // The documented subset: a `# Title` first line, paragraphs, *em*, **strong**, http(s) links and @xref@ mentions.
29
+ // mention(id) returns the HTML for a person, or null to leave the mention as written.
30
+ export function markdown(text, mention) {
31
+ const lines = redact(text).replace(/\r\n?/g, '\n').split('\n')
32
+ const title = lines[0].match(/^# (.+)/)?.[1].trim()
33
+ const paras = (title ? lines.slice(1) : lines).join('\n').split(/\n\s*\n/).map(p => p.trim()).filter(Boolean)
34
+ return { title: title ? inline(title, mention) : '', html: paras.map(p => `<p>${inline(p, mention)}</p>`).join('') }
35
+ }
36
+
37
+ const STAMP = /^(\d{4}-\d{2}-\d{2})(?:-(\d+))?\.changes\.json$/
38
+
39
+ export function readNews(dir) {
40
+ const files = fs.existsSync(dir) ? fs.readdirSync(dir).sort() : []
41
+ const entries = new Map(files.filter(f => f.endsWith('.md')).map(f => [f.slice(0, -3), fs.readFileSync(path.join(dir, f), 'utf8')]))
42
+ const order = f => {
43
+ const [, date, n = '1'] = f.match(STAMP)
44
+ return `${date} ${n.padStart(6, '0')}`
45
+ }
46
+ const deploys = files.filter(f => STAMP.test(f)).map(file => {
47
+ try {
48
+ return { entries: [], changes: [], ...JSON.parse(fs.readFileSync(path.join(dir, file), 'utf8')), file }
49
+ } catch (e) {
50
+ throw new Error(`${path.join(dir, file)}: ${e.message}`)
51
+ }
52
+ }).sort((a, b) => order(b.file).localeCompare(order(a.file)))
53
+ const stamped = new Set(deploys.flatMap(d => d.entries))
54
+ return { entries, deploys, pending: [...entries.keys()].filter(e => !stamped.has(e)) }
55
+ }
56
+
57
+ const localDate = d => [d.getFullYear(), d.getMonth() + 1, d.getDate()].map(n => String(n).padStart(2, '0')).join('-')
58
+
59
+ export function stampNews(config, oldFile, { today = new Date(), log = console.log } = {}) {
60
+ if (!config.news) throw new Error('the config has no "news" directory to stamp')
61
+ const changes = diffTrees(readGedcom(oldFile), readGedcom(config.gedcom))
62
+ const { pending: entries } = readNews(config.news)
63
+ if (!changes.length && !entries.length) {
64
+ log('Nothing to stamp: no changes and no new entries.')
65
+ return null
66
+ }
67
+ const date = localDate(today)
68
+ fs.mkdirSync(config.news, { recursive: true })
69
+ let file = path.join(config.news, `${date}.changes.json`)
70
+ for (let n = 2; fs.existsSync(file); n++) file = path.join(config.news, `${date}-${n}.changes.json`)
71
+ fs.writeFileSync(file, JSON.stringify({ date, entries, changes }, null, 2) + '\n')
72
+ log(`Wrote ${path.relative(process.cwd(), file)}: ${count(entries.length, 'entry', 'entries')}, ${count(changes.length, 'change')}`)
73
+ return file
74
+ }
75
+
76
+ // A fact restricted in today's GEDCOM drops out of past entries, and so do its earlier versions. Walking back from
77
+ // today, a fact changed to a hidden or restricted version, or removed while restricted, is hidden in older deploys.
78
+ const FACT = ['tag', 'type', 'val', 'date', 'phrase', 'plac']
79
+ const sameFact = (a, b) => FACT.every(k => (a[k] ?? '') === (b[k] ?? ''))
80
+ const FACTS = new Set(['event', 'preferred', 'marriage'])
81
+ function unrestricted(deploys, tree) {
82
+ const hidden = new Map()
83
+ const hide = (key, f) => hidden.set(key, [...(hidden.get(key) ?? []), f])
84
+ const isHidden = (key, f) => !!f && !!hidden.get(key)?.some(v => sameFact(v, f))
85
+ const key = r => (r.kind === 'marriage' ? r.fam : r.id)
86
+ for (const [id, p] of tree.indi) for (const e of p.events.filter(restricted)) hide(id, e)
87
+ for (const [id, f] of tree.fam) if (restricted(f.marr)) hide(id, { tag: 'MARR', ...f.marr })
88
+ return deploys.map(d => {
89
+ const kept = d.changes.filter(r => ![r.event, ...(FACTS.has(r.kind) ? [r.from, r.to, r.marr] : [])].some(f => isHidden(key(r), f)))
90
+ for (const r of d.changes) {
91
+ if (r.op === 'added' || !['event', 'marriage'].includes(r.kind)) continue
92
+ const earlier = r.from ?? r.marr, later = r.op === 'changed' ? r.to : earlier
93
+ if (restricted(later) || isHidden(key(r), later)) hide(key(r), earlier)
94
+ }
95
+ return kept
96
+ })
97
+ }
98
+
99
+ const MONTHS = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
100
+ const longDate = (d, len) => {
101
+ const [y, m, day] = (d ?? '').split('-').map(Number)
102
+ return MONTHS[m - 1] && day ? `${day} ${MONTHS[m - 1].slice(0, len)} ${y}` : d ?? ''
103
+ }
104
+
105
+ // Each deploy's What's new section, and the people it changed or mentioned under this build's rules.
106
+ // indi is the built (possibly anonymized) tree; tree is the parsed GEDCOM the records are described against.
107
+ export function newsSections(news, indi, tree, config, warn) {
108
+ const shown = id => indi.has(id) && !indi.get(id).private
109
+ const mention = (file, people) => id => {
110
+ const p = indi.get(id)
111
+ if (!p) {
112
+ warn(`news ${file}: @${id}@ is not in the tree`)
113
+ return null
114
+ }
115
+ if (p.private) return 'Private'
116
+ people.add(id)
117
+ return `<a href="${id}.html">${esc(p.name || '(unnamed)')}</a>`
118
+ }
119
+ // The preview, when there is one, is newer than every deploy.
120
+ const all = [news.preview, ...news.deploys].filter(Boolean)
121
+ // People removed since keep the snapshot their newest removal recorded, so older records can still name them.
122
+ const snapshots = all.flatMap(d => d.changes).filter(c => c.kind === 'person' && c.op === 'removed').map(c => [c.id, c.was]).reverse()
123
+ const past = { indi: new Map([...tree.indi, ...snapshots.filter(([id]) => !tree.indi.has(id))]), fam: tree.fam }
124
+ const linked = i => {
125
+ const p = indi.get(i.id), label = shown(i.id) ? redact(`${p.name || '(unnamed)'} (${i.id})`) : null
126
+ const at = label ? i.text.indexOf(label) : -1
127
+ if (at < 0) return esc(i.text)
128
+ return esc(i.text.slice(0, at)) + `<a href="${i.id}.html">${esc(label)}</a>` + esc(i.text.slice(at + label.length))
129
+ }
130
+ const kept = unrestricted(all, tree)
131
+ return all.map((d, n) => {
132
+ const people = new Set()
133
+ const stories = [...d.entries].sort().flatMap(e => {
134
+ if (!news.entries.has(e)) {
135
+ warn(`news ${d.file}: ${e}.md not found`)
136
+ return []
137
+ }
138
+ const { title, html } = markdown(news.entries.get(e), mention(`${e}.md`, people))
139
+ return title || html ? [`<div class=card>${title ? `<h3>${title}</h3>` : ''}${html}</div>`] : []
140
+ })
141
+ const items = describe(kept[n], past, config)
142
+ for (const i of items) if (shown(i.id)) people.add(i.id)
143
+ const pending = d === news.preview
144
+ const anchor = pending ? 'pending' : path.basename(d.file, '.changes.json')
145
+ const list = items.map(i => `<li>${linked(i)}` +
146
+ (i.lines.length ? `<ul>${i.lines.map(l => `<li>${esc(l)}</li>`).join('')}</ul>` : '') + '</li>').join('')
147
+ const body = stories.join('') + (list ? `<ul class=changes>${list}</ul>` : '')
148
+ const label = esc(pending ? 'Not yet published' : longDate(d.date))
149
+ const self = pending ? '' : `<a class=self href="#${anchor}" aria-label="Link to ${label}">#</a>`
150
+ const heading = `<h2 id=${anchor}>${label}${self}</h2>`
151
+ const html = body ? heading + body : pending ? `${heading}<p class=sub>Nothing yet.</p>` : ''
152
+ return { anchor, date: d.date, pending, html, people }
153
+ })
154
+ }
155
+
156
+ // For each person changed or mentioned: the latest stamped section, and whether the preview has them.
157
+ // Sections are newest first.
158
+ export function lastUpdated(sections) {
159
+ const updated = new Map()
160
+ for (const s of sections) {
161
+ for (const id of s.people) {
162
+ const u = updated.get(id) ?? {}
163
+ if (s.pending) u.pending = true
164
+ else if (!u.date) Object.assign(u, { anchor: s.anchor, date: longDate(s.date, 3) })
165
+ updated.set(id, u)
166
+ }
167
+ }
168
+ return updated
169
+ }
170
+
171
+ export function whatsNewPage(sections, r) {
172
+ const title = "What's new"
173
+ return r.page(title, `<p class=back><a href="index.html">&larr; All people</a></p><h1>${esc(title)}</h1>` +
174
+ (sections.map(s => s.html).join('') || '<p class=sub>Nothing yet.</p>'))
175
+ }
package/lib/render.mjs CHANGED
@@ -1,16 +1,19 @@
1
1
  // HTML for the person pages and the index. Output is pinned by test/golden.test.mjs.
2
2
  import path from 'node:path'
3
3
  import { place, redact } from './redact.mjs'
4
- import { restricted } from './gedcom.mjs'
4
+ import { restricted, mainChildren } from './gedcom.mjs'
5
5
  import { esc } from './html.mjs'
6
6
  import { yr, byBirth, birthYear } from './dates.mjs'
7
7
  import { hourglassLayout, hourglassSvg } from './hourglass.mjs'
8
+ import { cropBox } from './media.mjs'
8
9
 
9
10
  export { esc, yr }
10
11
  export const DEFAULT_TITLE = 'Family Tree'
11
12
  export const IMG_EXT = new Set(['.jpg', '.jpeg', '.png', '.gif', '.webp'])
13
+ const CROP_MAX_HEIGHT = 260
14
+ const pct = n => `${+(n * 100).toFixed(3)}%`
12
15
 
13
- const known = s => ((s ?? '').trim() === '?' ? '' : s ?? '')
16
+ export const known = s => ((s ?? '').trim() === '?' ? '' : s ?? '')
14
17
 
15
18
  export function life(p) {
16
19
  const b = restricted(p.birt) ? '' : yr(p.birt.date), d = restricted(p.deat) ? '' : yr(p.deat.date)
@@ -40,9 +43,9 @@ const LABELS = {
40
43
  }
41
44
  const ORDER = { BIRT: -3, CHR: -2, BAPM: -1, DEAT: 1, BURI: 2 }
42
45
  // Repeats of these are alternate versions; GEDCOM 7 puts the preferred one first.
43
- const ONCE = new Set(Object.keys(ORDER))
46
+ export const ONCE = new Set(Object.keys(ORDER))
44
47
  const counter = (n = 0) => () => ++n
45
- const cited = c => [c.title, c.page, c.text, ...c.notes].some(s => s.trim())
48
+ export const cited = c => [c.title, c.page, c.text, ...c.notes].some(s => s.trim())
46
49
  const evtBits = e => {
47
50
  const bits = [], val = known(e.val), plac = place(known(e.plac))
48
51
  if (val && val !== 'Y') bits.push(esc(redact(val)))
@@ -50,11 +53,17 @@ const evtBits = e => {
50
53
  if (plac) bits.push(esc(plac.replace(/[, ]+$/, '')))
51
54
  return bits
52
55
  }
56
+ // How a child belongs to a parent family; a main family born into needs no label.
57
+ export const linkLabel = (l, main = false) => [
58
+ l.pedi === 'OTHER' ? l.phrase || 'other' : main && l.pedi === 'BIRTH' ? '' : l.pedi.toLowerCase(),
59
+ l.stat.toLowerCase(),
60
+ l.only && `on the ${l.only === 'child' ? "child's" : 'family'} record only`,
61
+ ].filter(Boolean).join(', ')
53
62
  const notesHtml = notes => (notes ?? []).filter(n => n.trim()).map(n => `<div class=enote>${esc(redact(n))}</div>`).join('')
54
63
 
55
64
  export class Renderer {
56
- constructor({ indi, fam, kin, copied, title = DEFAULT_TITLE, source = '', citations = true, notes = true }) {
57
- Object.assign(this, { indi, fam, kin, copied, title, source, citations, notes })
65
+ constructor({ indi, fam, kin, copied, sizes = new Map(), title = DEFAULT_TITLE, source = '', citations = true, notes = true, news = false, updated = new Map() }) {
66
+ Object.assign(this, { indi, fam, kin, copied, sizes, title, source, citations, notes, news, updated })
58
67
  }
59
68
 
60
69
  page(title, body) {
@@ -111,6 +120,43 @@ export class Renderer {
111
120
  return text && !restricted(mar) ? ` <span class=yr>(m. ${esc(text)})</span>` : ''
112
121
  }
113
122
 
123
+ parentIds(fid) {
124
+ const f = this.fam.get(fid)
125
+ return [f.husb, f.wife].filter(Boolean)
126
+ }
127
+
128
+ nameLink(pid) {
129
+ const p = this.indi.get(pid)
130
+ return p ? `<a href="${pid}.html">${esc(p.name || '(unnamed)')}</a>` : this.plink(pid)
131
+ }
132
+
133
+ parentsHtml(p) {
134
+ const { fam } = this
135
+ const links = (p.parentFams ?? []).filter(l => fam.has(l.fam))
136
+ const main = links.find(l => l.fam === p.famc)
137
+ const items = main ? this.parentIds(main.fam).map(id => this.plink(id)) : []
138
+ for (const l of links) {
139
+ if (l === main) continue
140
+ const label = linkLabel(l)
141
+ const names = this.parentIds(l.fam).map(id => this.plink(id)).join(' and ') || 'unrecorded parents'
142
+ items.push(`Also listed as a child of ${names}` + (label ? ` <span class=pref>${esc(label)}</span>` : ''))
143
+ }
144
+ if (!items.length) return ''
145
+ const label = main && linkLabel(main, true)
146
+ return `<h2>Parents${label ? `<span class=pref>${esc(label)}</span>` : ''}</h2>` +
147
+ '<ul class=rel>' + items.map(x => `<li>${x}</li>`).join('') + '</ul>'
148
+ }
149
+
150
+ // A child whose main parent family is another one, or whose link is one-sided, says so.
151
+ childHtml(c, fid) {
152
+ const k = this.indi.get(c)
153
+ const link = k?.parentFams?.find(l => l.fam === fid)
154
+ if (!k || (k.famc === fid && !link?.only)) return this.plink(c)
155
+ const main = k.famc !== fid && this.fam.has(k.famc) && this.parentIds(k.famc).map(id => this.nameLink(id)).join(' and ')
156
+ const note = [link && esc(linkLabel(link)), main && `main parents: ${main}`].filter(Boolean).join('; ')
157
+ return this.plink(c) + (note ? ` <span class=yr>(${note})</span>` : '')
158
+ }
159
+
114
160
  chartSvg(pid) {
115
161
  const label = id => {
116
162
  const p = this.indi.get(id)
@@ -132,6 +178,51 @@ export class Renderer {
132
178
  return { imgs: pairs.filter(isImg), docs: pairs.filter(x => !isImg(x)) }
133
179
  }
134
180
 
181
+ get photos() {
182
+ if (!this._photos) {
183
+ const links = new Map()
184
+ for (const [pid, p] of this.indi) {
185
+ for (const [md] of this.attachments(p).imgs) if (md.obje) links.set(md.obje, [...(links.get(md.obje) ?? []), { pid, md }])
186
+ }
187
+ this._photos = new Map([...links].filter(([, l]) => l.length > 1 || l.some(({ md }) => md.crop)))
188
+ }
189
+ return this._photos
190
+ }
191
+
192
+ figure(md, src, name) {
193
+ const { title, caption } = md
194
+ const size = this.sizes.get(md.file)
195
+ const box = md.crop && cropBox(md.crop, size)
196
+ const alt = esc(box && name ? [name, title].filter(Boolean).join(' in ') : title || caption)
197
+ const text = title && caption && caption !== title ? `${esc(title)}<span class=cn>${esc(caption)}</span>` : esc(title || caption)
198
+ const href = esc(this.photos.has(md.obje) ? `${md.obje}.html` : src)
199
+ const img = box
200
+ ? `<a class=crop href="${href}" style="aspect-ratio:${box.width}/${box.height};width:min(100%,${Math.round(CROP_MAX_HEIGHT * box.width / box.height)}px)">` +
201
+ `<img src="${esc(src)}" alt="${alt}" style="width:${pct(size.width / box.width)};left:${pct(-box.left / box.width)};top:${pct(-box.top / box.height)}"></a>`
202
+ : `<a href="${href}"><img src="${esc(src)}" alt="${alt}"></a>`
203
+ return `<figure>${img}<figcaption>${text}</figcaption></figure>`
204
+ }
205
+
206
+ photoPage(oid) {
207
+ const links = this.photos.get(oid), { file, title } = links[0].md
208
+ const src = esc(this.copied.get(file)), size = this.sizes.get(file), heading = title || 'Photo'
209
+ const boxed = links.map(l => ({ ...l, box: l.md.crop && cropBox(l.md.crop, size) }))
210
+ const placed = boxed.filter(l => l.box).sort((a, b) => a.box.left - b.box.left || a.box.top - b.box.top)
211
+ const unplaced = boxed.filter(l => !l.box)
212
+ const item = ({ pid, md }) => `<li>${this.plink(pid)}${md.caption ? ` <span class=cn>${esc(md.caption)}</span>` : ''}</li>`
213
+ const boxes = placed.map(({ pid, md, box }, i) => {
214
+ const label = [this.indi.get(pid).name || '(unnamed)', md.caption].filter(Boolean).join(' · ')
215
+ const right = box.left + box.width / 2 > size.width / 2 ? ' r' : ''
216
+ return `<a class="who${right}" href="${pid}.html" style="left:${pct(box.left / size.width)};top:${pct(box.top / size.height)};` +
217
+ `width:${pct(box.width / size.width)};height:${pct(box.height / size.height)}"><b>${i + 1}</b><span>${esc(label)}</span></a>`
218
+ })
219
+ const b = ['<p class=back><a href="index.html">&larr; All people</a></p>', `<h1>${esc(heading)}</h1>`,
220
+ `<div class=stage><a href="${src}"><img src="${src}" alt="${esc(heading)}"></a>${boxes.join('')}</div>`]
221
+ if (placed.length) b.push(`<h2>In this photo</h2><ol class=placed>${placed.map(item).join('')}</ol>`)
222
+ if (unplaced.length) b.push(`<h2>Also in this photo (not yet placed)</h2><ul class=rel>${unplaced.map(item).join('')}</ul>`)
223
+ return this.page(heading, b.join(''))
224
+ }
225
+
135
226
  personPage(pid) {
136
227
  const p = this.indi.get(pid), { kin, fam } = this
137
228
  const b = ['<p class=back><a href="index.html">&larr; All people</a></p>',
@@ -140,6 +231,14 @@ export class Renderer {
140
231
  b.push('<p class=sub>Details of living people are withheld.</p>')
141
232
  return { html: this.page(p.name, b.join('')), withPhoto: false }
142
233
  }
234
+ const up = this.updated.get(pid)
235
+ if (up) {
236
+ const links = [
237
+ up.date && `<a href="whats-new.html#${up.anchor}">Updated ${esc(up.date)}</a>`,
238
+ up.pending && '<a href="whats-new.html#pending">Changed since last deploy</a>',
239
+ ]
240
+ b.push(`<p class=updated>${links.filter(Boolean).join(' · ')}</p>`)
241
+ }
143
242
  const meta = [{ M: 'Male', F: 'Female' }[p.sex] ?? '', life(p)].filter(Boolean).join(' &middot; ')
144
243
  if (meta) b.push(`<p class=sub>${meta}</p>`)
145
244
 
@@ -158,24 +257,15 @@ export class Renderer {
158
257
  b.push('<h2>Family</h2>' + this.chartSvg(pid))
159
258
 
160
259
  const { imgs, docs } = this.attachments(p)
161
- if (imgs.length) {
162
- const cells = imgs.map(([md, src]) =>
163
- `<figure><a href="${esc(src)}"><img src="${esc(src)}" alt="${esc(md.title)}"></a>` +
164
- `<figcaption>${esc(md.title)}</figcaption></figure>`).join('')
165
- b.push(`<div class="photos">${cells}</div>`)
166
- }
260
+ if (imgs.length) b.push(`<div class="photos">${imgs.map(([md, src]) => this.figure(md, src, p.name)).join('')}</div>`)
167
261
 
168
262
  const num = counter()
169
263
  const vit = this.eventsHtml(p, num)
170
264
  if (vit) b.push(`<div class=card>${vit}</div>`)
171
265
 
172
266
  const rel = []
173
- const par = []
174
- if (p.famc && fam.has(p.famc)) {
175
- const f = fam.get(p.famc)
176
- for (const who of [f.husb, f.wife]) if (who) par.push(this.plink(who))
177
- }
178
- if (par.length) rel.push('<h2>Parents</h2><ul class=rel>' + par.map(x => `<li>${x}</li>`).join('') + '</ul>')
267
+ const par = this.parentsHtml(p)
268
+ if (par) rel.push(par)
179
269
  for (const fid of p.fams) {
180
270
  const f = fam.get(fid)
181
271
  if (!f) continue
@@ -184,12 +274,12 @@ export class Renderer {
184
274
  if (spouse) {
185
275
  sp.push(`<li>${this.plink(spouse)}${this.marriageHtml(f.marr)}</li>`)
186
276
  }
187
- const kids = [...f.chil].sort(byBirth(this.indi)).map(c => `<li>${this.plink(c)}</li>`)
277
+ const kids = [...f.chil].sort(byBirth(this.indi)).map(c => `<li>${this.childHtml(c, fid)}</li>`)
188
278
  rel.push('<h2>Spouse &amp; children</h2><ul class=rel>' + sp.join('') + kids.join('') + '</ul>')
189
279
  }
190
280
  if (rel.length) b.push(rel.join(''))
191
281
 
192
- const sibs = p.famc ? (fam.get(p.famc)?.chil ?? []).filter(c => c !== pid).sort(byBirth(this.indi)) : []
282
+ const sibs = fam.has(p.famc) ? mainChildren(fam.get(p.famc), this.indi).filter(c => c !== pid).sort(byBirth(this.indi)) : []
193
283
  if (sibs.length) b.push('<h2>Siblings</h2><ul class=rel>' + sibs.map(c => `<li>${this.plink(c)}</li>`).join('') + '</ul>')
194
284
 
195
285
  const desc = this.descendantsHtml(pid, 3)
@@ -230,6 +320,7 @@ export class Renderer {
230
320
  const body = `<h1>${esc(this.title)}</h1>` +
231
321
  `<p class=sub>${this.indi.size} individuals &middot; ${this.fam.size} families ` +
232
322
  `&middot; ${withphoto} with photos</p>` +
323
+ (this.news ? `<p><a href="whats-new.html">${esc("What's new")}</a></p>` : '') +
233
324
  hero +
234
325
  '<h2>All people</h2>' +
235
326
  '<input id=q placeholder="Filter by name…" autocomplete=off>' +
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "kinsite",
3
- "version": "0.3.0",
3
+ "version": "0.5.0",
4
4
  "type": "module",
5
5
  "description": "Static HTML family-tree site from a GEDCOM file",
6
6
  "license": "MIT",
@@ -23,6 +23,7 @@
23
23
  },
24
24
  "files": [
25
25
  "lib/",
26
+ "scripts/",
26
27
  "build.mjs"
27
28
  ],
28
29
  "bin": {
@@ -0,0 +1,56 @@
1
+ #!/usr/bin/env node
2
+ // Usage: npm run dev [-- path/to/kinsite.config.json] (default: the sample; SINCE=old.ged previews What's new)
3
+ import fs from 'node:fs'
4
+ import path from 'node:path'
5
+ import { fileURLToPath } from 'node:url'
6
+ import { execFileSync } from 'node:child_process'
7
+ import { loadConfig } from '../lib/config.mjs'
8
+ import { createServer } from './serve.mjs'
9
+ import { whoHandler } from './who.mjs'
10
+
11
+ const repo = path.join(path.dirname(fileURLToPath(import.meta.url)), '..')
12
+ const here = process.env.INIT_CWD ?? process.cwd()
13
+ const configFile = path.resolve(here, process.argv[2] ?? path.join(repo, 'sample', 'kinsite.config.json'))
14
+ const since = process.env.SINCE && path.resolve(here, process.env.SINCE)
15
+ const env = since ? { ...process.env, SINCE: since } : process.env
16
+ const port = Number(process.env.PORT || 4000)
17
+ const state = { version: 1 }
18
+
19
+ function rebuild() {
20
+ try {
21
+ const config = loadConfig(configFile)
22
+ // In-process rebuilds would reuse the cached lib/ modules.
23
+ execFileSync(process.execPath, [path.join(repo, 'build.mjs'), configFile], { env, stdio: ['ignore', 'ignore', 'pipe'] })
24
+ state.version++
25
+ console.log(`built (v${state.version})`)
26
+ return config.out
27
+ } catch (e) {
28
+ console.error(`build failed, serving last good output: ${e.stderr?.toString().trim() || e.message}`)
29
+ }
30
+ }
31
+
32
+ let out = rebuild()
33
+ if (!out) process.exit(1)
34
+
35
+ const server = createServer(() => out, state, whoHandler(configFile)).listen(port, () => {
36
+ const url = `http://localhost:${server.address().port}`
37
+ console.log(`${url}\nidentify people in photos: ${url}/who`)
38
+ })
39
+
40
+ let timer
41
+ const schedule = () => {
42
+ clearTimeout(timer)
43
+ timer = setTimeout(() => { out = rebuild() ?? out }, 150)
44
+ }
45
+ const inside = (dir, f) => !path.relative(dir, f).startsWith('..')
46
+ const config = loadConfig(configFile)
47
+ const watched = [
48
+ [path.join(repo, 'lib'), true], [path.join(repo, 'build.mjs'), false], [path.dirname(configFile), true],
49
+ [path.dirname(config.gedcom), false], [config.news, false], [since && path.dirname(since), false],
50
+ ]
51
+ for (const [p, recursive] of watched) {
52
+ if (!p || !fs.existsSync(p)) continue
53
+ fs.watch(p, { recursive }, (_, f) => {
54
+ if (!f || !inside(out, path.join(p, f))) schedule()
55
+ })
56
+ }
@@ -0,0 +1,56 @@
1
+ import fs from 'node:fs'
2
+ import path from 'node:path'
3
+ import http from 'node:http'
4
+
5
+ export const RELOAD_SCRIPT = `<script>(()=>{const v=()=>fetch('/__version').then(r=>r.text()).catch(()=>null);let c;v().then(x=>{c=x;setInterval(async()=>{const n=await v();if(n&&c&&n!==c)location.reload();c=n||c},700)})})()</script>`
6
+
7
+ export const TYPES = {
8
+ '.html': 'text/html; charset=utf-8',
9
+ '.css': 'text/css; charset=utf-8',
10
+ '.js': 'text/javascript; charset=utf-8',
11
+ '.json': 'application/json',
12
+ '.svg': 'image/svg+xml',
13
+ '.png': 'image/png',
14
+ '.jpg': 'image/jpeg',
15
+ '.jpeg': 'image/jpeg',
16
+ '.gif': 'image/gif',
17
+ '.webp': 'image/webp',
18
+ '.ico': 'image/x-icon',
19
+ '.txt': 'text/plain; charset=utf-8',
20
+ }
21
+
22
+ export function resolvePath(root, urlPath) {
23
+ let p
24
+ try { p = decodeURIComponent(urlPath.split('?')[0]) } catch { return null }
25
+ if (p.includes('\0') || p.split(/[\\/]/).includes('..')) return null
26
+ const file = path.resolve(root, '.' + path.posix.normalize('/' + p))
27
+ const rel = path.relative(root, file)
28
+ if (path.isAbsolute(rel) || rel.split(path.sep)[0] === '..') return null
29
+ return file
30
+ }
31
+
32
+ export function createServer(getRoot, state, handle = () => false) {
33
+ return http.createServer((req, res) => {
34
+ if (handle(req, res)) return
35
+ const send = (status, body, type = 'text/plain; charset=utf-8') => {
36
+ res.writeHead(status, { 'content-type': type, 'cache-control': 'no-store' })
37
+ res.end(body)
38
+ }
39
+ if (req.method !== 'GET' && req.method !== 'HEAD') return send(405, 'method not allowed')
40
+ if (req.url.split('?')[0] === '/__version') return send(200, String(state.version))
41
+ const root = path.resolve(getRoot())
42
+ let file = resolvePath(root, req.url)
43
+ if (!file) return send(403, 'forbidden')
44
+ try {
45
+ if (fs.statSync(file).isDirectory()) file = path.join(file, 'index.html')
46
+ const ext = path.extname(file).toLowerCase()
47
+ const type = TYPES[ext] ?? 'application/octet-stream'
48
+ const data = fs.readFileSync(file)
49
+ if (ext !== '.html') return send(200, data, type)
50
+ const html = data.toString('utf8')
51
+ send(200, html.includes('</body>') ? html.replace('</body>', RELOAD_SCRIPT + '</body>') : html + RELOAD_SCRIPT, type)
52
+ } catch {
53
+ send(404, 'not found')
54
+ }
55
+ })
56
+ }