kinsite 0.3.0 → 0.4.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/README.md CHANGED
@@ -14,6 +14,9 @@ Needs Node 22 or later; no dependencies. Live demo: https://chrismo.github.io/ki
14
14
  node build.mjs sample/kinsite.config.json # build the fictional sample tree into site/
15
15
  open site/index.html
16
16
  npm run dev # preview the sample at http://localhost:4000 (PORT=... to change); rebuilds and reloads on edits
17
+ npm run dev -- my/kinsite.config.json # the same for your own tree
18
+ node build.mjs diff sample/kinsite.config.json old.ged # what changed on the site since old.ged (see "What changed")
19
+ node build.mjs news stamp kinsite.config.json old.ged # record a deploy's changes for the What's new page (see "What's new")
17
20
  npm test
18
21
  ```
19
22
 
@@ -39,9 +42,11 @@ For your own tree, write a `kinsite.config.json` next to your GEDCOM:
39
42
  | `anonymizeLiving` | Show living people only as "Private", for a public site (see Goals) | `false` |
40
43
  | `citations` | Show source citations on person pages; event notes follow `notes` | `true` |
41
44
  | `notes` | Show person and event notes; a citation's own notes go with the citation | `true` |
45
+ | `news` | Directory of What's new entries and stamped changes (see "What's new") | unset: no page |
42
46
 
43
47
  Relative paths resolve against the config file's directory. `FOCUS=I3` or `OUT=dir` in
44
- the environment override the config for one run. The build log says what was
48
+ the environment override the config for one run. `SINCE=old.ged` previews unpublished
49
+ changes on the What's new page; it is never a config key (see "What's new"). The build log says what was
45
50
  published, e.g. `published : citations shown, notes hidden, living anonymized`.
46
51
 
47
52
  ### A research site or a public site
@@ -95,6 +100,156 @@ quoted text of the record. Citations on the person record or on the name shown a
95
100
  listed under Sources at the foot of the page. Marriages don't show notes or citations
96
101
  yet.
97
102
 
103
+ ## Parent families
104
+
105
+ A person listed as a child in more than one family (several `FAMC`) gets one main
106
+ parent family: the first `FAMC` in file order that points at a family in the file and isn't marked
107
+ `STAT DISPROVEN`. `PROVEN`
108
+ is shown as a label but doesn't reorder anything. Parents, Siblings, the chart and the
109
+ "Path to" breadcrumb all use the main family. The other families are listed under
110
+ Parents as "Also listed as a child of …", labeled with their `PEDI` (adopted, foster,
111
+ birth, or the `PHRASE` of `PEDI OTHER`) and `STAT`; the main family gets a label too
112
+ when it has a `PEDI` other than `BIRTH`, or a `STAT`. On those other parents' pages the
113
+ child is listed with a pointer to the main parents.
114
+
115
+ With `anonymizeLiving`, `DISPROVEN` families are left out, and a living person appears
116
+ only in their main family, with no `PEDI` or `STAT`.
117
+
118
+ The build warns about links recorded on one side only, such as a `FAMC` with no
119
+ matching `CHIL`, a `CHIL` with no `FAMC`, or the same for `FAMS` and `HUSB`/`WIFE`:
120
+ `warning: F2 CHIL @I7@ has no matching FAMC in I7`. A child link recorded on one side
121
+ still shows on both, labeled with the side that recorded it ("on the family record only"
122
+ or "on the child's record only"), so the child stays in the chart and the "Path to"
123
+ line. A child's own `FAMC` comes before a link found only on a family's `CHIL` when
124
+ choosing the main family. Add the missing line to the file to clear the label and the
125
+ warning.
126
+
127
+ ## What changed
128
+
129
+ Before deploying, `kinsite diff kinsite.config.json old.ged` compares an older GEDCOM
130
+ with the config's current one and prints one sentence per change, grouped by person.
131
+ It builds nothing and never touches git: getting `old.ged`, from a tag, a backup or
132
+ anywhere else, is up to you.
133
+
134
+ ```
135
+ Ada Fenwick (I1)
136
+ Changed birth date from 1859 to about 1858
137
+ Added: residence 1880, Marrowby
138
+ Now listed as a child of Tobias Fenwick and Mara Quill
139
+ Removed: Jonas Pell (I9) and his marriage to Ada Fenwick
140
+ ```
141
+
142
+ It reports what changed on the site, not in the GEDCOM: people and marriages added or
143
+ removed, the name shown, events, notes, citations, photos and documents (by `FILE`),
144
+ marriage date and place, and parent families with their `PEDI` and `STAT`. A child whose
145
+ main parent family changes gets one "Now listed as a child of …" line. Tags the site
146
+ doesn't show never appear, and neither do marriage notes and citations.
147
+
148
+ GEDCOM facts have no IDs, so versions of one event on one person (and one `TYPE`, for
149
+ `EVEN`) are matched like this: identical versions are unchanged; the rest are paired in
150
+ file order when they share a date or a place, and read as changed; anything left over
151
+ was added or removed. A fact whose date and place both changed reads as one removal and
152
+ one addition. Notes are matched by text, and citations by source and page, so
153
+ retitling a `SOUR` record changes nothing.
154
+
155
+ The list follows the config's privacy settings, so the same two files can be checked
156
+ against a research site and a public site. With `anonymizeLiving`, nothing is said
157
+ about a Private person, including links to them, or about media of theirs or media
158
+ shared with them; a removed person is named only if they would not be Private; and
159
+ removals name only what kind of thing went ("Removed a burial record"), not what it
160
+ said. With `notes` or `citations` off, there are no note or citation lines. Versions
161
+ marked `RESN PRIVACY` or `CONFIDENTIAL` never appear, and all text is redacted as on
162
+ the site.
163
+
164
+ Most of this rests on xrefs staying the same, as stable URLs already do. If more than
165
+ half of `old.ged`'s people are missing from the new file, the command stops with
166
+ `error: xrefs look renumbered` rather than reporting the whole tree as removed and
167
+ re-added.
168
+
169
+ ## What's new
170
+
171
+ Set `"news": "news"` in the config to publish a `whats-new.html` page that relatives
172
+ can read: what you worked on, in your own words, then what changed on the site, with
173
+ links to the people. The index links to it. With `news` unset, nothing changes.
174
+
175
+ **Entries.** Each `.md` file in the directory is one entry, written while doing the
176
+ research. Mention people by xref:
177
+
178
+ ```
179
+ # The two Ada Fenwicks
180
+
181
+ Sorted out the two Adas in Marrowby. @I1@ is the one who married
182
+ @I9@; the *other* Ada was her cousin. See https://example.org/marrowby-1880.
183
+ ```
184
+
185
+ Entries use a small subset of Markdown: an optional `# Title` first line, paragraphs
186
+ separated by a blank line, `*emphasis*`, `**strong**`, `[text](https://…)` links and
187
+ bare http(s) URLs, and `@I12@` mentions. Anything else, raw HTML included, shows as
188
+ plain text, and only http(s) links become links. All text is redacted as on the site.
189
+ A mention links to the person, or reads "Private" with no link when they are Private
190
+ in this build; a mention of an xref that isn't in the tree is left as written, and the
191
+ build warns. An entry is free text, though: like a note, it can still name a living
192
+ person in words, and nothing hides that.
193
+
194
+ **Stamping a deploy.** `kinsite news stamp kinsite.config.json old.ged` runs the "What
195
+ changed" diff between `old.ged` and the config's GEDCOM and writes one file per deploy,
196
+ such as `news/2026-11-14.changes.json` (`-2`, `-3`, … for later deploys that day):
197
+
198
+ ```json
199
+ { "date": "2026-11-14", "entries": ["pell-family", "two-adas"], "changes": [ … ] }
200
+ ```
201
+
202
+ Every entry not yet listed in a changes file is included, so entries written during one
203
+ round of research share one change list. A deploy with changes but no entry still gets a
204
+ file, and shows on the page with only its date. With no changes and no new entries, the
205
+ command writes nothing. Entries are never edited; whether one is waiting is decided by
206
+ the changes files. To drop a line, delete its record from `changes`; to reword
207
+ something, say it in an entry.
208
+
209
+ **The page.** Deploys are listed newest first: the date, the entries in file-name order,
210
+ then the change list. The sentences are written at each build from the stored records,
211
+ under that build's privacy settings, as `kinsite diff` would, so one `news/` directory
212
+ can feed a research site and a public site. A person later found to be living, or a fact
213
+ later marked `RESN PRIVACY` or `CONFIDENTIAL`, drops out of past deploys on the next
214
+ rebuild, and a deploy left with nothing to show is left off. Entries not yet stamped
215
+ aren't shown. The build log says, for example,
216
+ `news : 4 deploys, 2 entries not yet stamped`.
217
+
218
+ **Previewing the next deploy.** To read the next entry as it will appear, build with
219
+ `SINCE` set to the GEDCOM that's live now:
220
+
221
+ ```sh
222
+ SINCE=old.ged node build.mjs kinsite.config.json
223
+ SINCE=old.ged npm run dev -- kinsite.config.json # rebuilds as the GEDCOM and the entries change
224
+ ```
225
+
226
+ `whats-new.html` then starts with a "Not yet published" section: every entry not yet
227
+ stamped, followed by a fresh "What changed" diff between `old.ged` and the config's
228
+ GEDCOM, under the same privacy settings as the rest of the page. The build log says
229
+ `news : previewing changes since old.ged`. `SINCE` is only ever an environment
230
+ variable, never a config key, so a deploy can't publish the preview by accident; and
231
+ with the recipe below (stamp, then build) nothing is pending at deploy anyway.
232
+
233
+ **Updated notes.** A person page shows "Updated 14 Nov 2026" under the name, linking to
234
+ that deploy on the page (`whats-new.html#2026-11-14`). The date is the latest deploy that,
235
+ under this build's rules, lists a change under the person or has an entry mentioning
236
+ them, so a line that isn't shown can't date-stamp a page. Private people never get the
237
+ note, entries not yet stamped don't count, and the note doesn't age out. When building
238
+ with `SINCE`, a person changed or mentioned in the preview also gets a "Changed since
239
+ last deploy" link to the "Not yet published" section.
240
+
241
+ **A deploy recipe.** kinsite never touches git; this is one way to run it:
242
+
243
+ 1. Get the GEDCOM that's live now, as `old.ged`.
244
+ 2. `kinsite news stamp kinsite.config.json old.ged`
245
+ 3. Build.
246
+ 4. Commit `news/`.
247
+ 5. Deploy.
248
+ 6. Record the GEDCOM you just deployed as the new live version.
249
+
250
+ Links to individual facts aren't possible: a fact has no ID that survives a rebuild.
251
+ Marriage notes and citations aren't covered, as in "What changed".
252
+
98
253
  ## Goals
