@museumwnf/viewer-core 2.19.0 → 2.21.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,6 @@
1
1
  {
2
2
  "name": "@museumwnf/viewer-core",
3
- "version": "2.19.0",
3
+ "version": "2.21.0",
4
4
  "description": "Application engine for MWNF websites: turns a dataset.config.js into a mounted Vue application.",
5
5
  "type": "module",
6
6
  "license": "SEE LICENSE IN LICENSE.md",
@@ -0,0 +1,123 @@
1
+ import { computed, toValue } from 'vue'
2
+ import { useDataPackage } from '../composables/useDataPackage.js'
3
+ import { entityRef } from '../composables/useEntities.js'
4
+ import { useI18n } from '../i18n/index.js'
5
+ import { renderInline, renderPlain } from '../i18n/markdown.js'
6
+ import { dateRange } from './dates.js'
7
+ import { useFacets } from './facets.js'
8
+ import { useListQuery } from './listQuery.js'
9
+ import { sortChronological, usePagination } from './pagination.js'
10
+
11
+ /**
12
+ * A results page's engine: the records of one entity, narrowed by the filters
13
+ * and the page the URL carries, in order, a page at a time, each drawn as a
14
+ * row. viewer-layout's `CatalogueResultsView` draws it; a page of another
15
+ * shape can call it directly and draw the result its own way.
16
+ *
17
+ * `spec` (an object, a ref or a getter) is the view's spec — its `entity`,
18
+ * `keys`, `facets`, `facetScope`, `scope`, `match`, `narrow`, `dates`,
19
+ * `sort`, `pageSize`, `record`, `recordRoute`, `summary` and `summaryLabel`;
20
+ * see CatalogueResultsView's header for each. `entity` is the route's own,
21
+ * for a `features.entities` page, used when the spec names none.
22
+ *
23
+ * Returns the query state (`filters`, `page`, `active`, `apply`, `reset`,
24
+ * `goToPage`), the records (`records`, `matching`), the facets' `options`,
25
+ * `pageInfo`, the page's `rows`, the `summary` parts, and `state`: all of it
26
+ * in one object, which is what the view hands each of its slots.
27
+ */
28
+ export function useCatalogueResults(spec, { entity: routeEntity = '' } = {}) {
29
+ const { t, locale } = useI18n()
30
+ const pkg = useDataPackage()
31
+ const current = computed(() => toValue(spec))
32
+
33
+ // Read once, as the URL keys are: a page does not change entity.
34
+ const entity = current.value.entity ?? routeEntity
35
+ const records = entityRef(entity)
36
+ if (entity) pkg.loadTranslations(entity, 'en')
37
+
38
+ const dates = current.value.dates
39
+ const keys = current.value.keys ?? [
40
+ ...Object.keys(current.value.facets ?? {}),
41
+ ...(dates ? [dates.begin ?? 'begin', dates.end ?? 'end'] : []),
42
+ ]
43
+ const { filters, page, active, apply, reset, goToPage } = useListQuery({ keys })
44
+
45
+ const helpers = {
46
+ t,
47
+ locale,
48
+ tr: (name, id) => pkg.tr(name, id, locale.value, 'en'),
49
+ renderInline,
50
+ renderPlain,
51
+ }
52
+
53
+ const matching = computed(() => {
54
+ const s = current.value
55
+ let list = records.value ?? []
56
+ if (s.scope) list = list.filter((record) => s.scope(record, filters, helpers))
57
+ for (const [key, facet] of Object.entries(s.facets ?? {})) {
58
+ const wanted = filters[key]
59
+ if (!wanted) continue
60
+ list = list.filter((record) => facetValues(record, facet).map(String).includes(String(wanted)))
61
+ }
62
+ if (s.match) list = list.filter((record) => s.match(record, filters, helpers))
63
+ if (s.narrow) list = s.narrow(list, filters, helpers)
64
+ if (s.dates) {
65
+ list = dateRange(list, {
66
+ begin: filters[s.dates.begin ?? 'begin'],
67
+ end: filters[s.dates.end ?? 'end'],
68
+ mode: s.dates.mode ?? 'overlap',
69
+ fields: s.dates.fields,
70
+ })
71
+ }
72
+ const sort = s.sort ?? 'chronological'
73
+ if (typeof sort === 'function') return sort(list)
74
+ if (sort === 'chronological') return sortChronological(list)
75
+ if (sort && typeof sort === 'object') return sortChronological(list, sort)
76
+ return list
77
+ })
78
+
79
+ const facetSource = computed(() => (current.value.facetScope === 'matching' ? matching.value : records.value ?? []))
80
+ const options = useFacets(facetSource, () => current.value.facets ?? {})
81
+ const pageInfo = usePagination(matching, { page, size: () => current.value.pageSize ?? 20 })
82
+
83
+ const recordRoute = computed(() => current.value.recordRoute ?? (routeEntity ? `${routeEntity}-detail` : 'item'))
84
+ function defaultRecord(record) {
85
+ const text = helpers.tr(entity, record.id)
86
+ const name = text.name ?? record.internal_name ?? record.id
87
+ return {
88
+ id: record.id,
89
+ image: record.images?.[0]?.url ?? '',
90
+ imageAlt: renderPlain(String(name)),
91
+ name: renderInline(String(name)),
92
+ meta: [],
93
+ badge: record.type ?? '',
94
+ to: { name: recordRoute.value, params: { id: record.id } },
95
+ }
96
+ }
97
+ const rows = computed(() => pageInfo.value.rows.map((record) => (current.value.record ?? defaultRecord)(record, helpers)))
98
+
99
+ const state = computed(() => ({
100
+ filters,
101
+ active: active.value,
102
+ apply,
103
+ reset,
104
+ goToPage,
105
+ matching: matching.value,
106
+ pageInfo: pageInfo.value,
107
+ options: options.value,
108
+ }))
109
+
110
+ const summary = computed(() => {
111
+ const s = current.value
112
+ if (s.summary) return s.summary({ ...state.value, t, total: (records.value ?? []).length })
113
+ return [{ label: t(s.summaryLabel ?? 'catalogue.results.itemsFound'), count: pageInfo.value.total }]
114
+ })
115
+
116
+ return { entity, records, filters, page, active, apply, reset, goToPage, matching, options, pageInfo, rows, summary, state, helpers }
117
+ }
118
+
119
+ function facetValues(record, facet) {
120
+ if (typeof facet.values === 'function') return [facet.values(record)].flat()
121
+ const raw = record?.[facet.field]
122
+ return Array.isArray(raw) ? raw : [raw]
123
+ }
@@ -54,6 +54,20 @@ export function overlapsRange(event, begin, end) {
54
54
  return yf <= end
55
55
  }
56
56
 
57
+ /**
58
+ * Whether `event` falls in `[begin, end]` by an exhibition's own chronology,
59
+ * legacy's `/thg/timeline?na=&nz=`: unlike the country rule above, its bounds
60
+ * are inclusive, so an event ending the year a search begins, or beginning
61
+ * the year it ends, is in it. An event with no known end is its start year.
62
+ */
63
+ export function touchesRange(event, begin, end) {
64
+ const yf = event?.year_from
65
+ if (begin == null && end == null) return true
66
+ if (!Number.isFinite(yf)) return false
67
+ const yt = effectiveYearTo(event) ?? yf
68
+ return (begin == null || yt >= begin) && (end == null || yf <= end)
69
+ }
70
+
57
71
  /**
58
72
  * The label under an event, trying the three rules the sites share in the
59
73
  * order the data disambiguates them: a curated description pair
@@ -206,7 +220,7 @@ export function useTimelineEvents({
206
220
  // renders no picker for this scope.
207
221
  if (scope !== 'local' && countryId && event.country_id !== countryId) return false
208
222
  if (collection !== undefined && !matchesCollection(event, collection)) return false
209
- return overlapsRange(event, from, to)
223
+ return scope === 'local' ? touchesRange(event, from, to) : overlapsRange(event, from, to)
210
224
  })
211
225
  .map((event) => ({ ...event, text: tr ? tr(event.id) : {} }))
212
226
  .sort((a, b) => {
@@ -29,12 +29,15 @@ import { mergeMessages } from './i18n/index.js'
29
29
  * website still imports its own family's `catalogues` and passes it as
30
30
  * `dictionary`.
31
31
  *
32
+ * Every website calls it as `createStandardViewer(config, { dictionary,
33
+ * ownMessages })`. The older three-argument form, `(config, siteClass,
34
+ * options)`, still works: a second argument that carries none of the option
35
+ * keys below is taken for the shell component.
36
+ *
32
37
  * @param {object} config - the site's `dataset.config.js` object, exactly
33
38
  * as passed to {@link createViewer} today
34
- * @param {object} [siteClass] - the site's `SiteShell` component, used as
35
- * `config.shell` when `config` does not already set one (a config that
36
- * still declares its own `shell` keeps taking precedence, so existing
37
- * `dataset.config.js` files need no change)
39
+ * @param {object} [siteClass] - (older form) the site's shell component, used
40
+ * as `config.shell` when `config` does not set one
38
41
  * @param {object} [options]
39
42
  * @param {object} [options.dictionary] - the family's shared catalogue,
40
43
  * i.e. `catalogues` imported from
@@ -49,6 +52,10 @@ import { mergeMessages } from './i18n/index.js'
49
52
  * `.unmount()` on it, e.g. in a test)
50
53
  */
51
54
  export function createStandardViewer(config, siteClass, options = {}) {
55
+ if (isOptions(siteClass) && arguments.length < 3) {
56
+ options = siteClass
57
+ siteClass = undefined
58
+ }
52
59
  const { dictionary, ownMessages, el = '#app' } = options
53
60
 
54
61
  const messages = dictionary
@@ -59,3 +66,24 @@ export function createStandardViewer(config, siteClass, options = {}) {
59
66
  app.mount(el)
60
67
  return app
61
68
  }
69
+
70
+ const OPTION_KEYS = ['dictionary', 'ownMessages', 'el']
71
+
72
+ function isOptions(value) {
73
+ return Boolean(value) && typeof value === 'object' && OPTION_KEYS.some((key) => key in value)
74
+ }
75
+
76
+ /**
77
+ * A website's own texts, by language, from its `locales/<lang>.json` files as
78
+ * `import.meta.glob('../locales/*.json', { eager: true })` returns them — the
79
+ * glob itself stays in the site's `main.js`, where Vite resolves it:
80
+ *
81
+ * ownMessages: textsByLanguage(import.meta.glob('../locales/*.json', { eager: true }))
82
+ */
83
+ export function textsByLanguage(modules) {
84
+ const texts = {}
85
+ for (const [path, module] of Object.entries(modules ?? {})) {
86
+ texts[path.split('/').pop().replace(/\.json$/, '')] = module.default ?? module
87
+ }
88
+ return texts
89
+ }
@@ -55,8 +55,12 @@ export function useExhibitionData(config = {}) {
55
55
  // because the item sheet's holder line is the one surface that needs the
56
56
  // opposite of `visible` — the museum keeps its name and loses only the
57
57
  // link, because it has no page to link to.
58
+ //
59
+ // So is a partner the package says has no text in any language: it has no
60
+ // name, and legacy lists no such partner, nor serves its page.
58
61
  const hiddenPartnerIds = computed(() => new Set(exhibition.value?.hidden_partner_ids ?? []))
59
62
  function isHiddenPartner(partner) {
63
+ if (Array.isArray(partner?.languages) && partner.languages.length === 0) return true
60
64
  return hiddenPartnerIds.value.has(partner?.id)
61
65
  }
62
66
 
@@ -80,7 +84,8 @@ export function useExhibitionData(config = {}) {
80
84
  // descriptions. Hence the `!i.languages?.length ||` guard, which
81
85
  // reads like a redundant null-check and is not.
82
86
  items: (i) => !i.languages?.length || i.languages.includes(defaultLang),
83
- partners: (p) => !hiddenPartnerIds.value.has(p.id),
87
+ // A partner is another case: see `isHiddenPartner` above.
88
+ partners: (p) => !isHiddenPartner(p),
84
89
  },
85
90
  })
86
91
 
@@ -114,11 +114,13 @@ export function useExhibitionItemDetail(data, timeline) {
114
114
  // an exhibition with a chronology of its own and both flags off (The
115
115
  // Hijaz Railway); it is withheld when the exhibition has no chronology
116
116
  // in force, when the item has no date to anchor a range on, or when no
117
- // event falls in it.
117
+ // event falls in it. Legacy asked for the item's own years, and showed
118
+ // them; only its "search this period" link rounded them out to
119
+ // centuries.
118
120
  timeline: (record, ctx) => {
119
121
  if (!hasTimeline.value && !usesLocalTimeline?.value) return null
120
- const range = roundOutward(record.start_date, record.end_date)
121
- if (range[0] == null) return null
122
+ if (!Number.isFinite(record.start_date)) return null
123
+ const range = [record.start_date, Number.isFinite(record.end_date) ? record.end_date : record.start_date]
122
124
  if (findEvents({ begin: range[0], end: range[1] }).length === 0) return null
123
125
  return {
124
126
  heading: 'core.section.timeline',
@@ -127,7 +129,7 @@ export function useExhibitionItemDetail(data, timeline) {
127
129
  events: (country) => findEvents({ country, begin: range[0], end: range[1] }),
128
130
  range,
129
131
  era: (year) => eraLabel(year, ctx.t),
130
- searchTo: periodSearch,
132
+ searchTo: (country) => periodSearch(country, roundOutward(record.start_date, record.end_date)),
131
133
  }
132
134
  },
133
135
  },
package/src/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  export { createViewer } from './createViewer.js'
2
- export { createStandardViewer } from './createStandardViewer.js'
2
+ export { createStandardViewer, textsByLanguage } from './createStandardViewer.js'
3
3
  export { useCatalogueData } from './composables/useCatalogueData.js'
4
4
  export {
5
5
  CATALOGUE_DATE_MODE, CATALOGUE_PAGE_SIZE, objectsAndMonumentsSummary, useCatalogue,
@@ -24,6 +24,7 @@ export { LEGACY_SITES, toNewSite, watchNewSiteLinks, withScheme } from './legacy
24
24
 
25
25
  // The list pages: query state, pagination, facets, dates, keyword search.
26
26
  export { useListQuery } from './catalogue/listQuery.js'
27
+ export { useCatalogueResults } from './catalogue/catalogueResults.js'
27
28
  export { paginate, sortChronological, usePagination } from './catalogue/pagination.js'
28
29
  export { facetOptions, useFacets } from './catalogue/facets.js'
29
30
  export {
@@ -34,7 +35,7 @@ export {
34
35
  combineExpansions, countryExpansion, glossaryExpansion, parseBooleanQuery, useKeywordIndex,
35
36
  } from './catalogue/keywordIndex.js'
36
37
  export {
37
- effectiveYearTo, eventDateLabel, overlapsRange, useTimelineEvents,
38
+ effectiveYearTo, eventDateLabel, overlapsRange, touchesRange, useTimelineEvents,
38
39
  } from './catalogue/timeline.js'
39
40
 
40
41
  // The record page: the sheet engine and its derivations.
@@ -0,0 +1,35 @@
1
+ import { createHash } from 'node:crypto'
2
+ import { existsSync, readdirSync, readFileSync } from 'node:fs'
3
+ import { relative, resolve, sep } from 'node:path'
4
+
5
+ /**
6
+ * What is wrong with a site's chrome taken from legacy (decision D7,
7
+ * inventory-app#2233): `sources` is the folder's SOURCES.json, whose `files`
8
+ * name each file by its path from the site's root with the sha256 of the
9
+ * bytes legacy serves. Every listed file must be there, byte for byte, and the
10
+ * folder must hold nothing the list does not name.
11
+ *
12
+ * Returns one line per problem, so a site's test reads
13
+ * `expect(checkChromeSources(sources)).toEqual([])` and a failure names every
14
+ * file at once. Paths resolve from `root`, the site's own directory (where
15
+ * Vitest runs).
16
+ */
17
+ export function checkChromeSources(sources, { folder = 'theme/assets/legacy', root = process.cwd() } = {}) {
18
+ const problems = []
19
+ const listed = new Set(Object.keys(sources.files ?? {}))
20
+ for (const [path, { sha256 }] of Object.entries(sources.files ?? {})) {
21
+ const file = resolve(root, path)
22
+ if (!existsSync(file)) {
23
+ problems.push(`${path}: missing`)
24
+ continue
25
+ }
26
+ if (createHash('sha256').update(readFileSync(file)).digest('hex') !== sha256) {
27
+ problems.push(`${path}: not the file legacy serves`)
28
+ }
29
+ }
30
+ const present = readdirSync(resolve(root, folder), { recursive: true, withFileTypes: true })
31
+ .filter((entry) => entry.isFile() && entry.name !== 'SOURCES.json')
32
+ .map((entry) => `${relative(root, entry.parentPath).split(sep).join('/')}/${entry.name}`)
33
+ for (const path of present.filter((p) => !listed.has(p))) problems.push(`${path}: not listed in SOURCES.json`)
34
+ return problems
35
+ }
@@ -1,3 +1,4 @@
1
+ export { checkChromeSources } from './chromeSources.js'
1
2
  export { checkOfferedLanguages } from './checkOfferedLanguages.js'
2
3
  export { checkRoutes, checkSectionMeta, checkTextsRendered, mountSite } from './smoke.js'
3
4
  export { defineViewerConfig } from './viteConfig.js'