kinsite 0.4.0 → 0.5.1

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,7 +14,8 @@ 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
17
+ npm run dev -- my/kinsite.config.json # the same for your own tree; /who places people in photos (see "Photos")
18
+ npx kinsite dev my/kinsite.config.json # the same, with kinsite installed from npm
18
19
  node build.mjs diff sample/kinsite.config.json old.ged # what changed on the site since old.ged (see "What changed")
19
20
  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")
20
21
  npm test
@@ -43,6 +44,7 @@ For your own tree, write a `kinsite.config.json` next to your GEDCOM:
43
44
  | `citations` | Show source citations on person pages; event notes follow `notes` | `true` |
44
45
  | `notes` | Show person and event notes; a citation's own notes go with the citation | `true` |
45
46
  | `news` | Directory of What's new entries and stamped changes (see "What's new") | unset: no page |
47
+ | `who` | Directory for identify-mode sessions (see "Photos") | `who` |
46
48
 
47
49
  Relative paths resolve against the config file's directory. `FOCUS=I3` or `OUT=dir` in
48
50
  the environment override the config for one run. `SINCE=old.ged` previews unpublished
@@ -124,6 +126,81 @@ line. A child's own `FAMC` comes before a link found only on a family's `CHIL` w
124
126
  choosing the main family. Add the missing line to the file to clear the label and the
125
127
  warning.
126
128
 
129
+ ## Photos
130
+
131
+ A person's page shows each image linked by an `OBJE` pointer, captioned by the `OBJE`
132
+ record's `TITL`, and lists other files as documents. Files are copied into the site as
133
+ they are.
134
+
135
+ **One person in a group photo.** A `CROP` under the person's `OBJE` link marks their
136
+ part of a shared image. A `TITL` there adds a line under the photo's title for that
137
+ person, and the image's alt text names them, as in "Corwin Quill in The harvest show":
138
+
139
+ ```
140
+ 0 @I3@ INDI
141
+ 1 OBJE @O2@
142
+ 2 CROP
143
+ 3 TOP 100
144
+ 3 LEFT 100
145
+ 3 HEIGHT 180
146
+ 3 WIDTH 140
147
+ 2 TITL Corwin, far left
148
+ ```
149
+
150
+ The page shows just that region, at most 260px tall. Values
151
+ are pixels of the photo as it's shown, upright: for a JPEG that a phone saved sideways
152
+ with an Exif orientation, measure the turned picture, the way browsers and photo apps
153
+ display it. Sizes are read from JPEG, PNG, GIF and WebP files. A missing `LEFT` or `TOP` is 0, and a missing `WIDTH`
154
+ or `HEIGHT` runs to the edge. A crop that runs past the edge is cut off there. If the
155
+ size can't be read from the file, or no part of the crop is inside it, the page shows the
156
+ whole image. Placing or moving a crop isn't listed on What's new.
157
+
158
+ **A page for each shared photo.** An image that two or more people link to, or that
159
+ anyone has a `CROP` of, gets a page of its own, and each of those people's thumbnails
160
+ links to it. The page shows the whole image with a faint numbered outline on each
161
+ cropped person; hovering or focusing an outline shows their name and the link's `TITL`,
162
+ so a caption like "(unconfirmed)" says how sure the placement is. A "Show outlines"
163
+ box under the photo, ticked to start, can be unticked to see the photo plain. Hovering a
164
+ name in the list lights that person's outline, even with outlines unticked, and hovering
165
+ an outline lights the name. Below it, "In this
166
+ photo" lists the outlined people by number, left to right, and "Also in this photo (not
167
+ yet placed)" lists the people linked without a crop, so readers can see who still needs
168
+ a place. With `anonymizeLiving`, a photo shared with a living person is withheld from
169
+ everyone, so it has no page.
170
+
171
+ **Placing people in a photo.** While `npm run dev` (or `kinsite dev`) runs, http://localhost:4000/who lists
172
+ every image `OBJE` in the GEDCOM, linked to anyone or not, with how many people are
173
+ placed and how many are still to place. Open one to identify who's in it:
174
+
175
+ - Drag on the photo to draw a box around someone. Drag a box to move it, or its
176
+ corner to resize it.
177
+ - Pick a box to see a close-up of it, and search for who it is. The search lists the
178
+ people linked to the photo first, then the people alive in the year it was taken.
179
+ That year comes from the first four-digit number in the `OBJE` title, and you can
180
+ change it on the page.
181
+ - An answer can also be "Someone not in the tree" or "Not sure". "This is a guess"
182
+ marks a name you aren't sure of. Each box has a caption, which becomes the link's
183
+ `TITL`, and notes.
184
+ - The lists below the photo sort the boxes into placed, guessed, unknown and to place.
185
+ People linked to the photo who have no box yet count as to place.
186
+ - "For your GEDCOM" gives the `OBJE` link lines, with `CROP` and `TITL`, for each placed
187
+ person whose link is new or differs from the GEDCOM. Copy them into your genealogy
188
+ app, or under that person's record in the file.
189
+
190
+ kinsite never writes the GEDCOM. A photo's boxes, answers and notes save as you go to
191
+ `<OBJE id>.json` in the config's `who` folder, such as `who/O2.json`. Guesses, unknowns
192
+ and notes stay only in that file, and committing it is up to you.
193
+
194
+ A new session starts from the crops already in the GEDCOM. The session also remembers
195
+ the GEDCOM's crops as it last saw them. If you then move or add a crop in your
196
+ genealogy app, the next visit takes the new crop for that person's box and says so.
197
+ Boxes you've changed and not yet pasted are kept. The session also records the
198
+ photo's file. If the `OBJE` with that ID now names a different file, as happens when
199
+ an app renumbers IDs on export, the page warns you and saves nothing until you
200
+ either move that session aside or say its boxes are for this photo.
201
+ The page shows the whole tree, living people included, so it answers only on your
202
+ own machine, at `localhost`.
203
+
127
204
  ## What changed
128
205
 
129
206
  Before deploying, `kinsite diff kinsite.config.json old.ged` compares an older GEDCOM
@@ -238,6 +315,10 @@ note, entries not yet stamped don't count, and the note doesn't age out. When bu
238
315
  with `SINCE`, a person changed or mentioned in the preview also gets a "Changed since
239
316
  last deploy" link to the "Not yet published" section.
240
317
 
318
+ **Sharing one deploy.** Each dated heading on What's new has a faint `#` link to
319
+ itself, in the left margin (beside the date on a phone), so a reader can copy the link
320
+ to one deploy's news and send it to a relative. "Not yet published" has none.
321
+
241
322
  **A deploy recipe.** kinsite never touches git; this is one way to run it:
242
323
 
243
324
  1. Get the GEDCOM that's live now, as `old.ged`.
package/build.mjs CHANGED
@@ -8,6 +8,7 @@
8
8
  // SINCE=old.ged node build.mjs kinsite.config.json # preview unstamped news on What's new
9
9
  // node build.mjs diff kinsite.config.json old.ged # what changed on the site since old.ged
10
10
  // node build.mjs news stamp kinsite.config.json old.ged # record this deploy's changes for What's new
11
+ // node build.mjs dev kinsite.config.json # preview at localhost, rebuilt on change; /who places people in photos
11
12
  import { loadConfig } from './lib/config.mjs'
12
13
  import { buildSite } from './lib/build.mjs'
13
14
  import { changeReport } from './lib/diff.mjs'
@@ -15,20 +16,27 @@ import { stampNews } from './lib/news.mjs'
15
16
 
