@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.
package/package.json CHANGED
@@ -1,6 +1,42 @@
1
1
  {
2
2
  "name": "@micropasts/authority-card",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.0",
4
+ "description": "Zero-dependency JavaScript Web Components for resolving and rendering Linked Open Data authority records (Pleiades, Wikidata, Getty AAT/TGN/ULAN, Nomisma) with Shadow DOM and Tailwind CSS support.",
5
+ "type": "module",
6
+ "main": "./dist/authority-card.esm.js",
7
+ "module": "./dist/authority-card.esm.js",
8
+ "unpkg": "./dist/authority-card.iife.js",
9
+ "jsdelivr": "./dist/authority-card.iife.js",
10
+ "exports": {
11
+ ".": {
12
+ "import": "./dist/authority-card.esm.js",
13
+ "default": "./src/index.js"
14
+ },
15
+ "./core": "./src/core.js",
16
+ "./shadow": "./src/shadow.js",
17
+ "./tailwind": "./src/tailwind.js"
18
+ },
19
+ "files": [
20
+ "dist",
21
+ "src",
22
+ "README.md"
23
+ ],
24
+ "scripts": {
25
+ "build": "node scripts/build.js",
26
+ "dev": "npm run build && npx serve docs",
27
+ "prepare": "npm run build"
28
+ },
29
+ "keywords": [
30
+ "linked-open-data",
31
+ "linked-art",
32
+ "digital-humanities",
33
+ "pleiades",
34
+ "wikidata",
35
+ "getty",
36
+ "nomisma",
37
+ "web-components",
38
+ "tailwindcss",
39
+ "micropasts"
40
+ ],
41
+ "license": "MIT"
6
42
  }
