kinsite 0.3.0 → 0.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +238 -1
- package/build.mjs +29 -8
- package/lib/build.mjs +26 -4
- package/lib/config.mjs +6 -1
- package/lib/css.mjs +21 -2
- package/lib/diff.mjs +266 -0
- package/lib/gedcom.mjs +66 -12
- package/lib/hourglass.mjs +4 -2
- package/lib/kin.mjs +2 -1
- package/lib/living.mjs +15 -5
- package/lib/media.mjs +74 -0
- package/lib/news.mjs +175 -0
- package/lib/render.mjs +111 -20
- package/package.json +2 -1
- package/scripts/dev.mjs +56 -0
- package/scripts/serve.mjs +56 -0
- package/scripts/who.mjs +595 -0
package/scripts/who.mjs
ADDED
|
@@ -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="/">← 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">← All photos</a></p><h1>${esc(t)}</h1>` +
|
|
204
|
+
`<p class=sub>${esc(photo.oid)} · ${esc(photo.file)} · <label>Taken about <input id=year inputmode=numeric maxlength=4 size=4 placeholder=year></label>` +
|
|
205
|
+
` · <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>— ${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
|
+
`
|