@hippo-digital/hippocampus 1.0.0-rc.8 → 1.0.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.
Files changed (52) hide show
  1. package/CHANGELOG.md +88 -3
  2. package/README.md +36 -0
  3. package/assets/dist/hippocampus.css +1 -1
  4. package/assets/hippocampus.scss +994 -133
  5. package/assets/javascript/blueprint.js +21 -0
  6. package/assets/javascript/trace.js +54 -0
  7. package/bin/hippocampus.js +9 -3
  8. package/index.js +2 -1
  9. package/lib/breadcrumb.js +80 -0
  10. package/lib/create-router.js +246 -6
  11. package/lib/discover-projects.js +5 -0
  12. package/lib/filter.js +81 -0
  13. package/lib/flow-map.js +214 -0
  14. package/lib/lint-knowledge.js +31 -0
  15. package/lib/load-knowledge.js +335 -34
  16. package/lib/record-links.js +51 -0
  17. package/lib/templates.js +174 -0
  18. package/package.json +1 -1
  19. package/scripts/doctor.js +10 -0
  20. package/scripts/lib/make-blueprint-template.py +107 -0
  21. package/scripts/smoke-routes.js +19 -0
  22. package/templates/service-blueprint.xlsx +0 -0
  23. package/views/hippocampus/_layout.html +116 -3
  24. package/views/hippocampus/blueprint-classic.html +0 -1
  25. package/views/hippocampus/blueprint.html +0 -1
  26. package/views/hippocampus/components/_blueprint-cell.njk +6 -3
  27. package/views/hippocampus/components/_blueprint-controls.njk +2 -1
  28. package/views/hippocampus/components/_breadcrumb.njk +29 -0
  29. package/views/hippocampus/components/_connections.njk +38 -0
  30. package/views/hippocampus/components/_filters.njk +56 -0
  31. package/views/hippocampus/components/_journey-step.njk +11 -7
  32. package/views/hippocampus/components/_screen-preview.njk +41 -0
  33. package/views/hippocampus/doc.html +0 -1
  34. package/views/hippocampus/docs.html +67 -6
  35. package/views/hippocampus/evidence-impact.html +66 -33
  36. package/views/hippocampus/graph.html +137 -31
  37. package/views/hippocampus/handover-empty.html +0 -1
  38. package/views/hippocampus/handover.html +0 -1
  39. package/views/hippocampus/index.html +102 -13
  40. package/views/hippocampus/journey-flow.html +0 -1
  41. package/views/hippocampus/journey.html +21 -6
  42. package/views/hippocampus/journeys.html +63 -0
  43. package/views/hippocampus/project.html +19 -2
  44. package/views/hippocampus/record.html +33 -0
  45. package/views/hippocampus/research.html +14 -2
  46. package/views/hippocampus/route-review.html +0 -1
  47. package/views/hippocampus/scenarios.html +21 -3
  48. package/views/hippocampus/screens.html +45 -0
  49. package/views/hippocampus/trace.html +35 -22
  50. package/views/hippocampus/user-needs.html +55 -19
  51. package/views/hippocampus/user.html +131 -79
  52. package/views/hippocampus/users.html +33 -19
@@ -78,6 +78,27 @@ if (controls) {
78
78
  }
79
79
  }
80
80
 
81
+ // How far down the step menu has to start.
82
+ //
83
+ // The controls bar is sticky at the top of the viewport and sits above the
84
+ // menu on z-index, so anything the menu puts in that band is simply covered -
85
+ // which is what happened to steps 1 and 2. Its height is not a constant: the
86
+ // lane checkboxes wrap, so it grows as the window narrows. Measured here and
87
+ // published as a custom property, which is the only place that knows.
88
+ if (controls) {
89
+ const publishHeight = () => {
90
+ document.documentElement.style.setProperty(
91
+ '--blueprint-controls-height', `${Math.ceil(controls.getBoundingClientRect().height)}px`)
92
+ }
93
+
94
+ publishHeight()
95
+ if (typeof ResizeObserver === 'function') {
96
+ new ResizeObserver(publishHeight).observe(controls)
97
+ } else {
98
+ window.addEventListener('resize', publishHeight)
99
+ }
100
+ }
101
+
81
102
  const minimap = document.querySelector('[data-blueprint-minimap]')
82
103
 
