linked-rolls 0.57.0 → 0.59.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 (130) hide show
  1. package/README.md +54 -367
  2. package/lib/{constraints.d.ts → analysis/constraints.d.ts} +1 -1
  3. package/lib/{constraints.js → analysis/constraints.js} +8 -7
  4. package/lib/analysis/ownPaper.d.ts +26 -0
  5. package/lib/analysis/ownPaper.js +41 -0
  6. package/lib/{reservations.d.ts → analysis/reservations.d.ts} +3 -3
  7. package/lib/{reservations.js → analysis/reservations.js} +3 -3
  8. package/lib/{sigla.d.ts → analysis/sigla.d.ts} +2 -2
  9. package/lib/{sigla.js → analysis/sigla.js} +4 -4
  10. package/lib/{witnesses.d.ts → analysis/witnesses.d.ts} +2 -2
  11. package/lib/{witnesses.js → analysis/witnesses.js} +2 -2
  12. package/lib/{Collation.d.ts → collation/Collation.d.ts} +4 -4
  13. package/lib/{Collation.js → collation/Collation.js} +4 -4
  14. package/lib/{alignment.d.ts → collation/alignment.d.ts} +4 -4
  15. package/lib/{alignment.js → collation/alignment.js} +10 -16
  16. package/lib/{scatter.d.ts → collation/scatter.d.ts} +4 -4
  17. package/lib/{scatter.js → collation/scatter.js} +3 -3
  18. package/lib/{statistics.d.ts → collation/statistics.d.ts} +1 -1
  19. package/lib/{statistics.js → collation/statistics.js} +2 -2
  20. package/lib/{substitution.d.ts → collation/substitution.d.ts} +9 -24
  21. package/lib/{substitution.js → collation/substitution.js} +13 -37
  22. package/lib/emulation/Emulation.d.ts +64 -0
  23. package/lib/emulation/Emulation.js +282 -0
  24. package/lib/emulation/negotiation.d.ts +14 -0
  25. package/lib/emulation/negotiation.js +20 -0
  26. package/lib/index.d.ts +43 -35
  27. package/lib/index.js +36 -35
  28. package/lib/{asJsonLd.d.ts → io/asJsonLd.d.ts} +1 -1
  29. package/lib/{asJsonLd.js → io/asJsonLd.js} +3 -3
  30. package/lib/{context.d.ts → io/context.d.ts} +4 -4
  31. package/lib/{context.js → io/context.js} +4 -4
  32. package/lib/{importJsonLd.d.ts → io/importJsonLd.d.ts} +1 -1
  33. package/lib/io/importJsonLd.js +128 -0
  34. package/lib/{migrate.js → io/migrate.js} +59 -55
  35. package/lib/{Agent.d.ts → model/Agent.d.ts} +1 -1
  36. package/lib/{Assumption.d.ts → model/Assumption.d.ts} +1 -1
  37. package/lib/{Edit.d.ts → model/Edit.d.ts} +1 -1
  38. package/lib/{Edition.d.ts → model/Edition.d.ts} +2 -2
  39. package/lib/{Feature.d.ts → model/Feature.d.ts} +1 -1
  40. package/lib/{FeatureSource.d.ts → model/FeatureSource.d.ts} +1 -1
  41. package/lib/{Perforator.d.ts → model/Perforator.d.ts} +1 -1
  42. package/lib/{RollCopy.d.ts → model/RollCopy.d.ts} +3 -10
  43. package/lib/{RollCopy.js → model/RollCopy.js} +3 -5
  44. package/lib/{Symbol.d.ts → model/Symbol.d.ts} +1 -1
  45. package/lib/{Version.d.ts → model/Version.d.ts} +10 -2
  46. package/lib/{Version.js → model/Version.js} +24 -1
  47. package/lib/{vocabulary.js → model/vocabulary.js} +2 -2
  48. package/lib/ops/beliefs.d.ts +9 -0
  49. package/lib/ops/beliefs.js +31 -0
  50. package/lib/ops/collation.d.ts +62 -0
  51. package/lib/ops/collation.js +228 -0
  52. package/lib/ops/commands.d.ts +9 -0
  53. package/lib/ops/commands.js +29 -0
  54. package/lib/ops/copies.d.ts +74 -0
  55. package/lib/ops/copies.js +135 -0
  56. package/lib/ops/draft.d.ts +59 -0
  57. package/lib/ops/draft.js +81 -0
  58. package/lib/ops/edits.d.ts +10 -0
  59. package/lib/ops/edits.js +82 -0
  60. package/lib/ops/features.d.ts +84 -0
  61. package/lib/ops/features.js +296 -0
  62. package/lib/ops/forget.d.ts +31 -0
  63. package/lib/ops/forget.js +110 -0
  64. package/lib/ops/immutable.d.ts +16 -0
  65. package/lib/ops/immutable.js +46 -0
  66. package/lib/ops/index.d.ts +13 -0
  67. package/lib/ops/index.js +7 -0
  68. package/lib/ops/versions.d.ts +33 -0
  69. package/lib/ops/versions.js +95 -0
  70. package/lib/readers/AtonParser.js +5 -7
  71. package/lib/readers/phillipsEroll.d.ts +3 -3
  72. package/lib/readers/phillipsEroll.js +4 -5
  73. package/lib/readers/spencerBar.d.ts +2 -2
  74. package/lib/readers/spencerBar.js +2 -3
  75. package/lib/readers/stanfordAton.d.ts +3 -3
  76. package/lib/readers/stanfordAton.js +2 -3
  77. package/lib/schema.json +0 -13
  78. package/lib/{ReproducingSystem.d.ts → systems/ReproducingSystem.d.ts} +3 -3
  79. package/lib/{TrackerBar.d.ts → systems/TrackerBar.d.ts} +48 -8
  80. package/lib/{TrackerBar.js → systems/TrackerBar.js} +11 -2
  81. package/lib/systems/index.d.ts +8 -2
  82. package/lib/systems/index.js +7 -1
  83. package/lib/systems/welte.d.ts +100 -0
  84. package/lib/systems/welte.js +119 -0
  85. package/lib/systems/welteLicensee/bar.d.ts +1 -1
  86. package/lib/systems/welteLicensee/bar.js +5 -2
  87. package/lib/systems/welteLicensee/system.d.ts +1 -1
  88. package/lib/systems/welteLicensee/system.js +1 -1
  89. package/lib/systems/welteT100/bar.d.ts +27 -1
  90. package/lib/systems/welteT100/bar.js +44 -2
  91. package/lib/systems/welteT100/system.d.ts +6 -39
  92. package/lib/systems/welteT100/system.js +19 -128
  93. package/lib/systems/welteT98/bar.d.ts +1 -1
  94. package/lib/systems/welteT98/bar.js +18 -2
  95. package/lib/systems/welteT98/system.d.ts +20 -38
  96. package/lib/systems/welteT98/system.js +20 -121
  97. package/lib/validate.d.ts +1 -1
  98. package/lib/{EditionView.d.ts → view/EditionView.d.ts} +17 -41
  99. package/lib/{EditionView.js → view/EditionView.js} +26 -75
  100. package/package.json +7 -2
  101. package/lib/Emulation.d.ts +0 -36
  102. package/lib/Emulation.js +0 -250
  103. package/lib/editionOps.d.ts +0 -260
  104. package/lib/editionOps.js +0 -1079
  105. package/lib/importJsonLd.js +0 -57
  106. /package/lib/{migrate.d.ts → io/migrate.d.ts} +0 -0
  107. /package/lib/{Agent.js → model/Agent.js} +0 -0
  108. /package/lib/{Assumption.js → model/Assumption.js} +0 -0
  109. /package/lib/{ConditionState.d.ts → model/ConditionState.d.ts} +0 -0
  110. /package/lib/{ConditionState.js → model/ConditionState.js} +0 -0
  111. /package/lib/{Edit.js → model/Edit.js} +0 -0
  112. /package/lib/{Edition.js → model/Edition.js} +0 -0
  113. /package/lib/{Feature.js → model/Feature.js} +0 -0
  114. /package/lib/{FeatureSource.js → model/FeatureSource.js} +0 -0
  115. /package/lib/{Perforator.js → model/Perforator.js} +0 -0
  116. /package/lib/{Quantity.d.ts → model/Quantity.d.ts} +0 -0
  117. /package/lib/{Quantity.js → model/Quantity.js} +0 -0
  118. /package/lib/{Symbol.js → model/Symbol.js} +0 -0
  119. /package/lib/{TrackCalibration.d.ts → model/TrackCalibration.d.ts} +0 -0
  120. /package/lib/{TrackCalibration.js → model/TrackCalibration.js} +0 -0
  121. /package/lib/{notes.d.ts → model/notes.d.ts} +0 -0
  122. /package/lib/{notes.js → model/notes.js} +0 -0
  123. /package/lib/{procedures.d.ts → model/procedures.d.ts} +0 -0
  124. /package/lib/{procedures.js → model/procedures.js} +0 -0
  125. /package/lib/{vocabulary.d.ts → model/vocabulary.d.ts} +0 -0
  126. /package/lib/{sorted.d.ts → shared/sorted.d.ts} +0 -0
  127. /package/lib/{sorted.js → shared/sorted.js} +0 -0
  128. /package/lib/{utils.d.ts → shared/utils.d.ts} +0 -0
  129. /package/lib/{utils.js → shared/utils.js} +0 -0
  130. /package/lib/{ReproducingSystem.js → systems/ReproducingSystem.js} +0 -0