99
254
 
100
255
  - **Static output only.** No server, no database. JavaScript in the browser is fine,
@@ -116,6 +271,10 @@ yet.
116
271
  whole tree shrunk until the text is useless.
117
272
  - **Works on a phone.**
118
273
  - **Stable URLs.** A person keeps the same page address across rebuilds.
274
+ - **Show the file as recorded.** kinsite never adds a relationship or fact the GEDCOM
275
+ doesn't state. When the file contradicts itself or is ambiguous, it shows what each
276
+ record says, labeled where GEDCOM provides labels, and the build log warns. Fixing
277
+ the data is the owner's call, not the generator's.
119
278
 
120
279
  ## Contributing
121
280
 
package/build.mjs CHANGED
@@ -5,16 +5,29 @@
5
5
  // node build.mjs path/to/kinsite.config.json
6
6
  // FOCUS=I3 node build.mjs kinsite.config.json # re-center on another person
7
7
  // OUT=/tmp/site node build.mjs kinsite.config.json
8
+ // SINCE=old.ged node build.mjs kinsite.config.json # preview unstamped news on What's new
9
+ // node build.mjs diff kinsite.config.json old.ged # what changed on the site since old.ged
10
+ // node build.mjs news stamp kinsite.config.json old.ged # record this deploy's changes for What's new
8
11
  import { loadConfig } from './lib/config.mjs'
9
12
  import { buildSite } from './lib/build.mjs'
13
+ import { changeReport } from './lib/diff.mjs'
14
+ import { stampNews } from './lib/news.mjs'
10
15
 