16
17
  const USAGE = `usage: kinsite path/to/kinsite.config.json
17
18
  kinsite diff path/to/kinsite.config.json old.ged
18
- kinsite news stamp path/to/kinsite.config.json old.ged`
19
+ kinsite news stamp path/to/kinsite.config.json old.ged
20
+ kinsite dev path/to/kinsite.config.json`
19
21
  const [first, ...rest] = process.argv.slice(2)
20
22
  const [cmd, file, old] = first === 'diff' ? [first, ...rest]
23
+ : first === 'dev' ? [first, rest[0]]
21
24
  : first === 'news' ? (rest[0] === 'stamp' ? ['stamp', ...rest.slice(1)] : [])
22
25
  : ['build', first]
23
- if (!file || (cmd !== 'build' && !old)) {
26
+ if (!file || (cmd !== 'build' && cmd !== 'dev' && !old)) {
24
27
  console.error(USAGE)
25
28
  process.exit(2)
26
29
  }
27
- try {
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 })
31
- } catch (e) {
32
- console.error(`error: ${e.message}`)
33
- process.exit(1)
30
+ if (cmd === 'dev') {
31
+ process.argv = [...process.argv.slice(0, 2), file]
32
+ await import('./scripts/dev.mjs')
33
+ } else {
34
+ try {
35
+ if (cmd === 'diff') console.log(changeReport(loadConfig(file), old))
36
+ else if (cmd === 'stamp') stampNews(loadConfig(file), old)
37
+ else buildSite(loadConfig(file, { focus: process.env.FOCUS, out: process.env.OUT }), { since: process.env.SINCE })
38
+ } catch (e) {
39
+ console.error(`error: ${e.message}`)
40
+ process.exit(1)
41
+ }
34
42
  }
package/lib/build.mjs CHANGED
@@ -7,6 +7,9 @@ import { CSS } from './css.mjs'
7
7
  import { anonymize } from './living.mjs'
8
8
  import { readNews, newsSections, lastUpdated, whatsNewPage, count } from './news.mjs'
9
9
  import { diffTrees, readGedcom } from './diff.mjs'
10
+ import { imageSize } from './media.mjs'
11
+
12
+ export const mediaSource = (f, mediaRoot) => (path.isAbsolute(f) && fs.existsSync(f) ? f : path.join(mediaRoot, f))
10
13
 
11
14
  // since: an older GEDCOM to preview What's new against (the SINCE environment variable, never a config key).
12
15
  export function buildSite(config, { log = console.log, since } = {}) {
@@ -19,7 +22,7 @@ export function buildSite(config, { log = console.log, since } = {}) {
19
22
  const rel = path.relative(dir, f)
20
23
  return !path.isAbsolute(rel) && rel.split(path.sep)[0] !== '..'
21
24
  }
22
- for (const keep of [gedcom, mediaRoot]) {
25
+ for (const keep of [gedcom, mediaRoot, config.who].filter(Boolean)) {
23
26
  if (inside(out, keep)) throw new Error(`refusing to delete ${out}: it contains ${keep}`)
24
27
  }
25
28
 
@@ -38,7 +41,7 @@ export function buildSite(config, { log = console.log, since } = {}) {
38
41
  for (const md of p.media) {
39
42
  const f = md.file
40
43
  if (!f || copied.has(f)) continue
41
- const src = path.isAbsolute(f) && fs.existsSync(f) ? f : path.join(mediaRoot, f)
44
+ const src = mediaSource(f, mediaRoot)
42
45
  if (!isFile(src)) continue
43
46
  const base = path.basename(f)
44
47
  let dst = path.join(mediaOut, base)
@@ -52,6 +55,12 @@ export function buildSite(config, { log = console.log, since } = {}) {
52
55
  copied.set(f, 'media/' + path.basename(dst))
53
56
  }
54
57
  }
58
+ const sizes = new Map()
59
+ for (const md of [...indi.values()].flatMap(p => p.media)) {
60
+ if (md.crop && copied.has(md.file) && !sizes.has(md.file)) {
61
+ sizes.set(md.file, imageSize(fs.readFileSync(path.join(out, copied.get(md.file)))))
62
+ }
63
+ }
55
64
 
56
65
  fs.writeFileSync(path.join(out, 'style.css'), CSS)
57
66
 
@@ -59,13 +68,14 @@ export function buildSite(config, { log = console.log, since } = {}) {
59
68
  const news = config.news && readNews(config.news)
60
69
  if (old) news.preview = { entries: news.pending, changes: diffTrees(old, parsed) }
61
70
  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) })
71
+ const r = new Renderer({ indi, fam, kin, copied, sizes, title, source: path.basename(gedcom), citations, notes, news: !!news, updated: lastUpdated(sections) })
63
72
  let withPhoto = 0
64
73
  for (const pid of indi.keys()) {
65
74
  const page = r.personPage(pid)
66
75
  if (page.withPhoto) withPhoto++
67
76
  fs.writeFileSync(path.join(out, `${pid}.html`), page.html)
68
77
  }
78
+ for (const oid of r.photos.keys()) fs.writeFileSync(path.join(out, `${oid}.html`), r.photoPage(oid))
69
79
  fs.writeFileSync(path.join(out, 'index.html'), r.indexPage())
70
80
  if (news) fs.writeFileSync(path.join(out, 'whats-new.html'), whatsNewPage(sections, r))
71
81
 
package/lib/config.mjs CHANGED
@@ -12,8 +12,9 @@ export const DEFAULTS = {
12
12
  citations: true,
13
13
  notes: true,
14
14
  news: null,
15
+ who: 'who',
15
16
  }
16
- const PATHS = ['gedcom', 'out', 'mediaRoot']
17
+ const PATHS = ['gedcom', 'out', 'mediaRoot', 'who']
17
18
  const FLAGS = ['anonymizeLiving', 'citations', 'notes']
18
19
 
19
20
  export function loadConfig(file, overrides = {}) {
@@ -27,6 +28,7 @@ export function loadConfig(file, overrides = {}) {
27
28
  for (const k of FLAGS) {
28
29
  if (typeof c[k] !== 'boolean') throw new Error(`${k} must be true or false, not ${JSON.stringify(c[k])} (in ${file})`)
29
30
  }
31
+ if (typeof c.who !== 'string') throw new Error(`who must be a directory path, not ${JSON.stringify(c.who)} (in ${file})`)
30
32
  if (c.news !== null && typeof c.news !== 'string') throw new Error(`news must be a directory path, not ${JSON.stringify(c.news)} (in ${file})`)
31
33
  const base = path.dirname(path.resolve(file))
32
34
  for (const k of PATHS) c[k] = path.resolve(base, c[k])
package/lib/css.mjs CHANGED
@@ -2,7 +2,7 @@ export const CSS = `
2
2
  :root{--ink:#222;--mut:#777;--line:#e3e0d8;--bg:#faf8f4;--accent:#7a5c3e}
3
3
  *{box-sizing:border-box}
4
4
  body{font:16px/1.55 -apple-system,Segoe UI,Roboto,sans-serif;color:var(--ink);
5
- background:var(--bg);margin:0}
5
+ background:var(--bg);margin:0;overflow-wrap:break-word}
6
6
  .wrap{max-width:820px;margin:0 auto;padding:24px}
7
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}
@@ -16,12 +16,32 @@ a{color:var(--accent);text-decoration:none}a:hover{text-decoration:underline}
16
16
  .yr{color:var(--mut);font-size:.9em}
17
17
  .unknown{color:var(--mut)}
18
18
  h2{font-size:.95em;text-transform:uppercase;letter-spacing:.05em;color:var(--mut);
19
- border-bottom:1px solid var(--line);padding-bottom:4px;margin:1.4em 0 .6em}
19
+ border-bottom:1px solid var(--line);padding-bottom:4px;margin:1.4em 0 .6em;position:relative}
20
+ h2 a.self{position:absolute;left:-1.2em;color:var(--mut);opacity:.35}
21
+ h2 a.self:hover,h2 a.self:focus-visible{opacity:1;text-decoration:none}
22
+ @media(max-width:880px){h2 a.self{position:static;margin-left:.5em}}
20
23
  ul.rel{list-style:none;padding:0;margin:0}ul.rel li{margin:.2em 0}
21
24
  .photos{display:flex;flex-wrap:wrap;gap:12px;margin:.4em 0}
22
25
  .photos figure{margin:0;width:200px}
23
26
  .photos img{width:100%;border:1px solid var(--line);border-radius:6px;display:block}
27
+ .photos a.crop{display:block;position:relative;overflow:hidden;border:1px solid var(--line);border-radius:6px}
28
+ .photos a.crop img{position:absolute;max-width:none;border:0;border-radius:0}
24
29
  .photos figcaption{font-size:.8em;color:var(--mut);margin-top:4px}
