kinsite 0.2.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
 
@@ -37,32 +40,241 @@ For your own tree, write a `kinsite.config.json` next to your GEDCOM:
37
40
  | `out` | Output directory (deleted and rebuilt on each run) | `site` |
38
41
  | `mediaRoot` | Base directory for relative `FILE` paths of photos and documents | the config's directory |
39
42
  | `anonymizeLiving` | Show living people only as "Private", for a public site (see Goals) | `false` |
43
+ | `citations` | Show source citations on person pages; event notes follow `notes` | `true` |
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 |
40
46
 
41
47
  Relative paths resolve against the config file's directory. `FOCUS=I3` or `OUT=dir` in
42
- the environment override the config for one run.
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
50
+ published, e.g. `published : citations shown, notes hidden, living anonymized`.
51
+
52
+ ### A research site or a public site
53
+
54
+ The defaults suit a **research site**: one you and other researchers reach behind
55
+ proper authorization, showing everything the GEDCOM records, living people included.
56
+
57
+ ```json
58
+ {
59
+ "gedcom": "my-tree.ged",
60
+ "title": "My Family Tree (research)",
61
+ "out": "site-research"
62
+ }
63
+ ```
64
+
65
+ A **public site** is for relatives and anyone else to browse without a login: living
66
+ people appear only as "Private", and the working notes and citations behind the
67
+ research are left out.
68
+
69
+ ```json
70
+ {
71
+ "gedcom": "my-tree.ged",
72
+ "title": "My Family Tree",
73
+ "out": "site-public",
74
+ "anonymizeLiving": true,
75
+ "citations": false,
76
+ "notes": false
77
+ }
78
+ ```
79
+
80
+ Each setting stands alone, so a public site can still show citations or notes. With
81
+ `anonymizeLiving`, a living person's own notes and citations are withheld whatever these
82
+ say, but notes and citations on other people's records are shown as written: they can
83
+ still name a living relative. A citation's own notes go with the citation, so turning off
84
+ only `notes` still publishes them.
43
85
 
44
86
  Everything in `sample/` is invented: names, places, dates, numbers and addresses.
45
87
 
88
+ ## Facts and their sources
89
+
90
+ When a GEDCOM records a birth, christening, baptism, death or burial more than once,
91
+ the person page shows the versions together, in file order, which GEDCOM 7 uses for
92
+ preference: the first shown is marked preferred and the rest alternates. Versions
93
+ with nothing to show, and those marked `RESN PRIVACY` or `CONFIDENTIAL`, are left out.
94
+ Life spans and the birth-year sort use the first version with a year. With
95
+ `anonymizeLiving`, every birth version counts toward deciding who is living,
96
+ restricted or not.
97
+
98
+ Under each event come its notes and citations, numbered: source title, page, and the
99
+ quoted text of the record. Citations on the person record or on the name shown are
100
+ listed under Sources at the foot of the page. Marriages don't show notes or citations
101
+ yet.
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
+
46
253
  ## Goals
47
254
 
48
255
  - **Static output only.** No server, no database. JavaScript in the browser is fine,
49
256
  but every page must be readable without it.
50
257
  - **No contact details.** The build removes phone numbers, email addresses, street