83
104
  if (minimap) {
@@ -0,0 +1,54 @@
1
+ // Filter the entity list as soon as a type is picked.
2
+ //
3
+ // The server already does this: pick a type, press the button, and the page
4
+ // comes back with the entity list narrowed. That is a whole round trip to
5
+ // populate a select, and until you press the button the control looks broken -
6
+ // you have chosen "Insight" and the list still offers 467 of everything.
7
+ //
8
+ // This is an enhancement, not a replacement. Without it the form still works
9
+ // exactly as before, which is why the options are rendered with `hidden` and
10
+ // `disabled` server-side rather than being written in by script.
11
+
12
+ const form = document.querySelector('[data-hippocampus-trace-form]')
13
+ const type = form && form.querySelector('[data-trace-type]')
14
+ const entity = form && form.querySelector('[data-trace-entity]')
15
+
16
+ if (form && type && entity) {
17
+ const apply = () => {
18
+ const wanted = type.value
19
+ let matches = 0
20
+
21
+ for (const option of entity.options) {
22
+ // The placeholder has no type and always stays.
23
+ if (!option.value) continue
24
+ const belongs = !wanted || option.dataset.entityType === wanted
25
+ option.hidden = !belongs
26
+ option.disabled = !belongs
27
+ if (belongs) matches += 1
28
+ }
29
+
30
+ // A selection left over from the previous type would still be submitted,
31
+ // and the trace that came back would not be the type on screen.
32
+ const current = entity.selectedOptions[0]
33
+ if (current && current.value && current.hidden) entity.value = ''
34
+
35
+ entity.disabled = matches === 0
36
+ if (status) {
37
+ status.textContent = wanted
38
+ ? `${matches} ${wanted.toLowerCase()}${matches === 1 ? '' : 's'} to choose from`
39
+ : ''
40
+ }
41
+ }
42
+
43
+ // After the form, not inside it. Inside, it is a third line in one field's
44
+ // group and the bar aligns to the bottom of it, so picking a type nudged the
45
+ // Type select down relative to the Entity select beside it. It also belongs
46
+ // where the list pages put "Showing 9 of 132" - same job, same place.
47
+ const status = document.createElement('p')
48
+ status.className = 'nhsuk-body-s knowledge-find__count'
49
+ status.setAttribute('role', 'status')
50
+ form.insertAdjacentElement('afterend', status)
51
+
52
+ type.addEventListener('change', apply)
53
+ apply()
54
+ }
@@ -4,9 +4,14 @@ const { spawnSync } = require('child_process')
4
4
  const packagePaths = require('../lib/package-paths')
5
5
 
6
6
  // Every public command is a compatibility promise, so this list is deliberately
7
- // shorter than the scripts directory. Things that are internal (the blueprint
8
- // spreadsheet importer) or better folded into another command (smoke routes,
9
- // which belongs inside doctor) are not exposed here.
7
+ // shorter than the scripts directory. Things better folded into another command
8
+ // (smoke routes, which belongs inside doctor) are not exposed here.
9
+ //
10
+ // The blueprint importer was on that list until the package started shipping a
11
+ // blank blueprint to fill in. Handing somebody a form and hiding the letterbox
12
+ // is not a smaller compatibility promise, it is the same promise made badly:
13
+ // they run the script by its path instead, which is a longer-lived commitment
14
+ // than the command name would have been.
10
15
  const COMMANDS = {
11
16
  init: 'init.js',
12
17
  doctor: 'doctor.js',
@@ -17,6 +22,7 @@ const COMMANDS = {
17
22
  'research triage': 'triage-research-corpus.js',
18
23
  'research batch': 'import-research-batch.js',
19
24
  'import research-deck': 'import-research-deck.js',
25
+ 'import blueprint': 'import-blueprint-spreadsheet.js',
20
26
  'import project-context': 'import-project-context.js',
21
27
  'import design-actions': 'import-design-actions.js',
22
28
  'promote research': 'promote-research-draft.js',
package/index.js CHANGED
@@ -21,7 +21,8 @@ function createHippocampus (options = {}) {
21
21
  for (const project of projects) {
22
22
  router.use(project.basePath, createHippocampusRouter({
23
23
  basePath: project.basePath,
24
- knowledgeStore: project.store
24
+ knowledgeStore: project.store,
25
+ paths: project.paths
25
26
  }))
26
27
  }
27
28
 
@@ -0,0 +1,80 @@
1
+ // The trail from the knowledge base to the page you are on.
2
+ //
3
+ // Replaces a per-page back link. Those were written one at a time and had
4
+ // drifted: eleven pages said "Back to knowledge base", a persona said "Back to
5
+ // users", and a blueprint said "Back to journey" - so the same control meant a
6
+ // different distance on different pages, and none of them said where you were.
7
+ //
8
+ // Derived from the URL rather than passed in by each view, because a trail
9
+ // assembled by hand on twenty pages is a trail that disagrees with itself
10
+ // within a month.
11
+
12
+ // Longest prefix wins, so /user-needs is not swallowed by /users. `listPath`
13
+ // is for detail pages whose list lives at a different URL - a need is at
14
+ // /needs/:id while the list of needs is /user-needs.
15
+ const SECTIONS = [
16
+ { prefix: '/project', text: 'Project' },
17
+ { prefix: '/user-needs', text: 'Needs' },
18
+ { prefix: '/users', text: 'Users' },
19
+ { prefix: '/needs', text: 'Needs', listPath: '/user-needs' },
20
+ { prefix: '/scenarios', text: 'Scenarios' },
21
+ { prefix: '/screens', text: 'Screens' },
22
+ { prefix: '/research', text: 'Research' },
23
+ { prefix: '/insights', text: 'Research', listPath: '/research' },
24
+ { prefix: '/graph', text: 'Relationship graph' },
25
+ { prefix: '/trace', text: 'Trace tree' },
26
+ { prefix: '/docs', text: 'Documentation' },
27
+ // The slice's own handover is a journey view like any other; it just does not
28
+ // name its journey in the URL. Listing it under Journeys keeps it where the
29
+ // navigation already puts it.
30
+ { prefix: '/handover', text: 'Journeys', listPath: '/journeys' },
31
+ { prefix: '/route-review', text: 'Route review' },
32
+ { prefix: '/journeys', text: 'Journeys' },
33
+ { prefix: '/evidence', text: 'Evidence' }
34
+ ].sort((a, b) => b.prefix.length - a.prefix.length)
35
+
36
+ /**
37
+ * @param path the request path within the viewer, e.g. "/users/a-persona"
38
+ * @param leaf the current record's own name, when the page is about one record
39
+ * @param crumbs entries between the section and the leaf, for a page that is a
40
+ * view OF a record rather than the record itself - a journey's blueprint sits
41
+ * under the journey, and a trail that skips it claims the blueprint is a
42
+ * journey
43
+ * @returns [{ text, href }] - the last entry has no href and is the current page
44
+ */
45
+ function buildTrail ({ basePath, path, leaf, crumbs = [] }) {
46
+ const root = { text: 'Knowledge base', href: basePath }
47
+ const clean = (path || '/').replace(/\/+$/, '') || '/'
48
+
49
+ if (clean === '/') return [{ text: root.text }]
50
+
51
+ const section = SECTIONS.find((candidate) =>
52
+ clean === candidate.prefix || clean.startsWith(`${candidate.prefix}/`))
53
+
54
+ if (!section) return [root, { text: leaf || 'Page' }]
55
+
56
+ const listPath = section.listPath || section.prefix
57
+ const onSection = clean === section.prefix || clean === listPath
58
+
59
+ if (onSection && !leaf && !crumbs.length) return [root, { text: section.text }]
60
+
61
+ // A section with no list page of its own - a journey or a piece of evidence,
62
+ // both reached from elsewhere - is left out rather than shown unlinked. An
63
+ // unlinked middle crumb reads as the page you are on, which it is not.
64
+ if (NO_LIST.includes(section.prefix)) {
65
+ return [root, ...crumbs, { text: leaf || section.text }]
66
+ }
67
+
68
+ return [
69
+ root,
70
+ { text: section.text, href: `${basePath}${listPath}` },
71
+ ...crumbs,
72
+ { text: leaf || section.text }
73
+ ]
74
+ }
75
+
76
+ // Reached from other pages; no index of its own to link back to. Journeys had
77
+ // been in here for the same reason, until they got one.
78
+ const NO_LIST = ['/evidence']
79
+
80
+ module.exports = { buildTrail, SECTIONS }
@@ -2,8 +2,12 @@ const express = require('express')
2
2
  const path = require('path')
3
3
  const packagePaths = require('./package-paths')
4
4
  const { listDocs, readDoc, packageVersion } = require('./docs')
5
+ const { listTemplates, allTemplates } = require('./templates')
6
+ const { hrefFor, listHrefFor } = require('./record-links')
7
+ const { matchesText, facet, matchesFacet, queryWithout } = require('./filter')
8
+ const { buildTrail } = require('./breadcrumb')
5
9
 
6
- function createHippocampusRouter ({ basePath, knowledgeStore }) {
10
+ function createHippocampusRouter ({ basePath, knowledgeStore, paths }) {
7
11
  const {
8
12
  getKnowledge,
9
13
  getJourney,
@@ -11,6 +15,8 @@ function createHippocampusRouter ({ basePath, knowledgeStore }) {
11
15
  getGraphExplorer,
12
16
  getTraceExplorer,
13
17
  getEvidenceImpact,
18
+ getRecordDetail,
19
+ getServiceTitle,
14
20
  getResearchViewModel,
15
21
  buildBlueprintViewModel,
16
22
  buildJourneyFlowDiagram,
@@ -38,19 +44,75 @@ function createHippocampusRouter ({ basePath, knowledgeStore }) {
38
44
  // to this body class so /patient and /policy prototype screens (which
39
45
  // should still look like a real NHS.UK page) are unaffected.
40
46
  res.locals.bodyClasses = 'knowledge-admin-theme'
47
+ // The nav marks the current section from this. The Prototype Kit sets a
48
+ // currentPage of its own, but relying on a host's template internals for
49
+ // our own navigation is how a viewer breaks on a kit upgrade.
50
+ res.locals.currentPage = `${basePath}${req.path === '/' ? '' : req.path}`
51
+ res.locals.serviceTitle = getServiceTitle()
52
+
53
+ // The trail is derived from the URL. A page about one record adds its own
54
+ // name by setting res.locals.breadcrumbLeaf before rendering.
55
+ res.locals.breadcrumbItems = buildTrail({ basePath, path: req.path })
41
56
  const result = validateKnowledge()
42
57
  res.locals.knowledgeValidation = result
58
+
59
+ // Formatted here rather than in the template: the viewer registers no
60
+ // nunjucks filters of its own, and adding one to a host's environment to
61
+ // print a single date is a larger footprint than the date is worth.
62
+ res.locals.knowledgeSourcesUpdated = result.sourcesUpdatedAt
63
+ ? result.sourcesUpdatedAt.toLocaleDateString('en-GB', {
64
+ day: 'numeric', month: 'long', year: 'numeric'
65
+ })
66
+ : null
43
67
  next()
44
68
  })
45
69
 
46
70
  router.get('/', (req, res) => {
47
71
  const knowledge = getKnowledge()
48
- res.render('hippocampus/index', { knowledge })
72
+ const research = getResearchViewModel()
73
+
74
+ // The landing page showed how much there is. What a team wants on opening
75
+ // it is what has moved and what is waiting - counts answer neither.
76
+ const latestRound = research.rounds[0] || null
77
+ const needsWithoutScreen = knowledge.needs.filter((need) =>
78
+ !knowledge.screens.some((screen) => (screen.needIds || []).includes(need.id)))
79
+ const insightsWithoutNeed = knowledge.insights.filter((insight) =>
80
+ !(knowledge.relationships || []).some((rel) =>
81
+ rel.type === 'tests-need' && rel.from === insight.id))
82
+
83
+ res.render('hippocampus/index', {
84
+ knowledge,
85
+ // /route-review reads two records by a hardcoded id. Linking to it
86
+ // unconditionally would give a fresh install a card that 404s, so the
87
+ // landing page offers it only where those records actually exist. The
88
+ // route itself is project content living in the package; this keeps it
89
+ // from misleading anyone until that is sorted out.
90
+ hasRouteReview: Boolean(knowledge.index.screens['screen-route-review-workbench'] &&
91
+ knowledge.index.journeys['route-review-workflow']),
92
+ status: {
93
+ latestRound,
94
+ outstandingActions: research.outstandingTotal,
95
+ needsWithoutScreen: needsWithoutScreen.length,
96
+ insightsWithoutNeed: insightsWithoutNeed.length,
97
+ roundsNotMined: research.rounds.filter((round) => !round.insights.length).length
98
+ }
99
+ })
49
100
  })
50
101
 
51
102
  router.get('/users', (req, res) => {
52
103
  const knowledge = getKnowledge()
53
- res.render('hippocampus/users', { knowledge })
104
+
105
+ // Two figures, not three. Responsibilities and access needs came off the
106
+ // card because every persona has three or four of each, so they filled the
107
+ // list without separating anybody - and a count of them has the same
108
+ // problem, at the cost of a second line on a narrow card. How many needs
109
+ // and scenarios a user carries is what actually differs between them.
110
+ const users = knowledge.users.map((user) => ({
111
+ ...user,
112
+ needCount: knowledge.needs.filter((need) => need.userId === user.id).length,
113
+ scenarioCount: knowledge.scenarios.filter((s) => s.userId === user.id).length
114
+ }))
115
+ res.render('hippocampus/users', { knowledge, users })
54
116
  })
55
117
 
56
118
  router.get('/project', (req, res) => {
@@ -62,17 +124,147 @@ function createHippocampusRouter ({ basePath, knowledgeStore }) {
62
124
  const knowledge = getKnowledge()
63
125
  const userGraph = getUserKnowledgeGraph(req.params.userId)
64
126
  if (!userGraph) return res.status(404).render('hippocampus/not-found')
127
+ withLeaf(res, req, userGraph.user.label)
65
128
  res.render('hippocampus/user', { knowledge, userGraph })
66
129
  })
67
130
 
131
+ // A page that renders one journey a particular way - a blueprint, a flow
132
+ // diagram, a handover - sits under that journey rather than beside it. The
133
+ // journey's own crumb is what makes the four of them read as views of one
134
+ // thing instead of four separate artefacts.
135
+ function withJourneyView (res, req, journey, viewName) {
136
+ res.locals.breadcrumbItems = buildTrail({
137
+ basePath,
138
+ path: req.path,
139
+ leaf: viewName,
140
+ crumbs: [{ text: journey.title, href: `${basePath}/journeys/${journey.id}` }]
141
+ })
142
+ }
143
+
144
+ // Pages about one record replace the final crumb with that record's name.
145
+ function withLeaf (res, req, leaf) {
146
+ res.locals.breadcrumbItems = buildTrail({ basePath, path: req.path, leaf })
147
+ }
148
+ // Detail pages. A record's own fields are shown as facts; everything it
149
+ // connects to is resolved once by getRecordDetail and rendered the same way
150
+ // on every page, so a reader learns one layout rather than three.
151
+ const FACTS = {
152
+ Need: (r) => [
153
+ { key: 'Priority', value: r.priority },
154
+ { key: 'Reference', value: r.reference }
155
+ ],
156
+ Insight: (r) => [
157
+ { key: 'Confidence', value: r.confidence },
158
+ { key: 'Summary', value: r.summary }
159
+ ],
160
+ Screen: (r) => [
161
+ { key: 'Route', value: r.route },
162
+ { key: 'Purpose', value: r.purpose },
163
+ { key: 'Components', value: (r.components || []).join(', ') },
164
+ { key: 'Served by this prototype', value: r.external ? 'No - external to this repo' : 'Yes' }
165
+ ]
166
+ }
167
+
168
+ function renderRecord (expectedType, backHref, backLabel) {
169
+ return (req, res) => {
170
+ const detail = getRecordDetail(req.params.id)
171
+ if (!detail || detail.entity.type !== expectedType) {
172
+ return res.status(404).render('hippocampus/not-found')
173
+ }
174
+ for (const group of detail.groups) {
175
+ for (const item of group.items) item.href = hrefFor(item, basePath)
176
+ }
177
+ withLeaf(res, req, detail.entity.label)
178
+ const build = FACTS[detail.entity.type]
179
+ res.render('hippocampus/record', {
180
+ knowledge: getKnowledge(),
181
+ detail,
182
+ facts: (detail.record && build) ? build(detail.record) : [],
183
+ backHref: `${basePath}${backHref}`,
184
+ backLabel
185
+ })
186
+ }
187
+ }
188
+
189
+ router.get('/needs/:id', renderRecord('Need', '/user-needs', 'user needs'))
190
+ router.get('/insights/:id', renderRecord('Insight', '/research', 'research'))
191
+ router.get('/screens/:id', renderRecord('Screen', '/screens', 'screens'))
192
+
193
+ // Screens had no list page at all, so the only way to a screen was to know
194
+ // its id. They are the thing a content designer is looking for.
195
+ router.get('/screens', (req, res) => {
196
+ const knowledge = getKnowledge()
197
+ const query = { q: req.query.q || '' }
198
+ const screens = knowledge.screens.filter((screen) =>
199
+ matchesText(screen, query.q, ['title', 'route', 'purpose', 'components']))
200
+ res.render('hippocampus/screens', {
201
+ knowledge, screens, query, hasFilters: Boolean(query.q), facets: []
202
+ })
203
+ })
204
+
68
205
  router.get('/user-needs', (req, res) => {
69
206
  const knowledge = getKnowledge()
70
- res.render('hippocampus/user-needs', { knowledge })
207
+ const query = { q: req.query.q || '', priority: req.query.priority || '', userId: req.query.userId || '' }
208
+
209
+ const matches = knowledge.needs.filter((need) =>
210
+ matchesText(need, query.q, ['statement', 'reference']) &&
211
+ matchesFacet(need, 'priority', query.priority) &&
212
+ matchesFacet(need, 'userId', query.userId))
213
+
214
+ // Each facet is counted against the records matching the OTHER filters, so
215
+ // its numbers predict what clicking it will do.
216
+ const forPriority = knowledge.needs.filter((need) =>
217
+ matchesText(need, query.q, ['statement', 'reference']) && matchesFacet(need, 'userId', query.userId))
218
+ const forUser = knowledge.needs.filter((need) =>
219
+ matchesText(need, query.q, ['statement', 'reference']) && matchesFacet(need, 'priority', query.priority))
220
+
221
+ res.render('hippocampus/user-needs', {
222
+ knowledge,
223
+ needs: matches,
224
+ query,
225
+ hasFilters: Boolean(query.q || query.priority || query.userId),
226
+ facets: [
227
+ facet({ items: forPriority, key: 'priority', label: 'Priority', selected: query.priority }),
228
+ facet({
229
+ items: forUser,
230
+ key: 'userId',
231
+ label: 'User',
232
+ selected: query.userId,
233
+ labelFor: (id) => (knowledge.index.users[id] || {}).label || id
234
+ })
235
+ ]
236
+ })
71
237
  })
72
238
 
73
239
  router.get('/scenarios', (req, res) => {
74
240
  const knowledge = getKnowledge()
75
- res.render('hippocampus/scenarios', { knowledge })
241
+ const query = { q: req.query.q || '', userId: req.query.userId || '', riskLevel: req.query.riskLevel || '' }
242
+ const text = (s) => matchesText(s, query.q, ['title', 'context', 'trigger'])
243
+
244
+ const scenarios = knowledge.scenarios.filter((s) =>
245
+ text(s) && matchesFacet(s, 'userId', query.userId) && matchesFacet(s, 'riskLevel', query.riskLevel))
246
+
247
+ res.render('hippocampus/scenarios', {
248
+ knowledge,
249
+ scenarios,
250
+ query,
251
+ hasFilters: Boolean(query.q || query.userId || query.riskLevel),
252
+ facets: [
253
+ facet({
254
+ items: knowledge.scenarios.filter((s) => text(s) && matchesFacet(s, 'riskLevel', query.riskLevel)),
255
+ key: 'userId',
256
+ label: 'User',
257
+ selected: query.userId,
258
+ labelFor: (id) => (knowledge.index.users[id] || {}).label || id
259
+ }),
260
+ facet({
261
+ items: knowledge.scenarios.filter((s) => text(s) && matchesFacet(s, 'userId', query.userId)),
262
+ key: 'riskLevel',
263
+ label: 'Risk',
264
+ selected: query.riskLevel
265
+ })
266
+ ]
267
+ })
76
268
  })
77
269
 
78
270
  router.get('/research', (req, res) => {
@@ -84,6 +276,10 @@ function createHippocampusRouter ({ basePath, knowledgeStore }) {
84
276
  router.get('/graph', (req, res) => {
85
277
  const knowledge = getKnowledge()
86
278
  const graph = getGraphExplorer()
279
+ for (const box of graph.flowMap.boxes) box.href = listHrefFor(box.type, basePath)
280
+ for (const group of graph.unconnected) {
281
+ for (const item of group.items) item.href = hrefFor(item, basePath)
282
+ }
87
283
  res.render('hippocampus/graph', { knowledge, graph })
88
284
  })
89
285
 
@@ -97,13 +293,34 @@ function createHippocampusRouter ({ basePath, knowledgeStore }) {
97
293
  const knowledge = getKnowledge()
98
294
  const impact = getEvidenceImpact(req.params.evidenceId)
99
295
  if (!impact) return res.status(404).render('hippocampus/not-found')
296
+ for (const group of [...impact.citedGroups, ...impact.reachedGroups]) {
297
+ for (const item of group.items) item.href = hrefFor(item, basePath)
298
+ }
299
+ withLeaf(res, req, impact.evidence.title)
100
300
  res.render('hippocampus/evidence-impact', { knowledge, impact })
101
301
  })
102
302
 
303
+ // Journeys had no index, so the landing page's card grid was the only way to
304
+ // one - and the only way to the three views generated from each. A section
305
+ // that exists only as a link from the home page is not in the navigation.
306
+ router.get('/journeys', (req, res) => {
307
+ const knowledge = getKnowledge()
308
+ const journeys = knowledge.journeys.map((journey) => ({
309
+ ...journey,
310
+ scenario: knowledge.index.scenarios[journey.scenarioId] || null,
311
+ screenCount: uniqueById(
312
+ (journey.steps || []).flatMap((step) =>
313
+ (step.screenIds || []).map((id) => knowledge.index.screens[id]).filter(Boolean))
314
+ ).length
315
+ }))
316
+ res.render('hippocampus/journeys', { knowledge, journeys })
317
+ })
318
+
103
319
  router.get('/journeys/:journeyId', (req, res) => {
104
320
  const knowledge = getKnowledge()
105
321
  const journey = getJourney(req.params.journeyId)
106
322
  if (!journey) return res.status(404).render('hippocampus/not-found')
323
+ withLeaf(res, req, journey.title)
107
324
  res.render('hippocampus/journey', { knowledge, journey })
108
325
  })
109
326
 
@@ -111,6 +328,7 @@ function createHippocampusRouter ({ basePath, knowledgeStore }) {
111
328
  const knowledge = getKnowledge()
112
329
  const blueprint = buildBlueprintViewModel(req.params.journeyId)
113
330
  if (!blueprint) return res.status(404).render('hippocampus/not-found')
331
+ withJourneyView(res, req, blueprint.journey, 'Blueprint')
114
332
  res.render('hippocampus/blueprint', { knowledge, blueprint })
115
333
  })
116
334
 
@@ -118,6 +336,7 @@ function createHippocampusRouter ({ basePath, knowledgeStore }) {
118
336
  const knowledge = getKnowledge()
119
337
  const blueprint = buildBlueprintViewModel(req.params.journeyId)
120
338
  if (!blueprint) return res.status(404).render('hippocampus/not-found')
339
+ withJourneyView(res, req, blueprint.journey, 'Blueprint matrix')
121
340
  res.render('hippocampus/blueprint-classic', { knowledge, blueprint })
122
341
  })
123
342
 
@@ -125,6 +344,7 @@ function createHippocampusRouter ({ basePath, knowledgeStore }) {
125
344
  const knowledge = getKnowledge()
126
345
  const flow = buildJourneyFlowDiagram(req.params.journeyId)
127
346
  if (!flow) return res.status(404).render('hippocampus/not-found')
347
+ withJourneyView(res, req, flow.journey, 'Flow diagram')
128
348
  res.render('hippocampus/journey-flow', { knowledge, flow })
129
349
  })
130
350
 
@@ -145,12 +365,27 @@ function createHippocampusRouter ({ basePath, knowledgeStore }) {
145
365
  // Documentation is served from the package rather than copied into the host,
146
366
  // so what a team reads always matches the version they are running.
147
367
  router.get('/docs', (req, res) => {
148
- res.render('hippocampus/docs', { docs: listDocs(), packageVersion: packageVersion() })
368
+ res.render('hippocampus/docs', {
369
+ docs: listDocs(),
370
+ templates: listTemplates(paths),
371
+ packageVersion: packageVersion()
372
+ })
373
+ })
374
+
375
+ // The blank workbooks, served from the package for the same reason the docs
376
+ // are: a copy in the host is a copy whose columns stop matching the importer
377
+ // one release later. `Content-Disposition` because a browser handed an xlsx
378
+ // with no filename saves it as the route.
379
+ router.get('/templates/:file', (req, res) => {
380
+ const template = allTemplates(paths).find((item) => item.file === req.params.file)
381
+ if (!template) return res.status(404).render('hippocampus/not-found')
382
+ res.download(template.path, template.file)
149
383
  })
150
384
 
151
385
  router.get('/docs/:slug', (req, res) => {
152
386
  const doc = readDoc(req.params.slug)
153
387
  if (!doc) return res.status(404).render('hippocampus/not-found')
388
+ withLeaf(res, req, doc.title)
154
389
  res.render('hippocampus/doc', { doc, packageVersion: packageVersion() })
155
390
  })
156
391
 
@@ -172,6 +407,11 @@ function createHippocampusRouter ({ basePath, knowledgeStore }) {
172
407
  const knowledge = getKnowledge()
173
408
  const blueprint = buildBlueprintViewModel(journeyId)
174
409
  if (!blueprint) return res.status(404).render('hippocampus/not-found')
410
+ if (req.path.startsWith('/journeys/')) {
411
+ withJourneyView(res, req, blueprint.journey, 'Handover')
412
+ } else {
413
+ withLeaf(res, req, `Handover: ${blueprint.journey.title}`)
414
+ }
175
415
 
176
416
  const screens = uniqueById(blueprint.steps.flatMap((step) => step.screens))
177
417
  res.render('hippocampus/handover', { knowledge, blueprint, screens })
@@ -38,6 +38,11 @@ function discoverProjects ({ root, config = {} } = {}) {
38
38
  name: entry.name,
39
39
  basePath: entry.basePath,
40
40
  dir: entry.dir,
41
+ // The paths travel with the project. The viewer needs more than the
42
+ // store from them - a host keeps its own templates alongside its
43
+ // knowledge, and until this was passed through, the only templates the
44
+ // docs page could see were the package's.
45
+ paths: createPaths({ root, dataDir: entry.dir, artefactsDir }),
41
46
  store: createKnowledgeStore(createPaths({ root, dataDir: entry.dir, artefactsDir }))
42
47
  }))
43
48
  }
package/lib/filter.js ADDED
@@ -0,0 +1,81 @@
1
+ // Finding a record in the explorer.
2
+ //
3
+ // 132 needs and 108 insights, and until now not one input field in the whole
4
+ // viewer - the only way to a record was to scroll past the others. This is the
5
+ // filtering behind that, kept server-side and driven by query parameters so it
6
+ // works without JavaScript, survives a refresh, and gives a filtered view a URL
7
+ // somebody can paste to a colleague.
8
+
9
+ /**
10
+ * Case-insensitive match across the named fields. A multi-word query matches
11
+ * when every word appears somewhere in the record: people type two or three
12
+ * remembered words in the order they happen to recall them, not a phrase.
13
+ */
14
+ function matchesText (item, query, fields) {
15
+ if (!query) return true
16
+ const haystack = fields
17
+ .map((field) => item[field])
18
+ .flatMap((value) => Array.isArray(value) ? value : [value])
19
+ .filter((value) => typeof value === 'string')
20
+ .join(' ')
21
+ .toLowerCase()
22
+ return query.toLowerCase().split(/\s+/).filter(Boolean)
23
+ .every((word) => haystack.includes(word))
24
+ }
25
+
26
+ /**
27
+ * The options for one facet, each carrying how many records it would leave.
28
+ *
29
+ * Counted against the records matching every OTHER active filter, not against
30
+ * the whole collection - so the numbers say what will happen if you click,
31
+ * and an option that would strand you on an empty page is marked rather than
32
+ * silently offered.
33
+ */
34
+ function facet ({ items, key, label, selected, labelFor = (value) => value }) {
35
+ const counts = new Map()
36
+ for (const item of items) {
37
+ const values = Array.isArray(item[key]) ? item[key] : [item[key]]
38
+ for (const value of values) {
39
+ if (value === undefined || value === null || value === '') continue
40
+ counts.set(value, (counts.get(value) || 0) + 1)
41
+ }
42
+ }
43
+ const options = [...counts.entries()]
44
+ .map(([value, count]) => ({ value, count, label: labelFor(value), selected: value === selected }))
45
+ .sort((a, b) => b.count - a.count || String(a.label).localeCompare(String(b.label)))
46
+ return { key, label, selected: selected || '', options }
47
+ }
48
+
49
+ function matchesFacet (item, key, selected) {
50
+ if (!selected) return true
51
+ const values = Array.isArray(item[key]) ? item[key] : [item[key]]
52
+ return values.some((value) => String(value) === String(selected))
53
+ }
54
+
55
+ /**
56
+ * The query string for this page minus one parameter - what a "clear this
57
+ * filter" link needs. Built here rather than in a template because getting it
58
+ * subtly wrong strands somebody on a filtered page with no way back.
59
+ */
60
+ function queryWithout (query, dropKey) {
61
+ const params = new URLSearchParams()
62
+ for (const [key, value] of Object.entries(query || {})) {
63
+ if (key === dropKey || !value) continue
64
+ params.set(key, value)
65
+ }
66
+ const text = params.toString()
67
+ return text ? `?${text}` : ''
68
+ }
69
+
70
+ function activeFilters (query, labels = {}) {
71
+ return Object.entries(query || {})
72
+ .filter(([, value]) => value)
73
+ .map(([key, value]) => ({
74
+ key,
75
+ value,
76
+ label: labels[key] || key,
77
+ display: (labels.display && labels.display[key] && labels.display[key](value)) || value
78
+ }))
79
+ }
80
+
81
+ module.exports = { matchesText, facet, matchesFacet, queryWithout, activeFilters }