package/lib/editionOps.js DELETED
@@ -1,1079 +0,0 @@
1
- import { current, isDraft } from "immer";
2
- import { v4 } from "uuid";
3
- import { getAt } from "./EditionView.js";
4
- import { isCommand, placementRelations } from "./Symbol.js";
5
- import { collationsOf, defaultCollationTolerance, isCollationsOwn, unchecked, uncheckedMotivation } from "./Collation.js";
6
- import { collationToleranceOf, editsOf, insertedBy, principalDerivationOf } from "./Version.js";
7
- import { asSymbols, barOf, featuresByAct, featuresOf, isPaperStretch, statesNothing } from "./RollCopy.js";
8
- import { systemOf } from "./TrackerBar.js";
9
- import { substitutionsBetween } from "./substitution.js";
10
- import { trackerBarOf } from "./systems/index.js";
11
- import { applyShift, applyScale, revertShift, revertScale, revertShortening, shortenChains } from "./alignment.js";
12
- import { assignReference, idOf } from "./Assumption.js";
13
- import { conditions as conditionsAllowed, featuresBorneBy, isPatch, withBorneFeatures } from "./Feature.js";
14
- import { distance, mm, subtract } from "./Quantity.js";
15
- const noChange = () => undefined;
16
- const onCopy = (copyId, op) => draft => {
17
- const copy = draft.copies.find(c => c.id === copyId);
18
- if (copy)
19
- op(copy, draft);
20
- };
21
- const onVersion = (versionId, op) => draft => {
22
- const version = draft.versions.find(v => v.id === versionId);
23
- if (version)
24
- op(version, draft);
25
- };
26
- const onFeature = (copyId, featureId, op) => onCopy(copyId, copy => {
27
- const feature = featuresOf(copy).find(f => f.id === featureId);
28
- if (feature)
29
- op(feature);
30
- });
31
- /**
32
- * The state a draft stands at, as plain data. Reading a draft proxies
33
- * everything it touches, so what is only read is read from this.
34
- */
35
- const stateOf = (draft) => isDraft(draft) ? current(draft) : draft;
36
- /** The items that do not match, or the very same array when none does, so that a draft stays untouched. */
37
- const without = (items, matches) => items.some(matches) ? items.filter(item => !matches(item)) : items;
38
- /** The items each changed, or the very same array when the change left every one as it was. */
39
- const mapped = (items, change) => {
40
- const changed = items.map(change);
41
- return changed.every((item, i) => item === items[i]) ? items : changed;
42
- };
43
- /** The items each changed, less those the change emptied; the very same array where it changed none. */
44
- const pruned = (items, change, emptied) => {
45
- const changed = mapped(items, change);
46
- return changed === items ? items : changed.filter((item, i) => item === items[i] || !emptied(item));
47
- };
48
- /** The record with the field replaced, or the very same record where that is what stood there. */
49
- const replacing = (record, key, value) => record[key] === value ? record : { ...record, [key]: value };
50
- /** The ids of the items the rewriting left out. */
51
- const droppedIds = (before, after) => {
52
- const kept = new Set(after.map(item => item.id));
53
- return before.flatMap(item => kept.has(item.id) ? [] : [item.id]);
54
- };
55
- const insertion = (symbol) => ({ type: 'edit', id: v4(), insert: [symbol] });
56
- const deletion = (symbolId) => ({ type: 'edit', id: v4(), delete: [symbolId] });
57
- /** The edit as a collation leaves it: made by rule, and not yet read by anybody. */
58
- const asUnchecked = (edit) => ({ ...edit, motivation: unchecked });
59
- /**
60
- * The motivations with the unchecked one declared, where any edit
61
- * names it and the version does not state it yet. An edit naming a
62
- * motivation the version leaves undeclared points at nothing.
63
- */
64
- const declaring = (motivations, edits) => edits.some(edit => edit.motivation === unchecked)
65
- && !motivations.some(motivation => motivation.id === unchecked)
66
- ? [...motivations, uncheckedMotivation]
67
- : motivations;
68
- const isEmpty = (edit) => !edit.insert?.length && !edit.delete?.length;
69
- const insertedIn = (versions) => versions.flatMap(insertedBy);
70
- /** The edits with the change applied, less those it emptied; the very same array where it changed none. */
71
- const edited = (edits, change) => pruned(edits, change, isEmpty);
72
- /** The edit without the symbols among its insertions, or the very same edit where it inserts none of them. */
73
- const droppingInsertions = (symbolIds) => (edit) => {
74
- const insert = edit.insert && without(edit.insert, symbol => symbolIds.has(symbol.id));
75
- return insert === edit.insert ? edit : { ...edit, insert };
76
- };
77
- /** Takes the symbols out of the version's own insertions, and the edits that had nothing else. */
78
- const dropInsertions = (version, symbolIds) => {
79
- const edits = stateOf(version).edits;
80
- if (edits)
81
- version.edits = edited(edits, droppingInsertions(symbolIds));
82
- };
83
- /**
84
- * Puts the copy into the edition with a version of its own, which
85
- * inserts every symbol the copy's own tracker bar reads on it. The
86
- * version is a reading in that system's words, so it is coded for the
87
- * system the copy was cut for.
88
- */
89
- export const createVersion = (copy) => draft => {
90
- const bar = barOf(copy);
91
- draft.copies.push(copy);
92
- draft.versions.push({
93
- id: v4(),
94
- system: systemOf(bar),
95
- edits: asSymbols(featuresOf(copy), bar).map(insertion),
96
- motivations: []
97
- });
98
- };
99
- /**
100
- * Puts the copy into the edition without a version of its own, as for a
101
- * copy whose features are not read into symbols: one known only from a
102
- * recording states instead which versions it carries.
103
- */
104
- export const addCopy = (copy) => draft => {
105
- draft.copies.push(copy);
106
- };
107
- /** States what the scale is put down to, in place of an earlier reading. */
108
- const readScale = (copy, reading) => {
109
- if (reading.cause === 'paper') {
110
- copy.conditions = [...copy.conditions.filter(condition => !isPaperStretch(condition)), reading.condition];
111
- return;
112
- }
113
- if (!copy.production)
114
- copy.production = {};
115
- copy.production.speed = reading.speed;
116
- };
117
- /**
118
- * Shifts and then scales the copy's features into line with another
119
- * copy's, and puts the scale down to what the reading says: the paper,
120
- * or the speed the copy was cut for.
121
- */
122
- export const alignCopy = (copyId, shift, scale, reading) => onCopy(copyId, copy => {
123
- applyShift(shift, copy);
124
- applyScale(scale, copy);
125
- if (reading)
126
- readScale(copy, reading);
127
- });
128
- /**
129
- * Puts the copy's features back where they were measured. A paper
130
- * stretch read off the alignment goes with it; a speed stated stays,
131
- * being a fact about the copy.
132
- */
133
- export const unalignCopy = (copyId) => onCopy(copyId, copy => {
134
- revertScale(copy);
135
- revertShift(copy);
136
- copy.conditions = without(copy.conditions, isPaperStretch);
137
- });
138
- /**
139
- * Takes the extension a pneumatic reader adds off the ends of the
140
- * copy's chains of holes, and records how much was taken, so that their lengths
141
- * can be compared with a scanned copy's at all.
142
- */
143
- export const shortenCopy = (copyId, extension, leaving) => onCopy(copyId, copy => shortenChains(extension, copy, leaving));
144
- /** Puts the reader's extension back on the copy's chains of holes. */
145
- export const unshortenCopy = (copyId) => onCopy(copyId, copy => revertShortening(copy));
146
- /** States what the copy's features were read from, in place of any earlier statement. */
147
- export const stateSource = (copyId, source) => onCopy(copyId, copy => {
148
- copy.readFrom = source;
149
- });
150
- /** Takes back the statement, leaving the copy silent about its source again. */
151
- export const clearSource = (copyId) => onCopy(copyId, copy => {
152
- copy.readFrom = undefined;
153
- });
154
- /** Gives the copy the siglum it is referred to by, or takes it away where the siglum given is blank. */
155
- export const nameCopy = (copyId, siglum) => onCopy(copyId, copy => {
156
- const trimmed = siglum.trim();
157
- if (trimmed)
158
- copy.siglum = trimmed;
159
- else
160
- delete copy.siglum;
161
- });
162
- /** A reference under the belief given, where one is given. */
163
- const referenceHeld = (id, belief) => ({ ...assignReference(id), ...(belief && { '@annotation': { id: v4(), belief } }) });
164
- /** The references less those that match, or nothing where none is left. */
165
- const withoutReferences = (references, matches) => {
166
- const kept = references.filter(reference => !matches(reference));
167
- return kept.length > 0 ? kept : undefined;
168
- };
169
- /** Takes out the copy's statements that match, and the list itself where none is left. */
170
- const dropStatements = (copy, matches) => {
171
- const statements = stateOf(copy).carries;
172
- if (!statements?.some(matches))
173
- return;
174
- const kept = withoutReferences(statements, matches);
175
- if (kept)
176
- copy.carries = kept;
177
- else
178
- delete copy.carries;
179
- };
180
- /**
181
- * States that the copy carries the version, under the belief given. It
182
- * is meant for a copy whose features are not read into symbols, such as
183
- * one known only from a recording, and `carriageProblems` reports it
184
- * where features carry symbols already. A second statement about one
185
- * version is none.
186
- */
187
- export const stateCarriage = (copyId, versionId, belief) => onCopy(copyId, copy => {
188
- const statements = stateOf(copy).carries ?? [];
189
- if (statements.some(statement => idOf(statement) === versionId))
190
- return;
191
- copy.carries = [...statements, referenceHeld(versionId, belief)];
192
- });
193
- /** Takes back the copy's statement that it carries the version. */
194
- export const clearCarriage = (copyId, versionId) => onCopy(copyId, copy => dropStatements(copy, statement => idOf(statement) === versionId));
195
- /**
196
- * Adds a general condition to the copy, beside whatever is stated of it
197
- * already. The other condition a copy may be in, a paper stretch, is
198
- * read off an alignment and stated by `alignCopy`.
199
- */
200
- export const addGeneralCondition = (copyId, condition) => onCopy(copyId, copy => {
201
- copy.conditions.push(condition);
202
- });
203
- /**
204
- * Whether the feature's own kind allows a condition of this kind. The
205
- * type narrowed to is the weaker statement, holding of a condition any
206
- * kind of feature may be in.
207
- */
208
- const allows = (feature, condition) => {
209
- const allowed = conditionsAllowed[feature.type];
210
- return allowed.includes(condition.conditionType);
211
- };
212
- /**
213
- * States the condition of the feature, in place of any earlier
214
- * statement. Throws where the kind of feature is in no such condition;
215
- * `conditions` says which conditions each kind of feature may be in.
216
- */
217
- export const stateFeatureCondition = (copyId, featureId, condition) => onFeature(copyId, featureId, feature => {
218
- if (!allows(feature, condition)) {
219
- throw new Error(`A ${feature.type} is in no '${condition.conditionType}' condition`);
220
- }
221
- feature.condition = condition;
222
- });
223
- /** The ids of every feature the copy bears, those a patch bears among them. */
224
- const featureIdsOf = (copy) => new Set(featuresOf(copy).flatMap(withBorneFeatures).map(feature => feature.id));
225
- /**
226
- * A symbol every carrier of which lies among the features loses its
227
- * evidence with them. A symbol without carriers, such as a label,
228
- * stands on its own.
229
- */
230
- const carriedOnlyOn = (features) => (symbol) => symbol.carriers.length > 0 && symbol.carriers.every(carrier => features.has(idOf(carrier)));
231
- /** The symbols of the versions that no other copy carries. */
232
- export const symbolsCarriedOnlyBy = (edition, copyId) => {
233
- const copy = edition.copies.find(c => c.id === copyId);
234
- return copy ? insertedIn(edition.versions).filter(carriedOnlyOn(featureIdsOf(copy))) : [];
235
- };
236
- const references = [...placementRelations, 'pairedWith'];
237
- /** The command without its references to the dropped symbols, or the very same one where it makes none. */
238
- const forgettingReferences = (command, dropped) => {
239
- const stale = references.filter(relation => {
240
- const reference = command[relation];
241
- return reference !== undefined && dropped.has(idOf(reference));
242
- });
243
- if (stale.length === 0)
244
- return command;
245
- const kept = { ...command };
246
- stale.forEach(relation => { delete kept[relation]; });
247
- return kept;
248
- };
249
- /** The symbol without the features among its carriers, and without references to what went with them. */
250
- const forgettingCarriers = (features, dropped) => (symbol) => {
251
- const carriers = without(symbol.carriers, carrier => features.has(idOf(carrier)));
252
- const relieved = carriers === symbol.carriers ? symbol : { ...symbol, carriers };
253
- return isCommand(relieved) ? forgettingReferences(relieved, dropped) : relieved;
254
- };
255
- /** The edit without the dropped symbols and the features, or the very same edit where it had none of them. */
256
- const forgettingFeatures = (features, dropped) => {
257
- const forgetCarriers = forgettingCarriers(features, dropped);
258
- return (edit) => {
259
- const insert = edit.insert && mapped(without(edit.insert, symbol => dropped.has(symbol.id)), forgetCarriers);
260
- const deleted = edit.delete && without(edit.delete, id => dropped.has(id));
261
- if (insert === edit.insert && deleted === edit.delete)
262
- return edit;
263
- return { ...edit, ...(insert && { insert }), ...(deleted && { delete: deleted }) };
264
- };
265
- };
266
- const isRecord = (value) => typeof value === 'object' && value !== null;
267
- /** The record's values each changed, or the very same record where the change left every one as it was. */
268
- const withValues = (record, change) => {
269
- const entries = Object.entries(record);
270
- const changed = entries.map(([key, value]) => [key, change(value)]);
271
- return changed.every(([, value], i) => value === entries[i][1]) ? record : Object.fromEntries(changed);
272
- };
273
- /** The value with the change applied to every record within it and then to itself, innermost first. */
274
- const deeply = (change) => {
275
- const changed = (value) => Array.isArray(value) ? mapped(value, changed)
276
- : isRecord(value) ? change(withValues(value, changed))
277
- : value;
278
- return changed;
279
- };
280
- /** Whether the two stand alike, so that what differs within them can be written where it lies. */
281
- const alike = (before, after) => {
282
- if (!isRecord(before) || !isRecord(after))
283
- return false;
284
- if (Array.isArray(before))
285
- return Array.isArray(after) && before.length === after.length;
286
- return !Array.isArray(after);
287
- };
288
- /** Writes onto the draft what the rewriting changed, as deep as the change reaches. */
289
- const writeInto = (draft, before, after) => Object.entries(after).forEach(([key, value]) => {
290
- if (value === before[key])
291
- return;
292
- if (alike(before[key], value))
293
- writeInto(draft[key], before[key], value);
294
- else
295
- draft[key] = value;
296
- });
297
- const isCopy = (record) => 'type' in record && record.type === 'RollCopy';
298
- const isBelief = (record) => 'type' in record && record.type === 'belief';
299
- const isComprehension = (reason) => reason.type === 'meaningComprehension';
300
- const comprehendsNothing = (reason) => isComprehension(reason) && reason.comprehends.length === 0;
301
- /**
302
- * The modification with what it names rewritten, or the very same one
303
- * where that leaves it as it was. Only a removal names anything by id:
304
- * what an act produced or glued on it states itself.
305
- */
306
- const renamingMembers = (rename) => (modification) => modification.type === 'Removal'
307
- ? replacing(modification, 'removed', rename(modification.removed))
308
- : modification;
309
- /** The reason with what a comprehension comprehends rewritten; any other reason names nothing of the kind. */
310
- const renamingComprehended = (rename) => (reason) => isComprehension(reason) ? replacing(reason, 'comprehends', rename(reason.comprehends)) : reason;
311
- /**
312
- * The record with the ids it names rewritten: what a copy's removals
313
- * removed, and what the comprehensions among a belief's reasons
314
- * comprehend. A removal or a comprehension the rewriting emptied goes
315
- * with what it named; one that named nothing before stays, as an edit
316
- * that was empty before it does.
317
- */
318
- const renaming = (rename) => (record) => {
319
- if (isCopy(record)) {
320
- return replacing(record, 'modifications', pruned(record.modifications, renamingMembers(rename), statesNothing));
321
- }
322
- if (isBelief(record)) {
323
- return replacing(record, 'reasons', pruned(record.reasons, renamingComprehended(rename), comprehendsNothing));
324
- }
325
- return record;
326
- };
327
- /**
328
- * Rewrites the ids by which the edition names features and symbols
329
- * outside the versions. A belief is annotatable anywhere, so the whole
330
- * edition is read; what the rewriting leaves alone is left the very
331
- * object it was.
332
- */
333
- const renameReferences = (draft, rename) => {
334
- const before = stateOf(draft);
335
- const after = deeply(renaming(rename))(before);
336
- if (after !== before)
337
- writeInto(draft, before, after);
338
- };
339
- /**
340
- * Strikes the features from the edition: their carriers go, a symbol
341
- * that had no other carrier goes with them, an edit left exchanging
342
- * nothing goes as well, and so does every reference the versions, the
343
- * modifications of the copies and the comprehensions made to what went.
344
- */
345
- const forgetFeatures = (draft, features) => {
346
- const versions = stateOf(draft.versions);
347
- const dropped = new Set(insertedIn(versions).filter(carriedOnlyOn(features)).map(symbol => symbol.id));
348
- const forget = forgettingFeatures(features, dropped);
349
- const edits = versions.map(version => version.edits && edited(version.edits, forget));
350
- const gone = new Set([
351
- ...features,
352
- ...dropped,
353
- ...versions.flatMap((version, i) => droppedIds(editsOf(version), edits[i] ?? []))
354
- ]);
355
- renameReferences(draft, ids => without(ids, id => gone.has(id)));
356
- draft.versions.forEach((version, i) => {
357
- const stated = edits[i];
358
- if (stated)
359
- version.edits = stated;
360
- });
361
- };
362
- /**
363
- * The ids of the features named and of everything they bear: a feature
364
- * of a patch stands nowhere once the patch is gone.
365
- */
366
- const goneWith = (features, named) => features.flatMap(feature => named.has(feature.id)
367
- ? withBorneFeatures(feature).map(borne => borne.id)
368
- : goneWith(featuresBorneBy(feature), named));
369
- /** The feature with the named ones gone from what it bears, or the very same one where it bears none of them. */
370
- const withoutBorne = (feature, named) => {
371
- if (!isPatch(feature) || !feature.features)
372
- return feature;
373
- const borne = withoutFeatures(feature.features, named);
374
- return borne === feature.features ? feature : { ...feature, features: borne };
375
- };
376
- /** The features without those named, wherever they lie, and without whatever those bore. */
377
- const withoutFeatures = (features, named) => mapped(without(features, feature => named.has(feature.id)), feature => withoutBorne(feature, named));
378
- /** The act with its features rewritten, or the very same one where the rewriting left them. */
379
- const rewritingAct = (rewrite) => (modification) => {
380
- if (modification.type === 'Alteration')
381
- return replacing(modification, 'produced', rewrite(modification.produced));
382
- if (modification.type === 'Attachment')
383
- return replacing(modification, 'added', rewrite(modification.added));
384
- return modification;
385
- };
386
- /**
387
- * Writes the rewriting onto the features of every act of the copy, and
388
- * takes out an act it left with nothing to state.
389
- */
390
- const rewriteFeatures = (copy, rewrite) => {
391
- const state = stateOf(copy);
392
- const produced = state.production?.produced;
393
- if (produced && copy.production) {
394
- const rewritten = rewrite(produced);
395
- if (rewritten !== produced)
396
- copy.production.produced = rewritten;
397
- }
398
- copy.modifications = pruned(state.modifications, rewritingAct(rewrite), statesNothing);
399
- };
400
- /** The features of the act that brought the named feature about, where that act produces features. */
401
- const producedBeside = (copy, featureId) => {
402
- const names = (features) => features.some(feature => feature.id === featureId);
403
- const punched = copy.production?.produced;
404
- if (punched && names(punched))
405
- return punched;
406
- const act = copy.modifications.find(act => act.type === 'Alteration' && names(act.produced));
407
- return act?.type === 'Alteration' ? act.produced : undefined;
408
- };
409
- /** The patches of the attachment that glued the named one on. */
410
- const gluedBeside = (copy, patchId) => {
411
- const act = copy.modifications.find(act => act.type === 'Attachment' && act.added.some(patch => patch.id === patchId));
412
- return act?.type === 'Attachment' ? act.added : undefined;
413
- };
414
- /** The list the copy states a new feature in, making the act it belongs to where there is none. */
415
- const actFor = (copy, patch, act) => {
416
- const beside = act.beside !== undefined
417
- ? (patch ? gluedBeside(copy, act.beside) : producedBeside(copy, act.beside))
418
- : undefined;
419
- if (beside)
420
- return beside;
421
- if (patch) {
422
- const added = [];
423
- copy.modifications.push({ type: 'Attachment', added, ...(act.purpose && { purpose: act.purpose }) });
424
- return added;
425
- }
426
- if (act.punched) {
427
- if (!copy.production)
428
- copy.production = {};
429
- if (!copy.production.produced)
430
- copy.production.produced = [];
431
- return copy.production.produced;
432
- }
433
- const produced = [];
434
- copy.modifications.push({ type: 'Alteration', produced, ...(act.purpose && { purpose: act.purpose }) });
435
- return produced;
436
- };
437
- /**
438
- * States that the copy bears the feature, in the act that brought it
439
- * about: a patch was glued on by an attachment, anything else was
440
- * produced, by the punching or by a later act. Which act, `FeatureAct`
441
- * says; a `beside` that names nothing the copy bears is passed over and
442
- * the feature goes into an act of its own.
443
- */
444
- export const addFeature = (copyId, feature, act = {}) => onCopy(copyId, copy => {
445
- actFor(copy, isPatch(feature), act).push(feature);
446
- });
447
- /**
448
- * States that the patch bears the feature. What a patch bears came onto
449
- * the copy with the patch, so it belongs to no act of its own and
450
- * states no place: it stands where the patch stands.
451
- */
452
- export const addBorneFeature = (copyId, patchId, feature) => onCopy(copyId, copy => {
453
- const patch = featuresOf(copy).flatMap(withBorneFeatures).find(borne => borne.id === patchId);
454
- if (!patch || !isPatch(patch))
455
- return;
456
- if (!patch.features)
457
- patch.features = [];
458
- patch.features.push(feature);
459
- });
460
- /**
461
- * Takes the features off the copy, and out of the versions with what
462
- * only they carried. A feature may be named wherever the copy bears it:
463
- * a patch goes with everything glued onto it, and a feature of a patch
464
- * may be taken back on its own, the patch staying where it is. An act
465
- * left having produced or added nothing goes as well.
466
- */
467
- export const removeFeatures = (copyId, featureIds) => onCopy(copyId, (copy, draft) => {
468
- const named = new Set(featureIds);
469
- const features = featuresOf(stateOf(copy));
470
- rewriteFeatures(copy, (stated) => withoutFeatures(stated, named));
471
- forgetFeatures(draft, new Set(goneWith(features, named)));
472
- });
473
- /**
474
- * Takes the copy out of the edition together with the symbols only it
475
- * carries, and with every reference the versions and the argumentations
476
- * made to those symbols.
477
- */
478
- export const removeCopy = (copyId) => onCopy(copyId, (copy, draft) => {
479
- forgetFeatures(draft, featureIdsOf(copy));
480
- draft.copies = draft.copies.filter(c => c.id !== copyId);
481
- });
482
- /**
483
- * Whether two records of the edition state the same, the identity of a
484
- * statement left out: two transcriptions reading the same word say the
485
- * same, whichever ids they were given.
486
- */
487
- const sayTheSame = (a, b) => {
488
- if (a === b)
489
- return true;
490
- if (!isRecord(a) || !isRecord(b) || Array.isArray(a) !== Array.isArray(b))
491
- return false;
492
- const keys = new Set([...Object.keys(a), ...Object.keys(b)]);
493
- keys.delete('id');
494
- return [...keys].every(key => sayTheSame(a[key], b[key]));
495
- };
496
- /**
497
- * What a feature states beyond its identity, its place along the roll,
498
- * its depiction and its condition. What a patch bears counts by
499
- * identity: two patches bear the same only where they bear the very
500
- * same features, so that no merge takes a feature of a patch away.
501
- */
502
- const nature = (feature) => {
503
- const { id, horizontal, depiction, condition, ...rest } = feature;
504
- return isPatch(feature) && feature.features
505
- ? { ...rest, features: feature.features.map(borne => borne.id) }
506
- : rest;
507
- };
508
- const conditionsOf = (features) => features.flatMap(feature => feature.condition ? [feature.condition] : []);
509
- /**
510
- * What stands in the way of reading the features as one, or nothing
511
- * where they may be merged. Features may be merged where they differ
512
- * in nothing but their place along the roll, their depiction and the
513
- * condition at most one of them states. How far apart they lie is not
514
- * asked: whether a gap is a bridge of the perforator, a tear or two
515
- * perforations of their own is the editor's reading.
516
- */
517
- export const mergeObstacle = (features) => {
518
- if (features.length < 2)
519
- return 'fewer-than-two';
520
- const [first, ...rest] = features;
521
- if (rest.some(feature => feature.type !== first.type))
522
- return 'different-types';
523
- if (rest.some(feature => !sayTheSame(feature.vertical, first.vertical)))
524
- return 'different-tracks';
525
- if (rest.some(feature => !sayTheSame(nature(feature), nature(first))))
526
- return 'unlike-features';
527
- const conditions = conditionsOf(features);
528
- if (conditions.some(condition => !sayTheSame(condition, conditions[0])))
529
- return 'differing-conditions';
530
- return undefined;
531
- };
532
- /** The acts of the copy that state any of the named features. */
533
- const actsHolding = (copy, named) => featuresByAct(copy).filter(features => features.some(feature => named.has(feature.id)));
534
- /**
535
- * What stands in the way of reading the named features of the copy as
536
- * one, which is the whole of what `mergeFeatures` asks: whether one act
537
- * brought them all about, and what the features themselves say. An id
538
- * the copy does not bear at a place of its own is passed over.
539
- */
540
- const obstacleIn = (copy, featureIds) => {
541
- const named = new Set(featureIds);
542
- const acts = actsHolding(copy, named);
543
- return acts.length > 1
544
- ? 'different-acts'
545
- : mergeObstacle((acts[0] ?? []).filter(feature => named.has(feature.id)));
546
- };
547
- /**
548
- * What stands in the way of reading the features the ids name as one,
549
- * as `mergeFeatures` will find it. `mergeObstacle` asks only what the
550
- * features themselves say, which cannot reach `different-acts`: one
551
- * feature is the work of one act, and where the features stand is the
552
- * edition's business rather than theirs.
553
- */
554
- export const mergeObstacleIn = (view, featureIds) => {
555
- const copy = featureIds.map(id => view.copyOf(id)).find(copy => copy !== undefined);
556
- return copy ? obstacleIn(copy, featureIds) : 'fewer-than-two';
557
- };
558
- /** The items with the replacement in the place of the first it stands for, the others dropped. */
559
- const standingFor = (items, stands, replacement) => {
560
- const first = items.findIndex(stands);
561
- if (first < 0)
562
- return items;
563
- return items.flatMap((item, i) => i === first ? [replacement] : stands(item) ? [] : [item]);
564
- };
565
- const spanning = (features) => ({
566
- unit: 'mm',
567
- from: mm(Math.min(...features.map(feature => feature.horizontal.from))),
568
- to: mm(Math.max(...features.map(feature => feature.horizontal.to)))
569
- });
570
- /**
571
- * The feature the merged ones give way to. It spans them all and is in
572
- * every other respect the one of them that states a condition, the
573
- * others being alike in all but their place. The depiction goes: a
574
- * region of the scan showing one part depicts no more than that part.
575
- */
576
- const mergedFrom = (features, id) => {
577
- const stating = features.find(feature => feature.condition) ?? features[0];
578
- const merged = { ...stating, id, horizontal: spanning(features) };
579
- delete merged.depiction;
580
- return merged;
581
- };
582
- /** The symbol carried by the merged feature where it named one of those it replaces, and naming it once. */
583
- const carriedByMerged = (replaced, mergedId) => (symbol) => {
584
- const names = (carrier) => replaced.has(idOf(carrier));
585
- const first = symbol.carriers.find(names);
586
- if (!first)
587
- return symbol;
588
- return { ...symbol, carriers: standingFor(symbol.carriers, names, { ...first, id: mergedId }) };
589
- };
590
- /** Points the versions at the merged feature wherever they name one it replaces. */
591
- const carryOver = (draft, replaced, mergedId) => {
592
- const recarry = carriedByMerged(replaced, mergedId);
593
- const recarrying = (edit) => {
594
- const insert = edit.insert && mapped(edit.insert, recarry);
595
- return insert === edit.insert ? edit : { ...edit, insert };
596
- };
597
- const versions = stateOf(draft.versions);
598
- draft.versions.forEach((version, i) => {
599
- const edits = versions[i].edits;
600
- if (edits)
601
- version.edits = mapped(edits, recarrying);
602
- });
603
- };
604
- /**
605
- * Replaces the features of the copy with a single one covering them
606
- * all, where a scan has split what the editor reads as one feature.
607
- * The merged feature takes the place of the first it replaces and
608
- * spans from the first to the last, any gap between them included.
609
- * What the replaced features carried is carried by the merged one, and
610
- * whatever else named them, a modification or a comprehension, names
611
- * the merged one in their stead.
612
- *
613
- * Only the features the copy bears itself are merged. A feature of a
614
- * patch states no place along the roll of its own, so there is nothing
615
- * for a merge to span, and an id naming one is passed over as an id the
616
- * copy does not bear is. Features of two different acts are not merged
617
- * either: one feature is the work of one act.
618
- *
619
- * Throws where the features cannot stand for one; `mergeObstacle`
620
- * says beforehand whether they can.
621
- */
622
- export const mergeFeatures = (copyId, featureIds) => onCopy(copyId, (copy, draft) => {
623
- const state = stateOf(copy);
624
- const obstacle = obstacleIn(state, featureIds);
625
- if (obstacle) {
626
- throw new Error(`The features of copy ${copyId} cannot be merged: ${obstacle}`);
627
- }
628
- const named = new Set(featureIds);
629
- const toMerge = (actsHolding(state, named)[0] ?? []).filter(feature => named.has(feature.id));
630
- const replaced = new Set(toMerge.map(feature => feature.id));
631
- const mergedId = v4();
632
- rewriteFeatures(copy, (stated) => {
633
- const stands = (feature) => replaced.has(feature.id);
634
- return stated.some(stands) ? standingFor(stated, stands, mergedFrom(stated.filter(stands), mergedId)) : stated;
635
- });
636
- carryOver(draft, replaced, mergedId);
637
- renameReferences(draft, ids => standingFor(ids, id => replaced.has(id), mergedId));
638
- });
639
- /** The carriers of each collated symbol pass to its counterpart. */
640
- const handOverCarriers = (view, draft, collations) => collations.forEach(({ symbol, counterpart }) => {
641
- const path = view.getPath(counterpart.id);
642
- const target = path && getAt(path, draft);
643
- target?.carriers.push(...symbol.carriers);
644
- });
645
- /** Whether the two versions are coded for different reproducing systems. */
646
- const differ = (child, parent) => {
647
- const one = trackerBarOf(child?.system);
648
- const other = trackerBarOf(parent?.system);
649
- return one !== undefined && other !== undefined && one.id !== other.id;
650
- };
651
- /** Whether the version's text is read against the parent, its principal derivation naming it. */
652
- const readsAgainst = (version, parentId) => {
653
- const principal = principalDerivationOf(version);
654
- return principal !== undefined && idOf(principal) === parentId;
655
- };
656
- /** The derivations the version states beside its principal one, less any naming the parent. */
657
- const hypothesesBeside = (version, parentId) => {
658
- const principal = principalDerivationOf(version);
659
- return (version.basedOn ?? []).filter(derivation => derivation !== principal && idOf(derivation) !== parentId);
660
- };
661
- /** Takes out the derivations that match, and the list itself where none is left. */
662
- const dropDerivations = (version, matches) => {
663
- const derivations = stateOf(version).basedOn;
664
- if (!derivations?.some(matches))
665
- return;
666
- const kept = withoutReferences(derivations, matches);
667
- if (kept)
668
- version.basedOn = kept;
669
- else
670
- delete version.basedOn;
671
- };
672
- /** The symbols a set of edits speaks for, whether by inserting or by deleting them. */
673
- const spokenForBy = (edits) => new Set(edits.flatMap(edit => [
674
- ...(edit.insert ?? []).map(symbol => symbol.id),
675
- ...(edit.delete ?? [])
676
- ]));
677
- /** An exchange of symbols, as a key: what it puts in against what it takes out. */
678
- const exchangeKey = (inserted, deleted) => `${[...inserted].sort().join(',')}/${[...deleted].sort().join(',')}`;
679
- /**
680
- * The edits already stated, by the exchange each of them makes. An
681
- * equivalence the collation draws a second time is the one already
682
- * stated, and drawing it again is no reason to mint a new identifier or
683
- * to drop the motivation somebody wrote on it.
684
- */
685
- const byExchange = (edits) => new Map(edits.map(edit => [exchangeKey((edit.insert ?? []).map(symbol => symbol.id), edit.delete ?? []), edit]));
686
- /**
687
- * Bases the child on the parent. A symbol of the child that collates
688
- * with one the parent hands down adds its carriers to that symbol; the
689
- * rest become the child's insertions, and what the parent hands down
690
- * and the child lacks becomes its deletions. The derivation states the
691
- * tolerance it was collated at and becomes the principal one; the
692
- * hypotheses the child stated beside its former one stay.
693
- *
694
- * The edits the child already stated are rewritten only as far as a
695
- * collation wrote them (`isCollationsOwn`). An editor's reading of the
696
- * difference between the two texts stays, and the symbols it speaks for
697
- * are left out of the collation, so that connecting the two again
698
- * neither doubles them nor silently drops what somebody established by
699
- * hand. An equivalence is the collation's own, since it is drawn from
700
- * the two systems' vocabularies rather than read off the paper, but one
701
- * drawn again over the very same symbols is kept as it stands, with its
702
- * identifier and whatever was written on it.
703
- *
704
- * The child's own text is what it shows less what the parent hands
705
- * down, so that connecting two versions already connected collates the
706
- * child's symbols and not the parent's with themselves.
707
- */
708
- export const connectVersions = (view, childId, parentId, tolerance = defaultCollationTolerance) => {
709
- const child = view.version(childId);
710
- const stated = child ? editsOf(child) : [];
711
- const established = stated.filter(edit => !isCollationsOwn(edit));
712
- const spokenFor = spokenForBy(established);
713
- const unspoken = (symbol) => !spokenFor.has(symbol.id);
714
- // What the parent hands down and the child still shows passes
715
- // through: it is neither the child's own symbol nor one it lacks.
716
- // Without that, connecting a pair already connected would collate
717
- // the inherited symbols with themselves and double their carriers.
718
- const handedDown = view.snapshot(parentId).filter(unspoken);
719
- const shown = new Set(view.snapshot(childId).map(symbol => symbol.id));
720
- const inheritedIds = new Set(handedDown.map(symbol => symbol.id));
721
- const inherited = handedDown.filter(symbol => !shown.has(symbol.id));
722
- const own = view.snapshot(childId).filter(symbol => unspoken(symbol) && !inheritedIds.has(symbol.id));
723
- const locate = (symbol) => view.placeOf(symbol);
724
- const collations = collationsOf(own, inherited, locate, tolerance);
725
- const collated = new Set(collations.map(({ symbol }) => symbol.id));
726
- const matched = new Set(collations.map(({ counterpart }) => counterpart.id));
727
- /**
728
- * Where the child is coded for another system, a held command of
729
- * its own often stands for a latched pair of the parent's. Saying so
730
- * as one edit is the transfer being carried out, and leaving the two
731
- * apart would make the apparatus a list of unexplained losses beside
732
- * a list of unexplained gains.
733
- */
734
- const substituted = differ(child, view.version(parentId))
735
- ? substitutionsBetween(own.filter(symbol => !collated.has(symbol.id)), inherited.filter(symbol => !matched.has(symbol.id)), locate, tolerance)
736
- : [];
737
- const paired = new Set(substituted.flatMap(({ replaced, by }) => [...by, ...replaced].map(symbol => symbol.id)));
738
- const alreadyStated = byExchange(stated);
739
- const equivalence = ({ replaced, by }) => {
740
- const inserted = by.map(symbol => symbol.id);
741
- const deleted = replaced.map(symbol => symbol.id);
742
- return alreadyStated.get(exchangeKey(inserted, deleted)) ?? {
743
- type: 'edit',
744
- id: v4(),
745
- editType: 'replace-with-equivalent',
746
- motivation: unchecked,
747
- insert: [...by],
748
- delete: deleted
749
- };
750
- };
751
- const edits = [
752
- ...established,
753
- ...substituted.map(equivalence),
754
- ...own.filter(symbol => !collated.has(symbol.id) && !paired.has(symbol.id)).map(insertion).map(asUnchecked),
755
- ...inherited
756
- .filter(symbol => !matched.has(symbol.id) && !paired.has(symbol.id))
757
- .map(symbol => asUnchecked(deletion(symbol.id)))
758
- ];
759
- return onVersion(childId, (child, draft) => {
760
- handOverCarriers(view, draft, collations);
761
- child.edits = edits;
762
- child.motivations = declaring(stateOf(child).motivations, edits);
763
- child.basedOn = [
764
- { ...assignReference(parentId), collationTolerance: tolerance },
765
- ...hypothesesBeside(stateOf(child), parentId)
766
- ];
767
- });
768
- };
769
- /**
770
- * Folds the version's own symbols into those it inherits and collates
771
- * with: the carriers pass over, and the insertions go. Collates at the
772
- * tolerance of the derivation, where the caller names none.
773
- */
774
- export const collateSymbols = (view, versionId, symbolIds, tolerance) => {
775
- const version = view.version(versionId);
776
- const principal = version && principalDerivationOf(version);
777
- if (!version || !principal)
778
- return noChange;
779
- const chosen = new Set(symbolIds);
780
- const own = insertedIn([version]).filter(symbol => chosen.has(symbol.id));
781
- const collations = collationsOf(own, view.snapshot(idOf(principal)), symbol => view.placeOf(symbol), tolerance ?? collationToleranceOf(principal));
782
- const collated = new Set(collations.map(({ symbol }) => symbol.id));
783
- return onVersion(versionId, (version, draft) => {
784
- handOverCarriers(view, draft, collations);
785
- dropInsertions(version, collated);
786
- });
787
- };
788
- /** The symbol as one copy reads it: what it says, on the given carriers, standing in no relation of its own. */
789
- const readingOf = (symbol, carriers) => {
790
- const identity = { id: v4(), carriers };
791
- switch (symbol.type) {
792
- case 'note':
793
- return { type: 'note', pitch: symbol.pitch, ...identity };
794
- case 'expression':
795
- return { type: 'expression', expressionType: symbol.expressionType, scope: symbol.scope, ...identity };
796
- case 'text':
797
- return { type: 'text', text: symbol.text, ...identity };
798
- }
799
- };
800
- /** The symbol where the copy and at least one other carry it, with the carriers of each side. */
801
- /**
802
- * The symbol where the named copies and at least one other carry it,
803
- * with the carriers of each side.
804
- *
805
- * A symbol the named copies alone carry has no other side to be
806
- * separated from and is passed over. That covers the insertions, and it
807
- * covers a symbol an ancestor holds on one branch's witness alone,
808
- * where the two versions do not disagree and there is nothing to take
809
- * apart.
810
- */
811
- const sharedWith = (view, symbol, copies) => {
812
- const onNamedCopy = (carrier) => {
813
- const copy = view.copyOf(idOf(carrier));
814
- return copy !== undefined && copies.has(copy.id);
815
- };
816
- const mine = symbol.carriers.filter(onNamedCopy);
817
- const theirs = symbol.carriers.filter(carrier => !onNamedCopy(carrier));
818
- return mine.length > 0 && theirs.length > 0 ? [{ symbol, mine, theirs }] : [];
819
- };
820
- /**
821
- * Takes the named copies' reading of a symbol back out of the symbol it
822
- * was collated into: their carriers pass to a new symbol of the
823
- * version's own, the remaining copies keep the symbol they had, and the
824
- * version states the exchange.
825
- *
826
- * This is the inverse of the hand-over a collation makes, and it is
827
- * what lets a derivation be collated a second time. A collated symbol
828
- * is one symbol carrying every copy that reads it, so nothing else
829
- * takes the two readings apart again, and without that a tolerance
830
- * arrived at after the fact could never be applied.
831
- *
832
- * The copies named are one **side** of the derivation, the same side a
833
- * window is measured over, and `sidesOf` is what says which they are.
834
- * Naming one copy of a side that has several does not separate that
835
- * side: what stays behind is the rest of it, mixed with the other
836
- * side's copies, and a collation then compares one copy against that
837
- * mixture rather than the two texts against each other.
838
- *
839
- * Symbols the named copies alone carry are already the version's own
840
- * and are passed over, so a reading somebody has separated by hand
841
- * keeps its identifier and the edit that speaks for it. Named symbols
842
- * narrow the act to those; naming none separates the whole reading.
843
- */
844
- export const separateReadings = (view, versionId, copies, symbolIds) => {
845
- const version = view.version(versionId);
846
- if (!version)
847
- return noChange;
848
- const chosen = symbolIds && new Set(symbolIds);
849
- const shared = view.snapshot(versionId)
850
- .filter(symbol => chosen === undefined || chosen.has(symbol.id))
851
- .flatMap(symbol => sharedWith(view, symbol, copies));
852
- if (shared.length === 0)
853
- return noChange;
854
- const inserted = new Set(insertedBy(version).map(symbol => symbol.id));
855
- const stated = editsOf(version);
856
- const separations = shared.map(({ symbol, mine }) => ({
857
- type: 'edit',
858
- id: v4(),
859
- insert: [readingOf(symbol, [...mine])],
860
- // A symbol the version inserts itself stays where it is, minus
861
- // the carriers that leave it. Only one it inherits is exchanged.
862
- ...(inserted.has(symbol.id) ? {} : { delete: [symbol.id] })
863
- }));
864
- return onVersion(versionId, (version, draft) => {
865
- shared.forEach(({ symbol, theirs }) => {
866
- const path = view.getPath(symbol.id);
867
- const target = path && getAt(path, draft);
868
- if (target)
869
- target.carriers = theirs;
870
- });
871
- version.edits = [...stated, ...separations];
872
- });
873
- };
874
- /**
875
- * Makes the version stand on its own: what it inherited becomes its
876
- * own insertions, and its derivations go, the hypotheses among them,
877
- * with the motivations that belonged to them.
878
- */
879
- export const detachVersion = (view, versionId) => {
880
- const edits = view.snapshot(versionId).map(insertion);
881
- return onVersion(versionId, version => {
882
- version.edits = edits;
883
- delete version.basedOn;
884
- version.motivations = [];
885
- });
886
- };
887
- /**
888
- * Takes the version out. Whatever read its text against it comes to
889
- * stand on its own, a hypothesis that something derives from it goes,
890
- * and so does a copy's statement that it carries the version.
891
- */
892
- export const removeVersion = (view, versionId) => {
893
- const detachments = view.edition.versions
894
- .filter(version => readsAgainst(version, versionId))
895
- .map(version => detachVersion(view, version.id));
896
- const namesIt = (reference) => idOf(reference) === versionId;
897
- return draft => {
898
- detachments.forEach(detach => detach(draft));
899
- draft.versions.forEach(version => dropDerivations(version, namesIt));
900
- draft.copies.forEach(copy => dropStatements(copy, namesIt));
901
- draft.versions = without(draft.versions, version => version.id === versionId);
902
- };
903
- };
904
- /** Takes the symbols out of the version's own insertions, and the edits that had nothing else. */
905
- export const removeSymbols = (versionId, symbolIds) => onVersion(versionId, version => dropInsertions(version, new Set(symbolIds)));
906
- /** Moves the edits into a new version based on this one. */
907
- export const deriveVersion = (versionId, editIds) => onVersion(versionId, (version, draft) => {
908
- const chosen = new Set(editIds);
909
- const moved = editsOf(version).filter(edit => chosen.has(edit.id));
910
- if (version.edits)
911
- version.edits = without(version.edits, edit => chosen.has(edit.id));
912
- draft.versions.push({
913
- id: v4(),
914
- system: stateOf(version).system,
915
- basedOn: [assignReference(versionId)],
916
- edits: moved,
917
- motivations: []
918
- });
919
- });
920
- /**
921
- * States that the version may also derive from the parent, beside what
922
- * it derives from already: a hypothesis, such as a contamination, under
923
- * the belief given. The text stays read against the principal derivation
924
- * unless the belief holds this one more certain. A version derives from
925
- * itself, or twice from one parent, in no statement.
926
- */
927
- export const stateDerivation = (versionId, parentId, belief) => onVersion(versionId, version => {
928
- const derivations = stateOf(version).basedOn ?? [];
929
- if (parentId === versionId || derivations.some(derivation => idOf(derivation) === parentId))
930
- return;
931
- version.basedOn = [...derivations, referenceHeld(parentId, belief)];
932
- });
933
- /** Takes back the hypothesis that the version derives from the parent; the principal derivation goes with `detachVersion`. */
934
- export const clearDerivation = (versionId, parentId) => onVersion(versionId, version => {
935
- if (readsAgainst(stateOf(version), parentId))
936
- return;
937
- dropDerivations(version, derivation => idOf(derivation) === parentId);
938
- });
939
- const sameSequence = (a, b) => a.length === b.length && a.every((value, i) => value === b[i]);
940
- const expressionTypesOf = (symbols) => symbols.filter((symbol) => symbol.type === 'expression').map(symbol => symbol.expressionType);
941
- /**
942
- * How a single added accent is spelled. The red Welte latches a valve
943
- * on and off again, the green holds one perforation for as long as the
944
- * accent lasts, so the spelling is the system's and not the music's.
945
- * Which of them a bar can spell decides which ones it is offered.
946
- */
947
- const ACCENTS = [
948
- ['SlowCrescendoOn', 'SlowCrescendoOff'],
949
- ['ForzandoOn', 'ForzandoOff'],
950
- ['Crescendo'],
951
- ['SforzandoForte']
952
- ];
953
- const accentsOn = (bar) => bar ? ACCENTS.filter(accent => accent.every(type => bar.expressionTypes.includes(type))) : [];
954
- const lengthOf = (span) => subtract(span.to, span.from);
955
- /** How far apart two onsets may lie for the one symbol to count as a replacement of the other. */
956
- const REPLACEMENT_TOLERANCE = mm(5);
957
- /** Shorten or prolong, where the inserted symbol starts about where the deleted one did. */
958
- const replacementType = (view, inserted, deleted) => {
959
- const after = view.placeOf(inserted);
960
- const before = view.placeOf(deleted);
961
- if (!after || !before || distance(after.from, before.from) >= REPLACEMENT_TOLERANCE)
962
- return undefined;
963
- return lengthOf(after) < lengthOf(before) ? 'shorten' : 'prolong';
964
- };
965
- /**
966
- * A guess at what an edit does, from the symbols it exchanges and from
967
- * the systems the version and the one it is based on are coded for.
968
- */
969
- const guessEditType = (view, versionId, edit) => {
970
- const inserts = edit.insert ?? [];
971
- const deletes = view.symbols(edit.delete ?? []);
972
- const inserted = expressionTypesOf(inserts);
973
- const deleted = expressionTypesOf(deletes);
974
- const bar = trackerBarOf(view.version(versionId)?.system);
975
- const parentBar = trackerBarOf(view.predecessorOf(versionId)?.system);
976
- /**
977
- * Where the version is coded for another system than its parent, an
978
- * exchange of expression matter is the transfer being carried out:
979
- * a red ForzandoOn and ForzandoOff pair giving way to one held green
980
- * SforzandoForte says the same thing in the other system's words,
981
- * which is what 'replace-with-equivalent' is for. Calling it a
982
- * corrected error would say the editor made a mistake.
983
- */
984
- if (bar && parentBar && bar.id !== parentBar.id && inserted.length > 0 && deleted.length > 0) {
985
- return 'replace-with-equivalent';
986
- }
987
- if (deleted.length === 0 && accentsOn(bar).some(accent => sameSequence(inserted, accent)))
988
- return 'additional-accent';
989
- if (inserted.length > 1 && sameSequence(inserted, deleted))
990
- return 'shift';
991
- if (inserted.length === 0 && deleted.length === 1)
992
- return 'remove-redundancy';
993
- if (inserts.length === 1 && deletes.length === 1)
994
- return replacementType(view, inserts[0], deletes[0]) ?? 'correct-error';
995
- return 'correct-error';
996
- };
997
- /**
998
- * Replaces the edits with a single one carrying all their insertions
999
- * and deletions, classified by a guess at what the exchange does.
1000
- */
1001
- export const mergeEdits = (view, versionId, toMerge) => {
1002
- if (toMerge.length === 0)
1003
- return noChange;
1004
- const merged = {
1005
- ...toMerge[0],
1006
- id: v4(),
1007
- insert: toMerge.flatMap(edit => edit.insert ?? []),
1008
- delete: toMerge.flatMap(edit => edit.delete ?? [])
1009
- };
1010
- merged.editType = guessEditType(view, versionId, merged);
1011
- const mergedIds = new Set(toMerge.map(edit => edit.id));
1012
- return onVersion(versionId, version => {
1013
- version.edits = [...editsOf(version).filter(edit => !mergedIds.has(edit.id)), merged];
1014
- });
1015
- };
1016
- /** Replaces the edit with one edit per inserted and one per deleted symbol. */
1017
- export const splitEdit = (versionId, toSplit) => {
1018
- const parts = [
1019
- ...(toSplit.insert ?? []).map(insertion),
1020
- ...(toSplit.delete ?? []).map(deletion)
1021
- ];
1022
- return onVersion(versionId, version => {
1023
- version.edits = [...editsOf(version).filter(edit => edit.id !== toSplit.id), ...parts];
1024
- });
1025
- };
1026
- /**
1027
- * Runs the change on the command the view locates by id, in whichever
1028
- * version inserted it. A statement made there holds in every version
1029
- * that carries the command.
1030
- */
1031
- const onCommand = (view, id, op) => draft => {
1032
- const path = view.getPath(id);
1033
- const symbol = path && getAt(path, draft);
1034
- if (isCommand(symbol))
1035
- op(symbol);
1036
- };
1037
- const clearPlacement = (command) => placementRelations.forEach(relation => { delete command[relation]; });
1038
- /** States how the follower is placed relative to the reference, in place of any earlier statement. */
1039
- export const placeCommand = (view, followerId, referenceId, relation) => onCommand(view, followerId, command => {
1040
- clearPlacement(command);
1041
- command[relation] = assignReference(referenceId);
1042
- });
1043
- export const unplaceCommand = (view, followerId) => onCommand(view, followerId, clearPlacement);
1044
- /** The pair is stated on `statingId` only, as the format asks. */
1045
- export const pairCommands = (view, statingId, partnerId) => onCommand(view, statingId, command => {
1046
- command.pairedWith = assignReference(partnerId);
1047
- });
1048
- export const unpairCommand = (view, statingId) => onCommand(view, statingId, command => {
1049
- delete command.pairedWith;
1050
- });
1051
- const onAssumptionAt = (path, op) => draft => {
1052
- const assumption = getAt(path, draft);
1053
- if (assumption)
1054
- op(assumption);
1055
- };
1056
- const onBeliefAt = (path, op) => onAssumptionAt(path, assumption => {
1057
- const belief = assumption['@annotation']?.belief;
1058
- if (belief)
1059
- op(belief);
1060
- });
1061
- /** Annotates the assumption at the path with a belief held true, for reasons to be added. */
1062
- export const createBelief = (path) => onAssumptionAt(path, assumption => {
1063
- assumption['@annotation'] = {
1064
- id: v4(),
1065
- belief: { type: 'belief', id: v4(), certainty: 'true', reasons: [] }
1066
- };
1067
- });
1068
- export const clearBelief = (path) => onAssumptionAt(path, assumption => {
1069
- delete assumption['@annotation'];
1070
- });
1071
- export const setCertainty = (path, certainty) => onBeliefAt(path, belief => {
1072
- belief.certainty = certainty;
1073
- });
1074
- export const addReason = (path, reason) => onBeliefAt(path, belief => {
1075
- belief.reasons.push(reason);
1076
- });
1077
- export const removeReason = (path, index) => onBeliefAt(path, belief => {
1078
- belief.reasons.splice(index, 1);
1079
- });