@dita-viewer/core 0.2.0 → 0.2.2

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 (44) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +90 -58
  3. package/dist/editor/renderContext.d.ts +7 -0
  4. package/dist/editor/renderContext.js +24 -0
  5. package/dist/editor/topicRender.d.ts +9 -0
  6. package/dist/editor/topicRender.js +4 -2
  7. package/dist/index.js +3 -3
  8. package/dist/language/ditaLanguageUtils.js +2 -0
  9. package/dist/profiling.d.ts +9 -3
  10. package/dist/profiling.js +12 -6
  11. package/dist/render/baseTypeMap.js +28 -2
  12. package/dist/render/mapTypeMap.js +23 -23
  13. package/dist/render/renderer.d.ts +24 -0
  14. package/dist/render/renderer.js +36 -9
  15. package/dist-esm/bookRender.js +145 -0
  16. package/dist-esm/completion.js +142 -0
  17. package/dist-esm/completionData.js +155 -0
  18. package/dist-esm/diagnostics.js +378 -0
  19. package/dist-esm/editor/conkeyref.js +104 -0
  20. package/dist-esm/editor/keySpace.js +201 -0
  21. package/dist-esm/editor/refResolvers.js +633 -0
  22. package/dist-esm/editor/renderContext.js +138 -0
  23. package/dist-esm/editor/sourceText.js +142 -0
  24. package/dist-esm/editor/topicRender.js +328 -0
  25. package/dist-esm/index.js +66 -0
  26. package/dist-esm/keyMapForDocument.js +23 -0
  27. package/dist-esm/language/ditaLanguageUtils.js +659 -0
  28. package/dist-esm/language/referenceableFiles.js +108 -0
  29. package/dist-esm/mapRender.js +24 -0
  30. package/dist-esm/package.json +1 -0
  31. package/dist-esm/parser/ditaParser.js +409 -0
  32. package/dist-esm/parser/domTypes.js +1 -0
  33. package/dist-esm/parser/mapTagMap.js +77 -0
  34. package/dist-esm/parser/namedEntities.js +321 -0
  35. package/dist-esm/parser/standardTagMap.js +393 -0
  36. package/dist-esm/profiling.js +224 -0
  37. package/dist-esm/render/baseTypeMap.js +1057 -0
  38. package/dist-esm/render/cjkSpacing.js +94 -0
  39. package/dist-esm/render/mapTypeMap.js +568 -0
  40. package/dist-esm/render/renderer.js +519 -0
  41. package/dist-esm/siteRender.js +261 -0
  42. package/package.json +55 -53
  43. package/styles/TOKENS.md +59 -38
  44. package/styles/dita-content.css +1171 -1157