11
- const file = process.argv[2]
12
- if (!file) {
13
- console.error('usage: node build.mjs path/to/kinsite.config.json')
16
+ const USAGE = `usage: kinsite path/to/kinsite.config.json
17
+ kinsite diff path/to/kinsite.config.json old.ged
18
+ kinsite news stamp path/to/kinsite.config.json old.ged`
19
+ const [first, ...rest] = process.argv.slice(2)
20
+ const [cmd, file, old] = first === 'diff' ? [first, ...rest]
21
+ : first === 'news' ? (rest[0] === 'stamp' ? ['stamp', ...rest.slice(1)] : [])
22
+ : ['build', first]
23
+ if (!file || (cmd !== 'build' && !old)) {
24
+ console.error(USAGE)
14
25
  process.exit(2)
15
26
  }
16
27
  try {
17
- buildSite(loadConfig(file, { focus: process.env.FOCUS, out: process.env.OUT }))
28
+ if (cmd === 'diff') console.log(changeReport(loadConfig(file), old))
29
+ else if (cmd === 'stamp') stampNews(loadConfig(file), old)
30
+ else buildSite(loadConfig(file, { focus: process.env.FOCUS, out: process.env.OUT }), { since: process.env.SINCE })
18
31
  } catch (e) {
19
32
  console.error(`error: ${e.message}`)
20
33
  process.exit(1)
package/lib/build.mjs CHANGED
@@ -5,10 +5,15 @@ import { Kin } from './kin.mjs'
5
5
  import { Renderer } from './render.mjs'
6
6
  import { CSS } from './css.mjs'
7
7
  import { anonymize } from './living.mjs'
8
+ import { readNews, newsSections, lastUpdated, whatsNewPage, count } from './news.mjs'
9
+ import { diffTrees, readGedcom } from './diff.mjs'
8
10
 
9
- export function buildSite(config, { log = console.log } = {}) {
11
+ // since: an older GEDCOM to preview What's new against (the SINCE environment variable, never a config key).
12
+ export function buildSite(config, { log = console.log, since } = {}) {
10
13
  const { gedcom, out, mediaRoot, title, focus, anonymizeLiving, citations = true, notes = true } = config
11
14
  if (!fs.statSync(gedcom, { throwIfNoEntry: false })?.isFile()) throw new Error(`GEDCOM not found: ${gedcom}`)
15
+ if (since && !config.news) throw new Error('SINCE previews the What\'s new page, so the config needs "news" set')
16
+ const old = since && readGedcom(since)
12
17
  const mediaOut = path.join(out, 'media')
13
18
  const inside = (dir, f) => {
14
19
  const rel = path.relative(dir, f)
@@ -24,6 +29,7 @@ export function buildSite(config, { log = console.log } = {}) {
24
29
  fs.mkdirSync(mediaOut, { recursive: true })
25
30
 
26
31
  const parsed = parseGedcom(fs.readFileSync(gedcom, 'utf8'))
32
+ for (const w of parsed.warnings) log(` warning: ${w}`)
27
33
  const { indi, fam } = anonymizeLiving ? anonymize(parsed.indi, parsed.fam) : parsed
28
34
 
29
35
  const copied = new Map()
@@ -50,7 +56,10 @@ export function buildSite(config, { log = console.log } = {}) {
50
56
  fs.writeFileSync(path.join(out, 'style.css'), CSS)
51
57
 
52
58
  const kin = new Kin(indi, fam, focus)
53
- const r = new Renderer({ indi, fam, kin, copied, title, source: path.basename(gedcom), citations, notes })
59
+ const news = config.news && readNews(config.news)
60
+ if (old) news.preview = { entries: news.pending, changes: diffTrees(old, parsed) }
61
+ const sections = news ? newsSections(news, indi, parsed, config, w => log(` warning: ${w}`)) : []
62
+ const r = new Renderer({ indi, fam, kin, copied, title, source: path.basename(gedcom), citations, notes, news: !!news, updated: lastUpdated(sections) })
54
63
  let withPhoto = 0
55
64
  for (const pid of indi.keys()) {
56
65
  const page = r.personPage(pid)
@@ -58,6 +67,7 @@ export function buildSite(config, { log = console.log } = {}) {
58
67
  fs.writeFileSync(path.join(out, `${pid}.html`), page.html)
59
68
  }
60
69
  fs.writeFileSync(path.join(out, 'index.html'), r.indexPage())
70
+ if (news) fs.writeFileSync(path.join(out, 'whats-new.html'), whatsNewPage(sections, r))
61
71
 
62
72
  const stats = {
63
73
  individuals: indi.size, families: fam.size, withPhoto, media: copied.size,
@@ -69,6 +79,8 @@ export function buildSite(config, { log = console.log } = {}) {
69
79
  log(` media copied: ${stats.media}`)
70
80
  const shown = on => (on ? 'shown' : 'hidden')
71
81
  log(` published : citations ${shown(citations)}, notes ${shown(notes)}, living ${anonymizeLiving ? 'anonymized' : 'shown'}`)
82
+ if (news) log(` news : ${count(news.deploys.length, 'deploy')}, ${count(news.pending.length, 'entry', 'entries')} not yet stamped`)
83
+ if (old) log(` news : previewing changes since ${since}`)
72
84
  log(`Wrote ${stats.pages} HTML pages.`)
73
85
  log(`Open it: open "${path.join(out, 'index.html')}"`)
74
86
  return stats
package/lib/config.mjs CHANGED
@@ -11,6 +11,7 @@ export const DEFAULTS = {
11
11
  anonymizeLiving: false,
12
12
  citations: true,
13
13
  notes: true,
14
+ news: null,
14
15
  }
15
16
  const PATHS = ['gedcom', 'out', 'mediaRoot']
16
17
  const FLAGS = ['anonymizeLiving', 'citations', 'notes']
@@ -26,7 +27,9 @@ export function loadConfig(file, overrides = {}) {
26
27
  for (const k of FLAGS) {
27
28
  if (typeof c[k] !== 'boolean') throw new Error(`${k} must be true or false, not ${JSON.stringify(c[k])} (in ${file})`)
28
29
  }
30
+ if (c.news !== null && typeof c.news !== 'string') throw new Error(`news must be a directory path, not ${JSON.stringify(c.news)} (in ${file})`)
29
31
  const base = path.dirname(path.resolve(file))
30
32
  for (const k of PATHS) c[k] = path.resolve(base, c[k])
33
+ if (c.news) c.news = path.resolve(base, c.news)
31
34
  return c
32
35
  }
package/lib/css.mjs CHANGED
@@ -8,6 +8,7 @@ h1{font-family:Georgia,serif;font-weight:700;margin:.2em 0}
8
8
  a{color:var(--accent);text-decoration:none}a:hover{text-decoration:underline}
9
9
  .sub{color:var(--mut);margin:0 0 1.2em}
10
10
  .back{font-size:.9em}
11
+ .updated{font-size:.85em;margin:0 0 .3em}
11
12
  .card{background:#fff;border:1px solid var(--line);border-radius:10px;
12
13
  padding:18px 20px;margin:14px 0}
13
14
  .evt{margin:.15em 0}.lbl{display:inline-block;min-width:64px;color:var(--mut);
package/lib/diff.mjs ADDED
@@ -0,0 +1,265 @@
1
+ // What changed on the site between two GEDCOMs: records as data, sentences under one build's rules.
2
+ import fs from 'node:fs'
3
+ import path from 'node:path'
4
+ import { parseGedcom, restricted } from './gedcom.mjs'
5
+ import { isLiving } from './living.mjs'
6
+ import { place, redact } from './redact.mjs'
7
+ import { when, known, cited, linkLabel as label, ONCE, IMG_EXT } from './render.mjs'
8
+
9
+ const NOUNS = {
10
+ BIRT: 'birth', CHR: 'christening', BAPM: 'baptism', DEAT: 'death', BURI: 'burial',
11
+ RESI: 'residence', EMIG: 'emigration', OCCU: 'occupation',
12
+ }
13
+
14
+ const fact = e => ({
15
+ tag: e.tag, type: e.type ?? '', val: e.val ?? '', date: e.date ?? '', phrase: e.phrase ?? '', plac: e.plac ?? '', resn: e.resn ?? '',
16
+ })
17
+ const factKey = e => JSON.stringify({ ...fact(e), resn: restricted(e) })
18
+ const citeKey = c => `${c.sour || c.title}\n${c.page}`
19
+ const sameCite = (a, b) => citeKey(a) === citeKey(b) && a.text === b.text && a.notes.join('\n') === b.notes.join('\n')
20
+ const spouses = f => (f ? [f.husb, f.wife].filter(Boolean) : [])
21
+ const union = (a, b) => [...new Set([...a, ...b])]
22
+
23
+ function match(olds, news, same, near = () => false) {
24
+ const left = [...olds], pairs = [], rest = []
25
+ const take = (n, ok) => {
26
+ const i = left.findIndex(o => ok(o, n))
27
+ return i < 0 ? null : left.splice(i, 1)[0]
28
+ }
29
+ for (const n of news) {
30
+ const o = take(n, same)
31
+ if (o) pairs.push([o, n, true])
32
+ else rest.push(n)
33
+ }
34
+ const added = []
35
+ for (const n of rest) {
36
+ const o = take(n, near)
37
+ if (o) pairs.push([o, n, false])
38
+ else added.push(n)
39
+ }
40
+ pairs.sort((a, b) => news.indexOf(a[1]) - news.indexOf(b[1]))
41
+ return { pairs, removed: left, added }
42
+ }
43
+
44
+ export function diffTrees(old, cur) {
45
+ const gone = [...old.indi.keys()].filter(id => !cur.indi.has(id))
46
+ if (gone.length * 2 > old.indi.size) {
47
+ throw new Error(`xrefs look renumbered: ${gone.length} of ${old.indi.size} people in the old file are missing from the new one`)
48
+ }
49
+ const out = []
50
+ for (const [id, p] of cur.indi) {
51
+ if (old.indi.has(id)) out.push(...personChanges(old.indi.get(id), p, old, cur))
52
+ else out.push({ kind: 'person', op: 'added', id })
53
+ }
54
+ for (const fid of union(cur.fam.keys(), old.fam.keys())) out.push(...marriageChanges(fid, old.fam.get(fid), cur.fam.get(fid)))
55
+ for (const id of gone) out.push({ kind: 'person', op: 'removed', id, was: structuredClone(old.indi.get(id)) })
56
+ return out
57
+ }
58
+
59
+ function personChanges(o, p, old, cur) {
60
+ const id = p.id, out = []
61
+ const push = (kind, op, from, to, extra) =>
62
+ out.push({ kind, op, id, ...extra, ...(from !== undefined && { from }), ...(to !== undefined && { to }) })
63
+ if (o.name !== p.name) push('name', 'changed', o.name, p.name)
64
+
65
+ const notes = (olds, news, event) => {
66
+ const text = ns => (ns ?? []).filter(n => n.trim())
67
+ const { removed, added } = match(text(olds), text(news), (a, b) => a === b)
68
+ if (removed.length === 1 && added.length === 1) return push('note', 'changed', removed[0], added[0], { event })
69
+ for (const n of removed) push('note', 'removed', n, undefined, { event })
70
+ for (const n of added) push('note', 'added', undefined, n, { event })
71
+ }
72
+ const cites = (olds, news, event) => {
73
+ const shown = cs => (cs ?? []).filter(cited)
74
+ const { pairs, removed, added } = match(shown(olds), shown(news), sameCite, (a, b) => citeKey(a) === citeKey(b))
75
+ for (const [a, b, same] of pairs) if (!same) push('citation', 'changed', structuredClone(a), structuredClone(b), { event })
76
+ for (const c of removed) push('citation', 'removed', structuredClone(c), undefined, { event })
77
+ for (const c of added) push('citation', 'added', undefined, structuredClone(c), { event })
78
+ }
79
+
80
+ const group = e => (e.tag === 'EVEN' ? `EVEN ${e.type ?? ''}` : e.tag)
81
+ for (const g of union(o.events.map(group), p.events.map(group))) {
82
+ const olds = o.events.filter(e => group(e) === g), news = p.events.filter(e => group(e) === g)
83
+ const near = (a, b) => (a.date && a.date === b.date) || (a.plac && a.plac === b.plac)
84
+ const { pairs, removed, added } = match(olds, news, (a, b) => factKey(a) === factKey(b), near)
85
+ for (const [a, b, same] of pairs) {
86
+ if (!same) push('event', 'changed', fact(a), fact(b))
87
+ if (restricted(a)) continue
88
+ notes(a.notes, b.notes, fact(b))
89
+ cites(a.sources, b.sources, fact(b))
90
+ }
91
+ for (const e of removed) push('event', 'removed', fact(e))
92
+ for (const e of added) push('event', 'added', undefined, fact(e))
93
+ if (ONCE.has(g)) {
94
+ const was = olds.find(e => !restricted(e)), now = news.find(e => !restricted(e))
95
+ const counterpart = pairs.find(([a]) => a === was)?.[1]
96
+ if (counterpart && now && counterpart !== now && !restricted(counterpart)) push('preferred', 'changed', fact(counterpart), fact(now))
97
+ }
98
+ }
99
+ notes(o.notes, p.notes)
100
+ cites(o.sources, p.sources)
101
+
102
+ const media = match(o.media, p.media, (a, b) => a.file === b.file && a.title === b.title, (a, b) => a.file === b.file)
103
+ for (const [a, b, same] of media.pairs) if (!same) push('media', 'changed', { ...a }, { ...b })
104
+ for (const m of media.removed) push('media', 'removed', { ...m })
105
+ for (const m of media.added) push('media', 'added', undefined, { ...m })
106
+
107
+ // Which side of the file records a link (only) is bookkeeping, not a change to report.
108
+ const links = q => new Map(q.parentFams.map(({ only, ...l }) => [l.fam, l]))
109
+ const was = links(o), now = links(p)
110
+ if (p.famc && p.famc !== o.famc) push('parents', 'main', undefined, undefined, { fam: p.famc, parents: spouses(cur.fam.get(p.famc)) })
111
+ for (const fam of union(was.keys(), now.keys())) {
112
+ const a = was.get(fam), b = now.get(fam)
113
+ const parents = spouses((b ? cur : old).fam.get(fam))
114
+ if (a && b) {
115
+ if (label(a) !== label(b)) push('parents', 'changed', { ...a }, { ...b }, { fam, parents })
116
+ } else if (b) {
117
+ if (fam !== p.famc) push('parents', 'added', undefined, { ...b }, { fam, parents })
118
+ } else if (fam !== o.famc || !p.famc) push('parents', 'removed', { ...a }, undefined, { fam, parents })
119
+ }
120
+ return out
121
+ }
122
+
123
+ function marriageChanges(fam, a, b) {
124
+ const was = spouses(a), now = spouses(b), marr = f => fact({ tag: 'MARR', ...f.marr })
125
+ if (was.length === 2 && now.length === 2 && was[0] === now[0] && was[1] === now[1]) {
126
+ const from = marr(a), to = marr(b)
127
+ return factKey(from) === factKey(to) ? [] : [{ kind: 'marriage', op: 'changed', fam, spouses: now, from, to }]
128
+ }
129
+ return [[a, was, 'removed'], [b, now, 'added']].filter(([, pair]) => pair.length === 2)
130
+ .map(([f, pair, op]) => ({ kind: 'marriage', op, fam, spouses: pair, marr: marr(f) }))
131
+ }
132
+
133
+ export function describe(records, tree, { anonymizeLiving = false, notes = true, citations = true } = {}, { year } = {}) {
134
+ const people = op => records.filter(r => r.kind === 'person' && r.op === op)
135
+ const removed = new Map(people('removed').map(r => [r.id, r.was])), added = new Set(people('added').map(r => r.id))
136
+ const person = id => tree.indi.get(id) ?? removed.get(id)
137
+ const hidden = id => anonymizeLiving && (!person(id) || isLiving(person(id), year))
138
+ const name = id => person(id)?.name || '(unnamed)'
139
+ const names = ids => ids.map(name).join(' and ')
140
+ const quote = !anonymizeLiving
141
+ const withheld = new Set(anonymizeLiving
142
+ ? [...tree.indi.values(), ...removed.values()].filter(p => isLiving(p, year)).flatMap(p => p.media.map(m => m.file)) : [])
143
+ const order = new Map([...tree.indi.keys()].map((id, i) => [id, i]))
144
+ const first = ids => [...ids].sort((a, b) => (order.get(a) ?? Infinity) - (order.get(b) ?? Infinity))[0]
145
+
146
+ const items = [], groups = new Map()
147
+ const under = (id, line) => {
148
+ if (!groups.has(id)) {
149
+ groups.set(id, { id, text: `${name(id)} (${id})`, lines: [] })
150
+ items.push(groups.get(id))
151
+ }
152
+ groups.get(id).lines.push(line)
153
+ }
154
+
155
+ const folded = new Map()
156
+ for (const r of records) {
157
+ if (r.kind !== 'marriage' || r.op === 'changed' || r.spouses.some(hidden)) continue
158
+ const who = r.spouses.find(id => (r.op === 'added' ? added : removed).has(id))
159
+ if (who) folded.set(r, who)
160
+ }
161
+ const marriagesOf = id => {
162
+ const partners = [...folded].filter(([, who]) => who === id).map(([r]) => r.spouses.find(s => s !== id))
163
+ if (!partners.length) return ''
164
+ const pron = { M: 'his', F: 'her' }[person(id).sex] ?? 'their'
165
+ return ` and ${pron} marriage${partners.length > 1 ? 's' : ''} to ${names(partners)}`
166
+ }
167
+
168
+ const noun = e => (e.tag === 'MARR' ? 'marriage' : e.tag !== 'EVEN' ? NOUNS[e.tag] : e.type === 'Living' ? 'residence' : e.type || 'event')
169
+ const article = w => (/^[aeiou]/i.test(w) ? 'an' : 'a')
170
+ const where = e => place(known(e.plac)).replace(/[, ]+$/, '')
171
+ const bits = e => [known(e.val) !== 'Y' && known(e.val), when(e), where(e)].filter(Boolean).join(', ')
172
+ const factText = e => [noun(e), bits(e)].filter(Boolean).join(' ')
173
+ const changed = (from, to, what) => {
174
+ const field = from.val !== to.val ? '' : from.plac === to.plac ? 'date' : from.date === to.date && from.phrase === to.phrase ? 'place' : ''
175
+ const show = e => ({ date: when, place: where }[field] ?? bits)(e) || 'none'
176
+ return `Changed ${what(field)} ${quote && !restricted(from) ? `from ${show(from)} ` : ''}to ${show(to)}`
177
+ }
178
+ const citeText = c => [c.title.trim(), c.page.trim(), c.text.trim() && `“${c.text.trim()}”`].filter(Boolean).join(', ')
179
+ const mediaKind = m => (IMG_EXT.has(path.extname(m.file).toLowerCase()) ? 'photo' : 'document')
180
+
181
+ const line = r => {
182
+ const ctx = prep => (r.event ? ` ${prep} the ${noun(r.event)}` : '')
183
+ const { from, to } = r
184
+ if (r.event && restricted(r.event)) return null
185
+ switch (r.kind) {
186
+ case 'name':
187
+ return quote ? `Changed name from ${from} to ${to}` : `Changed name to ${to}`
188
+ case 'event':
189
+ if ((to && restricted(to)) || (!to && restricted(from))) return null
190
+ if (!from || restricted(from)) return `Added: ${factText(to)}`
191
+ if (!to) return quote ? `Removed: ${factText(from)}` : `Removed ${article(noun(from))} ${noun(from)} record`
192
+ return changed(from, to, field => [noun(to), field].filter(Boolean).join(' '))
193
+ case 'preferred':
194
+ return `Preferred ${noun(to)} is now ${bits(to)}` + (quote ? `, not ${bits(from)}` : '')
195
+ case 'note': {
196
+ if (!notes) return null
197
+ const text = n => `“${n.replace(/\s+/g, ' ').trim()}”`
198
+ if (r.op === 'added') return `Added a note${ctx('to')}: ${text(to)}`
199
+ if (r.op === 'removed') return `Removed a note${ctx('from')}` + (quote ? `: ${text(from)}` : '')
200
+ return `Changed a note${ctx('on')} to ${text(to)}`
201
+ }
202
+ case 'citation':
203
+ if (!citations) return null
204
+ if (r.op === 'added') return `Added a citation${ctx('to')}: ${citeText(to)}`
205
+ if (r.op === 'removed') return `Removed a citation${ctx('from')}` + (quote ? `: ${citeText(from)}` : '')
206
+ return `Changed a citation${ctx('on')}: ${citeText(to)}`
207
+ case 'media': {
208
+ const m = to ?? from, title = x => x.title || path.basename(x.file)
209
+ if (withheld.has(m.file)) return null
210
+ if (r.op === 'added') return `Added a ${mediaKind(m)}: ${title(m)}`
211
+ if (r.op === 'removed') return `Removed a ${mediaKind(m)}` + (quote ? `: ${title(m)}` : '')
212
+ return `Retitled a ${mediaKind(m)} ${quote ? `from ${title(from)} ` : ''}to ${title(to)}`
213
+ }
214
+ case 'parents': {
215
+ if (r.parents.some(hidden)) return null
216
+ const who = names(r.parents) || 'unrecorded parents'
217
+ let op = r.op
218
+ if (anonymizeLiving && op !== 'main') {
219
+ const seen = l => !!l && l.stat !== 'DISPROVEN', before = seen(from), after = seen(to)
220
+ if (!before && !after) return null
221
+ if (before !== after) op = after ? 'added' : 'removed'
222
+ if (op === 'added' && r.fam === person(r.id).famc) return null
223
+ }
224
+ if (op === 'main') return `Now listed as a child of ${who}`
225
+ if (op === 'added') return `Now also listed as a child of ${who}` + (label(to) ? ` (${label(to)})` : '')
226
+ if (op === 'removed') return `No longer listed as a child of ${who}`
227
+ return `Relabeled as a child of ${who} from ${label(from) || 'no label'} to ${label(to) || 'no label'}`
228
+ }
229
+ }
230
+ }
231
+
232
+ for (const r of records) {
233
+ if (r.kind === 'person') {
234
+ if (hidden(r.id)) continue
235
+ const p = person(r.id), parents = r.op === 'added' ? spouses(tree.fam.get(p.famc)) : []
236
+ const child = parents.length && !parents.some(hidden) ? `, a child of ${names(parents)}` : ''
237
+ const wed = marriagesOf(r.id)
238
+ items.push({ id: r.id, text: `${r.op === 'added' ? 'Added' : 'Removed'}: ${name(r.id)} (${r.id})${child}${child && wed && ','}${wed}`, lines: [] })
239
+ } else if (r.kind === 'marriage') {
240
+ if (folded.has(r) || r.spouses.some(hidden)) continue
241
+ const id = first(r.spouses), other = name(r.spouses.find(s => s !== id))
242
+ const details = () => (restricted(r.marr) || !bits(r.marr) ? '' : `, ${bits(r.marr)}`)
243
+ if (r.op === 'added') under(id, `Added: marriage to ${other}${details()}`)
244
+ else if (r.op === 'removed') under(id, quote ? `Removed: marriage to ${other}${details()}` : `Removed a marriage to ${other}`)
245
+ else if (!restricted(r.to)) under(id, changed(r.from, r.to, field => [field, field && 'of', 'the marriage to', other].filter(Boolean).join(' ')))
246
+ } else if (!hidden(r.id)) {
247
+ const text = line(r)
248
+ if (text) under(r.id, text)
249
+ }
250
+ }
251
+ return items.map(i => ({ ...i, text: redact(i.text), lines: i.lines.map(redact) }))
252
+ }
253
+
254
+ export const formatChanges = items =>
255
+ items.map(i => [i.text, ...i.lines.map(l => ` ${l}`)].join('\n')).join('\n') || 'No changes.'
256
+
257
+ export function readGedcom(f) {
258
+ if (!fs.statSync(f, { throwIfNoEntry: false })?.isFile()) throw new Error(`GEDCOM not found: ${f}`)
259
+ return parseGedcom(fs.readFileSync(f, 'utf8'))
260
+ }
261
+
262
+ export function changeReport(config, oldFile) {
263
+ const old = readGedcom(oldFile), cur = readGedcom(config.gedcom)
264
+ return formatChanges(describe(diffTrees(old, cur), cur, config))
265
+ }
package/lib/gedcom.mjs CHANGED
@@ -7,13 +7,13 @@ export const restricted = e => (e.resn ?? '').toUpperCase().split(/[\s,]+/).some
7
7
 
8
8
  export function parseGedcom(text) {
9
9
  const indi = new Map(), fam = new Map(), obje = new Map(), sour = new Map(), pointers = []
10
- let cur = null, ctype = null, evt = null, media = null, sub = null, cite = null, citeLvl = 0, cont = null, shownName = false
10
+ let cur = null, ctype = null, evt = null, famc = null, media = null, sub = null, cite = null, citeLvl = 0, cont = null, shownName = false
11
11
  const startCitation = (val, lvl, list) => {
12
- cite = { title: '', page: '', text: '', notes: [] }
12
+ const ptr = val.match(/^@(\w+)@$/)
13
+ cite = { sour: ptr?.[1] ?? '', title: '', page: '', text: '', notes: [] }
13
14
  citeLvl = lvl
14
15
  list.push(cite)
15
- const ptr = val.match(/^@(\w+)@$/)
16
- if (ptr) pointers.push([cite, ptr[1]])
16
+ if (ptr) pointers.push(cite)
17
17
  else {
18
18
  cite.title = val.trim()
19
19
  cont = { lvl, obj: cite, key: 'title' }
@@ -26,13 +26,13 @@ export function parseGedcom(text) {
26
26
  if (!m) continue
27
27
  const lvl = Number(m[1]), rest = m[2]
28
28
  if (lvl === 0) {
29
- cur = ctype = evt = media = cite = cont = null
29
+ cur = ctype = evt = famc = media = cite = cont = null
30
30
  const r = rest.match(/^@(\w+)@ (\w+)$/)
31
31
  if (r && r[2] === 'INDI') {
32
32
  ctype = 'INDI'
33
33
  if (!indi.has(r[1])) indi.set(r[1], {
34
34
  id: r[1], name: '', surn: '', giv: '', sex: '',
35
- birt: {}, deat: {}, events: [], famc: null, fams: [], media: [], notes: [], sources: [],
35
+ birt: {}, deat: {}, events: [], famc: null, parentFams: [], fams: [], media: [], notes: [], sources: [],
36
36
  })
37
37
  cur = indi.get(r[1])
38
38
  } else if (r && r[2] === 'FAM') {
@@ -92,7 +92,7 @@ export function parseGedcom(text) {
92
92
  }
93
93
  } else if (ctype === 'INDI') {
94
94
  if (lvl === 1) {
95
- evt = null
95
+ evt = famc = null
96
96
  shownName = tag === 'NAME' && !cur.name
97
97
  if (shownName) {
98
98
  cur.name = val.replaceAll('/', '').trim()
@@ -103,7 +103,10 @@ export function parseGedcom(text) {
103
103
  else if (EVENTS.has(tag)) {
104
104
  evt = { tag, val: val.trim() }
105
105
  cur.events.push(evt)
106
- } else if (tag === 'FAMC') cur.famc = stripAt(val)
106
+ } else if (tag === 'FAMC') {
107
+ famc = parentLink(stripAt(val))
108
+ cur.parentFams.push(famc)
109
+ }
107
110
  else if (tag === 'FAMS') cur.fams.push(stripAt(val))
108
111
  else if (tag === 'OBJE') cur.media.push(stripAt(val))
109
112
  else if (note) cont = { lvl, obj: cur.notes, key: cur.notes.push(val) - 1 }
@@ -118,6 +121,10 @@ export function parseGedcom(text) {
118
121
  else if (note) cont = { lvl, obj: (evt.notes ??= []), key: evt.notes.push(val) - 1 }
119
122
  } else if (evt && phrase) {
120
123
  evt.phrase = val.trim()
124
+ } else if (famc && lvl === 2 && (tag === 'PEDI' || tag === 'STAT')) {
125
+ famc[tag.toLowerCase()] = val.trim().toUpperCase()
126
+ } else if (famc && lvl === 3 && sub === 'PEDI' && tag === 'PHRASE') {
127
+ famc.phrase = val.trim()
121
128
  }
122
129
  } else {
123
130
  if (lvl === 1) {
@@ -133,7 +140,7 @@ export function parseGedcom(text) {
133
140
  } else if (evt && phrase) evt.phrase = val.trim()
134
141
  }
135
142
  }
136
- for (const [c, id] of pointers) c.title = sour.get(id)?.title ?? ''
143
+ for (const c of pointers) c.title = sour.get(c.sour)?.title ?? ''
137
144
  for (const p of indi.values()) {
138
145
  for (const [key, tag] of [['birt', 'BIRT'], ['deat', 'DEAT']]) {
139
146
  const all = p.events.filter(e => e.tag === tag)
@@ -141,7 +148,48 @@ export function parseGedcom(text) {
141
148
  }
142
149
  p.media = p.media.flatMap(id => obje.get(id) ?? [])
143
150
  }
144
- return { indi, fam }
151
+ const warnings = checkLinks(indi, fam)
152
+ for (const p of indi.values()) p.famc = p.parentFams.find(l => l.stat !== 'DISPROVEN' && fam.has(l.fam))?.fam ?? null
153
+ return { indi, fam, warnings }
154
+ }
155
+
156
+ export const parentLink = fam => ({ fam, pedi: '', phrase: '', stat: '' })
157
+
158
+ // Children in a family whose main parent family it is; ids with no record stay in.
159
+ export const mainChildren = (f, indi) => f.chil.filter(c => !indi.has(c) || indi.get(c).famc === f.id)
160
+
161
+ // Warns about links recorded on one side only, and shows a child link on both sides,
162
+ // marked with the side that recorded it (only: 'child' or 'family').
163
+ function checkLinks(indi, fam) {
164
+ const warnings = []
165
+ const warn = (from, tag, to, back) => warnings.push(`${from} ${tag} @${to}@ has no matching ${back} in ${to}`)
166
+ for (const p of indi.values()) {
167
+ for (const link of p.parentFams) {
168
+ const fid = link.fam
169
+ const f = fam.get(fid)
170
+ if (f?.chil.includes(p.id)) continue
171
+ warn(p.id, 'FAMC', fid, 'CHIL')
172
+ if (!f) continue
173
+ link.only = 'child'
174
+ f.chil.push(p.id)
175
+ }
176
+ for (const fid of p.fams) {
177
+ const f = fam.get(fid)
178
+ if (f?.husb !== p.id && f?.wife !== p.id) warn(p.id, 'FAMS', fid, 'HUSB or WIFE')
179
+ }
180
+ }
181
+ for (const f of fam.values()) {
182
+ for (const [tag, id] of [['HUSB', f.husb], ['WIFE', f.wife]]) {
183
+ if (id && !indi.get(id)?.fams.includes(f.id)) warn(f.id, tag, id, 'FAMS')
184
+ }
185
+ for (const c of f.chil) {
186
+ const p = indi.get(c)
187
+ if (p?.parentFams.some(l => l.fam === f.id)) continue
188
+ warn(f.id, 'CHIL', c, 'FAMC')
189
+ p?.parentFams.push({ ...parentLink(f.id), only: 'family' })
190
+ }
191
+ }
192
+ return warnings
145
193
  }
146
194
 
147
195
  const stripAt = s => s.replace(/^@+|@+$/g, '')
package/lib/hourglass.mjs CHANGED
@@ -3,6 +3,7 @@
3
3
  // "+N more" box so the chart stays a readable neighbourhood, never a whole tree.
4
4
  import { esc } from './html.mjs'
5
5
  import { byBirth } from './dates.mjs'
6
+ import { mainChildren } from './gedcom.mjs'
6
7
 
7
8
  export const BOX = { w: 150, h: 44 }
8
9
  export const CAPS = { sibs: 3, spouses: 2, kids: 4 } // sibs is per side of the focus
@@ -24,7 +25,8 @@ export function hourglassLayout(pid, { indi, fam }, caps = CAPS) {
24
25
  return f ? [has(f.husb), has(f.wife)].filter(Boolean) : []
25
26
  }
26
27
  const parents = parentsOf(pid)
27
- const chil = (fam.get(indi.get(pid)?.famc)?.chil ?? []).filter(c => c === pid || indi.has(c)).sort(byBirth(indi))
28
+ const pf = fam.get(indi.get(pid)?.famc)
29
+ const chil = (pf ? mainChildren(pf, indi) : []).filter(c => indi.has(c)).sort(byBirth(indi))
28
30
  const older = chil.slice(0, chil.indexOf(pid)), younger = chil.slice(chil.indexOf(pid) + 1)
29
31
  const spouses = [], kids = []
30
32
  for (const fid of indi.get(pid)?.fams ?? []) {
@@ -32,7 +34,7 @@ export function hourglassLayout(pid, { indi, fam }, caps = CAPS) {
32
34
  if (!f) continue
33
35
  const sp = has(f.husb === pid ? f.wife : f.husb)
34
36
  if (sp) spouses.push(sp)
35
- kids.push(...f.chil.filter(c => indi.has(c)))
37
+ kids.push(...mainChildren(f, indi).filter(c => indi.has(c)))
36
38
  }
37
39
  kids.sort(byBirth(indi))
38
40
  const grands = parents.map(parentsOf)
package/lib/kin.mjs CHANGED
@@ -1,4 +1,5 @@
1
1
  // Shortest parent/child path from anyone to the primary person (BFS).
2
+ import { mainChildren } from './gedcom.mjs'
2
3
 
3
4
  export class Kin {
4
5
  constructor(indi, fam, primaryId) {
@@ -32,7 +33,7 @@ export class Kin {
32
33
  const kids = []
33
34
  for (const fid of this.indi.get(pid)?.fams ?? []) {
34
35
  const f = this.fam.get(fid)
35
- if (f) kids.push(...f.chil)
36
+ if (f) kids.push(...mainChildren(f, this.indi))
36
37
  }
37
38
  return kids
38
39
  }
package/lib/living.mjs CHANGED
@@ -1,4 +1,5 @@
1
1
  // Living people on a public site: kept in the tree for its shape, shown only as "Private".
2
+ import { parentLink } from './gedcom.mjs'
2
3
 
3
4
  export function isLiving(p, year = new Date().getFullYear()) {
4
5
  if (p.deat?.tag) return false
@@ -7,17 +8,26 @@ export function isLiving(p, year = new Date().getFullYear()) {
7
8
  return !years.length || year - Math.max(...years) <= 100
8
9
  }
9
10
 
11
+ // A Private person keeps only the main parent family, without PEDI or STAT.
10
12
  const stub = ({ id, famc, fams }) => ({
11
13
  id, name: 'Private', surn: '', giv: '', sex: '', private: true,
12
- birt: {}, deat: {}, events: [], famc, fams, media: [], notes: [], sources: [],
14
+ birt: {}, deat: {}, events: [], famc, parentFams: famc ? [parentLink(famc)] : [], fams, media: [], notes: [], sources: [],
13
15
  })
14
16
 
15
17
  export function anonymize(indi, fam, year) {
16
18
  const living = new Set([...indi.values()].filter(p => isLiving(p, year)).map(p => p.id))
17
19
  const withheld = new Set([...indi.values()].filter(p => living.has(p.id)).flatMap(p => p.media.map(m => m.file)))
18
- const keep = p => p.media.some(m => withheld.has(m.file)) ? { ...p, media: p.media.filter(m => !withheld.has(m.file)) } : p
19
- return {
20
- indi: new Map([...indi].map(([id, p]) => [id, living.has(id) ? stub(p) : keep(p)])),
21
- fam: new Map([...fam].map(([id, f]) => [id, living.has(f.husb) || living.has(f.wife) ? { ...f, marr: {} } : f])),
20
+ const keep = p => {
21
+ const media = p.media.filter(m => !withheld.has(m.file))
22
+ const parentFams = p.parentFams?.filter(l => l.stat !== 'DISPROVEN')
23
+ return media.length < p.media.length || parentFams?.length < p.parentFams?.length ? { ...p, media, parentFams } : p
22
24
  }
25
+ const people = new Map([...indi].map(([id, p]) => [id, living.has(id) ? stub(p) : keep(p)]))
26
+ const listed = (c, f) => people.get(c)?.parentFams?.some(l => l.fam === f.id) ?? true
27
+ const shown = f => {
28
+ const chil = f.chil.filter(c => listed(c, f))
29
+ const g = chil.length < f.chil.length ? { ...f, chil } : f
30
+ return living.has(f.husb) || living.has(f.wife) ? { ...g, marr: {} } : g
31
+ }
32
+ return { indi: people, fam: new Map([...fam].map(([id, f]) => [id, shown(f)])) }
23
33
  }
package/lib/news.mjs ADDED
@@ -0,0 +1,173 @@
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 heading = `<h2 id=${anchor}>${esc(pending ? 'Not yet published' : longDate(d.date))}</h2>`
149
+ const html = body ? heading + body : pending ? `${heading}<p class=sub>Nothing yet.</p>` : ''
150
+ return { anchor, date: d.date, pending, html, people }
151
+ })
152
+ }
153
+
154
+ // For each person changed or mentioned: the latest stamped section, and whether the preview has them.
155
+ // Sections are newest first.
156
+ export function lastUpdated(sections) {
157
+ const updated = new Map()
158
+ for (const s of sections) {
159
+ for (const id of s.people) {
160
+ const u = updated.get(id) ?? {}
161
+ if (s.pending) u.pending = true
162
+ else if (!u.date) Object.assign(u, { anchor: s.anchor, date: longDate(s.date, 3) })
163
+ updated.set(id, u)
164
+ }
165
+ }
166
+ return updated
167
+ }
168
+
169
+ export function whatsNewPage(sections, r) {
170
+ const title = "What's new"
171
+ return r.page(title, `<p class=back><a href="index.html">&larr; All people</a></p><h1>${esc(title)}</h1>` +
172
+ (sections.map(s => s.html).join('') || '<p class=sub>Nothing yet.</p>'))
173
+ }
package/lib/render.mjs CHANGED
@@ -1,7 +1,7 @@
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'
@@ -10,7 +10,7 @@ export { esc, yr }
10
10
  export const DEFAULT_TITLE = 'Family Tree'
11
11
  export const IMG_EXT = new Set(['.jpg', '.jpeg', '.png', '.gif', '.webp'])
12
12
 
13
- const known = s => ((s ?? '').trim() === '?' ? '' : s ?? '')
13
+ export const known = s => ((s ?? '').trim() === '?' ? '' : s ?? '')
14
14
 
15
15
  export function life(p) {
16
16
  const b = restricted(p.birt) ? '' : yr(p.birt.date), d = restricted(p.deat) ? '' : yr(p.deat.date)
@@ -40,9 +40,9 @@ const LABELS = {
40
40
  }
41
41
  const ORDER = { BIRT: -3, CHR: -2, BAPM: -1, DEAT: 1, BURI: 2 }
42
42
  // Repeats of these are alternate versions; GEDCOM 7 puts the preferred one first.
43
- const ONCE = new Set(Object.keys(ORDER))
43
+ export const ONCE = new Set(Object.keys(ORDER))
44
44
  const counter = (n = 0) => () => ++n
45
- const cited = c => [c.title, c.page, c.text, ...c.notes].some(s => s.trim())
45
+ export const cited = c => [c.title, c.page, c.text, ...c.notes].some(s => s.trim())
46
46
  const evtBits = e => {
47
47
  const bits = [], val = known(e.val), plac = place(known(e.plac))
48
48
  if (val && val !== 'Y') bits.push(esc(redact(val)))
@@ -50,11 +50,17 @@ const evtBits = e => {
50
50
  if (plac) bits.push(esc(plac.replace(/[, ]+$/, '')))
51
51
  return bits
52
52
  }
53
+ // How a child belongs to a parent family; a main family born into needs no label.
54
+ export const linkLabel = (l, main = false) => [
55
+ l.pedi === 'OTHER' ? l.phrase || 'other' : main && l.pedi === 'BIRTH' ? '' : l.pedi.toLowerCase(),
56
+ l.stat.toLowerCase(),
57
+ l.only && `on the ${l.only === 'child' ? "child's" : 'family'} record only`,
58
+ ].filter(Boolean).join(', ')
53
59
  const notesHtml = notes => (notes ?? []).filter(n => n.trim()).map(n => `<div class=enote>${esc(redact(n))}</div>`).join('')
54
60
 
55
61
  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 })
62
+ constructor({ indi, fam, kin, copied, title = DEFAULT_TITLE, source = '', citations = true, notes = true, news = false, updated = new Map() }) {
63
+ Object.assign(this, { indi, fam, kin, copied, title, source, citations, notes, news, updated })
58
64
  }
59
65
 
60
66
  page(title, body) {
@@ -111,6 +117,43 @@ export class Renderer {
111
117
  return text && !restricted(mar) ? ` <span class=yr>(m. ${esc(text)})</span>` : ''
112
118
  }
113
119
 
120
+ parentIds(fid) {
121
+ const f = this.fam.get(fid)
122
+ return [f.husb, f.wife].filter(Boolean)
123
+ }
124
+
125
+ nameLink(pid) {
126
+ const p = this.indi.get(pid)
127
+ return p ? `<a href="${pid}.html">${esc(p.name || '(unnamed)')}</a>` : this.plink(pid)
128
+ }
129
+
130
+ parentsHtml(p) {
131
+ const { fam } = this
132
+ const links = (p.parentFams ?? []).filter(l => fam.has(l.fam))
133
+ const main = links.find(l => l.fam === p.famc)
134
+ const items = main ? this.parentIds(main.fam).map(id => this.plink(id)) : []
135
+ for (const l of links) {
136
+ if (l === main) continue
137
+ const label = linkLabel(l)
138
+ const names = this.parentIds(l.fam).map(id => this.plink(id)).join(' and ') || 'unrecorded parents'
139
+ items.push(`Also listed as a child of ${names}` + (label ? ` <span class=pref>${esc(label)}</span>` : ''))
140
+ }
141
+ if (!items.length) return ''
142
+ const label = main && linkLabel(main, true)
143
+ return `<h2>Parents${label ? `<span class=pref>${esc(label)}</span>` : ''}</h2>` +
144
+ '<ul class=rel>' + items.map(x => `<li>${x}</li>`).join('') + '</ul>'
145
+ }
146
+
147
+ // A child whose main parent family is another one, or whose link is one-sided, says so.
148
+ childHtml(c, fid) {
149
+ const k = this.indi.get(c)
150
+ const link = k?.parentFams?.find(l => l.fam === fid)
151
+ if (!k || (k.famc === fid && !link?.only)) return this.plink(c)
152
+ const main = k.famc !== fid && this.fam.has(k.famc) && this.parentIds(k.famc).map(id => this.nameLink(id)).join(' and ')
153
+ const note = [link && esc(linkLabel(link)), main && `main parents: ${main}`].filter(Boolean).join('; ')
154
+ return this.plink(c) + (note ? ` <span class=yr>(${note})</span>` : '')
155
+ }
156
+
114
157
  chartSvg(pid) {
115
158
  const label = id => {
116
159
  const p = this.indi.get(id)
@@ -140,6 +183,14 @@ export class Renderer {
140
183
  b.push('<p class=sub>Details of living people are withheld.</p>')
141
184
  return { html: this.page(p.name, b.join('')), withPhoto: false }
142
185
  }
186
+ const up = this.updated.get(pid)
187
+ if (up) {
188
+ const links = [
189
+ up.date && `<a href="whats-new.html#${up.anchor}">Updated ${esc(up.date)}</a>`,
190
+ up.pending && '<a href="whats-new.html#pending">Changed since last deploy</a>',
191
+ ]
192
+ b.push(`<p class=updated>${links.filter(Boolean).join(' · ')}</p>`)
193
+ }
143
194
  const meta = [{ M: 'Male', F: 'Female' }[p.sex] ?? '', life(p)].filter(Boolean).join(' &middot; ')
144
195
  if (meta) b.push(`<p class=sub>${meta}</p>`)
145
196
 
@@ -170,12 +221,8 @@ export class Renderer {
170
221
  if (vit) b.push(`<div class=card>${vit}</div>`)
171
222
 
172
223
  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>')
224
+ const par = this.parentsHtml(p)
225
+ if (par) rel.push(par)
179
226
  for (const fid of p.fams) {
180
227
  const f = fam.get(fid)
181
228
  if (!f) continue
@@ -184,12 +231,12 @@ export class Renderer {
184
231
  if (spouse) {
185
232
  sp.push(`<li>${this.plink(spouse)}${this.marriageHtml(f.marr)}</li>`)
186
233
  }
187
- const kids = [...f.chil].sort(byBirth(this.indi)).map(c => `<li>${this.plink(c)}</li>`)
234
+ const kids = [...f.chil].sort(byBirth(this.indi)).map(c => `<li>${this.childHtml(c, fid)}</li>`)
188
235
  rel.push('<h2>Spouse &amp; children</h2><ul class=rel>' + sp.join('') + kids.join('') + '</ul>')
189
236
  }
190
237
  if (rel.length) b.push(rel.join(''))
191
238
 
192
- const sibs = p.famc ? (fam.get(p.famc)?.chil ?? []).filter(c => c !== pid).sort(byBirth(this.indi)) : []
239
+ const sibs = fam.has(p.famc) ? mainChildren(fam.get(p.famc), this.indi).filter(c => c !== pid).sort(byBirth(this.indi)) : []
193
240
  if (sibs.length) b.push('<h2>Siblings</h2><ul class=rel>' + sibs.map(c => `<li>${this.plink(c)}</li>`).join('') + '</ul>')
194
241
 
195
242
  const desc = this.descendantsHtml(pid, 3)
@@ -230,6 +277,7 @@ export class Renderer {
230
277
  const body = `<h1>${esc(this.title)}</h1>` +
231
278
  `<p class=sub>${this.indi.size} individuals &middot; ${this.fam.size} families ` +
232
279
  `&middot; ${withphoto} with photos</p>` +
280
+ (this.news ? `<p><a href="whats-new.html">${esc("What's new")}</a></p>` : '') +
233
281
  hero +
234
282
  '<h2>All people</h2>' +
235
283
  '<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.4.0",
4
4
  "type": "module",
5
5
  "description": "Static HTML family-tree site from a GEDCOM file",
6
6
  "license": "MIT",