package/src/core.js ADDED
@@ -0,0 +1,316 @@
1
+ const MEMORY_CACHE = new Map();
2
+ const IN_FLIGHT = new Map();
3
+ const ADAPTERS = [];
4
+
5
+ const GETTY_FALLBACKS = {
6
+ 'http://vocab.getty.edu/aat/300037222': {
7
+ source: 'Getty AAT',
8
+ badgeColor: '#881337',
9
+ id: '300037222',
10
+ label: 'denarii',
11
+ subtitle: 'Vocabulary Authority · 300037222 (Cached Fallback)',
12
+ scopeNote:
13
+ 'Silver coins of the Roman Republic and Empire, first struck around 211 BCE.',
14
+ aliases: ['denarius', 'denier'],
15
+ },
16
+ 'http://vocab.getty.edu/tgn/7011781': {
17
+ source: 'Getty TGN',
18
+ badgeColor: '#881337',
19
+ id: '7011781',
20
+ label: 'London',
21
+ subtitle: 'Vocabulary Authority · 7011781 (Cached Fallback)',
22
+ scopeNote:
23
+ 'Inhabited place; capital city of the United Kingdom on the River Thames, founded as Roman Londinium.',
24
+ aliases: ['Londinium', 'Greater London'],
25
+ meta: [{ label: 'Coordinates', value: '51.5072°, -0.1276°' }],
26
+ },
27
+ };
28
+
29
+ export function registerAdapter(adapter) {
30
+ ADAPTERS.unshift(adapter);
31
+ }
32
+
33
+ export function seedRecords(recordsMap) {
34
+ for (const [uri, record] of Object.entries(recordsMap)) {
35
+ MEMORY_CACHE.set(uri, { ...record, uri });
36
+ }
37
+ }
38
+
39
+ export function clearCache() {
40
+ MEMORY_CACHE.clear();
41
+ }
42
+
43
+ export async function copyTextToClipboard(text) {
44
+ const value = String(text ?? '').trim();
45
+ if (!value) return false;
46
+
47
+ if (
48
+ typeof navigator !== 'undefined' &&
49
+ navigator.clipboard &&
50
+ typeof navigator.clipboard.writeText === 'function' &&
51
+ typeof window !== 'undefined' &&
52
+ window.isSecureContext
53
+ ) {
54
+ try {
55
+ await navigator.clipboard.writeText(value);
56
+ return true;
57
+ } catch {
58
+ // Fall through to execCommand fallback below
59
+ }
60
+ }
61
+
62
+ try {
63
+ const ta = document.createElement('textarea');
64
+ ta.value = value;
65
+ ta.setAttribute('readonly', '');
66
+ ta.style.position = 'fixed';
67
+ ta.style.top = '-9999px';
68
+ ta.style.left = '-9999px';
69
+ document.body.appendChild(ta);
70
+ ta.focus();
71
+ ta.select();
72
+ const ok = document.execCommand('copy');
73
+ document.body.removeChild(ta);
74
+ return Boolean(ok);
75
+ } catch {
76
+ return false;
77
+ }
78
+ }
79
+
80
+ export async function resolveAuthority(uri, fallbackLabel = '') {
81
+ if (!uri) return null;
82
+ if (MEMORY_CACHE.has(uri)) return MEMORY_CACHE.get(uri);
83
+ if (IN_FLIGHT.has(uri)) return IN_FLIGHT.get(uri);
84
+
85
+ const adapter = ADAPTERS.find((a) => a.match(uri));
86
+ if (!adapter) {
87
+ return {
88
+ source: 'External URI',
89
+ badgeColor: '#52525b',
90
+ id: uri,
91
+ label: fallbackLabel || uri,
92
+ subtitle: 'Unmapped Authority Endpoint',
93
+ scopeNote: '',
94
+ meta: [],
95
+ aliases: [],
96
+ sameAs: [],
97
+ uri,
98
+ };
99
+ }
100
+
101
+ const promise = adapter
102
+ .fetch(adapter.match(uri), uri)
103
+ .then((data) => {
104
+ const normalized = {
105
+ source: adapter.name,
106
+ badgeColor: adapter.badgeColor || '#334155',
107
+ meta: [],
108
+ aliases: [],
109
+ sameAs: [],
110
+ ...data,
111
+ uri: data?.uri || uri,
112
+ };
113
+ MEMORY_CACHE.set(uri, normalized);
114
+ IN_FLIGHT.delete(uri);
115
+ return normalized;
116
+ })
117
+ .catch(() => {
118
+ IN_FLIGHT.delete(uri);
119
+ return {
120
+ source: adapter.name,
121
+ badgeColor: adapter.badgeColor || '#334155',
122
+ id: uri,
123
+ label: fallbackLabel || uri,
124
+ subtitle: 'Live remote fetch unavailable or blocked in browser',
125
+ scopeNote:
126
+ 'Seed records via seedRecords() or resolve server-side for offline or restricted endpoints.',
127
+ meta: [],
128
+ aliases: [],
129
+ sameAs: [],
130
+ uri,
131
+ fallback: true,
132
+ };
133
+ });
134
+
135
+ IN_FLIGHT.set(uri, promise);
136
+ return promise;
137
+ }
138
+
139
+ export function emitSelect(target, uri, record = null) {
140
+ target.dispatchEvent(
141
+ new CustomEvent('heritage:select', {
142
+ bubbles: true,
143
+ composed: true,
144
+ detail: { uri, record },
145
+ })
146
+ );
147
+ }
148
+
149
+ registerAdapter({
150
+ name: 'Nomisma',
151
+ badgeColor: '#9a3412',
152
+ match: (uri) => /nomisma\.org\/id\/([^/?#]+)/i.exec(uri),
153
+ async fetch([, id]) {
154
+ const url = `https://nomisma.org/id/${id}.jsonld`;
155
+ const res = await fetch(url);
156
+ if (!res.ok) throw new Error(`HTTP ${res.status}`);
157
+ const json = await res.json();
158
+ const graph = json['@graph'] || [json];
159
+ const entity = graph.find((n) => n['@id']?.endsWith(`/id/${id}`)) || graph[0];
160
+
161
+ const labelObj = Array.isArray(entity['skos:prefLabel'])
162
+ ? entity['skos:prefLabel'].find((l) => l['@language'] === 'en') || entity['skos:prefLabel'][0]
163
+ : entity['skos:prefLabel'];
164
+ const defObj = Array.isArray(entity['skos:definition'])
165
+ ? entity['skos:definition'].find((d) => d['@language'] === 'en') || entity['skos:definition'][0]
166
+ : entity['skos:definition'];
167
+
168
+ const lat = entity['geo:lat']?.['@value'] || entity['geo:lat'];
169
+ const long = entity['geo:long']?.['@value'] || entity['geo:long'];
170
+
171
+ return {
172
+ id,
173
+ label: labelObj?.['@value'] || labelObj || id,
174
+ subtitle: 'Numismatic Concept · Nomisma.org',
175
+ scopeNote: defObj?.['@value'] || defObj || '',
176
+ meta:
177
+ lat && long
178
+ ? [{ label: 'Coordinates', value: `${Number(lat).toFixed(4)}°, ${Number(long).toFixed(4)}°` }]
179
+ : [],
180
+ };
181
+ },
182
+ });
183
+
184
+ registerAdapter({
185
+ name: 'Getty',
186
+ badgeColor: '#881337',
187
+ match: (uri) => /^https?:\/\/vocab\.getty\.edu\/(?:page\/)?(aat|tgn|ulan)\/(\d+)/i.exec(uri),
188
+ async fetch([, vocab, id], uri) {
189
+ const canonicalUri = `http://vocab.getty.edu/${vocab}/${id}`;
190
+ const httpsUri = `https://vocab.getty.edu/${vocab}/${id}`;
191
+ const fallback =
192
+ GETTY_FALLBACKS[canonicalUri] ||
193
+ GETTY_FALLBACKS[httpsUri] ||
194
+ GETTY_FALLBACKS[uri];
195
+
196
+ try {
197
+ const query = `
198
+ PREFIX skos: <http://www.w3.org/2004/02/skos/core#>
199
+ PREFIX gvp: <http://vocab.getty.edu/ontology#>
200
+ SELECT ?label ?note WHERE {
201
+ { <${canonicalUri}> (gvp:prefLabelGVP/xl:literalForm|skos:prefLabel) ?label . }
202
+ UNION
203
+ { <${httpsUri}> (gvp:prefLabelGVP/xl:literalForm|skos:prefLabel) ?label . }
204
+ FILTER (LANG(?label) = "en" || LANG(?label) = "")
205
+ OPTIONAL {
206
+ { <${canonicalUri}> skos:scopeNote ?note . }
207
+ UNION
208
+ { <${httpsUri}> skos:scopeNote ?note . }
209
+ FILTER (LANG(?note) = "en" || LANG(?note) = "")
210
+ }
211
+ }
212
+ LIMIT 1
213
+ `;
214
+
215
+ const url = `https://vocab.getty.edu/sparql.json?query=${encodeURIComponent(query)}`;
216
+ const res = await fetch(url, {
217
+ headers: { Accept: 'application/sparql-results+json' },
218
+ });
219
+
220
+ if (!res.ok) {
221
+ throw new Error(`Getty SPARQL HTTP ${res.status}`);
222
+ }
223
+
224
+ const data = await res.json();
225
+ const binding = data?.results?.bindings?.[0];
226
+ if (!binding) {
227
+ throw new Error('No SPARQL binding returned');
228
+ }
229
+
230
+ const label = binding.label?.value || fallback?.label || `${vocab.toUpperCase()} ${id}`;
231
+ const rawNote = binding.note?.value || fallback?.scopeNote || '';
232
+ const scopeNote = rawNote.length > 240 ? `${rawNote.slice(0, 240)}…` : rawNote;
233
+
234
+ return {
235
+ source: `Getty ${vocab.toUpperCase()}`,
236
+ id,
237
+ label,
238
+ subtitle: `Vocabulary Authority · ${id}`,
239
+ scopeNote,
240
+ uri: httpsUri,
241
+ };
242
+ } catch {
243
+ if (fallback) {
244
+ return { ...fallback, uri: httpsUri };
245
+ }
246
+
247
+ return {
248
+ source: `Getty ${vocab.toUpperCase()}`,
249
+ id,
250
+ label: `${vocab.toUpperCase()} ${id}`,
251
+ subtitle: 'Getty HTTPS SPARQL blocked in browser',
252
+ scopeNote:
253
+ 'Seed Getty terms via seedRecords() or resolve via your own server/build step for static sites.',
254
+ uri: httpsUri,
255
+ };
256
+ }
257
+ },
258
+ });
259
+
260
+ registerAdapter({
261
+ name: 'Wikidata',
262
+ badgeColor: '#0369a1',
263
+ match: (uri) => /wikidata\.org\/(entity|wiki)\/(Q\d+)/i.exec(uri),
264
+ async fetch([, , qid]) {
265
+ const url = `https://www.wikidata.org/wiki/Special:EntityData/${qid}.json`;
266
+ const res = await fetch(url);
267
+ if (!res.ok) throw new Error(`HTTP ${res.status}`);
268
+ const data = await res.json();
269
+ const entity = data.entities[qid];
270
+
271
+ const label = entity.labels?.en?.value || qid;
272
+ const description = entity.descriptions?.en?.value || '';
273
+ const aliases = (entity.aliases?.en || []).slice(0, 4).map((a) => a.value);
274
+ const img = entity.claims?.P18?.[0]?.mainsnak?.datavalue?.value;
275
+ const thumb = img
276
+ ? `https://commons.wikimedia.org/wiki/Special:FilePath/${encodeURIComponent(img)}?width=180`
277
+ : null;
278
+
279
+ return {
280
+ id: qid,
281
+ label,
282
+ subtitle: description,
283
+ scopeNote: description,
284
+ aliases,
285
+ thumb,
286
+ };
287
+ },
288
+ });
289
+
290
+ registerAdapter({
291
+ name: 'Pleiades',
292
+ badgeColor: '#15803d',
293
+ match: (uri) => /pleiades\.stoa\.org\/places\/(\d+)/i.exec(uri),
294
+ async fetch([, id]) {
295
+ const url = `https://pleiades.stoa.org/places/${id}/json`;
296
+ const res = await fetch(url);
297
+ if (!res.ok) throw new Error(`HTTP ${res.status}`);
298
+ const data = await res.json();
299
+
300
+ const coords = data.reprPoint
301
+ ? `${data.reprPoint[1].toFixed(4)}°, ${data.reprPoint[0].toFixed(4)}°`
302
+ : null;
303
+
304
+ return {
305
+ id,
306
+ label: data.title || `Place ${id}`,
307
+ subtitle: (data.placeTypes || []).join(', ') || 'Ancient Place',
308
+ scopeNote: data.description || '',
309
+ aliases: (data.names || [])
310
+ .slice(0, 4)
311
+ .map((n) => n.attested || n.romanized)
312
+ .filter(Boolean),
313
+ meta: coords ? [{ label: 'Coordinates', value: coords }] : [],
314
+ };
315
+ },
316
+ });
package/src/demo.html ADDED
@@ -0,0 +1,189 @@
1
+ <!doctype html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="UTF-8" />
5
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
6
+ <title>@micropasts/authority-card — Linked Open Data Web Components</title>
7
+ <script>
8
+ (function () {
9
+ const saved = localStorage.getItem('ac-demo-theme');
10
+ const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
11
+ if (saved === 'dark' || (!saved && prefersDark)) {
12
+ document.documentElement.classList.add('dark');
13
+ }
14
+ })();
15
+ </script>
16
+ <script src="https://cdn.tailwindcss.com"></script>
17
+ <script>
18
+ tailwind.config = { darkMode: 'class' };
19
+ </script>
20
+ <style>
21
+ authority-card.museum-gold {
22
+ --ac-bg: #1c1917;
23
+ --ac-fg: #fafaf9;
24
+ --ac-muted: #a8a29e;
25
+ --ac-border: #b45309;
26
+ --ac-radius: 0.25rem;
27
+ }
28
+ authority-card.museum-gold::part(title) {
29
+ font-family: Georgia, Cambria, serif;
30
+ color: #fbbf24;
31
+ }
32
+ </style>
33
+ </head>
34
+ <body class="bg-stone-50 text-stone-900 dark:bg-zinc-950 dark:text-zinc-100 min-h-screen transition-colors">
35
+ <div class="max-w-5xl mx-auto px-6 py-10 space-y-10">
36
+
37
+ <header class="flex flex-wrap items-start justify-between gap-4 border-b border-stone-200 dark:border-zinc-800 pb-6">
38
+ <div>
39
+ <div class="inline-flex items-center gap-2 text-xs font-mono uppercase tracking-wider text-sky-700 dark:text-sky-400 mb-1">
40
+ <span>Zero-Dependency Web Components</span>
41
+ <span>·</span>
42
+ <span>ES2022 JavaScript</span>
43
+ </div>
44
+ <h1 class="text-3xl font-bold tracking-tight">@micropasts/authority-card</h1>
45
+ <p class="text-sm text-stone-600 dark:text-zinc-400 mt-1.5 max-w-2xl">
46
+ Turn persistent cultural heritage URIs (Pleiades, Wikidata, Getty AAT/TGN/ULAN, Nomisma) into cached hover popovers or synchronized inspector panels.
47
+ </p>
48
+ </div>
49
+
50
+ <div class="flex items-center gap-2">
51
+ <button id="theme-toggle" type="button"
52
+ class="rounded-md border border-stone-300 dark:border-zinc-700 px-3 py-1.5 text-xs font-medium hover:bg-stone-100 dark:hover:bg-zinc-900">
53
+ Toggle Dark Mode
54
+ </button>
55
+ <button id="clear-cache" type="button"
56
+ class="rounded-md border border-stone-300 dark:border-zinc-700 px-3 py-1.5 text-xs font-medium hover:bg-stone-100 dark:hover:bg-zinc-900">
57
+ Clear Cache
58
+ </button>
59
+ </div>
60
+ </header>
61
+
62
+ <div class="grid grid-cols-1 lg:grid-cols-12 gap-8 items-start">
63
+
64
+ <div class="lg:col-span-7 space-y-8">
65
+
66
+ <section class="rounded-xl border border-stone-200 dark:border-zinc-800 bg-white dark:bg-zinc-900/60 p-6 space-y-3">
67
+ <div class="flex items-center justify-between">
68
+ <h2 class="text-xs font-semibold uppercase tracking-wider text-stone-500 dark:text-zinc-400">
69
+ 1. Tailwind CSS Light-DOM (&lt;authority-card-tw&gt;)
70
+ </h2>
71
+ <span class="text-[11px] font-mono text-stone-400">hover or click</span>
72
+ </div>
73
+ <p class="leading-7 text-[15px]">
74
+ Excavations at
75
+ <authority-card-tw uri="https://pleiades.stoa.org/places/79739" prevent-navigation>
76
+ Verulamium
77
+ </authority-card-tw>
78
+ in the territory of the Catuvellauni recovered a silver
79
+ <authority-card-tw uri="https://nomisma.org/id/denarius" prevent-navigation>
80
+ denarius
81
+ </authority-card-tw>
82
+ minted under
83
+ <authority-card-tw uri="http://www.wikidata.org/entity/Q1405" prevent-navigation>
84
+ Augustus
85
+ </authority-card-tw>
86
+ and catalogued under
87
+ <authority-card-tw
88
+ uri="http://vocab.getty.edu/aat/300037222"
89
+ card-class="border-amber-500 ring-2 ring-amber-500/20"
90
+ prevent-navigation>
91
+ denarii (Getty AAT)
92
+ </authority-card-tw>.
93
+ </p>
94
+ </section>
95
+
96
+ <section class="rounded-xl border border-stone-200 dark:border-zinc-800 bg-white dark:bg-zinc-900/60 p-6 space-y-3">
97
+ <div class="flex items-center justify-between">
98
+ <h2 class="text-xs font-semibold uppercase tracking-wider text-stone-500 dark:text-zinc-400">
99
+ 2. Shadow DOM + CSS Variables &amp; ::part() (&lt;authority-card&gt;)
100
+ </h2>
101
+ <span class="text-[11px] font-mono text-stone-400">custom theme</span>
102
+ </div>
103
+ <p class="leading-7 text-[15px]">
104
+ Styled via CSS custom properties and <code>::part(title)</code> without touching component internals:
105
+ <authority-card class="museum-gold" uri="https://pleiades.stoa.org/places/79574" prevent-navigation>
106
+ Londinium
107
+ </authority-card>
108
+ and
109
+ <authority-card class="museum-gold" uri="http://vocab.getty.edu/tgn/7011781" prevent-navigation>
110
+ London (Getty TGN)
111
+ </authority-card>.
112
+ </p>
113
+ </section>
114
+
115
+ <section class="rounded-xl border border-stone-200 dark:border-zinc-800 bg-white dark:bg-zinc-900/60 p-6 space-y-3">
116
+ <div class="flex items-center justify-between">
117
+ <h2 class="text-xs font-semibold uppercase tracking-wider text-stone-500 dark:text-zinc-400">
118
+ 3. Custom Endpoint Adapter (Historic England NHLE)
119
+ </h2>
120
+ <span class="text-[11px] font-mono text-stone-400">registerAdapter()</span>
121
+ </div>
122
+ <p class="leading-7 text-[15px]">
123
+ Plug in institutional or local datasets in 10 lines of JS—for example,
124
+ <authority-card-tw uri="https://historicengland.org.uk/listing/the-list/list-entry/1003516" prevent-navigation>
125
+ Verulamium Roman Town (NHLE 1003516)
126
+ </authority-card-tw>.
127
+ </p>
128
+ </section>
129
+
130
+ </div>
131
+
132
+ <aside class="lg:col-span-5 space-y-3 lg:sticky lg:top-8">
133
+ <div class="flex items-center justify-between">
134
+ <h2 class="text-xs font-semibold uppercase tracking-wider text-stone-500 dark:text-zinc-400">
135
+ Synchronized Inspector Panel
136
+ </h2>
137
+ <span class="text-[11px] font-mono text-emerald-600 dark:text-emerald-400">listen="heritage:select"</span>
138
+ </div>
139
+
140
+ <authority-card-tw
141
+ mode="panel"
142
+ listen="heritage:select"
143
+ uri="https://pleiades.stoa.org/places/79739">
144
+ </authority-card-tw>
145
+
146
+ <div class="rounded-lg border border-stone-200 dark:border-zinc-800 bg-stone-100/70 dark:bg-zinc-900/40 p-3 text-xs text-stone-600 dark:text-zinc-400">
147
+ Clicking any inline entity broadcasts a <code class="font-mono">heritage:select</code> event on the DOM so maps, timelines, and this panel stay in sync.
148
+ </div>
149
+ </aside>
150
+
151
+ </div>
152
+ </div>
153
+
154
+ <script type="module">
155
+ import { registerAdapter, clearCache } from './authority-card.esm.js';
156
+
157
+ registerAdapter({
158
+ name: 'Historic England',
159
+ badgeColor: '#7c2d12',
160
+ match: (uri) => /historicengland\.org\.uk\/listing\/the-list\/list-entry\/(\d+)/i.exec(uri),
161
+ async fetch([, listEntry]) {
162
+ return {
163
+ id: listEntry,
164
+ label: `Scheduled Monument ${listEntry}`,
165
+ subtitle: 'National Heritage List for England (NHLE)',
166
+ scopeNote: 'Verulamium Roman town: defences, theatre, forum-basilica, and extramural cemeteries.',
167
+ meta: [
168
+ { label: 'Designation', value: 'Scheduled Monument' },
169
+ { label: 'List Entry', value: listEntry },
170
+ ],
171
+ };
172
+ },
173
+ });
174
+
175
+ document.getElementById('theme-toggle').addEventListener('click', () => {
176
+ const isDark = document.documentElement.classList.toggle('dark');
177
+ localStorage.setItem('ac-demo-theme', isDark ? 'dark' : 'light');
178
+ });
179
+
180
+ document.getElementById('clear-cache').addEventListener('click', (e) => {
181
+ clearCache();
182
+ e.currentTarget.textContent = 'Cache Cleared';
183
+ setTimeout(() => {
184
+ e.currentTarget.textContent = 'Clear Cache';
185
+ }, 1200);
186
+ });
187
+ </script>
188
+ </body>
189
+ </html>
package/src/index.js ADDED
@@ -0,0 +1,10 @@
1
+ export {
2
+ registerAdapter,
3
+ seedRecords,
4
+ clearCache,
5
+ copyTextToClipboard,
6
+ resolveAuthority,
7
+ emitSelect,
8
+ } from './core.js';
9
+ export { AuthorityCard } from './shadow.js';
10
+ export { AuthorityCardTailwind } from './tailwind.js';