51
- addresses and PO boxes from places and notes; never reads contact fields (`ADDR`,
258
+ addresses and PO boxes from places, notes and citations; never reads contact fields (`ADDR`,
52
259
  `PHON`, `EMAIL`); and hides events marked `RESN PRIVACY` or `CONFIDENTIAL`.
53
260
  - **Living people suited to the audience.** By default living people appear as-is,
54
261
  which is fine for a site behind proper authorization. For a public site, set
55
262
  `"anonymizeLiving": true`: anyone with no `DEAT` event who was born within the last
56
263
  100 years, or has no birth date, still appears in the tree but only as "Private",
57
- with name, sex, dates, places, events, marriages, notes and media withheld and their
264
+ with name, sex, dates, places, events, marriages, notes, citations and media withheld and their
58
265
  media files not copied. A photo also attached to someone else, such as a group
59
266
  photo, is withheld from their page too. Their page stays at the same address and says only "Private".
60
- Notes on deceased people's records are shown as written, even if they mention a
61
- living person.
267
+ Notes and citations on deceased people's records are shown as written, even if they
268
+ mention a living person, unless `notes` and `citations` are off (see "A research site
269
+ or a public site").
62
270
  - **A chart that stays readable.** A focused neighborhood around one person, never a
63
271
  whole tree shrunk until the text is useless.
64
272
  - **Works on a phone.**
65
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.
66
278
 
67
279
  ## Contributing
68
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 } = {}) {
10
- const { gedcom, out, mediaRoot, title, focus, anonymizeLiving } = config
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 } = {}) {
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) })
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,
@@ -67,6 +77,10 @@ export function buildSite(config, { log = console.log } = {}) {
67
77
  log(` families : ${stats.families}`)
68
78
  log(` with photos : ${stats.withPhoto}`)
69
79
  log(` media copied: ${stats.media}`)
80
+ const shown = on => (on ? 'shown' : 'hidden')
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}`)
70
84
  log(`Wrote ${stats.pages} HTML pages.`)
71
85
  log(`Open it: open "${path.join(out, 'index.html')}"`)
72
86
  return stats
package/lib/config.mjs CHANGED
@@ -9,8 +9,12 @@ export const DEFAULTS = {
9
9
  out: 'site',
10
10
  mediaRoot: '.',
11
11
  anonymizeLiving: false,
12
+ citations: true,
13
+ notes: true,
14
+ news: null,
12
15
  }
13
16
  const PATHS = ['gedcom', 'out', 'mediaRoot']
17
+ const FLAGS = ['anonymizeLiving', 'citations', 'notes']
14
18
 
15
19
  export function loadConfig(file, overrides = {}) {
16
20
  const raw = JSON.parse(fs.readFileSync(file, 'utf8'))
@@ -20,7 +24,12 @@ export function loadConfig(file, overrides = {}) {
20
24
  const set = Object.fromEntries(Object.entries(overrides).filter(([, v]) => v !== undefined))
21
25
  const c = { ...DEFAULTS, ...raw, ...set }
22
26
  if (!c.gedcom) throw new Error(`config needs a "gedcom" path (in ${file})`)
27
+ for (const k of FLAGS) {
28
+ if (typeof c[k] !== 'boolean') throw new Error(`${k} must be true or false, not ${JSON.stringify(c[k])} (in ${file})`)
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})`)
23
31
  const base = path.dirname(path.resolve(file))
24
32
  for (const k of PATHS) c[k] = path.resolve(base, c[k])
33
+ if (c.news) c.news = path.resolve(base, c.news)
25
34
  return c
26
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);
@@ -31,6 +32,12 @@ ul.people{list-style:none;padding:0;margin:0;columns:2;column-gap:28px}
31
32
  @media(max-width:640px){ul.people{columns:1}}
32
33
  ul.people li{margin:.12em 0;break-inside:avoid}
33
34
  details{margin:.5em 0}summary{cursor:pointer;color:var(--mut)}
35
+ .pref{margin-left:.6em;color:var(--mut);font-size:.72em;text-transform:uppercase;letter-spacing:.04em}
36
+ .ev{margin:.1em 0 .5em 68px;color:#444;font-size:.9em}
37
+ @media(max-width:640px){.ev{margin-left:14px}}
38
+ .enote{white-space:pre-wrap;margin:.1em 0}
39
+ .cite{margin:.15em 0}.cite q{white-space:pre-wrap}.cn{color:var(--mut)}.cite .enote{padding-left:1.8em}
40
+ .sources{color:#444;font-size:.92em}
34
41
  .note{white-space:pre-wrap;font-size:.92em;color:#444;border-left:3px solid var(--line);
35
42
  padding-left:10px;margin:.4em 0}
36
43
  footer{color:var(--mut);font-size:.85em;margin:2em 0 1em;border-top:1px solid var(--line);
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
+ }