@@ -0,0 +1,393 @@
1
+ export const STANDARD_TAG_TO_BASETYPE = {
2
+ // Root & structure
3
+ topic: 'topic/topic',
4
+ title: 'topic/title',
5
+ shortdesc: 'topic/shortdesc',
6
+ prolog: 'topic/prolog',
7
+ body: 'topic/body',
8
+ section: 'topic/section',
9
+ example: 'topic/example',
10
+ // Paragraphs & notes
11
+ p: 'topic/p',
12
+ note: 'topic/note',
13
+ // Lists
14
+ ul: 'topic/ul',
15
+ ol: 'topic/ol',
16
+ li: 'topic/li',
17
+ sl: 'topic/sl',
18
+ sli: 'topic/sli',
19
+ // Definition lists
20
+ dl: 'topic/dl',
21
+ dlentry: 'topic/dlentry',
22
+ dt: 'topic/dt',
23
+ dd: 'topic/dd',
24
+ // Complex table (CALS)
25
+ table: 'topic/table',
26
+ tgroup: 'topic/tgroup',
27
+ colspec: 'topic/colspec',
28
+ thead: 'topic/thead',
29
+ tbody: 'topic/tbody',
30
+ row: 'topic/row',
31
+ entry: 'topic/entry',
32
+ // Simple table
33
+ simpletable: 'topic/simpletable',
34
+ sthead: 'topic/sthead',
35
+ strow: 'topic/strow',
36
+ stentry: 'topic/stentry',
37
+ // Media
38
+ image: 'topic/image',
39
+ fig: 'topic/fig',
40
+ // Code & preformatted
41
+ codeblock: 'topic/codeblock',
42
+ pre: 'topic/pre',
43
+ // Links
44
+ xref: 'topic/xref',
45
+ link: 'topic/link',
46
+ linktext: 'topic/linktext',
47
+ 'related-links': 'topic/related-links',
48
+ // Inline formatting
49
+ b: 'topic/b',
50
+ i: 'topic/i',
51
+ u: 'topic/u',
52
+ tt: 'topic/tt',
53
+ sup: 'topic/sup',
54
+ sub: 'topic/sub',
55
+ // Quotes
56
+ q: 'topic/q',
57
+ lq: 'topic/lq',
58
+ // Semantic inline
59
+ keyword: 'topic/keyword',
60
+ term: 'topic/term',
61
+ // UI & interaction
62
+ uicontrol: 'topic/uicontrol',
63
+ wintitle: 'topic/wintitle',
64
+ menucascade: 'topic/menucascade',
65
+ // Computer interaction
66
+ filepath: 'topic/filepath',
67
+ userinput: 'topic/userinput',
68
+ systemoutput: 'topic/systemoutput',
69
+ // API & code references
70
+ apiname: 'topic/apiname',
71
+ option: 'topic/option',
72
+ parmname: 'topic/parmname',
73
+ cmdname: 'topic/cmdname',
74
+ varname: 'topic/varname',
75
+ msgnum: 'topic/msgnum',
76
+ // Misc
77
+ ph: 'topic/ph',
78
+ 'draft-comment': 'topic/draft-comment',
79
+ 'required-cleanup': 'topic/required-cleanup',
80
+ data: 'topic/data',
81
+ 'data-about': 'topic/data-about',
82
+ foreign: 'topic/foreign',
83
+ state: 'topic/state',
84
+ // Programming domain (missing)
85
+ codeph: 'topic/codeph',
86
+ coderef: 'topic/coderef',
87
+ synph: 'topic/synph',
88
+ kwd: 'topic/kwd',
89
+ var: 'topic/var',
90
+ oper: 'topic/oper',
91
+ sep: 'topic/sep',
92
+ delim: 'topic/delim',
93
+ fragment: 'topic/fragment',
94
+ fragref: 'topic/fragref',
95
+ synblk: 'topic/synblk',
96
+ synnote: 'topic/synnote',
97
+ synnoteref: 'topic/synnoteref',
98
+ syntaxdiagram: 'topic/syntaxdiagram',
99
+ // Software domain
100
+ screen: 'topic/screen',
101
+ msgph: 'topic/msgph',
102
+ msgblock: 'topic/msgblock',
103
+ // Common body elements
104
+ lines: 'topic/lines',
105
+ fn: 'topic/fn',
106
+ cite: 'topic/cite',
107
+ boolean: 'topic/boolean',
108
+ tm: 'topic/tm',
109
+ indexterm: 'topic/indexterm',
110
+ indextermref: 'topic/indextermref',
111
+ 'index-see': 'topic/index-see',
112
+ 'index-see-also': 'topic/index-see-also',
113
+ 'index-sort-as': 'topic/index-sort-as',
114
+ 'index-base': 'topic/index-base',
115
+ div: 'topic/div',
116
+ sectiondiv: 'topic/sectiondiv',
117
+ bodydiv: 'topic/bodydiv',
118
+ desc: 'topic/desc',
119
+ alt: 'topic/alt',
120
+ // Parameter lists
121
+ parml: 'topic/parml',
122
+ plentry: 'topic/plentry',
123
+ pt: 'topic/pt',
124
+ pd: 'topic/pd',
125
+ // Abbreviation & glossary
126
+ 'abbreviated-form': 'topic/abbreviated-form',
127
+ glossterm: 'topic/glossterm',
128
+ glossdef: 'topic/glossdef',
129
+ glossentry: 'topic/glossentry',
130
+ glossref: 'topic/glossref',
131
+ glossgroup: 'topic/glossgroup',
132
+ // Hazard
133
+ hazardstatement: 'topic/hazardstatement',
134
+ typeofhazard: 'topic/typeofhazard',
135
+ hazardsymbol: 'topic/hazardsymbol',
136
+ howtoavoid: 'topic/howtoavoid',
137
+ consequence: 'topic/consequence',
138
+ // Multimedia
139
+ object: 'topic/object',
140
+ param: 'topic/param',
141
+ // Anchors
142
+ anchor: 'topic/anchor',
143
+ anchorid: 'topic/anchorid',
144
+ anchorkey: 'topic/anchorkey',
145
+ anchorref: 'topic/anchorref',
146
+ // Task module (mapped to the topic/* ancestor of the spec class chain,
147
+ // e.g. steps = "- topic/ol task/steps " -> topic/ol)
148
+ task: 'topic/topic',
149
+ taskbody: 'topic/body',
150
+ prereq: 'topic/section',
151
+ context: 'topic/section',
152
+ steps: 'topic/ol',
153
+ 'steps-unordered': 'topic/ul',
154
+ 'steps-informal': 'topic/section',
155
+ step: 'topic/li',
156
+ stepsection: 'topic/li',
157
+ cmd: 'topic/ph',
158
+ info: 'topic/itemgroup',
159
+ substeps: 'topic/ol',
160
+ substep: 'topic/li',
161
+ tutorialinfo: 'topic/itemgroup',
162
+ stepxmp: 'topic/itemgroup',
163
+ stepresult: 'topic/itemgroup',
164
+ steptroubleshooting: 'topic/itemgroup',
165
+ choices: 'topic/ul',
166
+ choice: 'topic/li',
167
+ choicetable: 'topic/simpletable',
168
+ chhead: 'topic/sthead',
169
+ chrow: 'topic/strow',
170
+ choptionhd: 'topic/stentry',
171
+ chdeschd: 'topic/stentry',
172
+ choption: 'topic/stentry',
173
+ chdesc: 'topic/stentry',
174
+ result: 'topic/section',
175
+ tasktroubleshooting: 'topic/section',
176
+ postreq: 'topic/section',
177
+ // Concept module
178
+ concept: 'topic/topic',
179
+ conbody: 'topic/body',
180
+ conbodydiv: 'topic/bodydiv',
181
+ // Reference module
182
+ reference: 'topic/topic',
183
+ refbody: 'topic/body',
184
+ refbodydiv: 'topic/bodydiv',
185
+ refsyn: 'topic/section',
186
+ properties: 'topic/simpletable',
187
+ prophead: 'topic/sthead',
188
+ property: 'topic/strow',
189
+ proptypehd: 'topic/stentry',
190
+ propvaluehd: 'topic/stentry',
191
+ propdeschd: 'topic/stentry',
192
+ proptype: 'topic/stentry',
193
+ propvalue: 'topic/stentry',
194
+ propdesc: 'topic/stentry',
195
+ // ── Highlight domain additions (element-specific baseType + renderer, ──
196
+ // matching the existing b/i/u convention so distinct visual styling is ──
197
+ // preserved even when the class attribute is omitted from the XML). ──
198
+ // Evidence: base/dtd/highlightDomain.mod — class "+ topic/ph hi-d/line-through "
199
+ 'line-through': 'topic/line-through',
200
+ // Evidence: base/dtd/highlightDomain.mod — class "+ topic/ph hi-d/overline "
201
+ overline: 'topic/overline',
202
+ // ── Equation domain ── baseType = first pair of the class chain ──
203
+ // Evidence: technicalContent/dtd/equationDomain.mod
204
+ 'equation-inline': 'topic/ph',
205
+ 'equation-block': 'topic/div',
206
+ 'equation-number': 'topic/ph',
207
+ 'equation-figure': 'topic/fig',
208
+ // ── Troubleshooting module ── Evidence: technicalContent/dtd/troubleshooting.mod
209
+ troubleshooting: 'topic/topic',
210
+ troublebody: 'topic/body',
211
+ troubleSolution: 'topic/bodydiv',
212
+ cause: 'topic/section',
213
+ condition: 'topic/section',
214
+ remedy: 'topic/section',
215
+ responsibleParty: 'topic/p',
216
+ // ── Glossentry module ── Evidence: technicalContent/dtd/glossentry.mod
217
+ glossBody: 'topic/body',
218
+ glossAbbreviation: 'topic/title',
219
+ glossAcronym: 'topic/title',
220
+ glossShortForm: 'topic/title',
221
+ glossSynonym: 'topic/title',
222
+ glossPartOfSpeech: 'topic/data',
223
+ glossProperty: 'topic/data',
224
+ glossStatus: 'topic/data',
225
+ glossAlt: 'topic/section',
226
+ glossAlternateFor: 'topic/xref',
227
+ glossScopeNote: 'topic/note',
228
+ glossSurfaceForm: 'topic/p',
229
+ glossSymbol: 'topic/image',
230
+ glossUsage: 'topic/note',
231
+ // ── Task requirements domain (taskreq-d) ── ──
232
+ // Evidence: technicalContent/dtd/taskreqDomain.mod — each class chain's ──
233
+ // first pair is the topic/* ancestor (section/ul/ol/li/p/data). ──
234
+ prelreqs: 'topic/section',
235
+ closereqs: 'topic/section',
236
+ reqconds: 'topic/ul',
237
+ noconds: 'topic/li',
238
+ reqcond: 'topic/li',
239
+ reqcontp: 'topic/li',
240
+ reqpers: 'topic/ul',
241
+ personnel: 'topic/li',
242
+ perscat: 'topic/li',
243
+ perskill: 'topic/li',
244
+ esttime: 'topic/li',
245
+ supequip: 'topic/p',
246
+ nosupeq: 'topic/data',
247
+ supeqli: 'topic/ul',
248
+ supequi: 'topic/li',
249
+ supplies: 'topic/p',
250
+ nosupply: 'topic/data',
251
+ supplyli: 'topic/ul',
252
+ supply: 'topic/li',
253
+ spares: 'topic/p',
254
+ nospares: 'topic/data',
255
+ sparesli: 'topic/ul',
256
+ spare: 'topic/li',
257
+ safety: 'topic/ol',
258
+ nosafety: 'topic/li',
259
+ safecond: 'topic/li',
260
+ // ── Delay-resolution domain (delay-d) ──
261
+ // Evidence: base/dtd/delayResolutionDomain.mod:94 — class
262
+ // "+ topic/keywords delay-d/exportanchors". exportanchors always lives
263
+ // inside <prolog>, so it never renders on its own (see topic/prolog
264
+ // suppression in baseTypeMap.ts) — mapped here for baseType correctness.
265
+ exportanchors: 'topic/keywords',
266
+ // ── Ditavalref domain (ditavalref-d) ──
267
+ // Evidence: base/dtd/ditavalrefDomain.mod:163-166
268
+ dvrResourcePrefix: 'topic/data',
269
+ dvrResourceSuffix: 'topic/data',
270
+ dvrKeyscopePrefix: 'topic/data',
271
+ dvrKeyscopeSuffix: 'topic/data',
272
+ // ── Hazard statement domain (additional) ──
273
+ // Evidence: base/dtd/hazardstatementDomain.mod:233
274
+ messagepanel: 'topic/ul',
275
+ // ── Utilities domain (image maps) ──
276
+ // Evidence: base/dtd/utilitiesDomain.mod:151-155 — class
277
+ // "+ topic/fig ut-d/imagemap ", "+ topic/figgroup ut-d/area ",
278
+ // "+ topic/keyword ut-d/shape ", "+ topic/ph ut-d/coords ".
279
+ //
280
+ // imagemap/area deliberately get their OWN baseTypes rather than their
281
+ // topic ancestors: mapping imagemap → topic/fig made the generic fig
282
+ // renderer dump every child (including the area groups) straight into
283
+ // the page, and figgroup rendered each <area>'s shape/coords/xref as
284
+ // visible text while never producing the HTML <map>/<area> structure
285
+ // that makes the image clickable at all. Dedicated baseTypes carry
286
+ // dedicated renderers (see baseTypeMap.ts) that build the real
287
+ // <img usemap> + <map><area shape coords href></map> output.
288
+ //
289
+ // shape/coords follow the index-see/index-see-also convention: their
290
+ // text is authoring metadata consumed directly by the parent <area>
291
+ // renderer (which reads the parsed nodes itself), so a standalone
292
+ // visit — only reachable through malformed markup — renders nothing
293
+ // rather than leaking "rect" / "0,0,10,10" into the page.
294
+ imagemap: 'topic/imagemap',
295
+ area: 'topic/area',
296
+ shape: 'topic/shape',
297
+ coords: 'topic/coords',
298
+ 'sort-as': 'topic/data',
299
+ // ── Markup domain ──
300
+ // Evidence: technicalContent/dtd/markupDomain.mod:45
301
+ markupname: 'topic/keyword',
302
+ // ── MathML domain ──
303
+ // Evidence: technicalContent/dtd/mathmlDomain.mod:89-90
304
+ mathml: 'topic/foreign',
305
+ mathmlref: 'topic/xref',
306
+ // ── Programming domain (grouping elements) ──
307
+ // Evidence: technicalContent/dtd/programmingDomain.mod:677-679,688
308
+ groupchoice: 'topic/figgroup',
309
+ groupcomp: 'topic/figgroup',
310
+ groupseq: 'topic/figgroup',
311
+ repsep: 'topic/ph',
312
+ // ── Release-management domain (relmgmt-d) ──
313
+ // Evidence: technicalContent/dtd/releaseManagementDomain.mod:231-241.
314
+ // change-historylist always lives inside <prolog> like exportanchors above.
315
+ 'change-historylist': 'topic/metadata',
316
+ 'change-item': 'topic/data',
317
+ 'change-person': 'topic/data',
318
+ 'change-organization': 'topic/data',
319
+ 'change-revisionid': 'topic/data',
320
+ 'change-request-reference': 'topic/data',
321
+ 'change-request-system': 'topic/data',
322
+ 'change-request-id': 'topic/data',
323
+ 'change-started': 'topic/data',
324
+ 'change-completed': 'topic/data',
325
+ 'change-summary': 'topic/data',
326
+ // ── SVG domain ──
327
+ // Evidence: technicalContent/dtd/svgDomain.mod:70-71
328
+ 'svg-container': 'topic/foreign',
329
+ svgref: 'topic/xref',
330
+ // ── UI domain (additional) ──
331
+ // Evidence: technicalContent/dtd/uiDomain.mod:158
332
+ shortcut: 'topic/keyword',
333
+ // ── XML domain ──
334
+ // Evidence: technicalContent/dtd/xmlDomain.mod:154-160
335
+ numcharref: 'topic/keyword',
336
+ parameterentity: 'topic/keyword',
337
+ textentity: 'topic/keyword',
338
+ xmlatt: 'topic/keyword',
339
+ xmlelement: 'topic/keyword',
340
+ xmlnsname: 'topic/keyword',
341
+ xmlpi: 'topic/keyword',
342
+ // ── Bookmap metadata fields ──
343
+ // Evidence: bookmap/dtd/bookmap.mod:1204-1259. These are front-matter
344
+ // metadata (copyright/publisher/revision info), not body content — no
345
+ // dedicated visual treatment needed, generic topic/data|ph|title covers
346
+ // them the same way it already covers the rest of the bookmeta block.
347
+ approved: 'topic/data',
348
+ bookchangehistory: 'topic/data',
349
+ bookevent: 'topic/data',
350
+ bookeventtype: 'topic/data',
351
+ bookid: 'topic/data',
352
+ booklibrary: 'topic/ph',
353
+ booknumber: 'topic/data',
354
+ bookowner: 'topic/data',
355
+ bookpartno: 'topic/data',
356
+ bookrestriction: 'topic/data',
357
+ bookrights: 'topic/data',
358
+ // NOTE: booktitle/booktitlealt/mainbooktitle already have dedicated,
359
+ // real-world-tested entries in mapTagMap.ts (all → 'map/map-title', added
360
+ // 2026-07-28 with the BookMap feature, driving the book title-page
361
+ // renderer). A real .bookmap file always goes through parseDitamap, which
362
+ // only consults mapTagMap.ts — so these three topic-side entries below
363
+ // are DTD-correct but effectively unreachable for actual bookmap
364
+ // documents; they only matter if parseDita ever sees one of these tags
365
+ // outside a bookmap context.
366
+ booktitle: 'topic/title',
367
+ booktitlealt: 'topic/ph',
368
+ completed: 'topic/ph',
369
+ copyrfirst: 'topic/data',
370
+ copyrlast: 'topic/data',
371
+ day: 'topic/ph',
372
+ edited: 'topic/data',
373
+ edition: 'topic/data',
374
+ isbn: 'topic/data',
375
+ mainbooktitle: 'topic/ph',
376
+ maintainer: 'topic/data',
377
+ month: 'topic/ph',
378
+ organization: 'topic/data',
379
+ person: 'topic/data',
380
+ printlocation: 'topic/data',
381
+ published: 'topic/data',
382
+ // publisherinformation always lives inside <prolog>/bookmeta like
383
+ // exportanchors/change-historylist above.
384
+ publisherinformation: 'topic/publisher',
385
+ publishtype: 'topic/data',
386
+ reviewed: 'topic/data',
387
+ revisionid: 'topic/ph',
388
+ started: 'topic/ph',
389
+ summary: 'topic/ph',
390
+ tested: 'topic/data',
391
+ volume: 'topic/data',
392
+ year: 'topic/ph',
393
+ };
@@ -0,0 +1,224 @@
1
+ // Conditional processing: which profiled content a .ditaval file, or a hand
2
+ // picked set of values, leaves out of a preview.
3
+ //
4
+ // Host-neutral and DOM-free. The renderer
5
+ // already stamps every profiled element with `data-profile-keys`, a list of
6
+ // `attribute:value` pairs, and the stylesheet already hides anything carrying
7
+ // `.profile-filtered-out`. What was missing is the decision: does this
8
+ // element stay or go? That decision is here, so a host only has to read the
9
+ // attribute, ask `isExcluded`, and flip the class.
10
+ //
11
+ // The rules follow DITA-OT's filtering, which is what a .ditaval is written
12
+ // for:
13
+ // - an element is judged attribute by attribute (audience, platform,
14
+ // product, otherprops, deliveryTarget, props, and any attribute
15
+ // generalised through `props="name(value ...)"`);
16
+ // - for one attribute it is left out only when EVERY one of its values is
17
+ // excluded -- `audience="internal admin"` stays if admin is not excluded;
18
+ // - it is left out when ANY attribute leaves it out;
19
+ // - a `<prop att="x" action=...>` with no `val` is the default for every
20
+ // value of x that has no rule of its own; no rule at all means include.
21
+ // `flag`, `passthrough`, `<revprop>` and `<style-conflict>` never remove
22
+ // content and are read but ignored here.
23
+ import sax from 'sax';
24
+ /**
25
+ * The attributes the renderer records in data-profile-keys, in its order.
26
+ * Kept in step with PROFILING_ATTRS in render/renderer.ts (not exported from
27
+ * there); a test renders each one to catch drift.
28
+ *
29
+ * deliveryTarget joins the filter-atts group: DITA 1.3 added it to the
30
+ * select-atts (it replaces the deprecated DITA 1.2 @print), and DITA-OT
31
+ * filters on it exactly like the rest of the group, so an element carrying
32
+ * it must show up highlighted, in the filter panel, and in .ditaval
33
+ * filtering like any other profiling attribute.
34
+ */
35
+ export const PROFILE_ATTRS = ['props', 'platform', 'product', 'audience', 'otherprops', 'deliveryTarget', 'base', 'importance', 'rev', 'status'];
36
+ /**
37
+ * Attributes a .ditaval never acts on: DITA-OT filters on audience, platform,
38
+ * product, otherprops, props and their specialisations only. The rest are
39
+ * still shown, and can still be turned off by hand.
40
+ */
41
+ const NOT_DITAVAL_FILTERABLE = new Set(['base', 'importance', 'rev', 'status']);
42
+ const ACTIONS = new Set(['include', 'exclude', 'flag', 'passthrough']);
43
+ /** The key a hand-picked value is stored under. */
44
+ export function profileKey(att, value) {
45
+ return `${att}:${value}`;
46
+ }
47
+ const tokens = (s) => s.split(/\s+/).filter(Boolean);
48
+ function add(out, att, values) {
49
+ if (values.length === 0)
50
+ return;
51
+ (out[att] ??= []).push(...values);
52
+ }
53
+ /** `props` carries `name(value value)` groups for specialised attributes, plus bare values. */
54
+ function expandProps(raw, out) {
55
+ const bare = raw.replace(/([^\s()]+)\(([^)]*)\)/g, (_m, name, values) => {
56
+ add(out, name, tokens(values));
57
+ return ' ';
58
+ });
59
+ add(out, 'props', tokens(bare));
60
+ }
61
+ /** The profiling values an element's attributes carry. */
62
+ export function profileValuesOf(attrs) {
63
+ const out = {};
64
+ if (!attrs)
65
+ return out;
66
+ for (const name of PROFILE_ATTRS) {
67
+ const raw = attrs[name];
68
+ if (!raw || !raw.trim())
69
+ continue;
70
+ if (name === 'props')
71
+ expandProps(raw, out);
72
+ else
73
+ add(out, name, tokens(raw));
74
+ }
75
+ return out;
76
+ }
77
+ /**
78
+ * The same values read back from a `data-profile-keys` attribute. The renderer
79
+ * splits every attribute on whitespace, which cuts `props="platform(a b)"` in
80
+ * two; joining an attribute's tokens again restores the original text.
81
+ */
82
+ export function profileValuesOfKeys(keys) {
83
+ const raw = {};
84
+ for (const pair of (keys ?? '').split(',')) {
85
+ const colon = pair.indexOf(':');
86
+ if (colon <= 0)
87
+ continue;
88
+ let att;
89
+ let value;
90
+ try {
91
+ att = decodeURIComponent(pair.slice(0, colon));
92
+ value = decodeURIComponent(pair.slice(colon + 1));
93
+ }
94
+ catch {
95
+ continue;
96
+ }
97
+ (raw[att] ??= []).push(value);
98
+ }
99
+ const attrs = {};
100
+ for (const [att, values] of Object.entries(raw))
101
+ attrs[att] = values.join(' ');
102
+ return profileValuesOf(attrs);
103
+ }
104
+ /** Read a .ditaval. Never throws: a broken file yields the rules before the break, and `error`. */
105
+ export function parseDitaval(xml) {
106
+ const rules = [];
107
+ let error;
108
+ const parser = sax.parser(true, { trim: true });
109
+ parser.onopentag = (node) => {
110
+ if (node.name !== 'prop')
111
+ return;
112
+ const a = node.attributes;
113
+ if (!a.att || !a.action || !ACTIONS.has(a.action))
114
+ return;
115
+ const rule = { att: a.att, action: a.action };
116
+ if (a.val !== undefined && a.val !== '')
117
+ rule.val = a.val;
118
+ rules.push(rule);
119
+ };
120
+ parser.onerror = (e) => {
121
+ error ??= e.message.split('\n')[0];
122
+ // Stop at the first error: what follows it cannot be trusted.
123
+ parser.error = null;
124
+ parser.onopentag = undefined;
125
+ };
126
+ try {
127
+ parser.write(xml).close();
128
+ }
129
+ catch (e) {
130
+ error ??= e instanceof Error ? e.message : String(e);
131
+ }
132
+ return error === undefined ? { rules } : { rules, error };
133
+ }
134
+ /** What a .ditaval says to do with one value of one attribute; `include` when it is silent. */
135
+ export function ditavalAction(ditaval, att, value) {
136
+ if (!ditaval || NOT_DITAVAL_FILTERABLE.has(att))
137
+ return 'include';
138
+ let fallback = 'include';
139
+ for (const rule of ditaval.rules) {
140
+ if (rule.att !== att)
141
+ continue;
142
+ if (rule.val === value)
143
+ return rule.action;
144
+ if (rule.val === undefined)
145
+ fallback = rule.action;
146
+ }
147
+ return fallback;
148
+ }
149
+ /** True when the filter would remove nothing, so a host can skip the work. */
150
+ export function isEmptyFilter(filter) {
151
+ if (!filter)
152
+ return true;
153
+ const ditavalActs = filter.ditaval?.rules.some((r) => r.action === 'exclude') ?? false;
154
+ return !ditavalActs && (filter.hidden?.size ?? 0) === 0;
155
+ }
156
+ /** Is a value left out, by the file or by hand? */
157
+ export function isValueExcluded(filter, att, value) {
158
+ return filter.hidden?.has(profileKey(att, value)) === true || ditavalAction(filter.ditaval, att, value) === 'exclude';
159
+ }
160
+ /** Would an element carrying these profiling values be left out? */
161
+ export function isExcluded(values, filter) {
162
+ if (isEmptyFilter(filter))
163
+ return false;
164
+ const f = filter;
165
+ for (const [att, list] of Object.entries(values)) {
166
+ if (list.length > 0 && list.every((v) => isValueExcluded(f, att, v)))
167
+ return true;
168
+ }
169
+ return false;
170
+ }
171
+ /**
172
+ * The attributes and values to offer in a filter panel: everything the given
173
+ * elements carry, plus every value already turned off by hand. The second part
174
+ * matters in book and site view, where hiding a value can remove the only
175
+ * element that carried it; without it the box could never be ticked again.
176
+ */
177
+ export function profileGroups(valueSets, hidden = []) {
178
+ const byAtt = new Map();
179
+ const put = (att, value) => {
180
+ let set = byAtt.get(att);
181
+ if (!set)
182
+ byAtt.set(att, (set = new Set()));
183
+ set.add(value);
184
+ };
185
+ for (const values of valueSets) {
186
+ for (const [att, list] of Object.entries(values))
187
+ for (const v of list)
188
+ put(att, v);
189
+ }
190
+ for (const key of hidden) {
191
+ const colon = key.indexOf(':');
192
+ if (colon > 0)
193
+ put(key.slice(0, colon), key.slice(colon + 1));
194
+ }
195
+ return [...byAtt.entries()]
196
+ .sort(([a], [b]) => a.localeCompare(b))
197
+ .map(([att, set]) => ({ att, values: [...set].sort((a, b) => a.localeCompare(b)) }));
198
+ }
199
+ /**
200
+ * Remove from a parsed map every element the filter leaves out, with
201
+ * everything below it: a topicref filtered out takes its sub-topics with it.
202
+ * The element's own attributes decide. An element that merely inherits an
203
+ * attribute cannot be left out when its parent was kept, because the parent
204
+ * was judged on the very same values. Returns how many elements were removed.
205
+ */
206
+ export function pruneExcluded(root, filter) {
207
+ if (isEmptyFilter(filter))
208
+ return 0;
209
+ let removed = 0;
210
+ const walk = (node) => {
211
+ const kept = [];
212
+ for (const child of node.children ?? []) {
213
+ if (child.type === 'element' && isExcluded(profileValuesOf(child.attributes), filter)) {
214
+ removed++;
215
+ continue;
216
+ }
217
+ walk(child);
218
+ kept.push(child);
219
+ }
220
+ node.children = kept;
221
+ };
222
+ walk(root);
223
+ return removed;
224
+ }