30
+ .photos figcaption .cn{display:block;font-style:italic}
31
+ .stage{position:relative;margin:.5em 0 1em}
32
+ .stage img{display:block;width:100%;height:auto;border:1px solid var(--line);border-radius:8px}
33
+ .stage a.who{position:absolute;border:2px solid rgba(255,255,255,.7);border-radius:4px;box-shadow:0 0 0 1px rgba(0,0,0,.35)}
34
+ .stage a.who::after{content:'';position:absolute;inset:min(0px,calc((100% - 44px)/2))}
35
+ .stage a.who b{position:absolute;left:0;top:0;min-width:1.5em;padding:0 .25em;font-size:12px;line-height:1.5em;
36
+ text-align:center;color:#fff;background:rgba(0,0,0,.55);border-radius:0 0 3px 0}
37
+ .stage a.who span{display:none;position:absolute;top:100%;left:-2px;margin-top:4px;padding:2px 8px;z-index:1;
38
+ width:max-content;max-width:min(18em,45vw);font-size:.8em;color:#fff;background:var(--ink);border-radius:4px}
39
+ .stage a.who.r span{left:auto;right:-2px}
40
+ .stage a.who:hover,.stage a.who:focus-visible,.stage a.who.on{border-color:#fff;box-shadow:0 0 0 2px var(--accent);text-decoration:none}
41
+ .stage a.who:hover span,.stage a.who:focus-visible span,.stage a.who.on span{display:block}
42
+ .stage:has(+ .outlines input:not(:checked)) a.who:not(.on){display:none}
43
+ .outlines{display:block;color:var(--mut);font-size:.85em;margin:-.6em 0 0;cursor:pointer}
44
+ ol.placed{margin:0;padding-left:1.6em}ol.placed li{margin:.2em 0;border-radius:4px}ol.placed li.on{background:#f1ece2}
25
45
  .docs a{display:inline-block;margin:.2em .6em .2em 0}
26
46
  #q{width:100%;padding:10px 12px;font-size:1em;border:1px solid var(--line);
27
47
  border-radius:8px;margin:.6em 0 .4em}
package/lib/diff.mjs CHANGED
@@ -99,10 +99,11 @@ function personChanges(o, p, old, cur) {
99
99
  notes(o.notes, p.notes)
100
100
  cites(o.sources, p.sources)
101
101
 
102
+ const obje = ({ file, title, form }) => ({ file, title, form })
102
103
  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 })
104
+ for (const [a, b, same] of media.pairs) if (!same) push('media', 'changed', obje(a), obje(b))
105
+ for (const m of media.removed) push('media', 'removed', obje(m))
106
+ for (const m of media.added) push('media', 'added', undefined, obje(m))
106
107
 
107
108
  // Which side of the file records a link (only) is bookkeeping, not a change to report.
108
109
  const links = q => new Map(q.parentFams.map(({ only, ...l }) => [l.fam, l]))
package/lib/gedcom.mjs CHANGED
@@ -1,13 +1,14 @@
1
1
  // Minimal GEDCOM 7.0 reader: only what the site renders.
2
2
  import { yr } from './dates.mjs'
3
3
 
4
+ const CROP = new Set(['TOP', 'LEFT', 'HEIGHT', 'WIDTH'])
4
5
  const EVENTS = new Set(['BIRT', 'CHR', 'BAPM', 'DEAT', 'BURI', 'RESI', 'EMIG', 'OCCU', 'EVEN'])
5
6
 
6
7
  export const restricted = e => (e.resn ?? '').toUpperCase().split(/[\s,]+/).some(t => t === 'PRIVACY' || t === 'CONFIDENTIAL')
7
8
 
8
9
  export function parseGedcom(text) {
9
10
  const indi = new Map(), fam = new Map(), obje = new Map(), sour = new Map(), pointers = []
10
- let cur = null, ctype = null, evt = null, famc = null, media = null, sub = null, cite = null, citeLvl = 0, cont = null, shownName = false
11
+ let cur = null, ctype = null, evt = null, famc = null, media = null, link = null, sub = null, cite = null, citeLvl = 0, cont = null, shownName = false
11
12
  const startCitation = (val, lvl, list) => {
12
13
  const ptr = val.match(/^@(\w+)@$/)
13
14
  cite = { sour: ptr?.[1] ?? '', title: '', page: '', text: '', notes: [] }
@@ -26,7 +27,7 @@ export function parseGedcom(text) {
26
27
  if (!m) continue
27
28
  const lvl = Number(m[1]), rest = m[2]
28
29
  if (lvl === 0) {
29
- cur = ctype = evt = famc = media = cite = cont = null
30
+ cur = ctype = evt = famc = media = link = cite = cont = null
30
31
  const r = rest.match(/^@(\w+)@ (\w+)$/)
31
32
  if (r && r[2] === 'INDI') {
32
33
  ctype = 'INDI'
@@ -92,7 +93,7 @@ export function parseGedcom(text) {
92
93
  }
93
94
  } else if (ctype === 'INDI') {
94
95
  if (lvl === 1) {
95
- evt = famc = null
96
+ evt = famc = link = null
96
97
  shownName = tag === 'NAME' && !cur.name
97
98
  if (shownName) {
98
99
  cur.name = val.replaceAll('/', '').trim()
@@ -108,7 +109,7 @@ export function parseGedcom(text) {
108
109
  cur.parentFams.push(famc)
109
110
  }
110
111
  else if (tag === 'FAMS') cur.fams.push(stripAt(val))
111
- else if (tag === 'OBJE') cur.media.push(stripAt(val))
112
+ else if (tag === 'OBJE') cur.media.push(link = { id: stripAt(val) })
112
113
  else if (note) cont = { lvl, obj: cur.notes, key: cur.notes.push(val) - 1 }
113
114
  else if (tag === 'SOUR') startCitation(val, 1, cur.sources)
114
115
  } else if (lvl === 2 && tag === 'SOUR' && (evt || shownName)) {
@@ -121,6 +122,11 @@ export function parseGedcom(text) {
121
122
  else if (note) cont = { lvl, obj: (evt.notes ??= []), key: evt.notes.push(val) - 1 }
122
123
  } else if (evt && phrase) {
123
124
  evt.phrase = val.trim()
125
+ } else if (link && lvl === 2) {
126
+ if (tag === 'TITL') link.caption = val.trim()
127
+ else if (tag === 'CROP') link.crop = {}
128
+ } else if (link?.crop && lvl === 3 && sub === 'CROP' && CROP.has(tag) && /^\d+$/.test(val.trim())) {
129
+ link.crop[tag.toLowerCase()] = Number(val)
124
130
  } else if (famc && lvl === 2 && (tag === 'PEDI' || tag === 'STAT')) {
125
131
  famc[tag.toLowerCase()] = val.trim().toUpperCase()
126
132
  } else if (famc && lvl === 3 && sub === 'PEDI' && tag === 'PHRASE') {
@@ -146,11 +152,11 @@ export function parseGedcom(text) {
146
152
  const all = p.events.filter(e => e.tag === tag)
147
153
  p[key] = all.find(e => !restricted(e) && yr(e.date)) ?? all[0] ?? {}
148
154
  }
149
- p.media = p.media.flatMap(id => obje.get(id) ?? [])
155
+ p.media = p.media.flatMap(({ id, ...own }) => (obje.has(id) ? { obje: id, ...obje.get(id), ...own } : []))
150
156
  }
151
157
  const warnings = checkLinks(indi, fam)
152
158
  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 }
159
+ return { indi, fam, obje, warnings }
154
160
  }
155
161
 
156
162
  export const parentLink = fam => ({ fam, pedi: '', phrase: '', stat: '' })
package/lib/media.mjs ADDED
@@ -0,0 +1,74 @@
1
+ // Image sizes from PNG, JPEG, GIF and WebP headers, and GEDCOM 7.0 CROP regions within them.
2
+ const PNG = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])
3
+ const SOF = new Set([0xc0, 0xc1, 0xc2, 0xc3, 0xc5, 0xc6, 0xc7, 0xc9, 0xca, 0xcb, 0xcd, 0xce, 0xcf])
4
+
5
+ const sized = (width, height) => (width > 0 && height > 0 ? { width, height } : null)
6
+
7
+ function orientation(buf, at, end) {
8
+ if (buf.toString('latin1', at, at + 6) !== 'Exif\0\0') return 1
9
+ const tiff = at + 6, le = buf.toString('latin1', tiff, tiff + 2) === 'II'
10
+ const u16 = i => (le ? buf.readUInt16LE(i) : buf.readUInt16BE(i)), u32 = i => (le ? buf.readUInt32LE(i) : buf.readUInt32BE(i))
11
+ try {
12
+ const ifd = tiff + u32(tiff + 4)
13
+ for (let i = 0, n = u16(ifd); i < n; i++) {
14
+ const entry = ifd + 2 + i * 12
15
+ if (entry + 12 > end) break
16
+ if (u16(entry) === 0x0112) return u16(entry + 8)
17
+ }
18
+ } catch {}
19
+ return 1
20
+ }
21
+
22
+ function jpegSize(buf) {
23
+ let at = 2, turned = false
24
+ while (at + 4 <= buf.length) {
25
+ if (buf[at] !== 0xff) return null
26
+ const marker = buf[at + 1]
27
+ if (marker === 0xff) {
28
+ at++
29
+ continue
30
+ }
31
+ if (marker === 0xd9 || marker === 0xda) return null
32
+ const len = buf.readUInt16BE(at + 2)
33
+ if (marker === 0xe1) turned ||= orientation(buf, at + 4, at + 2 + len) >= 5
34
+ if (SOF.has(marker)) {
35
+ if (at + 9 > buf.length) return null
36
+ const width = buf.readUInt16BE(at + 7), height = buf.readUInt16BE(at + 5)
37
+ return turned ? sized(height, width) : sized(width, height)
38
+ }
39
+ at += 2 + len
40
+ }
41
+ return null
42
+ }
43
+
44
+ function webpSize(buf) {
45
+ const chunk = buf.toString('latin1', 12, 16)
46
+ if (chunk === 'VP8 ' && buf.length >= 30 && buf[23] === 0x9d && buf[24] === 0x01 && buf[25] === 0x2a) {
47
+ return sized(buf.readUInt16LE(26) & 0x3fff, buf.readUInt16LE(28) & 0x3fff)
48
+ }
49
+ if (chunk === 'VP8L' && buf.length >= 25 && buf[20] === 0x2f) {
50
+ const bits = buf.readUInt32LE(21)
51
+ return sized((bits & 0x3fff) + 1, ((bits >>> 14) & 0x3fff) + 1)
52
+ }
53
+ if (chunk === 'VP8X' && buf.length >= 30) return sized(buf.readUIntLE(24, 3) + 1, buf.readUIntLE(27, 3) + 1)
54
+ return null
55
+ }
56
+
57
+ // A JPEG's size is upright, as browsers show it after applying its Exif orientation.
58
+ export function imageSize(buf) {
59
+ if (buf.length >= 24 && buf.subarray(0, 8).equals(PNG) && buf.toString('latin1', 12, 16) === 'IHDR') {
60
+ return sized(buf.readUInt32BE(16), buf.readUInt32BE(20))
61
+ }
62
+ if (buf.length >= 10 && /^GIF8[79]a$/.test(buf.toString('latin1', 0, 6))) return sized(buf.readUInt16LE(6), buf.readUInt16LE(8))
63
+ if (buf.length >= 16 && buf.toString('latin1', 0, 4) === 'RIFF' && buf.toString('latin1', 8, 12) === 'WEBP') return webpSize(buf)
64
+ if (buf[0] === 0xff && buf[1] === 0xd8) return jpegSize(buf)
65
+ return null
66
+ }
67
+
68
+ export function cropBox(crop, size) {
69
+ if (!size) return null
70
+ const left = crop.left ?? 0, top = crop.top ?? 0
71
+ const width = Math.min(crop.width ?? Infinity, size.width - left)
72
+ const height = Math.min(crop.height ?? Infinity, size.height - top)
73
+ return width > 0 && height > 0 ? { left, top, width, height } : null
74
+ }
package/lib/news.mjs CHANGED
@@ -145,7 +145,9 @@ export function newsSections(news, indi, tree, config, warn) {
145
145
  const list = items.map(i => `<li>${linked(i)}` +
146
146
  (i.lines.length ? `<ul>${i.lines.map(l => `<li>${esc(l)}</li>`).join('')}</ul>` : '') + '</li>').join('')
147
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>`
148
+ const label = esc(pending ? 'Not yet published' : longDate(d.date))
149
+ const self = pending ? '' : `<a class=self href="#${anchor}" aria-label="Link to ${label}">#</a>`
150
+ const heading = `<h2 id=${anchor}>${label}${self}</h2>`
149
151
  const html = body ? heading + body : pending ? `${heading}<p class=sub>Nothing yet.</p>` : ''
150
152
  return { anchor, date: d.date, pending, html, people }
151
153
  })
package/lib/render.mjs CHANGED
@@ -5,10 +5,20 @@ import { restricted, mainChildren } from './gedcom.mjs'
5
5
  import { esc } from './html.mjs'
6
6
  import { yr, byBirth, birthYear } from './dates.mjs'
7
7
  import { hourglassLayout, hourglassSvg } from './hourglass.mjs'
8
+ import { cropBox } from './media.mjs'
8
9
 
9
10
  export { esc, yr }
10
11
  export const DEFAULT_TITLE = 'Family Tree'
11
12
  export const IMG_EXT = new Set(['.jpg', '.jpeg', '.png', '.gif', '.webp'])
13
+ const CROP_MAX_HEIGHT = 260
14
+ const PAIR_SCRIPT = "<script>var W=document.querySelectorAll('.stage a.who'),P=document.querySelectorAll('ol.placed li');" +
15
+ "function on(i,v){W[i].classList.toggle('on',v);P[i].classList.toggle('on',v);}" +
16
+ "[W,P].forEach(function(g){[].forEach.call(g,function(e,i){" +
17
+ "e.addEventListener('mouseenter',function(){on(i,true);});e.addEventListener('mouseleave',function(){on(i,false);});});});" +
18
+ "[].forEach.call(P,function(e,i){e.addEventListener('focusin',function(ev){on(i,ev.target.matches(':focus-visible'));});" +
19
+ "e.addEventListener('focusout',function(){on(i,false);});});" +
20
+ "addEventListener('pageshow',function(){for(var i=0;i<W.length;i++)on(i,false);});</script>"
21
+ const pct = n => `${+(n * 100).toFixed(3)}%`
12
22
 
13
23
  export const known = s => ((s ?? '').trim() === '?' ? '' : s ?? '')
14
24
 
@@ -59,8 +69,8 @@ export const linkLabel = (l, main = false) => [
59
69
  const notesHtml = notes => (notes ?? []).filter(n => n.trim()).map(n => `<div class=enote>${esc(redact(n))}</div>`).join('')
60
70
 
61
71
  export class Renderer {
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 })
72
+ constructor({ indi, fam, kin, copied, sizes = new Map(), title = DEFAULT_TITLE, source = '', citations = true, notes = true, news = false, updated = new Map() }) {
73
+ Object.assign(this, { indi, fam, kin, copied, sizes, title, source, citations, notes, news, updated })
64
74
  }
65
75
 
66
76
  page(title, body) {
@@ -175,6 +185,51 @@ export class Renderer {
175
185
  return { imgs: pairs.filter(isImg), docs: pairs.filter(x => !isImg(x)) }
176
186
  }
177
187
 
188
+ get photos() {
189
+ if (!this._photos) {
190
+ const links = new Map()
191
+ for (const [pid, p] of this.indi) {
192
+ for (const [md] of this.attachments(p).imgs) if (md.obje) links.set(md.obje, [...(links.get(md.obje) ?? []), { pid, md }])
193
+ }
194
+ this._photos = new Map([...links].filter(([, l]) => l.length > 1 || l.some(({ md }) => md.crop)))
195
+ }
196
+ return this._photos
197
+ }
198
+
199
+ figure(md, src, name) {
200
+ const { title, caption } = md
201
+ const size = this.sizes.get(md.file)
202
+ const box = md.crop && cropBox(md.crop, size)
203
+ const alt = esc(box && name ? [name, title].filter(Boolean).join(' in ') : title || caption)
204
+ const text = title && caption && caption !== title ? `${esc(title)}<span class=cn>${esc(caption)}</span>` : esc(title || caption)
205
+ const href = esc(this.photos.has(md.obje) ? `${md.obje}.html` : src)
206
+ const img = box
207
+ ? `<a class=crop href="${href}" style="aspect-ratio:${box.width}/${box.height};width:min(100%,${Math.round(CROP_MAX_HEIGHT * box.width / box.height)}px)">` +
208
+ `<img src="${esc(src)}" alt="${alt}" style="width:${pct(size.width / box.width)};left:${pct(-box.left / box.width)};top:${pct(-box.top / box.height)}"></a>`
209
+ : `<a href="${href}"><img src="${esc(src)}" alt="${alt}"></a>`
210
+ return `<figure>${img}<figcaption>${text}</figcaption></figure>`
211
+ }
212
+
213
+ photoPage(oid) {
214
+ const links = this.photos.get(oid), { file, title } = links[0].md
215
+ const src = esc(this.copied.get(file)), size = this.sizes.get(file), heading = title || 'Photo'
216
+ const boxed = links.map(l => ({ ...l, box: l.md.crop && cropBox(l.md.crop, size) }))
217
+ const placed = boxed.filter(l => l.box).sort((a, b) => a.box.left - b.box.left || a.box.top - b.box.top)
218
+ const unplaced = boxed.filter(l => !l.box)
219
+ const item = ({ pid, md }) => `<li>${this.plink(pid)}${md.caption ? ` <span class=cn>${esc(md.caption)}</span>` : ''}</li>`
220
+ const boxes = placed.map(({ pid, md, box }, i) => {
221
+ const label = [this.indi.get(pid).name || '(unnamed)', md.caption].filter(Boolean).join(' · ')
222
+ const right = box.left + box.width / 2 > size.width / 2 ? ' r' : ''
223
+ return `<a class="who${right}" href="${pid}.html" style="left:${pct(box.left / size.width)};top:${pct(box.top / size.height)};` +
224
+ `width:${pct(box.width / size.width)};height:${pct(box.height / size.height)}"><b>${i + 1}</b><span>${esc(label)}</span></a>`
225
+ })
226
+ const b = ['<p class=back><a href="index.html">&larr; All people</a></p>', `<h1>${esc(heading)}</h1>`,
227
+ `<div class=stage><a href="${src}"><img src="${src}" alt="${esc(heading)}"></a>${boxes.join('')}</div>`]
228
+ if (placed.length) b.push('<label class=outlines><input type=checkbox checked> Show outlines</label>', `<h2>In this photo</h2><ol class=placed>${placed.map(item).join('')}</ol>`, PAIR_SCRIPT)
229
+ if (unplaced.length) b.push(`<h2>Also in this photo (not yet placed)</h2><ul class=rel>${unplaced.map(item).join('')}</ul>`)
230
+ return this.page(heading, b.join(''))
231
+ }
232
+
178
233
  personPage(pid) {
179
234
  const p = this.indi.get(pid), { kin, fam } = this
180
235
  const b = ['<p class=back><a href="index.html">&larr; All people</a></p>',
@@ -209,12 +264,7 @@ export class Renderer {
209
264
  b.push('<h2>Family</h2>' + this.chartSvg(pid))
210
265
 
211
266
  const { imgs, docs } = this.attachments(p)
212
- if (imgs.length) {
213
- const cells = imgs.map(([md, src]) =>
214
- `<figure><a href="${esc(src)}"><img src="${esc(src)}" alt="${esc(md.title)}"></a>` +
215
- `<figcaption>${esc(md.title)}</figcaption></figure>`).join('')
216
- b.push(`<div class="photos">${cells}</div>`)
217
- }
267
+ if (imgs.length) b.push(`<div class="photos">${imgs.map(([md, src]) => this.figure(md, src, p.name)).join('')}</div>`)
218
268
 
219
269
  const num = counter()
220
270
  const vit = this.eventsHtml(p, num)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "kinsite",
3
- "version": "0.4.0",
3
+ "version": "0.5.1",
4
4
  "type": "module",
5
5
  "description": "Static HTML family-tree site from a GEDCOM file",
6
6
  "license": "MIT",
@@ -23,6 +23,7 @@
23
23
  },
24
24
  "files": [
25
25
  "lib/",
26
+ "scripts/",
26
27
  "build.mjs"
27
28
  ],
28
29
  "bin": {
@@ -0,0 +1,56 @@
1
+ #!/usr/bin/env node
2
+ // Usage: npm run dev [-- path/to/kinsite.config.json] (default: the sample; SINCE=old.ged previews What's new)
3
+ import fs from 'node:fs'
4
+ import path from 'node:path'
5
+ import { fileURLToPath } from 'node:url'
6
+ import { execFileSync } from 'node:child_process'
7
+ import { loadConfig } from '../lib/config.mjs'
8
+ import { createServer } from './serve.mjs'
9
+ import { whoHandler } from './who.mjs'
10
+
11
+ const repo = path.join(path.dirname(fileURLToPath(import.meta.url)), '..')
12
+ const here = process.env.INIT_CWD ?? process.cwd()
13
+ const configFile = path.resolve(here, process.argv[2] ?? path.join(repo, 'sample', 'kinsite.config.json'))
14
+ const since = process.env.SINCE && path.resolve(here, process.env.SINCE)
15
+ const env = since ? { ...process.env, SINCE: since } : process.env
16
+ const port = Number(process.env.PORT || 4000)
17
+ const state = { version: 1 }
18
+
19
+ function rebuild() {
20
+ try {
21
+ const config = loadConfig(configFile)
22
+ // In-process rebuilds would reuse the cached lib/ modules.
23
+ execFileSync(process.execPath, [path.join(repo, 'build.mjs'), configFile], { env, stdio: ['ignore', 'ignore', 'pipe'] })
24
+ state.version++
25
+ console.log(`built (v${state.version})`)
26
+ return config.out
27
+ } catch (e) {
28
+ console.error(`build failed, serving last good output: ${e.stderr?.toString().trim() || e.message}`)
29
+ }
30
+ }
31
+
32
+ let out = rebuild()
33
+ if (!out) process.exit(1)
34
+
35
+ const server = createServer(() => out, state, whoHandler(configFile)).listen(port, () => {
36
+ const url = `http://localhost:${server.address().port}`
37
+ console.log(`${url}\nidentify people in photos: ${url}/who`)
38
+ })
39
+
40
+ let timer
41
+ const schedule = () => {
42
+ clearTimeout(timer)
43
+ timer = setTimeout(() => { out = rebuild() ?? out }, 150)
44
+ }
45
+ const inside = (dir, f) => !path.relative(dir, f).startsWith('..')
46
+ const config = loadConfig(configFile)
47
+ const watched = [
48
+ [path.join(repo, 'lib'), true], [path.join(repo, 'build.mjs'), false], [path.dirname(configFile), true],
49
+ [path.dirname(config.gedcom), false], [config.news, false], [since && path.dirname(since), false],
50
+ ]
51
+ for (const [p, recursive] of watched) {
52
+ if (!p || !fs.existsSync(p)) continue
53
+ fs.watch(p, { recursive }, (_, f) => {
54
+ if (!f || !inside(out, path.join(p, f))) schedule()
55
+ })
56
+ }
@@ -0,0 +1,56 @@
1
+ import fs from 'node:fs'
2
+ import path from 'node:path'
3
+ import http from 'node:http'
4
+
5
+ export const RELOAD_SCRIPT = `<script>(()=>{const v=()=>fetch('/__version').then(r=>r.text()).catch(()=>null);let c;v().then(x=>{c=x;setInterval(async()=>{const n=await v();if(n&&c&&n!==c)location.reload();c=n||c},700)})})()</script>`
6
+
7
+ export const TYPES = {
8
+ '.html': 'text/html; charset=utf-8',
9
+ '.css': 'text/css; charset=utf-8',
10
+ '.js': 'text/javascript; charset=utf-8',
11
+ '.json': 'application/json',
12
+ '.svg': 'image/svg+xml',
13
+ '.png': 'image/png',
14
+ '.jpg': 'image/jpeg',
15
+ '.jpeg': 'image/jpeg',
16
+ '.gif': 'image/gif',
17
+ '.webp': 'image/webp',
18
+ '.ico': 'image/x-icon',
19
+ '.txt': 'text/plain; charset=utf-8',
20
+ }
21
+
22
+ export function resolvePath(root, urlPath) {
23
+ let p
24
+ try { p = decodeURIComponent(urlPath.split('?')[0]) } catch { return null }
25
+ if (p.includes('\0') || p.split(/[\\/]/).includes('..')) return null
26
+ const file = path.resolve(root, '.' + path.posix.normalize('/' + p))
27
+ const rel = path.relative(root, file)
28
+ if (path.isAbsolute(rel) || rel.split(path.sep)[0] === '..') return null
29
+ return file
30
+ }
31
+
32
+ export function createServer(getRoot, state, handle = () => false) {
33
+ return http.createServer((req, res) => {
34
+ if (handle(req, res)) return
35
+ const send = (status, body, type = 'text/plain; charset=utf-8') => {
36
+ res.writeHead(status, { 'content-type': type, 'cache-control': 'no-store' })
37
+ res.end(body)
38
+ }
39
+ if (req.method !== 'GET' && req.method !== 'HEAD') return send(405, 'method not allowed')
40
+ if (req.url.split('?')[0] === '/__version') return send(200, String(state.version))
41
+ const root = path.resolve(getRoot())
42
+ let file = resolvePath(root, req.url)
43
+ if (!file) return send(403, 'forbidden')
44
+ try {
45
+ if (fs.statSync(file).isDirectory()) file = path.join(file, 'index.html')
46
+ const ext = path.extname(file).toLowerCase()
47
+ const type = TYPES[ext] ?? 'application/octet-stream'
48
+ const data = fs.readFileSync(file)
49
+ if (ext !== '.html') return send(200, data, type)
50
+ const html = data.toString('utf8')
51
+ send(200, html.includes('</body>') ? html.replace('</body>', RELOAD_SCRIPT + '</body>') : html + RELOAD_SCRIPT, type)
52
+ } catch {
53
+ send(404, 'not found')
54
+ }
55
+ })
56
+ }
@@ -0,0 +1,595 @@
1
+ // Identify mode for the dev server (`npm run dev`, `kinsite dev`): draw boxes on a photo, say who is in each, and get OBJE/CROP/TITL lines to paste.
2
+ // Answers are saved to <config who folder>/<OBJE id>.json; the GEDCOM is only read.
3
+ import fs from 'node:fs'
4
+ import path from 'node:path'
5
+ import { loadConfig } from '../lib/config.mjs'
6
+ import { parseGedcom, restricted } from '../lib/gedcom.mjs'
7
+ import { mediaSource } from '../lib/build.mjs'
8
+ import { imageSize, cropBox } from '../lib/media.mjs'
9
+ import { IMG_EXT, life } from '../lib/render.mjs'
10
+ import { esc } from '../lib/html.mjs'
11
+ import { yr } from '../lib/dates.mjs'
12
+ import { CSS } from '../lib/css.mjs'
13
+ import { TYPES } from './serve.mjs'
14
+
15
+ export function whoPhotos({ indi, obje }) {
16
+ const photos = new Map([...obje].filter(([, o]) => IMG_EXT.has(path.extname(o.file).toLowerCase()))
17
+ .map(([oid, o]) => [oid, { oid, file: o.file, title: o.title, links: [] }]))
18
+ for (const [pid, p] of indi) {
19
+ for (const md of p.media) photos.get(md.obje)?.links.push({ pid, caption: md.caption ?? '', crop: md.crop })
20
+ }
21
+ return photos
22
+ }
23
+
24
+ export function peopleList(indi) {
25
+ const lower = s => s.toLowerCase()
26
+ const cmp = (a, b) => (a < b ? -1 : a > b ? 1 : 0)
27
+ const year = e => (restricted(e) ? null : Number(yr(e.date)) || null)
28
+ return [...indi.values()]
29
+ .sort((a, b) => cmp(lower(a.surn), lower(b.surn)) || cmp(lower(a.giv), lower(b.giv)) || cmp(a.id, b.id))
30
+ .map(p => ({ id: p.id, name: p.name || '(unnamed)', life: life(p), b: year(p.birt), d: year(p.deat) }))
31
+ }
32
+
33
+ export const linkedBoxes = (photo, size) =>
34
+ Object.fromEntries(photo.links.map(({ pid, caption, crop }) => [pid, { caption, box: (crop && cropBox(crop, size)) || null }]))
35
+
36
+ export function seedSession(photo, size) {
37
+ const boxes = photo.links.flatMap(({ pid, caption, crop }) => {
38
+ const box = crop && cropBox(crop, size)
39
+ return box ? [{ ...box, who: pid, guess: false, caption, note: '' }] : []
40
+ }).sort((a, b) => a.left - b.left || a.top - b.top)
41
+ return { year: photo.title.match(/\b\d{4}\b/)?.[0] ?? '', file: photo.file, base: linkedBoxes(photo, size), boxes }
42
+ }
43
+
44
+ const WHO = /^(\w+|not in tree|not sure)?$/
45
+
46
+ export function cleanSession(raw) {
47
+ if (!raw || typeof raw !== 'object' || !Array.isArray(raw.boxes)) return null
48
+ const px = n => (Number.isFinite(n) ? Math.max(0, Math.round(n)) : 0)
49
+ const text = (s, max) => (typeof s === 'string' ? s.slice(0, max) : '')
50
+ const rect = b => ({ left: px(b.left), top: px(b.top), width: px(b.width), height: px(b.height) })
51
+ const base = Object.fromEntries(Object.entries(raw.base && typeof raw.base === 'object' ? raw.base : {})
52
+ .filter(([pid, l]) => /^\w+$/.test(pid) && l && typeof l === 'object' && typeof l.caption === 'string')
53
+ .map(([pid, l]) => [pid, { caption: text(l.caption, 500), box: l.box && typeof l.box === 'object' ? rect(l.box) : null }]))
54
+ const boxes = raw.boxes.filter(b => b && typeof b === 'object').slice(0, 1000).map(b => ({
55
+ ...rect(b),
56
+ who: typeof b.who === 'string' && WHO.test(b.who) ? b.who : '', guess: b.guess === true,
57
+ caption: text(b.caption, 500), note: text(b.note, 5000),
58
+ })).filter(b => b.width && b.height)
59
+ return { year: /^\d{4}$/.test(raw.year) ? raw.year : '', file: text(raw.file, 1000), base, boxes }
60
+ }
61
+
62
+ // base is the GEDCOM's links as the session last saw them: a crop changed in the GEDCOM since then wins over the box.
63
+ export function mergeGedcom(session, now) {
64
+ const boxes = session.boxes.map(b => ({ ...b })), updated = []
65
+ for (const [pid, link] of Object.entries(now)) {
66
+ const was = Object.hasOwn(session.base, pid) ? session.base[pid] : null
67
+ if (!link.box || JSON.stringify(link) === JSON.stringify(was)) continue
68
+ updated.push(pid)
69
+ const b = boxes.find(x => x.who === pid)
70
+ if (b) Object.assign(b, link.box, { caption: link.caption, guess: false })
71
+ else boxes.push({ ...link.box, who: pid, guess: false, caption: link.caption, note: '' })
72
+ }
73
+ return { session: { ...session, base: now, boxes }, updated }
74
+ }
75
+
76
+ // suggest, groups and linkBlocks also run in the page, so each must stand alone.
77
+ export function suggest(people, query, year, linked, limit = 12) {
78
+ const fold = s => s.normalize('NFD').replace(/[̀-ͯ]/g, '').toLowerCase()
79
+ const words = fold(query).split(/\s+/).filter(Boolean)
80
+ const y = /^\d{4}$/.test(year) ? Number(year) : 0
81
+ const alive = ({ b, d }) => {
82
+ if (!y || !(b || d) || (b && b > y) || (d && d < y)) return false
83
+ return d ? !!b || d - y <= 100 : y - b <= 100
84
+ }
85
+ const tier = p => (linked.includes(p.id) ? 'linked' : alive(p) ? 'alive' : '')
86
+ const order = { linked: 0, alive: 1, '': 2 }
87
+ return people
88
+ .filter(p => words.every(w => fold(p.name).includes(w)) || fold(query.trim()) === fold(p.id))
89
+ .map(p => ({ ...p, tier: tier(p) }))
90
+ .map((p, i) => [p, i]).sort(([a, i], [b, j]) => order[a.tier] - order[b.tier] || i - j)
91
+ .slice(0, limit).map(([p]) => p)
92
+ }
93
+
94
+ export function groups(boxes, linked, names) {
95
+ const g = { placed: [], guessed: [], unknown: [], open: [], unboxed: [] }
96
+ boxes.forEach((b, i) => {
97
+ const kind = Object.hasOwn(names, b.who) ? (b.guess ? 'guessed' : 'placed')
98
+ : b.who === 'not in tree' || b.who === 'not sure' ? 'unknown' : 'open'
99
+ g[kind].push(i)
100
+ })
101
+ g.unboxed = linked.filter(pid => !boxes.some(b => b.who === pid))
102
+ return g
103
+ }
104
+
105
+ export function linkBlocks(oid, boxes, linked, names) {
106
+ const blocks = []
107
+ let same = 0
108
+ for (const b of boxes) {
109
+ if (b.guess || !Object.hasOwn(names, b.who)) continue
110
+ const caption = b.caption.replace(/\s+/g, ' ').trim()
111
+ const was = Object.hasOwn(linked, b.who) ? linked[b.who] : null
112
+ if (was?.box && was.caption === caption && ['left', 'top', 'width', 'height'].every(k => was.box[k] === b[k])) {
113
+ same++
114
+ continue
115
+ }
116
+ const lines = [`1 OBJE @${oid}@`, '2 CROP', `3 TOP ${b.top}`, `3 LEFT ${b.left}`, `3 HEIGHT ${b.height}`, `3 WIDTH ${b.width}`]
117
+ if (caption) lines.push(`2 TITL ${caption.replace(/^@/, '@@')}`)
118
+ blocks.push({ pid: b.who, name: names[b.who], status: was ? 'changed' : 'new', text: lines.join('\n') })
119
+ }
120
+ return { blocks, same }
121
+ }
122
+
123
+ const sessionPath = (dir, oid) => path.join(dir, `${oid}.json`)
124
+
125
+ // Throws on a file it can't use, so that file is never overwritten.
126
+ export function readSession(dir, oid) {
127
+ let text
128
+ try {
129
+ text = fs.readFileSync(sessionPath(dir, oid), 'utf8')
130
+ } catch (e) {
131
+ if (e.code === 'ENOENT') return null
132
+ throw e
133
+ }
134
+ const s = cleanSession(JSON.parse(text))
135
+ if (!s) throw new Error('it has no "boxes" list')
136
+ return s
137
+ }
138
+
139
+ function saveSession(dir, photo, session) {
140
+ fs.mkdirSync(dir, { recursive: true })
141
+ const file = sessionPath(dir, photo.oid)
142
+ fs.writeFileSync(file + '.tmp', JSON.stringify({ obje: photo.oid, ...session, file: photo.file }, null, 2) + '\n')
143
+ fs.renameSync(file + '.tmp', file)
144
+ }
145
+
146
+ function sizeOf(file) {
147
+ try {
148
+ const fd = fs.openSync(file, 'r')
149
+ try {
150
+ const buf = Buffer.alloc(1 << 20)
151
+ return imageSize(buf.subarray(0, fs.readSync(fd, buf, 0, buf.length, 0)))
152
+ } finally {
153
+ fs.closeSync(fd)
154
+ }
155
+ } catch {
156
+ return null
157
+ }
158
+ }
159
+
160
+ const shell = (title, body, script = '') => `<!doctype html><html lang=en><head><meta charset=utf-8>` +
161
+ `<meta name=viewport content='width=device-width,initial-scale=1'><title>${esc(title)}</title>` +
162
+ `<style>${CSS}${WHO_CSS}</style></head><body><div class=wrap>${body}</div>${script}</body></html>`
163
+
164
+ const count = (n, one, many = one) => `${n} ${n === 1 ? one : many}`
165
+
166
+ // Without the image's size the GEDCOM crops can't be placed, and merging would forget them.
167
+ function openSession(dir, photo, size) {
168
+ const saved = readSession(dir, photo.oid)
169
+ if (!saved) return { session: seedSession(photo, size), saved: false, updated: [], movedFrom: '' }
170
+ const movedFrom = saved.file && saved.file !== photo.file ? saved.file : ''
171
+ if (movedFrom || !size) return { session: saved, saved: true, updated: [], movedFrom }
172
+ return { ...mergeGedcom(saved, linkedBoxes(photo, size)), saved: true, movedFrom }
173
+ }
174
+
175
+ function indexPage(photos, people, { dir, mediaRoot, shown, folder }) {
176
+ const names = Object.fromEntries(people.map(p => [p.id, p.name]))
177
+ const rows = [...photos.values()].map(photo => {
178
+ const href = `/who/${photo.oid}`, size = sizeOf(mediaSource(photo.file, mediaRoot))
179
+ let state = '', session
180
+ try {
181
+ const s = openSession(dir, photo, size)
182
+ session = s.session
183
+ if (s.saved) state = s.movedFrom ? ` · <b>saved for ${esc(s.movedFrom)}</b>` : ' · saved'
184
+ } catch {
185
+ session = seedSession(photo, size)
186
+ state = ` · <b>${esc(shown(photo.oid))} can't be read</b>`
187
+ }
188
+ const g = groups(session.boxes, photo.links.map(l => l.pid), names)
189
+ const counts = [count(photo.links.length, 'linked'), count(g.placed.length, 'placed'),
190
+ g.guessed.length && count(g.guessed.length, 'guessed'), g.unknown.length && count(g.unknown.length, 'unknown'),
191
+ count(g.open.length + g.unboxed.length, 'to place')].filter(Boolean).join(' · ')
192
+ return `<li><a href="${href}"><img src="${href}/image" alt="" loading=lazy></a><div><a href="${href}">${esc(photo.title || path.basename(photo.file))}</a>` +
193
+ ` <span class=yr>${esc(photo.oid)}</span><div class=cnt>${counts}${state}</div></div></li>`
194
+ })
195
+ return shell('Photos to identify', '<p class=back><a href="/">&larr; Site</a></p><h1>Photos to identify</h1>' +
196
+ `<p class=sub>Draw a box around each person and say who it is. Answers are saved in <code>${esc(folder)}/</code>; ` +
197
+ 'the GEDCOM is never changed.</p>' +
198
+ (rows.length ? `<ul class=whos>${rows.join('')}</ul>` : '<p>No image <code>OBJE</code> records in the GEDCOM.</p>'))
199
+ }
200
+
201
+ function photoPage(photo, data, notices) {
202
+ const t = photo.title || path.basename(photo.file), src = `/who/${photo.oid}/image`
203
+ const body = `<p class=back><a href="/who">&larr; All photos</a></p><h1>${esc(t)}</h1>` +
204
+ `<p class=sub>${esc(photo.oid)} &middot; ${esc(photo.file)} &middot; <label>Taken about <input id=year inputmode=numeric maxlength=4 size=4 placeholder=year></label>` +
205
+ ` &middot; <span id=status></span></p>${notices}` +
206
+ '<p class=hint>Drag on the photo to draw a box around someone. Drag a box to move it, or its corner to resize it.</p>' +
207
+ `<div class=who-grid><div id=stage class=stage><img id=photo src="${src}" alt="${esc(t)}" draggable=false></div>` +
208
+ '<aside id=panel><p id=empty class=sub>Draw a box, or pick one, to say who it is.</p><div id=editor hidden>' +
209
+ `<h2>Box <span id=num></span></h2><div id=zoom><img src="${src}" alt=""></div><p id=answer></p>` +
210
+ '<label for=find>Who is this?</label><input id=find type=search autocomplete=off placeholder="Search by name or ID"><ul id=hits></ul>' +
211
+ '<label class=check><input type=checkbox id=guess> This is a guess</label>' +
212
+ '<label for=caption>Caption for their link (<code>TITL</code>)</label><input id=caption type=text>' +
213
+ '<label for=note>Notes (kept in the session file only)</label><textarea id=note></textarea>' +
214
+ '<p><button type=button id=del>Delete box</button></p></div></aside></div>' +
215
+ '<h2>In this photo</h2><div id=lists></div><h2>For your GEDCOM</h2><div id=paste></div>'
216
+ const json = JSON.stringify(data).replace(/</g, '\\u003c')
217
+ return shell(`Identify: ${t}`, body, `<script>const DATA = ${json};\n(${client})(DATA, ${suggest}, ${groups}, ${linkBlocks})</script>`)
218
+ }
219
+
220
+ const LOCAL_HOST = /^(localhost|127\.0\.0\.1|\[::1\])(:\d+)?$/
221
+ const LOCAL_ADDR = new Set(['127.0.0.1', '::1', '::ffff:127.0.0.1'])
222
+
223
+ export function whoHandler(configFile) {
224
+ const home = path.dirname(path.resolve(configFile))
225
+ return (req, res) => {
226
+ const url = req.url.split('?')[0]
227
+ if (url !== '/who' && !url.startsWith('/who/')) return false
228
+ const send = (status, body, type = 'text/plain; charset=utf-8') => {
229
+ res.writeHead(status, { 'content-type': type, 'cache-control': 'no-store' })
230
+ res.end(body)
231
+ }
232
+ try {
233
+ route(req, url, send)
234
+ } catch (e) {
235
+ send(500, `error: ${e.message}`)
236
+ }
237
+ return true
238
+ }
239
+
240
+ function route(req, url, send) {
241
+ // The whole tree, living people included, and a file write: only for this machine, not the network or a rebound DNS name.
242
+ if (!LOCAL_ADDR.has(req.socket.remoteAddress) || !LOCAL_HOST.test(req.headers.host ?? '')) {
243
+ return send(403, `Identify mode answers only on this machine: http://localhost:${req.socket.localPort}/who`)
244
+ }
245
+ const m = url.match(/^\/who(?:\/(\w+)(\/image)?)?\/?$/)
246
+ if (!m) return send(404, 'not found')
247
+ const [, oid, image] = m
248
+ const config = loadConfig(configFile), dir = config.who
249
+ const shown = oid => path.relative(home, sessionPath(dir, oid))
250
+ const parsed = parseGedcom(fs.readFileSync(config.gedcom, 'utf8'))
251
+ const photos = whoPhotos(parsed), people = peopleList(parsed.indi)
252
+ const photo = oid && photos.get(oid)
253
+ if (oid && !photo) return send(404, 'not found')
254
+ if (req.method === 'POST' && photo && !image) return save(req, send, dir, photo, shown(oid))
255
+ if (req.method !== 'GET' && req.method !== 'HEAD') return send(405, 'method not allowed')
256
+ if (!photo) return send(200, indexPage(photos, people, { dir, mediaRoot: config.mediaRoot, shown, folder: path.relative(home, dir) }), TYPES['.html'])
257
+ const file = mediaSource(photo.file, config.mediaRoot)
258
+ if (image) {
259
+ if (!fs.statSync(file, { throwIfNoEntry: false })?.isFile()) return send(404, 'not found')
260
+ return send(200, fs.readFileSync(file), TYPES[path.extname(file).toLowerCase()])
261
+ }
262
+ const size = sizeOf(file)
263
+ let s
264
+ try {
265
+ s = openSession(dir, photo, size)
266
+ } catch (e) {
267
+ return send(500, `${shown(oid)} can't be read (${e.message}). Fix or move it; identify mode won't overwrite it.`)
268
+ }
269
+ const names = Object.fromEntries(people.map(p => [p.id, p.name]))
270
+ const notices = (s.movedFrom ? `<p class=warn>This session was saved for <code>${esc(s.movedFrom)}</code>, but ${esc(oid)} is now ` +
271
+ `<code>${esc(photo.file)}</code>. If the GEDCOM's IDs were renumbered, these boxes may belong to another photo: ` +
272
+ `move <code>${esc(shown(oid))}</code> aside. Changes won't save until you do, or until you say ` +
273
+ `<button type=button id=keep>These boxes are for ${esc(photo.file)}</button></p>` : '') +
274
+ (s.updated.length ? `<p class=merged>Updated from the GEDCOM since this session was saved: ${esc(s.updated.map(pid => names[pid]).join(', '))}.</p>` : '')
275
+ send(200, photoPage(photo, {
276
+ oid, file: photo.file, size, saved: s.saved, session: s.session, people, sessionFile: shown(oid),
277
+ linkedIds: photo.links.map(l => l.pid), linked: linkedBoxes(photo, size),
278
+ }, notices), TYPES['.html'])
279
+ }
280
+
281
+ function save(req, send, dir, photo, shown) {
282
+ // A JSON body makes a cross-site request preflight, which this server never grants.
283
+ if (!/^application\/json\b/.test(req.headers['content-type'] ?? '')) return send(415, 'send JSON')
284
+ if (req.headers.origin && req.headers.origin !== `http://${req.headers.host}`) return send(403, 'forbidden')
285
+ const chunks = []
286
+ let size = 0
287
+ req.on('data', c => {
288
+ size += c.length
289
+ if (size > 2 << 20) {
290
+ send(413, 'too large')
291
+ req.destroy()
292
+ } else chunks.push(c)
293
+ })
294
+ req.on('end', () => {
295
+ let session
296
+ try {
297
+ session = cleanSession(JSON.parse(Buffer.concat(chunks).toString('utf8')))
298
+ } catch {}
299
+ if (!session) return send(400, 'not a session')
300
+ try {
301
+ const was = readSession(dir, photo.oid)?.file
302
+ if (was && was !== photo.file && session.file !== photo.file) {
303
+ return send(409, `this session was saved for ${was}. Say the boxes are for ${photo.file}, or move ${shown} aside.`)
304
+ }
305
+ saveSession(dir, photo, session)
306
+ send(204, '')
307
+ } catch (e) {
308
+ send(500, `error: ${e.message}`)
309
+ }
310
+ })
311
+ }
312
+ }
313
+
314
+ function client(D, suggest, groups, linkBlocks) {
315
+ const $ = id => document.getElementById(id)
316
+ const stage = $('stage'), img = $('photo'), find = $('find'), hits = $('hits')
317
+ const names = Object.fromEntries(D.people.map(p => [p.id, p.name]))
318
+ const lives = Object.fromEntries(D.people.map(p => [p.id, p.life]))
319
+ const isPerson = who => Object.hasOwn(names, who)
320
+ const S = D.session, boxes = S.boxes
321
+ let size = D.size, sel = -1, drag = null, timer = null, undo = null
322
+ const h = s => String(s).replace(/[&<>"']/g, c => `&#${c.charCodeAt(0)};`)
323
+ const pct = (n, of) => `${(n / of) * 100}%`
324
+ const label = who => (isPerson(who) ? names[who] : who === 'not in tree' ? 'Someone not in the tree' : who === 'not sure' ? 'Not sure' : 'No answer yet')
325
+ const setValue = (el, v) => { if (el.value !== v) el.value = v }
326
+
327
+ function status(text) {
328
+ $('status').innerHTML = h(text) + (undo ? ` <button type=button id=undo>Undo</button>` : '')
329
+ }
330
+
331
+ function drawBoxes() {
332
+ stage.querySelectorAll('.box').forEach(e => e.remove())
333
+ if (!size) return
334
+ const g = groups(boxes, D.linkedIds, names), kind = {}
335
+ for (const k of ['placed', 'guessed', 'unknown', 'open']) for (const i of g[k]) kind[i] = k
336
+ boxes.forEach((b, i) => {
337
+ const e = document.createElement('div')
338
+ e.className = `box ${kind[i]}${i === sel ? ' sel' : ''}`
339
+ e.dataset.i = i
340
+ e.title = label(b.who)
341
+ Object.assign(e.style, { left: pct(b.left, size.width), top: pct(b.top, size.height), width: pct(b.width, size.width), height: pct(b.height, size.height) })
342
+ e.innerHTML = `<b>${i + 1}</b>${i === sel ? '<i class=handle></i>' : ''}`
343
+ stage.append(e)
344
+ })
345
+ }
346
+
347
+ function zoom(b) {
348
+ const z = $('zoom')
349
+ z.style.aspectRatio = `${b.width} / ${b.height}`
350
+ z.style.width = `min(100%, ${Math.round((280 * b.width) / b.height)}px)`
351
+ Object.assign(z.firstChild.style, { width: pct(size.width, b.width), left: pct(-b.left, b.width), top: pct(-b.top, b.height) })
352
+ }
353
+
354
+ function showHits() {
355
+ const b = boxes[sel], inBox = new Map(boxes.map((x, i) => [x.who, i]))
356
+ const why = { linked: 'linked to this photo', alive: `alive in ${S.year}` }
357
+ const free = p => !inBox.has(p.id) || inBox.get(p.id) === sel
358
+ const found = suggest(D.people, find.value, S.year, D.linkedIds, 50)
359
+ hits.innerHTML = [...found.filter(free), ...found.filter(p => !free(p))].slice(0, 12).map(p =>
360
+ `<li><button type=button data-who="${h(p.id)}"${p.id === b.who ? ' class=on' : ''}>${h(p.name)}` +
361
+ (p.life ? ` <span class=yr>${h(p.life)}</span>` : '') + (p.tier ? ` <small>${why[p.tier]}</small>` : '') +
362
+ (inBox.has(p.id) && inBox.get(p.id) !== sel ? ` <small>in box ${inBox.get(p.id) + 1}</small>` : '') + '</button></li>').join('') +
363
+ ['not in tree', 'not sure'].map(w => `<li><button type=button data-who="${w}" class="alt${b.who === w ? ' on' : ''}">${label(w)}</button></li>`).join('')
364
+ }
365
+
366
+ function showPanel() {
367
+ const b = boxes[sel]
368
+ $('editor').hidden = !b
369
+ $('empty').hidden = !!b
370
+ if (!b) return
371
+ $('num').textContent = sel + 1
372
+ $('answer').innerHTML = isPerson(b.who)
373
+ ? `<a href="/${h(b.who)}.html" target=_blank>${h(names[b.who])}</a>${lives[b.who] ? ` <span class=yr>(${h(lives[b.who])})</span>` : ''}`
374
+ : `<span class=unknown>${h(label(b.who))}</span>`
375
+ $('guess').checked = b.guess
376
+ $('guess').disabled = !isPerson(b.who)
377
+ setValue($('caption'), b.caption)
378
+ setValue($('note'), b.note)
379
+ zoom(b)
380
+ showHits()
381
+ }
382
+
383
+ function showLists() {
384
+ const g = groups(boxes, D.linkedIds, names)
385
+ const item = i => {
386
+ const b = boxes[i]
387
+ return `<li><button type=button class=pick data-i=${i}>Box ${i + 1}</button> ${h(label(b.who))}` +
388
+ (b.caption ? ` <span class=cn>${h(b.caption)}</span>` : '') + (b.note ? ` <span class=yr>&mdash; ${h(b.note)}</span>` : '') + '</li>'
389
+ }
390
+ const part = (title, items) => (items.length ? `<h3>${title} (${items.length})</h3><ul class=rel>${items.join('')}</ul>` : '')
391
+ $('lists').innerHTML = part('Placed', g.placed.map(item)) + part('Guessed', g.guessed.map(item)) + part('Unknown', g.unknown.map(item)) +
392
+ part('To place', [...g.open.map(item), ...g.unboxed.map(pid => `<li>${h(names[pid])} <span class=yr>linked, no box yet</span></li>`)]) ||
393
+ '<p class=sub>No boxes yet.</p>'
394
+ }
395
+
396
+ let blocks = []
397
+ function showPaste() {
398
+ const out = linkBlocks(D.oid, boxes, D.linked, names)
399
+ blocks = out.blocks
400
+ const what = { new: 'add this link', changed: `replace their link to @${D.oid}@ with this` }
401
+ const same = out.same ? `${out.same} placed ${out.same === 1 ? 'person already matches' : 'people already match'} the GEDCOM. ` : ''
402
+ $('paste').innerHTML = blocks.map((k, n) =>
403
+ `<div class=block><p><b>${h(k.name)}</b> <span class=yr>under <code>0 @${h(k.pid)}@ INDI</code>, ${what[k.status]}</span> ` +
404
+ `<button type=button class=copy data-n=${n}>Copy</button></p><pre>${h(k.text)}</pre></div>`).join('') +
405
+ `<p class=sub>${blocks.length ? '' : 'Nothing new to paste. '}${same}Guesses, unknowns and notes stay in <code>${h(D.sessionFile)}</code>.</p>`
406
+ }
407
+
408
+ function render() {
409
+ drawBoxes()
410
+ showPanel()
411
+ showLists()
412
+ showPaste()
413
+ }
414
+
415
+ async function save(keepalive = false) {
416
+ clearTimeout(timer)
417
+ timer = null
418
+ try {
419
+ const r = await fetch(location.pathname, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(S), keepalive })
420
+ status(r.ok ? 'Saved' : `Not saved: ${await r.text()}`)
421
+ return r.ok
422
+ } catch {
423
+ status('Not saved: is npm run dev still running?')
424
+ }
425
+ }
426
+
427
+ function changed(keepUndo = false) {
428
+ if (!keepUndo) undo = null
429
+ render()
430
+ status('Saving…')
431
+ clearTimeout(timer)
432
+ timer = setTimeout(save, 400)
433
+ }
434
+
435
+ function select(i) {
436
+ sel = i
437
+ find.value = ''
438
+ render()
439
+ if (i >= 0) find.focus({ preventScroll: true })
440
+ }
441
+
442
+ const point = e => {
443
+ const r = img.getBoundingClientRect(), clamp = v => Math.min(Math.max(v, 0), 1)
444
+ return { x: clamp((e.clientX - r.left) / r.width) * size.width, y: clamp((e.clientY - r.top) / r.height) * size.height }
445
+ }
446
+ const span = (x0, y0, x1, y1) => ({
447
+ left: Math.round(Math.min(x0, x1)), top: Math.round(Math.min(y0, y1)),
448
+ width: Math.max(1, Math.round(Math.abs(x1 - x0))), height: Math.max(1, Math.round(Math.abs(y1 - y0))),
449
+ })
450
+
451
+ stage.addEventListener('pointerdown', e => {
452
+ if (!size || e.button !== 0) return
453
+ const p = point(e), el = e.target.closest('.box'), i = el ? +el.dataset.i : -1
454
+ if (e.target.classList.contains('handle')) drag = { mode: 'size', i, x0: boxes[i].left, y0: boxes[i].top }
455
+ else if (el) drag = { mode: 'move', i, dx: p.x - boxes[i].left, dy: p.y - boxes[i].top }
456
+ else drag = { mode: 'draw', i: -1, x0: p.x, y0: p.y }
457
+ if (el) sel = i
458
+ stage.setPointerCapture(e.pointerId)
459
+ e.preventDefault()
460
+ drawBoxes()
461
+ })
462
+ stage.addEventListener('pointermove', e => {
463
+ if (!drag) return
464
+ const p = point(e), b = boxes[drag.i]
465
+ if (drag.mode === 'move') {
466
+ b.left = Math.round(Math.min(Math.max(p.x - drag.dx, 0), size.width - b.width))
467
+ b.top = Math.round(Math.min(Math.max(p.y - drag.dy, 0), size.height - b.height))
468
+ } else if (b) Object.assign(b, span(drag.x0, drag.y0, p.x, p.y))
469
+ else if (Math.hypot(p.x - drag.x0, p.y - drag.y0) > (8 * size.width) / img.getBoundingClientRect().width) {
470
+ boxes.push({ ...span(drag.x0, drag.y0, p.x, p.y), who: '', guess: false, caption: '', note: '' })
471
+ drag.i = sel = boxes.length - 1
472
+ } else return
473
+ drag.moved = true
474
+ drawBoxes()
475
+ if (boxes[sel]) zoom(boxes[sel])
476
+ })
477
+ const end = () => {
478
+ if (!drag) return
479
+ const { moved, i } = drag
480
+ drag = null
481
+ select(i)
482
+ if (moved) changed()
483
+ }
484
+ stage.addEventListener('pointerup', end)
485
+ stage.addEventListener('pointercancel', end)
486
+
487
+ hits.addEventListener('click', e => {
488
+ const btn = e.target.closest('button')
489
+ if (!btn) return
490
+ const b = boxes[sel]
491
+ b.who = btn.dataset.who
492
+ if (!isPerson(b.who)) b.guess = false
493
+ find.value = ''
494
+ changed()
495
+ })
496
+ find.addEventListener('input', showHits)
497
+ find.addEventListener('keydown', e => {
498
+ if (e.key !== 'Enter') return
499
+ e.preventDefault()
500
+ hits.querySelector('button')?.click()
501
+ })
502
+ $('guess').addEventListener('change', e => { boxes[sel].guess = e.target.checked; changed() })
503
+ $('caption').addEventListener('input', e => { boxes[sel].caption = e.target.value; changed() })
504
+ $('note').addEventListener('input', e => { boxes[sel].note = e.target.value; changed() })
505
+ $('year').value = S.year
506
+ $('year').addEventListener('input', e => {
507
+ const v = e.target.value.trim()
508
+ S.year = /^\d{4}$/.test(v) ? v : ''
509
+ changed()
510
+ })
511
+ $('del').addEventListener('click', () => {
512
+ undo = { i: sel, box: boxes.splice(sel, 1)[0] }
513
+ sel = -1
514
+ changed(true)
515
+ })
516
+ $('status').addEventListener('click', e => {
517
+ if (e.target.id !== 'undo') return
518
+ boxes.splice(undo.i, 0, undo.box)
519
+ sel = undo.i
520
+ undo = null
521
+ changed()
522
+ })
523
+ $('lists').addEventListener('click', e => {
524
+ const b = e.target.closest('.pick')
525
+ if (b) select(+b.dataset.i)
526
+ })
527
+ $('paste').addEventListener('click', e => {
528
+ const b = e.target.closest('.copy')
529
+ if (!b) return
530
+ navigator.clipboard.writeText(blocks[+b.dataset.n].text).then(() => { b.textContent = 'Copied' })
531
+ })
532
+ $('keep')?.addEventListener('click', async () => {
533
+ S.file = D.file
534
+ if (await save()) $('keep').closest('.warn').remove()
535
+ })
536
+ addEventListener('beforeunload', () => { if (timer) save(true) })
537
+ addEventListener('keydown', e => { if (e.key === 'Escape' && sel >= 0) select(-1) })
538
+
539
+ const start = () => {
540
+ size ||= { width: img.naturalWidth, height: img.naturalHeight }
541
+ render()
542
+ }
543
+ status(D.saved ? 'Saved' : 'Starting from the GEDCOM; changes save as you go')
544
+ if (size) render()
545
+ else if (img.complete && img.naturalWidth) start()
546
+ else img.addEventListener('load', start)
547
+ }
548
+
549
+ const WHO_CSS = `
550
+ .wrap{max-width:1180px}
551
+ .hint{color:var(--mut);font-size:.9em;margin:0 0 .6em}
552
+ .warn,.merged{border-radius:8px;padding:8px 12px;margin:.6em 0}
553
+ .warn{background:#fff4d6;border:1px solid #e8c96a}
554
+ .merged{background:#eef4ea;border:1px solid #c9dbbf}
555
+ .sub input{width:4.2em;font:inherit;padding:1px 4px;border:1px solid var(--line);border-radius:4px}
556
+ #status button{font:inherit;font-size:.9em;padding:0 6px}
557
+ .who-grid{display:grid;grid-template-columns:minmax(0,1fr) 320px;gap:20px;align-items:start}
558
+ @media(max-width:860px){.who-grid{grid-template-columns:minmax(0,1fr)}}
559
+ #stage{margin:0;touch-action:none;user-select:none;-webkit-user-select:none;cursor:crosshair}
560
+ #stage img{pointer-events:none}
561
+ .box{position:absolute;border:2px solid #fff;box-shadow:0 0 0 1px rgba(0,0,0,.6);cursor:move}
562
+ .box b{position:absolute;left:0;top:0;min-width:1.5em;padding:0 .25em;font-size:12px;line-height:1.5em;
563
+ text-align:center;color:#fff;background:rgba(0,0,0,.6);border-radius:0 0 3px 0;pointer-events:none}
564
+ .box.guessed{border-style:dashed}
565
+ .box.unknown{border-color:#f3c86b}
566
+ .box.open{border-style:dotted}
567
+ .box.sel{border-color:var(--accent);box-shadow:0 0 0 2px #fff,0 0 0 3px rgba(0,0,0,.5)}
568
+ .handle{position:absolute;right:-8px;bottom:-8px;width:16px;height:16px;background:#fff;border:2px solid var(--accent);
569
+ border-radius:3px;cursor:nwse-resize}
570
+ #panel{position:sticky;top:12px;background:#fff;border:1px solid var(--line);border-radius:10px;padding:4px 16px 12px}
571
+ #panel h2{margin-top:.8em}
572
+ #zoom{position:relative;overflow:hidden;border-radius:6px;background:#eee;margin:.4em 0}
573
+ #zoom img{position:absolute;max-width:none}
574
+ #answer{margin:.3em 0;font-weight:600}
575
+ #panel label{display:block;font-size:.85em;color:var(--mut);margin:.7em 0 .2em}
576
+ #panel label.check{color:var(--ink)}
577
+ #panel input[type=search],#panel input[type=text],#panel textarea{width:100%;padding:7px 9px;font:inherit;
578
+ border:1px solid var(--line);border-radius:6px}
579
+ #panel textarea{min-height:5em;resize:vertical}
580
+ #hits{list-style:none;margin:.3em 0;padding:0;max-height:280px;overflow:auto}
581
+ #hits button{display:block;width:100%;text-align:left;padding:4px 8px;border:0;background:none;font:inherit;
582
+ color:var(--ink);border-radius:5px;cursor:pointer}
583
+ #hits button:hover,#hits button:focus{background:#f3ece0}
584
+ #hits button.on{background:#efe3d2;font-weight:600}
585
+ #hits button.alt{color:var(--mut);font-style:italic}
586
+ #hits small{color:var(--accent);font-size:.75em;margin-left:.3em}
587
+ #lists h3{font-size:.9em;margin:.8em 0 .3em}
588
+ #lists .pick{font:inherit;font-size:.85em;padding:0 6px}
589
+ .block p{margin:.6em 0 .2em}
590
+ .block pre{background:#fff;border:1px solid var(--line);border-radius:6px;padding:8px 10px;overflow-x:auto;margin:0}
591
+ ul.whos{list-style:none;padding:0;margin:0}
592
+ ul.whos li{display:flex;gap:14px;align-items:center;padding:8px 0;border-bottom:1px solid var(--line)}
593
+ ul.whos img{width:120px;height:80px;object-fit:cover;border-radius:6px;border:1px solid var(--line);display:block}
594
+ ul.whos .cnt{color:var(--mut);font-size:.9em}
595
+ `