@micropasts/authority-card 0.0.0-stage → 0.1.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.
@@ -0,0 +1,778 @@
1
+ /**
2
+ * @micropasts/authority-card v0.1.0
3
+ * Zero-dependency Linked Open Data authority cards (Shadow DOM + Tailwind CSS)
4
+ * License: MIT
5
+ */
6
+
7
+ // --- core.js ---
8
+ const MEMORY_CACHE = new Map();
9
+ const IN_FLIGHT = new Map();
10
+ const ADAPTERS = [];
11
+
12
+ const GETTY_FALLBACKS = {
13
+ 'http://vocab.getty.edu/aat/300037222': {
14
+ source: 'Getty AAT',
15
+ badgeColor: '#881337',
16
+ id: '300037222',
17
+ label: 'denarii',
18
+ subtitle: 'Vocabulary Authority · 300037222 (Cached Fallback)',
19
+ scopeNote:
20
+ 'Silver coins of the Roman Republic and Empire, first struck around 211 BCE.',
21
+ aliases: ['denarius', 'denier'],
22
+ },
23
+ 'http://vocab.getty.edu/tgn/7011781': {
24
+ source: 'Getty TGN',
25
+ badgeColor: '#881337',
26
+ id: '7011781',
27
+ label: 'London',
28
+ subtitle: 'Vocabulary Authority · 7011781 (Cached Fallback)',
29
+ scopeNote:
30
+ 'Inhabited place; capital city of the United Kingdom on the River Thames, founded as Roman Londinium.',
31
+ aliases: ['Londinium', 'Greater London'],
32
+ meta: [{ label: 'Coordinates', value: '51.5072°, -0.1276°' }],
33
+ },
34
+ };
35
+
36
+ export function registerAdapter(adapter) {
37
+ ADAPTERS.unshift(adapter);
38
+ }
39
+
40
+ export function seedRecords(recordsMap) {
41
+ for (const [uri, record] of Object.entries(recordsMap)) {
42
+ MEMORY_CACHE.set(uri, { ...record, uri });
43
+ }
44
+ }
45
+
46
+ export function clearCache() {
47
+ MEMORY_CACHE.clear();
48
+ }
49
+
50
+ export async function copyTextToClipboard(text) {
51
+ const value = String(text ?? '').trim();
52
+ if (!value) return false;
53
+
54
+ if (
55
+ typeof navigator !== 'undefined' &&
56
+ navigator.clipboard &&
57
+ typeof navigator.clipboard.writeText === 'function' &&
58
+ typeof window !== 'undefined' &&
59
+ window.isSecureContext
60
+ ) {
61
+ try {
62
+ await navigator.clipboard.writeText(value);
63
+ return true;
64
+ } catch {
65
+ // Fall through to execCommand fallback below
66
+ }
67
+ }
68
+
69
+ try {
70
+ const ta = document.createElement('textarea');
71
+ ta.value = value;
72
+ ta.setAttribute('readonly', '');
73
+ ta.style.position = 'fixed';
74
+ ta.style.top = '-9999px';
75
+ ta.style.left = '-9999px';
76
+ document.body.appendChild(ta);
77
+ ta.focus();
78
+ ta.select();
79
+ const ok = document.execCommand('copy');
80
+ document.body.removeChild(ta);
81
+ return Boolean(ok);
82
+ } catch {
83
+ return false;
84
+ }
85
+ }
86
+
87
+ export async function resolveAuthority(uri, fallbackLabel = '') {
88
+ if (!uri) return null;
89
+ if (MEMORY_CACHE.has(uri)) return MEMORY_CACHE.get(uri);
90
+ if (IN_FLIGHT.has(uri)) return IN_FLIGHT.get(uri);
91
+
92
+ const adapter = ADAPTERS.find((a) => a.match(uri));
93
+ if (!adapter) {
94
+ return {
95
+ source: 'External URI',
96
+ badgeColor: '#52525b',
97
+ id: uri,
98
+ label: fallbackLabel || uri,
99
+ subtitle: 'Unmapped Authority Endpoint',
100
+ scopeNote: '',
101
+ meta: [],
102
+ aliases: [],
103
+ sameAs: [],
104
+ uri,
105
+ };
106
+ }
107
+
108
+ const promise = adapter
109
+ .fetch(adapter.match(uri), uri)
110
+ .then((data) => {
111
+ const normalized = {
112
+ source: adapter.name,
113
+ badgeColor: adapter.badgeColor || '#334155',
114
+ meta: [],
115
+ aliases: [],
116
+ sameAs: [],
117
+ ...data,
118
+ uri: data?.uri || uri,
119
+ };
120
+ MEMORY_CACHE.set(uri, normalized);
121
+ IN_FLIGHT.delete(uri);
122
+ return normalized;
123
+ })
124
+ .catch(() => {
125
+ IN_FLIGHT.delete(uri);
126
+ return {
127
+ source: adapter.name,
128
+ badgeColor: adapter.badgeColor || '#334155',
129
+ id: uri,
130
+ label: fallbackLabel || uri,
131
+ subtitle: 'Live remote fetch unavailable or blocked in browser',
132
+ scopeNote:
133
+ 'Seed records via seedRecords() or resolve server-side for offline or restricted endpoints.',
134
+ meta: [],
135
+ aliases: [],
136
+ sameAs: [],
137
+ uri,
138
+ fallback: true,
139
+ };
140
+ });
141
+
142
+ IN_FLIGHT.set(uri, promise);
143
+ return promise;
144
+ }
145
+
146
+ export function emitSelect(target, uri, record = null) {
147
+ target.dispatchEvent(
148
+ new CustomEvent('heritage:select', {
149
+ bubbles: true,
150
+ composed: true,
151
+ detail: { uri, record },
152
+ })
153
+ );
154
+ }
155
+
156
+ registerAdapter({
157
+ name: 'Nomisma',
158
+ badgeColor: '#9a3412',
159
+ match: (uri) => /nomisma\.org\/id\/([^/?#]+)/i.exec(uri),
160
+ async fetch([, id]) {
161
+ const url = `https://nomisma.org/id/${id}.jsonld`;
162
+ const res = await fetch(url);
163
+ if (!res.ok) throw new Error(`HTTP ${res.status}`);
164
+ const json = await res.json();
165
+ const graph = json['@graph'] || [json];
166
+ const entity = graph.find((n) => n['@id']?.endsWith(`/id/${id}`)) || graph[0];
167
+
168
+ const labelObj = Array.isArray(entity['skos:prefLabel'])
169
+ ? entity['skos:prefLabel'].find((l) => l['@language'] === 'en') || entity['skos:prefLabel'][0]
170
+ : entity['skos:prefLabel'];
171
+ const defObj = Array.isArray(entity['skos:definition'])
172
+ ? entity['skos:definition'].find((d) => d['@language'] === 'en') || entity['skos:definition'][0]
173
+ : entity['skos:definition'];
174
+
175
+ const lat = entity['geo:lat']?.['@value'] || entity['geo:lat'];
176
+ const long = entity['geo:long']?.['@value'] || entity['geo:long'];
177
+
178
+ return {
179
+ id,
180
+ label: labelObj?.['@value'] || labelObj || id,
181
+ subtitle: 'Numismatic Concept · Nomisma.org',
182
+ scopeNote: defObj?.['@value'] || defObj || '',
183
+ meta:
184
+ lat && long
185
+ ? [{ label: 'Coordinates', value: `${Number(lat).toFixed(4)}°, ${Number(long).toFixed(4)}°` }]
186
+ : [],
187
+ };
188
+ },
189
+ });
190
+
191
+ registerAdapter({
192
+ name: 'Getty',
193
+ badgeColor: '#881337',
194
+ match: (uri) => /^https?:\/\/vocab\.getty\.edu\/(?:page\/)?(aat|tgn|ulan)\/(\d+)/i.exec(uri),
195
+ async fetch([, vocab, id], uri) {
196
+ const canonicalUri = `http://vocab.getty.edu/${vocab}/${id}`;
197
+ const httpsUri = `https://vocab.getty.edu/${vocab}/${id}`;
198
+ const fallback =
199
+ GETTY_FALLBACKS[canonicalUri] ||
200
+ GETTY_FALLBACKS[httpsUri] ||
201
+ GETTY_FALLBACKS[uri];
202
+
203
+ try {
204
+ const query = `
205
+ PREFIX skos: <http://www.w3.org/2004/02/skos/core#>
206
+ PREFIX gvp: <http://vocab.getty.edu/ontology#>
207
+ SELECT ?label ?note WHERE {
208
+ { <${canonicalUri}> (gvp:prefLabelGVP/xl:literalForm|skos:prefLabel) ?label . }
209
+ UNION
210
+ { <${httpsUri}> (gvp:prefLabelGVP/xl:literalForm|skos:prefLabel) ?label . }
211
+ FILTER (LANG(?label) = "en" || LANG(?label) = "")
212
+ OPTIONAL {
213
+ { <${canonicalUri}> skos:scopeNote ?note . }
214
+ UNION
215
+ { <${httpsUri}> skos:scopeNote ?note . }
216
+ FILTER (LANG(?note) = "en" || LANG(?note) = "")
217
+ }
218
+ }
219
+ LIMIT 1
220
+ `;
221
+
222
+ const url = `https://vocab.getty.edu/sparql.json?query=${encodeURIComponent(query)}`;
223
+ const res = await fetch(url, {
224
+ headers: { Accept: 'application/sparql-results+json' },
225
+ });
226
+
227
+ if (!res.ok) {
228
+ throw new Error(`Getty SPARQL HTTP ${res.status}`);
229
+ }
230
+
231
+ const data = await res.json();
232
+ const binding = data?.results?.bindings?.[0];
233
+ if (!binding) {
234
+ throw new Error('No SPARQL binding returned');
235
+ }
236
+
237
+ const label = binding.label?.value || fallback?.label || `${vocab.toUpperCase()} ${id}`;
238
+ const rawNote = binding.note?.value || fallback?.scopeNote || '';
239
+ const scopeNote = rawNote.length > 240 ? `${rawNote.slice(0, 240)}…` : rawNote;
240
+
241
+ return {
242
+ source: `Getty ${vocab.toUpperCase()}`,
243
+ id,
244
+ label,
245
+ subtitle: `Vocabulary Authority · ${id}`,
246
+ scopeNote,
247
+ uri: httpsUri,
248
+ };
249
+ } catch {
250
+ if (fallback) {
251
+ return { ...fallback, uri: httpsUri };
252
+ }
253
+
254
+ return {
255
+ source: `Getty ${vocab.toUpperCase()}`,
256
+ id,
257
+ label: `${vocab.toUpperCase()} ${id}`,
258
+ subtitle: 'Getty HTTPS SPARQL blocked in browser',
259
+ scopeNote:
260
+ 'Seed Getty terms via seedRecords() or resolve via your own server/build step for static sites.',
261
+ uri: httpsUri,
262
+ };
263
+ }
264
+ },
265
+ });
266
+
267
+ registerAdapter({
268
+ name: 'Wikidata',
269
+ badgeColor: '#0369a1',
270
+ match: (uri) => /wikidata\.org\/(entity|wiki)\/(Q\d+)/i.exec(uri),
271
+ async fetch([, , qid]) {
272
+ const url = `https://www.wikidata.org/wiki/Special:EntityData/${qid}.json`;
273
+ const res = await fetch(url);
274
+ if (!res.ok) throw new Error(`HTTP ${res.status}`);
275
+ const data = await res.json();
276
+ const entity = data.entities[qid];
277
+
278
+ const label = entity.labels?.en?.value || qid;
279
+ const description = entity.descriptions?.en?.value || '';
280
+ const aliases = (entity.aliases?.en || []).slice(0, 4).map((a) => a.value);
281
+ const img = entity.claims?.P18?.[0]?.mainsnak?.datavalue?.value;
282
+ const thumb = img
283
+ ? `https://commons.wikimedia.org/wiki/Special:FilePath/${encodeURIComponent(img)}?width=180`
284
+ : null;
285
+
286
+ return {
287
+ id: qid,
288
+ label,
289
+ subtitle: description,
290
+ scopeNote: description,
291
+ aliases,
292
+ thumb,
293
+ };
294
+ },
295
+ });
296
+
297
+ registerAdapter({
298
+ name: 'Pleiades',
299
+ badgeColor: '#15803d',
300
+ match: (uri) => /pleiades\.stoa\.org\/places\/(\d+)/i.exec(uri),
301
+ async fetch([, id]) {
302
+ const url = `https://pleiades.stoa.org/places/${id}/json`;
303
+ const res = await fetch(url);
304
+ if (!res.ok) throw new Error(`HTTP ${res.status}`);
305
+ const data = await res.json();
306
+
307
+ const coords = data.reprPoint
308
+ ? `${data.reprPoint[1].toFixed(4)}°, ${data.reprPoint[0].toFixed(4)}°`
309
+ : null;
310
+
311
+ return {
312
+ id,
313
+ label: data.title || `Place ${id}`,
314
+ subtitle: (data.placeTypes || []).join(', ') || 'Ancient Place',
315
+ scopeNote: data.description || '',
316
+ aliases: (data.names || [])
317
+ .slice(0, 4)
318
+ .map((n) => n.attested || n.romanized)
319
+ .filter(Boolean),
320
+ meta: coords ? [{ label: 'Coordinates', value: coords }] : [],
321
+ };
322
+ },
323
+ });
324
+
325
+ // --- shadow.js ---
326
+ let globalTemplate = null;
327
+
328
+ export class AuthorityCard extends HTMLElement {
329
+ static get observedAttributes() {
330
+ return ['uri', 'mode', 'listen'];
331
+ }
332
+
333
+ static setTemplate(fn) {
334
+ globalTemplate = fn;
335
+ }
336
+
337
+ constructor() {
338
+ super();
339
+ this.attachShadow({ mode: 'open' });
340
+ this._open = false;
341
+ this._data = null;
342
+ this.template = null;
343
+ this._onExternalSelect = this._onExternalSelect.bind(this);
344
+ }
345
+
346
+ connectedCallback() {
347
+ this.renderShell();
348
+ this._bindEvents();
349
+ if (this.mode === 'panel' && this.getAttribute('uri')) {
350
+ this.loadAndRender(this.getAttribute('uri'));
351
+ }
352
+ }
353
+
354
+ disconnectedCallback() {
355
+ const eventName = this.getAttribute('listen');
356
+ if (eventName) {
357
+ window.removeEventListener(eventName, this._onExternalSelect);
358
+ }
359
+ }
360
+
361
+ attributeChangedCallback(name, oldVal, newVal) {
362
+ if (oldVal === newVal || !this.isConnected) return;
363
+ if (name === 'uri' && this.mode === 'panel' && newVal) {
364
+ this.loadAndRender(newVal);
365
+ }
366
+ if (name === 'mode') {
367
+ this.renderShell();
368
+ this._bindEvents();
369
+ }
370
+ }
371
+
372
+ get mode() {
373
+ return this.getAttribute('mode') || 'popover';
374
+ }
375
+
376
+ _bindEvents() {
377
+ const eventName = this.getAttribute('listen');
378
+ if (eventName) {
379
+ window.addEventListener(eventName, this._onExternalSelect);
380
+ }
381
+
382
+ if (this.mode === 'popover') {
383
+ const trigger = this.shadowRoot.querySelector('[part="trigger"]');
384
+ trigger?.addEventListener('mouseenter', () => this.open());
385
+ trigger?.addEventListener('focus', () => this.open());
386
+ trigger?.addEventListener('click', (e) => {
387
+ emitSelect(this, this.getAttribute('uri'), this._data);
388
+ if (this.hasAttribute('prevent-navigation')) e.preventDefault();
389
+ });
390
+ this.addEventListener('mouseleave', () => this.close());
391
+ this.addEventListener('keydown', (e) => {
392
+ if (e.key === 'Escape') this.close();
393
+ });
394
+ }
395
+ }
396
+
397
+ _onExternalSelect(e) {
398
+ const uri = e.detail?.uri;
399
+ if (!uri) return;
400
+ this.setAttribute('uri', uri);
401
+ this.loadAndRender(uri);
402
+ }
403
+
404
+ async open() {
405
+ if (this.mode !== 'popover') return;
406
+ this._open = true;
407
+ this._updateCardVisibility();
408
+ const uri = this.getAttribute('uri');
409
+ if (!this._data && uri) {
410
+ await this.loadAndRender(uri);
411
+ }
412
+ }
413
+
414
+ close() {
415
+ if (this.mode !== 'popover') return;
416
+ this._open = false;
417
+ this._updateCardVisibility();
418
+ }
419
+
420
+ async loadAndRender(uri) {
421
+ this._renderLoading();
422
+ this._data = await resolveAuthority(uri, this.textContent.trim());
423
+ this._renderCardContent();
424
+ }
425
+
426
+ _updateCardVisibility() {
427
+ const card = this.shadowRoot.querySelector('[part="card"]');
428
+ if (!card) return;
429
+ card.hidden = !this._open;
430
+ if (this._open) {
431
+ const rect = this.getBoundingClientRect();
432
+ const cardWidth = 336;
433
+ if (rect.left + cardWidth > window.innerWidth - 16) {
434
+ card.style.left = 'auto';
435
+ card.style.right = '0';
436
+ } else {
437
+ card.style.left = '0';
438
+ card.style.right = 'auto';
439
+ }
440
+ }
441
+ }
442
+
443
+ _esc(str) {
444
+ return String(str ?? '')
445
+ .replace(/&/g, '&amp;')
446
+ .replace(/</g, '&lt;')
447
+ .replace(/>/g, '&gt;')
448
+ .replace(/"/g, '&quot;');
449
+ }
450
+
451
+ _renderLoading() {
452
+ const card = this.shadowRoot.querySelector('[part="card"]');
453
+ if (card) {
454
+ card.innerHTML = `<div part="loading" class="loading">Resolving authority record…</div>`;
455
+ }
456
+ }
457
+
458
+ _renderCardContent() {
459
+ const card = this.shadowRoot.querySelector('[part="card"]');
460
+ if (!card || !this._data) return;
461
+
462
+ const customRenderer = this.template || globalTemplate;
463
+ if (typeof customRenderer === 'function') {
464
+ card.innerHTML = customRenderer(this._data, this._esc.bind(this));
465
+ return;
466
+ }
467
+
468
+ const d = this._data;
469
+ const uriToCopy = d?.uri || this.getAttribute('uri') || '';
470
+
471
+ card.innerHTML = `
472
+ <div part="header" class="header">
473
+ <span part="badge" class="badge" style="background:${this._esc(d.badgeColor)}">${this._esc(d.source)}</span>
474
+ <a part="external-link" class="ext" href="${this._esc(uriToCopy)}" target="_blank" rel="noopener">Open ↗</a>
475
+ </div>
476
+ <div part="body" class="body">
477
+ ${d.thumb ? `<img part="thumb" class="thumb" src="${this._esc(d.thumb)}" alt="">` : ''}
478
+ <div>
479
+ <div part="title" class="title">${this._esc(d.label)}</div>
480
+ ${d.subtitle ? `<div part="subtitle" class="subtitle">${this._esc(d.subtitle)}</div>` : ''}
481
+ </div>
482
+ </div>
483
+ ${d.scopeNote ? `<p part="note" class="note">${this._esc(d.scopeNote)}</p>` : ''}
484
+ ${
485
+ d.meta?.length
486
+ ? `<div part="meta" class="meta">${d.meta
487
+ .map((m) => `<div><span>${this._esc(m.label)}</span><strong>${this._esc(m.value)}</strong></div>`)
488
+ .join('')}</div>`
489
+ : ''
490
+ }
491
+ ${d.aliases?.length ? `<div part="aliases" class="aliases">Also: ${d.aliases.map((a) => this._esc(a)).join(' · ')}</div>` : ''}
492
+ <div part="footer" class="footer">
493
+ <code part="uri" class="uri">${this._esc(uriToCopy)}</code>
494
+ <button part="copy-button" type="button" class="copy" data-uri="${this._esc(uriToCopy)}">Copy</button>
495
+ </div>
496
+ `;
497
+
498
+ const copyBtn = card.querySelector('.copy');
499
+ copyBtn?.addEventListener('click', async (e) => {
500
+ e.preventDefault();
501
+ e.stopPropagation();
502
+ const targetUri = e.currentTarget.getAttribute('data-uri') || uriToCopy;
503
+ if (!targetUri) return;
504
+ const copied = await copyTextToClipboard(targetUri);
505
+ if (copied) {
506
+ copyBtn.textContent = 'Copied';
507
+ setTimeout(() => {
508
+ copyBtn.textContent = 'Copy';
509
+ }, 1200);
510
+ }
511
+ });
512
+ }
513
+
514
+ renderShell() {
515
+ const uri = this.getAttribute('uri') || '#';
516
+ const isPanel = this.mode === 'panel';
517
+
518
+ this.shadowRoot.innerHTML = `
519
+ <style>
520
+ :host {
521
+ --ac-bg: #ffffff;
522
+ --ac-fg: #18181b;
523
+ --ac-muted: #71717a;
524
+ --ac-border: #e4e4e7;
525
+ --ac-surface: rgba(127, 127, 127, 0.08);
526
+ --ac-radius: 0.5rem;
527
+ --ac-shadow: 0 12px 28px -4px rgba(0, 0, 0, 0.14);
528
+ --ac-width: 336px;
529
+ --ac-font: system-ui, -apple-system, sans-serif;
530
+
531
+ position: relative;
532
+ display: ${isPanel ? 'block' : 'inline-block'};
533
+ font-family: var(--ac-font);
534
+ }
535
+
536
+ @media (prefers-color-scheme: dark) {
537
+ :host(:not([theme="light"])) {
538
+ --ac-bg: #18181b;
539
+ --ac-fg: #f4f4f5;
540
+ --ac-muted: #a1a1aa;
541
+ --ac-border: #27272a;
542
+ }
543
+ }
544
+
545
+ :host([theme="dark"]) {
546
+ --ac-bg: #18181b;
547
+ --ac-fg: #f4f4f5;
548
+ --ac-muted: #a1a1aa;
549
+ --ac-border: #27272a;
550
+ }
551
+
552
+ .trigger {
553
+ color: inherit;
554
+ text-decoration: underline;
555
+ text-decoration-style: dotted;
556
+ text-underline-offset: 3px;
557
+ cursor: pointer;
558
+ }
559
+
560
+ .card {
561
+ box-sizing: border-box;
562
+ background: var(--ac-bg);
563
+ color: var(--ac-fg);
564
+ border: 1px solid var(--ac-border);
565
+ border-radius: var(--ac-radius);
566
+ padding: 12px;
567
+ font-size: 13px;
568
+ line-height: 1.45;
569
+ ${
570
+ isPanel
571
+ ? 'width: 100%;'
572
+ : 'position: absolute; top: calc(100% + 6px); left: 0; z-index: 1000; width: var(--ac-width); box-shadow: var(--ac-shadow);'
573
+ }
574
+ }
575
+
576
+ .header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 8px; }
577
+ .badge { color: #fff; font-size: 10px; font-weight: 700; padding: 2px 6px; border-radius: 4px; letter-spacing: 0.04em; text-transform: uppercase; }
578
+ .ext { font-size: 11px; color: var(--ac-muted); text-decoration: none; }
579
+ .ext:hover { text-decoration: underline; }
580
+ .body { display: flex; gap: 10px; align-items: flex-start; }
581
+ .thumb { width: 52px; height: 52px; object-fit: cover; border-radius: 4px; flex-shrink: 0; }
582
+ .title { font-weight: 600; font-size: 15px; line-height: 1.25; }
583
+ .subtitle { font-size: 12px; color: var(--ac-muted); margin-top: 2px; }
584
+ .note { margin: 8px 0; font-size: 12.5px; }
585
+ .meta { display: grid; grid-template-columns: repeat(auto-fit, minmax(120px, 1fr)); gap: 6px; margin: 8px 0; padding: 6px 8px; background: var(--ac-surface); border-radius: 4px; font-size: 11px; }
586
+ .meta span { display: block; color: var(--ac-muted); }
587
+ .aliases { font-size: 11px; color: var(--ac-muted); margin-bottom: 8px; }
588
+ .footer { display: flex; justify-content: space-between; align-items: center; gap: 8px; border-top: 1px solid var(--ac-border); padding-top: 8px; margin-top: 8px; }
589
+ .uri { font-size: 10px; color: var(--ac-muted); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
590
+ .copy { font-size: 11px; padding: 2px 8px; border-radius: 4px; border: 1px solid var(--ac-border); background: transparent; color: inherit; cursor: pointer; }
591
+ .copy:hover { background: var(--ac-surface); }
592
+ .loading { color: var(--ac-muted); font-size: 12px; }
593
+ </style>
594
+ ${isPanel ? '' : `<a part="trigger" class="trigger" href="${this._esc(uri)}" target="_blank" rel="noopener"><slot></slot></a>`}
595
+ <div part="card" class="card" ${isPanel ? '' : 'role="tooltip" hidden'}>
596
+ ${isPanel ? '<div class="loading">Select an entity to inspect its authority record.</div>' : ''}
597
+ </div>
598
+ `;
599
+ }
600
+ }
601
+
602
+ if (!customElements.get('authority-card')) {
603
+ customElements.define('authority-card', AuthorityCard);
604
+ }
605
+
606
+ // --- tailwind.js ---
607
+ export class AuthorityCardTailwind extends HTMLElement {
608
+ static classes = {
609
+ trigger:
610
+ 'underline decoration-dotted underline-offset-4 text-sky-700 dark:text-sky-400 hover:text-sky-900 dark:hover:text-sky-300 cursor-pointer font-medium',
611
+ popover:
612
+ 'absolute left-0 top-full mt-1.5 z-50 w-80 rounded-lg border border-zinc-200 dark:border-zinc-800 bg-white dark:bg-zinc-900 p-3.5 text-left text-sm text-zinc-900 dark:text-zinc-100 shadow-xl',
613
+ panel:
614
+ 'w-full rounded-lg border border-zinc-200 dark:border-zinc-800 bg-white dark:bg-zinc-900 p-4 text-left text-sm text-zinc-900 dark:text-zinc-100',
615
+ badge:
616
+ 'inline-flex items-center rounded px-1.5 py-0.5 text-[10px] font-bold uppercase tracking-wider text-white',
617
+ title: 'text-base font-semibold leading-snug text-zinc-900 dark:text-zinc-50',
618
+ subtitle: 'text-xs text-zinc-500 dark:text-zinc-400',
619
+ note: 'mt-2 text-xs leading-relaxed text-zinc-700 dark:text-zinc-300',
620
+ metaBox:
621
+ 'mt-2.5 grid grid-cols-2 gap-2 rounded bg-zinc-100 dark:bg-zinc-800/70 p-2 text-xs',
622
+ footer:
623
+ 'mt-3 flex items-center justify-between gap-2 border-t border-zinc-200 dark:border-zinc-800 pt-2',
624
+ copyBtn:
625
+ 'shrink-0 rounded border border-zinc-300 dark:border-zinc-700 px-2 py-0.5 text-[11px] font-medium hover:bg-zinc-100 dark:hover:bg-zinc-800 transition-colors',
626
+ };
627
+
628
+ constructor() {
629
+ super();
630
+ this._open = false;
631
+ this._data = null;
632
+ this._initialized = false;
633
+ this._onExternalSelect = this._onExternalSelect.bind(this);
634
+ }
635
+
636
+ connectedCallback() {
637
+ if (this._initialized) return;
638
+ this._initialized = true;
639
+
640
+ const uri = this.getAttribute('uri') || '#';
641
+ const isPanel = this.getAttribute('mode') === 'panel';
642
+ const labelHtml = this.innerHTML;
643
+ const c = AuthorityCardTailwind.classes;
644
+
645
+ const triggerClasses = `${c.trigger} ${this.getAttribute('trigger-class') || ''}`.trim();
646
+ const cardClasses = `${isPanel ? c.panel : c.popover} ${this.getAttribute('card-class') || ''}`.trim();
647
+
648
+ this.classList.add(isPanel ? 'block' : 'relative', isPanel ? 'w-full' : 'inline-block');
649
+
650
+ this.innerHTML = isPanel
651
+ ? `<div data-ac-card class="${cardClasses}"><p class="text-xs text-zinc-500">Select an entity to inspect…</p></div>`
652
+ : `<a data-ac-trigger href="${this._esc(uri)}" target="_blank" rel="noopener" class="${triggerClasses}">${labelHtml}</a>
653
+ <div data-ac-card role="tooltip" hidden class="${cardClasses}"></div>`;
654
+
655
+ const listenEvent = this.getAttribute('listen');
656
+ if (listenEvent) {
657
+ window.addEventListener(listenEvent, this._onExternalSelect);
658
+ }
659
+
660
+ if (isPanel) {
661
+ if (this.getAttribute('uri')) this.load(this.getAttribute('uri'));
662
+ } else {
663
+ const trigger = this.querySelector('[data-ac-trigger]');
664
+ trigger.addEventListener('mouseenter', () => this.open());
665
+ trigger.addEventListener('focus', () => this.open());
666
+ trigger.addEventListener('click', (e) => {
667
+ emitSelect(this, this.getAttribute('uri'), this._data);
668
+ if (this.hasAttribute('prevent-navigation')) e.preventDefault();
669
+ });
670
+ this.addEventListener('mouseleave', () => this.close());
671
+ this.addEventListener('keydown', (e) => {
672
+ if (e.key === 'Escape') this.close();
673
+ });
674
+ }
675
+ }
676
+
677
+ disconnectedCallback() {
678
+ const listenEvent = this.getAttribute('listen');
679
+ if (listenEvent) {
680
+ window.removeEventListener(listenEvent, this._onExternalSelect);
681
+ }
682
+ }
683
+
684
+ _onExternalSelect(e) {
685
+ if (e.detail?.uri) {
686
+ this.setAttribute('uri', e.detail.uri);
687
+ this.load(e.detail.uri);
688
+ }
689
+ }
690
+
691
+ async open() {
692
+ this._open = true;
693
+ const card = this.querySelector('[data-ac-card]');
694
+ if (card) card.hidden = false;
695
+ if (!this._data && this.getAttribute('uri')) {
696
+ await this.load(this.getAttribute('uri'));
697
+ }
698
+ }
699
+
700
+ close() {
701
+ this._open = false;
702
+ const card = this.querySelector('[data-ac-card]');
703
+ if (card) card.hidden = true;
704
+ }
705
+
706
+ async load(uri) {
707
+ const card = this.querySelector('[data-ac-card]');
708
+ if (!card) return;
709
+ card.innerHTML = `<div class="text-xs text-zinc-500 animate-pulse">Resolving authority record…</div>`;
710
+
711
+ const fallback = this.querySelector('[data-ac-trigger]')?.textContent?.trim() || '';
712
+ this._data = await resolveAuthority(uri, fallback);
713
+ this._renderData(card, this._data);
714
+ }
715
+
716
+ _renderData(card, d) {
717
+ const c = AuthorityCardTailwind.classes;
718
+ const uriToCopy = d?.uri || this.getAttribute('uri') || '';
719
+
720
+ card.innerHTML = `
721
+ <div class="flex items-center justify-between mb-2">
722
+ <span class="${c.badge}" style="background:${this._esc(d.badgeColor)}">${this._esc(d.source)}</span>
723
+ <a href="${this._esc(uriToCopy)}" target="_blank" rel="noopener" class="text-xs text-zinc-500 hover:text-zinc-800 dark:hover:text-zinc-200">Open ↗</a>
724
+ </div>
725
+ <div class="flex items-start gap-3">
726
+ ${d.thumb ? `<img src="${this._esc(d.thumb)}" alt="" class="h-12 w-12 shrink-0 rounded object-cover border border-zinc-200 dark:border-zinc-700">` : ''}
727
+ <div class="min-w-0">
728
+ <div class="${c.title}">${this._esc(d.label)}</div>
729
+ ${d.subtitle ? `<div class="${c.subtitle}">${this._esc(d.subtitle)}</div>` : ''}
730
+ </div>
731
+ </div>
732
+ ${d.scopeNote ? `<p class="${c.note}">${this._esc(d.scopeNote)}</p>` : ''}
733
+ ${
734
+ d.meta?.length
735
+ ? `<div class="${c.metaBox}">${d.meta
736
+ .map(
737
+ (m) =>
738
+ `<div><span class="block text-[10px] uppercase tracking-wide text-zinc-500">${this._esc(m.label)}</span><strong class="font-medium">${this._esc(m.value)}</strong></div>`
739
+ )
740
+ .join('')}</div>`
741
+ : ''
742
+ }
743
+ ${d.aliases?.length ? `<div class="mt-2 text-[11px] text-zinc-500">Also: ${d.aliases.map((a) => this._esc(a)).join(' · ')}</div>` : ''}
744
+ <div class="${c.footer}">
745
+ <code class="truncate text-[10px] text-zinc-500">${this._esc(uriToCopy)}</code>
746
+ <button type="button" data-ac-copy data-uri="${this._esc(uriToCopy)}" class="${c.copyBtn}">Copy</button>
747
+ </div>
748
+ `;
749
+
750
+ const copyBtn = card.querySelector('[data-ac-copy]');
751
+ copyBtn?.addEventListener('click', async (e) => {
752
+ e.preventDefault();
753
+ e.stopPropagation();
754
+ const targetUri = e.currentTarget.getAttribute('data-uri') || uriToCopy;
755
+ if (!targetUri) return;
756
+ const copied = await copyTextToClipboard(targetUri);
757
+ if (copied) {
758
+ const prev = copyBtn.textContent;
759
+ copyBtn.textContent = 'Copied';
760
+ setTimeout(() => {
761
+ copyBtn.textContent = prev;
762
+ }, 1200);
763
+ }
764
+ });
765
+ }
766
+
767
+ _esc(str) {
768
+ return String(str ?? '')
769
+ .replace(/&/g, '&amp;')
770
+ .replace(/</g, '&lt;')
771
+ .replace(/>/g, '&gt;')
772
+ .replace(/"/g, '&quot;');
773
+ }
774
+ }
775
+
776
+ if (!customElements.get('authority-card-tw')) {
777
+ customElements.define('authority-card-tw', AuthorityCardTailwind);
778
+ }