@micropasts/period-card
v0.1.0
Published
Zero-dependency Chronology & PeriodO Authority Lookup Web Components (Shadow DOM + Tailwind Light DOM) for museum and archaeology records.
Maintainers
Readme
@micropasts/period-card
Zero-runtime-dependency web components for showing a collection record's chronology and resolving its dates or period labels against PeriodO authority data.
The package provides two renderers:
<period-card>— self-contained styles in Shadow DOM, with CSS custom properties and Shadow Parts for theming.<period-card-tw>— light-DOM markup styled with Tailwind CSS classes, which can be customized with a class map.
Both components match records by date span, period name, or PeriodO URI, use spatial coverage to rank matches, and present candidates for review.
Contents
- Installation
- Quick start
- Light and dark themes
- Component reference
- Record fields and date formats
- PeriodO data
- Custom templates and events
- JavaScript API
- Development and demo
Features
- Accepts numeric years, ISO-like calendar dates, BCE/CE strings, and date ranges.
- Reads common museum and archaeology record fields by default, or accepts a custom field-path configuration.
- Indexes PeriodO dataset JSON-LD and individual PeriodO definitions.
- Scores candidate periods using temporal containment/overlap, label, URI, and spatial matches.
- Offers interactive date- or label-based lookup in the standard and full display levels.
- Loads records and PeriodO JSON from URLs, with request de-duplication and a bounded in-memory cache.
- Exposes framework-independent parsing, indexing, lookup, and view-model utilities.
Installation
npm install @micropasts/period-cardUse a modern browser supporting custom elements, Shadow DOM, ES modules, and ES2022. The package has no runtime dependencies. The light-DOM component requires host-provided Tailwind CSS; see Tailwind configuration.
Quick start
Importing the package registers both custom elements. Supply a record and a PeriodO dataset; the dataset is not loaded automatically.
<period-card id="bronze" periodo-src="https://n2t.net/ark:/99152/p0dataset.json"></period-card>import '@micropasts/period-card';
const card = document.querySelector('#bronze');
card.record = {
title: 'Illustrative Bronze Age palstave',
objectBeginDate: -1500,
objectEndDate: -1300,
period: 'Middle Bronze Age',
country: 'England',
};The example record is illustrative; the demo includes a small snapshot of real PeriodO definitions, including Historic England's Bronze Age and Middle Bronze Age. It is not the full dataset. When data is already available in JavaScript, assign it with card.periodoData = dataset instead of periodo-src. You can also load a record JSON URL through src.
Alternatively, after building a source checkout, load the bundled module directly:
<script type="module" src="./dist/period-card.esm.js"></script>
<period-card src="./record.json" periodo-src="https://n2t.net/ark:/99152/p0dataset.json"></period-card>Remote JSON requests require an appropriate Content Security Policy and cross-origin permissions.
Light and dark themes
Both components accept a theme attribute and reflected JavaScript property:
<period-card theme="dark"></period-card>
<period-card-tw theme="light"></period-card-tw>card.theme = 'dark'; // Force dark mode
card.theme = 'light'; // Force light mode
card.theme = 'system'; // Follow prefers-color-scheme, including changesThe built-in Light, Dark, and System buttons are hidden by default. Opt in on either renderer and at any display level:
<period-card show-theme-controls></period-card>
<period-card-tw lod="compact" show-theme-controls></period-card-tw>card.showThemeControls = true; // Show the buttons.
card.showThemeControls = false; // Hide them without changing the theme.The buttons affect only their card and reflect changes made via the property or attribute. The default theme is system; removing the theme attribute also restores system behavior. The theme property rejects values other than system, light, and dark with a TypeError. An invalid HTML attribute logs a warning and behaves as system. Theme controls were previously shown by default; add show-theme-controls to retain that behavior.
The Shadow DOM component has built-in theme styles. The light-DOM component sets data-pc-theme="light" or "dark" to the effective theme and needs Tailwind configured to use that selector, as described below. Theme changes do not replace the record or selected period. Custom templates and custom class maps are responsible for their own theme-aware styling.
Tailwind dark mode configuration
For independent component-level themes, configure your application's Tailwind dark variant to use [data-pc-theme="dark"] rather than the default media-query strategy. With Tailwind CSS v3:
// tailwind.config.js
export default {
darkMode: ['selector', '[data-pc-theme="dark"]'],
content: [
'./src/**/*.{html,js,ts,jsx,tsx}',
'./node_modules/@micropasts/period-card/dist/**/*.js',
],
};With Tailwind CSS v4, define the equivalent custom variant in your CSS and register the package as a source if needed:
@import "tailwindcss";
@source "../node_modules/@micropasts/period-card/dist";
@custom-variant dark (&:where([data-pc-theme="dark"], [data-pc-theme="dark"] *));Adjust the source paths for your project. Tailwind must generate the package's utility classes, including its dark: variants. Do not put data-pc-theme="dark" on an ancestor of a card you want to force light: the Tailwind dark selector also matches descendants of that ancestor. Applications using another dark variant configuration must adapt their styles or configuration to this selector.
The demo has a page-wide System/Light/Dark selector. Changing it updates each example card and the page background; individual card buttons can then override their own theme. Neither control persists its selection.
Component reference
<period-card>
The Shadow DOM version has built-in styles and does not require Tailwind. It supports the attributes and properties listed below, plus template for supplying a custom render function.
<period-card id="chronology" lod="standard" title-key="object.title"></period-card>const card = document.querySelector('#chronology');
card.record = {
object: { title: 'Commemorative seal matrix' },
startDate: '1066-10-14',
country: 'England',
};
card.periodoData = periodDataset; // For example, the dataset in the PeriodO data section below.
card.addEventListener('period-resolve', (event) => {
console.log('Selected PeriodO match:', event.detail.period);
});The component's styles are scoped to its Shadow DOM. Use the --pc-* CSS custom properties or the exposed parts to theme it:
period-card {
--pc-accent: #0f766e;
--pc-radius: 4px;
}
period-card::part(card) {
max-width: 40rem;
}Available parts include card, header, eyebrow, title, range, labels, lookup, timeline, candidates, and footer.
<period-card-tw>
The Tailwind version renders into light DOM so the host page's styles apply. Load Tailwind CSS in the host application.
<period-card-tw id="record-card" lod="full"></period-card-tw>import '@micropasts/period-card';
const card = document.querySelector('#record-card');
card.record = {
title: 'Bronze Age vessel',
date_earliest: -1200,
date_latest: -800,
culture: 'Bronze Age',
spatialCoverage: 'Eastern Mediterranean',
};
card.periodoData = periodDataset; // For example, the dataset in the PeriodO data section below.You can override any entry in DEFAULT_PERIOD_TW_CLASSES through the classes property. A partial map is merged with the defaults:
import { DEFAULT_PERIOD_TW_CLASSES } from '@micropasts/period-card';
card.classes = {
...DEFAULT_PERIOD_TW_CLASSES,
card: 'rounded-none border-2 border-stone-300 bg-white p-5 shadow',
};Tailwind's production content scanner must see the package's class strings so it retains the utilities used by the component. Configure your scanner to include the installed package if it does not scan dependencies by default.
Component attributes and properties
The following API applies to both components unless noted. Configure JSON objects and functions through JavaScript properties, not HTML attributes. theme and showThemeControls are reflected properties; src, periodo-src, lod, and title-key are configured as attributes using markup or setAttribute.
HTML attributes
| Attribute | Type and default | Behavior |
| --- | --- | --- |
| src | URL string; absent by default | Fetches a record as JSON and displays it. Setting a new nonempty URL starts another fetch. |
| periodo-src | URL string; absent by default | Fetches and indexes PeriodO JSON. No dataset is loaded unless this attribute or periodoData is supplied. The older perio-src spelling remains supported. |
| lod | compact, standard, or full; default standard | Changes the built-in layout and candidate limit. An unrecognized value uses standard matching behavior. |
| title-key | Dot-separated path; default title | Selects the record field used as the title. A missing or falsy value displays Untitled Record. |
| theme | system, light, or dark; default system | Controls the card color scheme. Reflected by the read/write theme property. |
| show-theme-controls | Boolean attribute; absent by default | Shows the built-in Light/Dark/System buttons. Reflected by the read/write showThemeControls property. |
Boolean attributes are enabled by their presence: show-theme-controls="false" still enables the controls. Remove the attribute or set showThemeControls = false to hide them. Attribute changes rerender the card when needed; changing the theme alone does not reset the lookup or selected candidate.
card.setAttribute('lod', 'compact');
card.setAttribute('title-key', 'object.title');
card.setAttribute('periodo-src', 'https://n2t.net/ark:/99152/p0dataset.json');
card.setAttribute('show-theme-controls', '');
card.removeAttribute('show-theme-controls');Removing src, periodo-src, or perio-src does not clear already loaded data. If both PeriodO URL attributes are present, a nonempty periodo-src takes precedence; removing it falls back to perio-src. Removing lod or title-key does not restore their initial values; explicitly set lod="standard" or title-key="title" to reset them. URL requests are asynchronous: assign either the corresponding URL or JavaScript data consistently, because an outstanding request can later replace assigned data. Request failures reject; the components do not provide a built-in error event or error display.
JavaScript properties
| Property | Type; default | Access | Behavior |
| --- | --- | --- | --- |
| record | Object or null; null | Read/write | Record to display. Assignment rerenders and clears the selected candidate, but retains any interactive lookup query. |
| periodoData | PeriodO JSON object, indexed period array, or null; no dataset | Write-only | Indexes the supplied data and rerenders. Assign null or [] to clear the index. perioData remains a supported alias. See PeriodO data. |
| config | Array of { role, paths } rules; DEFAULT_DATE_CONFIG | Write-only | Replaces the complete field mapping and rerenders. Assign null to restore the default. |
| theme | 'system', 'light', or 'dark'; 'system' | Read/write | Sets and reflects the theme attribute; see Light and dark themes. |
| showThemeControls | Boolean; false | Read/write | Reflects the show-theme-controls attribute and rerenders when it changes. Applies to built-in templates. |
| template | Function or null; null | Write-only | Replaces the built-in HTML template; assigning null restores it. Called as (viewModel) for <period-card> or (viewModel, classes) for <period-card-tw>. |
| classes | Object mapping class keys to strings; {}; <period-card-tw> only | Write-only | Merges overrides over DEFAULT_PERIOD_TW_CLASSES and rerenders. Assign null to clear overrides. |
Write-only properties have no public getter; retain your own data or configuration if you need to read it back. Reassign an object or array after changing it: mutating an existing value in place does not automatically rerender or re-index.
card.record = { title: 'Brooch', objectBeginDate: 43, objectEndDate: 100, period: 'Roman' };
console.log(card.record.title);
card.periodoData = periodDataset;
card.config = [{ role: 'periodLabel', paths: ['period'] }];
card.showThemeControls = true;
card.theme = 'dark';For config, each rule uses one of startDate, endDate, displayDate, periodLabel, spatialLabel, or authorityUri, with a paths array of record paths. The complete default paths and an example are listed in Record fields and custom configuration.
For <period-card-tw>, classes accepts any keys in DEFAULT_PERIOD_TW_CLASSES: card, header, eyebrow, title, badge, chips, chip, lookupRow, lookupInput, lookupReset, timeline, track, recBar, authBar, authFill, candidates, candBtn, candBtnActive, footer, compactCard, compactHeader, compactTitleGroup, compactEyebrow, compactTitle, compactBadge, compactFooter, compactLabels, compactChip, compactAuthority, compactLink, themeControls, and themeButton. Overrides replace the entire string for that key. Some nested elements use fixed Tailwind classes outside this map.
Custom templates replace the entire built-in markup, including theme buttons, even if showThemeControls is true. They receive the view model described in Custom templates and must implement any desired controls themselves.
The display levels control the built-in interaction:
| Level | Timeline | Lookup input | Maximum candidates |
| --- | --- | --- | ---: |
| compact | No | No | 0 |
| standard | Yes | Yes | 4 |
| full | Yes | Yes | 8 |
In compact mode the card renders a condensed chronology row with the record title, date range, period labels, and a link to the best-matching PeriodO authority when available. It hides the timeline, lookup field, and candidate list, but still resolves a top match for the authority link.
Record fields and custom configuration
By default, the component checks the following paths. For each role, the first usable date/display/URI value is used; period and spatial labels may collect values from multiple paths.
| Role | Default paths |
| --- | --- |
| Start date | objectBeginDate, date_earliest, earliest_year, startDate, startYear |
| End date | objectEndDate, date_latest, latest_year, endDate, endYear |
| Display date | objectDate, date_display, dated, date_label |
| Period label | period, dynasty, reign, culture, classification, period_name |
| Spatial label or Wikidata location | country, region, county, province, locale, spatialCoverage, countryUri, country_uri, wikidataUri, wikidata_uri |
| Period URI | periodUri, perio_uri, periodo_uri, period_ark, authorityUri |
Paths can be nested and use dot notation. Replace the default mapping by setting config:
card.config = [
{ role: 'startDate', paths: ['dating.start.year'] },
{ role: 'endDate', paths: ['dating.end.year'] },
{ role: 'displayDate', paths: ['dating.label'] },
{ role: 'periodLabel', paths: ['period.name', 'period.alternates'] },
{ role: 'spatialLabel', paths: ['findspot.region'] },
{ role: 'authorityUri', paths: ['period.uri'] },
];
card.record = {
title: 'Example object',
dating: { start: { year: 1066 }, end: { year: 1066 }, label: '1066 CE' },
period: { name: 'Medieval', uri: 'http://n2t.net/ark:/99152/p0kh9dscbkd' },
findspot: { region: 'England' },
};Supported role values are startDate, endDate, displayDate, periodLabel, spatialLabel, and authorityUri. Each rule has a paths array. Period labels can be strings, arrays of strings, or objects containing a label, term, or text property. Spatial values can be strings, objects, or arrays of these. Spatial objects can have a label or name, and a Wikidata identifier in id, uri, or @id.
If a record has no explicit start/end values, its display date is parsed as a fallback. If only one endpoint is present, it is used for both ends of the record's span.
Location and dates
A country or other location name can be combined with dates without supplying a period name. Alternatively, supply a Wikidata location URI (not the URI of the object being described):
card.record = { title: 'Bronze Age find', country: 'England', startYear: -1500, endYear: -1300 };
// Equivalent when the PeriodO dataset includes this spatial coverage identifier:
card.record = { title: 'Bronze Age find', country: 'https://www.wikidata.org/entity/Q21', startYear: -1500, endYear: -1300 };
// A label and identifier can also be supplied together:
card.record = { title: 'Bronze Age find', country: { id: 'http://www.wikidata.org/entity/Q21', label: 'England' }, startYear: -1500, endYear: -1300 };Wikidata Q identifiers and HTTP/HTTPS wikidata.org/entity/Q… or wikidata.org/wiki/Q… URLs are matched against PeriodO spatial coverage identifiers. When a record contains only an identifier, its Q identifier is displayed. The package does not fetch Wikidata or translate between names and identifiers: a name is matched against PeriodO coverage names or descriptions, while an identifier requires a matching identifier in the supplied dataset.
For date queries with no period label or PeriodO URI, candidates with matching coverage rank ahead of other date matches. Geography is a ranking hint, not a strict filter: other locations or records without coverage can still appear, and if nothing matches the location the card may suggest a date match elsewhere. Location alone does not produce candidates. When a period label or PeriodO URI is present, geographic matches provide a smaller boost.
Date formats
Date parsing utilities accept:
- Numeric years, such as
1066or-43. - Year strings, such as
1066,1066 CE,43 BCE, orc. 450. - ISO-like month/day values such as
1066-10and-0043-03-15. - Range strings such as
15-13 BCE,27 BCE - 14 CE,43-410 CE,1450 - 1520, andc. 450–550 AD.
The parser represents BCE years as negative integers. This package works at year granularity for period comparison; month and day precision are retained for display but are not used in matching. The astronomical year 0 is formatted as 1 BCE / 1 CE.
PeriodO data
The components accept the current PeriodO dataset JSON (where each authority contains a periods map), older definitions/authorities datasets, a JSON-LD graph, an individual PeriodO Period, or an array of already indexed period objects. Current PeriodO period entries include localized labels, date bounds, and spatial coverage; these are normalized for matching. This minimal graph-style example uses a subset of the real Historic England Medieval definition:
const periodDataset = {
authorities: {
p0kh9ds: { source: { title: 'Historic England Periods' } },
},
definitions: {
p0kh9dscbkd: {
id: 'http://n2t.net/ark:/99152/p0kh9dscbkd',
authority: 'p0kh9ds',
label: 'Medieval',
spatialCoverageDescription: 'England',
spatialCoverage: [{ id: 'http://www.wikidata.org/entity/Q21', label: 'England' }],
start: { in: { year: '1066' } },
stop: { in: { year: '1540' } },
},
},
};Candidate results are ranked using exact/partial period-label matches, direct URI matches, temporal containment or overlap, and spatial coverage. Results are suggestions: inspect and select the appropriate candidate for the record. A selection emits period-resolve with the chosen indexed period in event.detail.period; this event bubbles.
Setting periodo-src or src causes the component to fetch JSON using the browser's fetch. The host must allow the request under its Content Security Policy and the remote server must permit cross-origin access when needed. PeriodO ARK URLs without a .json suffix are normalized to their JSON representation by RecordStore.resolve.
Custom templates
Set template to a function to render the provided view model instead of the default card. For the Tailwind element, the function receives (viewModel, classes); for the Shadow DOM element it receives only viewModel.
import { escapeHtml } from '@micropasts/period-card';
card.template = (vm) => `
<article>
<h2>${escapeHtml(vm.title)}</h2>
<p>${escapeHtml(vm.formattedRange)}</p>
<ul>${vm.candidates.map((period) =>
`<li>${escapeHtml(period.label)} — ${escapeHtml(period.uri)}</li>`
).join('')}</ul>
</article>
`;Templates return HTML strings. Escape untrusted record or authority values before interpolating them into HTML; the package's default templates escape displayed text.
The view model includes title, dating, formattedRange, activeQueryRange, customLookupQuery, candidates, resolvedPeriod, spanBar, showTimeline, showLookupInput, and lod. Candidate entries include their source fields, a score, and a temporal classification.
Events and shared selection
Selecting a candidate in either component dispatches a bubbling custom event:
document.addEventListener('period-resolve', (event) => {
const period = event.detail.period;
if (period) {
console.log(period.uri, period.label, period.authority);
}
});The event detail is { period }, where period is the selected indexed candidate (or null if it is no longer available). The two components also share the exported periodBus; selecting a candidate emits period:select with { candidateId, period }, allowing instances in the same loaded module to synchronize their selected candidate.
JavaScript API
The package root exports the components, defaults, and helpers:
import {
DEFAULT_DATE_CONFIG,
DEFAULT_PERIODO_DATASET_URL,
DEFAULT_PERIOD_TW_CLASSES,
LOD_ADAPTERS,
PeriodCardElement,
PeriodCardTailwindElement,
RecordStore,
buildPeriodViewModel,
classifyTemporalRelation,
defaultRecordStore,
extractDating,
formatCalendarPoint,
formatSpan,
formatYear,
indexPeriodDefinitions,
lookupPeriods,
parseCalendarPoint,
parseDateRangeString,
periodBus,
} from '@micropasts/period-card';The core helpers are also useful without rendering a component:
parseCalendarPoint(value)— parse one year/date into a point ornull.parseDateRangeString(value)— return{ start, end }points.formatYear(year),formatCalendarPoint(point),formatSpan(start, end, fallbackText)— format parsed dates.extractDating(record, config)— extract the normalized record dating and labels.indexPeriodDefinitions(dataset)— normalize PeriodO input into flat period entries.lookupPeriods(query, indexedPeriods, options)— rank possible authorities.classifyTemporalRelation(recordStart, recordEnd, periodStart, periodEnd)— classifycontained,encloses,overlaps,disjoint, orunboundeddate spans.buildPeriodViewModel(options)— prepare the data used by the built-in renderers.RecordStore/defaultRecordStore— resolve JSON URLs or PeriodO ARKs, with caching and in-flight request sharing.EventBus/periodBus— small event bus used to synchronize component selections.DEFAULT_DATE_CONFIG,DEFAULT_PERIODO_DATASET_URL, andLOD_ADAPTERS— exported defaults.getByPath(object, path)andescapeHtml(value)— dot-path access and HTML escaping helpers.positionPopover(anchor, popover, options)— position a popover within the viewport.
DEFAULT_PERIODO_DATASET_URL is https://n2t.net/ark:/99152/p0dataset.json; it is provided as a constant for consumers and is not fetched automatically. The old DEFAULT_PERIO_DATASET_URL export remains available as an alias.
Development and demo
npm install
npm run build
npm testThe build produces:
dist/period-card.esm.jsand its source map — package bundle.docs/index.htmlanddocs/period-card.esm.js— the browser demo and its bundle, suitable for the configured GitHub Pages deployment.
To rebuild on source changes and serve the demo at http://localhost:4173:
npm run devSet PORT to use a different local port. The demo in src/demo.html illustrates both components, the compact layout, and a prehistoric Bronze Age record using in-memory PeriodO data. The demo uses Tailwind's browser CDN for convenience; production applications should build Tailwind CSS themselves.
License
MIT. See LICENSE.md.
