@myrmidon/cadmus-core 0.0.22 → 0.2.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 (65) hide show
  1. package/README.md +24 -24
  2. package/esm2020/lib/cadmus-core.module.mjs +20 -0
  3. package/esm2020/lib/datation.mjs +520 -0
  4. package/esm2020/lib/guards/pending-changes.guard.mjs +24 -0
  5. package/esm2020/lib/historical-date.mjs +297 -0
  6. package/esm2020/lib/models.mjs +11 -0
  7. package/esm2020/lib/pipes/sort.pipe.mjs +41 -0
  8. package/esm2020/lib/services/gravatar.service.mjs +30 -0
  9. package/esm2020/lib/services/library-route.service.mjs +210 -0
  10. package/esm2020/lib/services/text-layer.service.mjs +680 -0
  11. package/esm2020/lib/text-range.mjs +58 -0
  12. package/esm2020/lib/token-location.mjs +74 -0
  13. package/esm2020/lib/token-point.mjs +65 -0
  14. package/esm2020/lib/validators/cadmus-validators.mjs +61 -0
  15. package/esm2020/lib/validators/password.validator.mjs +34 -0
  16. package/{esm2015/myrmidon-cadmus-core.js → esm2020/myrmidon-cadmus-core.mjs} +1 -1
  17. package/esm2020/public-api.mjs +19 -0
  18. package/fesm2015/{myrmidon-cadmus-core.js → myrmidon-cadmus-core.mjs} +83 -473
  19. package/fesm2015/myrmidon-cadmus-core.mjs.map +1 -0
  20. package/fesm2020/myrmidon-cadmus-core.mjs +2120 -0
  21. package/fesm2020/myrmidon-cadmus-core.mjs.map +1 -0
  22. package/lib/cadmus-core.module.d.ts +8 -0
  23. package/lib/guards/pending-changes.guard.d.ts +3 -0
  24. package/lib/models.d.ts +2 -19
  25. package/lib/pipes/sort.pipe.d.ts +3 -0
  26. package/lib/services/gravatar.service.d.ts +3 -0
  27. package/lib/services/library-route.service.d.ts +3 -0
  28. package/lib/services/text-layer.service.d.ts +3 -0
  29. package/lib/validators/cadmus-validators.d.ts +11 -0
  30. package/myrmidon-cadmus-core.d.ts +1 -0
  31. package/package.json +22 -10
  32. package/public-api.d.ts +0 -6
  33. package/bundles/myrmidon-cadmus-core.umd.js +0 -2903
  34. package/bundles/myrmidon-cadmus-core.umd.js.map +0 -1
  35. package/bundles/myrmidon-cadmus-core.umd.min.js +0 -2
  36. package/bundles/myrmidon-cadmus-core.umd.min.js.map +0 -1
  37. package/esm2015/lib/cadmus-core.module.js +0 -14
  38. package/esm2015/lib/datation.js +0 -520
  39. package/esm2015/lib/guards/pending-changes.guard.js +0 -22
  40. package/esm2015/lib/historical-date.js +0 -297
  41. package/esm2015/lib/models.js +0 -11
  42. package/esm2015/lib/pipes/sort.pipe.js +0 -37
  43. package/esm2015/lib/roman-number.js +0 -155
  44. package/esm2015/lib/services/env.service.js +0 -76
  45. package/esm2015/lib/services/env.service.provider.js +0 -31
  46. package/esm2015/lib/services/error.service.js +0 -38
  47. package/esm2015/lib/services/gravatar.service.js +0 -28
  48. package/esm2015/lib/services/library-route.service.js +0 -208
  49. package/esm2015/lib/services/local-storage.service.js +0 -99
  50. package/esm2015/lib/services/text-layer.service.js +0 -680
  51. package/esm2015/lib/text-range.js +0 -58
  52. package/esm2015/lib/token-location.js +0 -74
  53. package/esm2015/lib/token-point.js +0 -65
  54. package/esm2015/lib/utils.js +0 -36
  55. package/esm2015/lib/validators/cadmus-validators.js +0 -40
  56. package/esm2015/lib/validators/password.validator.js +0 -34
  57. package/esm2015/public-api.js +0 -25
  58. package/fesm2015/myrmidon-cadmus-core.js.map +0 -1
  59. package/lib/roman-number.d.ts +0 -34
  60. package/lib/services/env.service.d.ts +0 -52
  61. package/lib/services/env.service.provider.d.ts +0 -15
  62. package/lib/services/error.service.d.ts +0 -13
  63. package/lib/services/local-storage.service.d.ts +0 -32
  64. package/lib/utils.d.ts +0 -4
  65. package/myrmidon-cadmus-core.metadata.json +0 -1
@@ -0,0 +1,2120 @@
1
+ import { RomanNumber, NgToolsModule } from '@myrmidon/ng-tools';
2
+ import * as i0 from '@angular/core';
3
+ import { Injectable, Pipe, Inject, NgModule } from '@angular/core';
4
+ import * as gravatar from 'gravatar';
5
+ import * as rangy from 'rangy';
6
+ import { CommonModule } from '@angular/common';
7
+ import { HttpClientModule } from '@angular/common/http';
8
+
9
+ /**
10
+ * Default options for formatting a datation.
11
+ */
12
+ const DATATION_FORMAT_OPTIONS = {
13
+ aboutText: 'c.',
14
+ bcText: 'BC',
15
+ adText: 'AD',
16
+ dayNames: ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'],
17
+ monthNames: [
18
+ 'jan',
19
+ 'feb',
20
+ 'mar',
21
+ 'apr',
22
+ 'may',
23
+ 'jun',
24
+ 'jul',
25
+ 'aug',
26
+ 'sep',
27
+ 'oct',
28
+ 'nov',
29
+ 'dec',
30
+ ],
31
+ };
32
+ /**
33
+ * Single datation point in a historical date.
34
+ */
35
+ // https://github.com/angular/angular/issues/18867#issuecomment-357484102
36
+ // @dynamic
37
+ class Datation {
38
+ /**
39
+ * Create a new datation, optionally setting its data.
40
+ * @param datation The optional data to be copied into the newly created datation.
41
+ */
42
+ constructor(datation = null) {
43
+ if (datation) {
44
+ this.copyFrom(datation);
45
+ }
46
+ }
47
+ /**
48
+ * Sanitize the hint text representing a Datation's hint so that it does not
49
+ * include the reserved sequence -- (which gets replaced with Unicode EM
50
+ * space U+2014), nor the braces. This is because the double dashes are used
51
+ * to separate two datations, and braces to mark a hint in a datation.
52
+ * Also, the whitespaces are all flattened to simple spaces, and normalized
53
+ * (no whitespaces at start/end and no sequence of whitespaces).
54
+ * If the resulting sanitized string is empty, or it was null when received,
55
+ * null is returned.
56
+ * @param hint The hint or null/undefined.
57
+ * @returns The sanitized hint or undefined.
58
+ */
59
+ static sanitizeHint(hint) {
60
+ if (!hint || !hint.trim()) {
61
+ return undefined;
62
+ }
63
+ // replace reserved characters
64
+ hint = hint.replace('--', '\u2014');
65
+ hint = hint.replace('{', '');
66
+ hint = hint.replace('}', '');
67
+ // flatten and normalize whitespaces
68
+ const s = hint.replace(/\s+/g, ' ').trim();
69
+ return s ? s : undefined;
70
+ }
71
+ static regexEscape(text) {
72
+ // https://stackoverflow.com/questions/3561493/is-there-a-regexp-escape-function-in-javascript
73
+ return text.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
74
+ }
75
+ /**
76
+ * Get BC and AD patterns for matching.
77
+ * @param options The datation format options.
78
+ */
79
+ static getErasOptionsForRegex(options = DATATION_FORMAT_OPTIONS) {
80
+ return [
81
+ options.bcText ? this.regexEscape(options.bcText) : 'BC',
82
+ options.adText ? this.regexEscape(options.adText) : 'AD',
83
+ ];
84
+ }
85
+ static getParserRegex(options) {
86
+ const bcad = this.getErasOptionsForRegex(options);
87
+ return new RegExp(
88
+ // about (1)
89
+ '(c\\.)?\\s*' +
90
+ // day (2)
91
+ '(?:([0123]?\\d)\\s+)?' +
92
+ // month (3)
93
+ '(?:([a-zA-Z]{3,})\\s+)?' +
94
+ // year/span (4,5)
95
+ '(?:' +
96
+ '(?:(\\d+)(?:\\s*/\\s*(\\d+))?)|' +
97
+ // century (6)
98
+ '([ivxIVX]+)' +
99
+ ')\\s*' +
100
+ // era (7)
101
+ '(' +
102
+ bcad[0] +
103
+ '|' +
104
+ bcad[1] +
105
+ ')?' +
106
+ // perhaps (8)
107
+ '(\\s*\\?)?' +
108
+ // hint (9)
109
+ '(?:\\s*\\{([^}]+)\\})?', 'i');
110
+ }
111
+ /**
112
+ * Parse the specified text representing a datation.
113
+ * @param text The text to be parsed.
114
+ * @param options The formatter options.
115
+ * @returns The parsed datation, or undefined if invalid or empty.
116
+ * Note that here we return undefined to mean a non-existing point.
117
+ * We do not want a non-existing point to be represented as a null,
118
+ * as this would be included as in the JSON code when serializing.
119
+ */
120
+ static parse(text, options = DATATION_FORMAT_OPTIONS) {
121
+ if (!text) {
122
+ return undefined;
123
+ }
124
+ const datation = new Datation();
125
+ const datationRegex = this.getParserRegex(options);
126
+ const m = datationRegex.exec(text);
127
+ if (!m) {
128
+ return undefined;
129
+ }
130
+ // about
131
+ if (m[1]) {
132
+ datation.isApproximate = true;
133
+ }
134
+ // day
135
+ if (m[2]) {
136
+ datation.day = parseInt(m[2], 10);
137
+ }
138
+ // month
139
+ if (m[3]) {
140
+ const lowerMonth = m[3].toLowerCase();
141
+ const i = options.monthNames.findIndex((name) => name.toLowerCase() === lowerMonth);
142
+ if (i > -1) {
143
+ datation.month = i + 1;
144
+ }
145
+ }
146
+ // year, span
147
+ if (m[4]) {
148
+ datation.value = parseInt(m[4], 10);
149
+ if (m[5]) {
150
+ datation.isSpan = true;
151
+ }
152
+ }
153
+ else {
154
+ datation.value = RomanNumber.fromRoman(m[6].toUpperCase());
155
+ datation.isCentury = true;
156
+ }
157
+ // era
158
+ if (m[7]) {
159
+ const era = m[7].replace(' ', '').toLowerCase();
160
+ if (era === options.bcText.toLowerCase()) {
161
+ datation.value = -datation.value;
162
+ }
163
+ }
164
+ // dubious
165
+ if (m[8]) {
166
+ datation.isDubious = true;
167
+ }
168
+ // hint
169
+ if (m[9]) {
170
+ datation.hint = Datation.sanitizeHint(m[9]);
171
+ }
172
+ return datation;
173
+ }
174
+ /**
175
+ * Strip any era code from the specified datation format string.
176
+ * @param format The format string.
177
+ */
178
+ static stripFormatStringEra(format) {
179
+ if (!format) {
180
+ return 'i';
181
+ }
182
+ // convert ga gp Ga Gp into simple g G
183
+ format = format.replace(new RegExp('([gG])[ap]', 'gi'), '$1');
184
+ // replace g/G with i/I
185
+ format = format.replace('g', 'i');
186
+ format = format.replace('G', 'I');
187
+ // remove ea ep Ea Ep with preceding w/W if any
188
+ format = format.replace(new RegExp('[wW]?[eE][ap]?', 'gi'), '');
189
+ return format;
190
+ }
191
+ /**
192
+ * Reset this datation.
193
+ */
194
+ reset() {
195
+ this.value = 0;
196
+ this.isCentury = false;
197
+ this.isSpan = false;
198
+ this.isApproximate = false;
199
+ this.day = 0;
200
+ this.month = 0;
201
+ this.hint = undefined;
202
+ }
203
+ /**
204
+ * Copy data from the specified source datatation.
205
+ * @param datation The source datation.
206
+ */
207
+ copyFrom(datation) {
208
+ this.value = datation.value;
209
+ this.isCentury = datation.isCentury;
210
+ this.isSpan = datation.isSpan;
211
+ this.isApproximate = datation.isApproximate;
212
+ this.isDubious = datation.isDubious;
213
+ this.day = datation.day;
214
+ this.month = datation.month;
215
+ this.hint = datation.hint ? datation.hint : undefined;
216
+ }
217
+ /**
218
+ * True if this datation is undefined. A datation is undefined when
219
+ * its value is 0. Undefined datations are used as unknown points in a range
220
+ * for termini ante/post.
221
+ */
222
+ isUndefined() {
223
+ return !this.value;
224
+ }
225
+ /**
226
+ * Get a sort value from this datation.
227
+ */
228
+ getSortValue() {
229
+ let result;
230
+ if (this.isCentury) {
231
+ result = this.value * 100 + (this.value < 0 ? 50 : -50);
232
+ }
233
+ else {
234
+ result = this.value;
235
+ }
236
+ if (this.isSpan) {
237
+ result += 0.5;
238
+ }
239
+ if (this.month > 0 && this.month <= 12) {
240
+ result += this.month / 12;
241
+ }
242
+ if (this.day > 0 && this.day <= 31) {
243
+ result += this.day / (12 * 31);
244
+ }
245
+ return result;
246
+ }
247
+ /**
248
+ * Get the 2-years span end value from this datation.
249
+ * A span year is always represented with its beginning year: e.g. -776/5
250
+ * is -776 with span, and 56/7 is 56 with span. This method returns the end year
251
+ * for a span, i.e. in the above samples -775 and 57 respectively. If this datation
252
+ * is not a span, the function just returns the unique year value.
253
+ */
254
+ getSpanEnd() {
255
+ if (this.isCentury) {
256
+ return 0;
257
+ }
258
+ return this.isSpan ? this.value + 1 : this.value;
259
+ }
260
+ /**
261
+ * Get the century number corresponding this datation.
262
+ * This function returns 0 if the datation is null, or the century number,
263
+ * less than 0 if B.C. The result is based on the century value, if
264
+ * this is a century datation, or on the year, if this is not a century
265
+ * datation (e.g. -5 for 480 B.C., +1 for 31 A.D.).
266
+ */
267
+ getCentury() {
268
+ if (this.value === 0) {
269
+ return 0;
270
+ }
271
+ return this.isCentury
272
+ ? this.value
273
+ : Math.trunc(this.value / 100 + (this.value < 0 ? -1 : 1));
274
+ }
275
+ matchTokenAt(token, text, index) {
276
+ if (index + token.length > text.length) {
277
+ return false;
278
+ }
279
+ for (let i = 0; i < token.length; i++) {
280
+ if (token.charAt(i) !== text.charAt(i + index)) {
281
+ return false;
282
+ }
283
+ }
284
+ return true;
285
+ }
286
+ parseFormatString(format) {
287
+ if (!format) {
288
+ return ['G'];
289
+ }
290
+ // expand macros
291
+ const macros = [
292
+ 'ga',
293
+ 'awdwMMMwvwepwpwh',
294
+ 'Ga',
295
+ 'awdwMMMwvwepwpwh',
296
+ 'gp',
297
+ 'awdwMMMwvweawpwh',
298
+ 'Gp',
299
+ 'awdwMMMwvweawpwh',
300
+ 'g',
301
+ 'awdwMMMwvwewpwh',
302
+ 'G',
303
+ 'AwdwMMMwVwewPwH',
304
+ 'i',
305
+ 'awdwMMMwvwpwh',
306
+ 'I',
307
+ 'AwdwMMMwVwPwH',
308
+ ];
309
+ const sb = [];
310
+ let fi = 0;
311
+ let matched;
312
+ while (fi < format.length) {
313
+ matched = false;
314
+ for (let mi = 0; mi < macros.length; mi += 2) {
315
+ if (this.matchTokenAt(macros[mi], format, fi)) {
316
+ sb.push(macros[mi + 1]);
317
+ fi += macros[mi].length;
318
+ matched = true;
319
+ break;
320
+ }
321
+ }
322
+ if (!matched) {
323
+ sb.push(format[fi]);
324
+ fi++;
325
+ }
326
+ }
327
+ format = sb.join();
328
+ // split into tokens and literals
329
+ const tokens = [
330
+ 'ddd',
331
+ 'MMM',
332
+ 'dd',
333
+ 'ea',
334
+ 'ep',
335
+ 'Ea',
336
+ 'Ep',
337
+ 'ga',
338
+ 'Ga',
339
+ 'gp',
340
+ 'Gp',
341
+ 'MM',
342
+ ];
343
+ fi = 0;
344
+ const results = [];
345
+ while (fi < format.length) {
346
+ matched = false;
347
+ for (let ti = 0; ti < tokens.length; ti++) {
348
+ if (this.matchTokenAt(tokens[ti], format, fi)) {
349
+ results.push(tokens[ti]);
350
+ fi += tokens[ti].length;
351
+ matched = true;
352
+ break;
353
+ }
354
+ }
355
+ if (!matched) {
356
+ results.push(format.charAt(fi));
357
+ fi++;
358
+ }
359
+ }
360
+ return results;
361
+ }
362
+ /**
363
+ * Convert this datation to a string.
364
+ * @param format The format string, which can include any of the following:
365
+ * v = year or century value, lowercase
366
+ * V = year or century value, uppercase
367
+ * c = century, lowercase
368
+ * C = century, uppercase
369
+ * a or A = 'about' marker when present
370
+ * p or P = 'perhaps' marker when present
371
+ * d = day number when present
372
+ * dd = 2-digits (0-padded at left) day number when present
373
+ * ddd = weekday name when present
374
+ * M = month number when present
375
+ * MM = 2-digits (0-padded at left) month number when present
376
+ * MMM = month name when present
377
+ * e = era
378
+ * E = era, all uppercase
379
+ * ea = era, only if ante Christum natum
380
+ * ep = era, only if post Christum natum
381
+ * Ea = era all uppercase, only if ante Christum natum
382
+ * Ep = era all uppercase, only if post Christum natum
383
+ * h or H = hint when present
384
+ * w or W = smart whitespace (appended only when left char if any
385
+ * is not a whitespace)
386
+ * s or S = sort value
387
+ * g = generic: equal to awdwMMMwvwewpwh
388
+ * G = generic uppercase: equal to AwdwMMMwVwewPwH
389
+ * ga = generic ante Christum: era expressed only when post Christum
390
+ * natum. Equal to awdwMMMwvwepwpwh
391
+ * Ga = generic uppercase ante Christum: equal to awdwMMMwvwepwpwh
392
+ * gp = generic post Christum: era expressed only when ante Christum
393
+ * natum. Equal to awdwMMMwvweawpwh
394
+ * Gp = generic uppercase post Christum: equal to awdwMMMwvweawpwh
395
+ * i = generic with implicit (=not expressed) era: equal to awdwMMMwvwpwh
396
+ * I = generic uppercase with implicit (=not expressed) era: equal to
397
+ * AwdwMMMwVwPwH
398
+ * @param options The options.
399
+ */
400
+ toString(format = 'G', options = DATATION_FORMAT_OPTIONS) {
401
+ if (this.isUndefined()) {
402
+ return '';
403
+ }
404
+ if (!format) {
405
+ format = 'G';
406
+ }
407
+ if (!options) {
408
+ options = DATATION_FORMAT_OPTIONS;
409
+ }
410
+ const sb = [];
411
+ const tokens = this.parseFormatString(format);
412
+ tokens.forEach((token) => {
413
+ switch (token) {
414
+ case 'v':
415
+ case 'V':
416
+ // year or century
417
+ if (this.isCentury) {
418
+ sb.push(token === 'v'
419
+ ? RomanNumber.toRoman(Math.abs(this.value)).toLowerCase()
420
+ : RomanNumber.toRoman(Math.abs(this.value)).toUpperCase());
421
+ }
422
+ else {
423
+ const year = Math.abs(this.value);
424
+ sb.push(year.toString());
425
+ if (this.isSpan) {
426
+ sb.push(`/${year + (this.value < 0 ? -1 : +1)}`);
427
+ }
428
+ }
429
+ break;
430
+ case 'c':
431
+ case 'C':
432
+ const century = Math.abs(this.getCentury());
433
+ sb.push(token === 'c'
434
+ ? RomanNumber.toRoman(century).toLowerCase()
435
+ : RomanNumber.toRoman(century).toUpperCase());
436
+ break;
437
+ case 'a':
438
+ case 'A':
439
+ if (this.isApproximate) {
440
+ sb.push(options.aboutText);
441
+ }
442
+ break;
443
+ case 'p':
444
+ case 'P':
445
+ if (this.isDubious) {
446
+ sb.push('?');
447
+ }
448
+ break;
449
+ case 'd':
450
+ if (this.day > 0) {
451
+ sb.push(this.day.toString());
452
+ }
453
+ break;
454
+ case 'dd':
455
+ if (this.day > 0) {
456
+ sb.push(this.day.toString().padStart(2, '0'));
457
+ }
458
+ break;
459
+ case 'ddd':
460
+ if (this.day > 0) {
461
+ const date = new Date(this.value, this.month, this.day);
462
+ const dow = date.getDay();
463
+ sb.push(options.dayNames[dow]);
464
+ }
465
+ break;
466
+ case 'M':
467
+ if (this.month > 0) {
468
+ sb.push(this.month.toString());
469
+ }
470
+ break;
471
+ case 'MM':
472
+ if (this.month > 0) {
473
+ sb.push(this.month.toString().padStart(2, '0'));
474
+ }
475
+ break;
476
+ case 'MMM':
477
+ if (this.month > 0) {
478
+ sb.push(options.monthNames[this.month - 1]);
479
+ }
480
+ break;
481
+ case 'e':
482
+ sb.push(this.value < 0 ? options.bcText : options.adText);
483
+ break;
484
+ case 'E':
485
+ sb.push(this.value < 0
486
+ ? options.bcText.toUpperCase()
487
+ : options.adText.toUpperCase());
488
+ break;
489
+ case 'ea':
490
+ if (this.value < 0) {
491
+ sb.push(options.bcText);
492
+ }
493
+ break;
494
+ case 'ep':
495
+ if (this.value > 0) {
496
+ sb.push(options.adText);
497
+ }
498
+ break;
499
+ case 'h':
500
+ case 'H':
501
+ if (this.hint) {
502
+ sb.push(` {${this.hint}}`);
503
+ }
504
+ break;
505
+ case 'w':
506
+ case 'W':
507
+ if (sb.length > 0) {
508
+ const last = sb[sb.length - 1];
509
+ if (!last.endsWith(' ')) {
510
+ sb.push(' ');
511
+ }
512
+ }
513
+ break;
514
+ case 's':
515
+ case 'S':
516
+ sb.push(this.getSortValue().toString());
517
+ break;
518
+ default:
519
+ // literal
520
+ sb.push(token);
521
+ break;
522
+ }
523
+ });
524
+ return sb.join('').trim().replace(new RegExp('\\s+', 'g'), ' ');
525
+ }
526
+ }
527
+
528
+ const APPROX_DELTA = 10;
529
+ /**
530
+ * Type of historical date.
531
+ */
532
+ var HistoricalDateType;
533
+ (function (HistoricalDateType) {
534
+ HistoricalDateType[HistoricalDateType["undefined"] = 0] = "undefined";
535
+ HistoricalDateType[HistoricalDateType["point"] = 1] = "point";
536
+ HistoricalDateType[HistoricalDateType["range"] = 2] = "range";
537
+ })(HistoricalDateType || (HistoricalDateType = {}));
538
+ /**
539
+ * A historical date, including 0, 1, or 2 datation points.
540
+ */
541
+ class HistoricalDate {
542
+ constructor(date = null) {
543
+ if (!date) {
544
+ this.a = new Datation();
545
+ // B=undefined for a single point
546
+ }
547
+ else {
548
+ this.a = new Datation(date.a);
549
+ if (date.b) {
550
+ this.b = new Datation(date.b);
551
+ }
552
+ }
553
+ }
554
+ /**
555
+ * Parse the specified text representing a historical datation.
556
+ * @param text The text to be parsed.
557
+ * @param options The datation formatter options.
558
+ * @return The datation, or null if invalid.
559
+ */
560
+ static parse(text, options = DATATION_FORMAT_OPTIONS) {
561
+ if (!text) {
562
+ return null;
563
+ }
564
+ const dates = text.split('--');
565
+ let s1 = dates[0].trim();
566
+ const s2 = dates.length > 1 ? dates[1].trim() : null;
567
+ const date = new HistoricalDate();
568
+ if (dates.length > 1) {
569
+ // if both terms are specified, integrate BC/AD indication in 1st if required
570
+ if (s1 && s2) {
571
+ const bcad = Datation.getErasOptionsForRegex(options);
572
+ const tailRegexp = new RegExp(
573
+ // era (1)
574
+ '(' +
575
+ bcad[0] +
576
+ '|' +
577
+ bcad[1] +
578
+ ')?' +
579
+ // dubious (2)
580
+ '(\\s*\\?)?' +
581
+ // hint (3)
582
+ '(?:\\s*\\{?:([^)]+)\\})?\\s*$', 'gi');
583
+ const m1 = tailRegexp.exec(s1);
584
+ // if 1st has no era try integration from 2nd
585
+ if (m1 && m1[1]) {
586
+ // get era from 2nd (if 2nd hasn't it too, give up and AD will be assumed)
587
+ const m2 = tailRegexp.exec(s2);
588
+ if (m2 && m2[1]) {
589
+ const era = m2[1] || 'p.C.';
590
+ const sb1 = [];
591
+ if (m1.index > 0) {
592
+ sb1.push(s1.substr(0, m1.index));
593
+ }
594
+ sb1.push(' ' + era);
595
+ if (m1[2]) {
596
+ sb1.push('?');
597
+ }
598
+ if (m1[3]) {
599
+ sb1.push(` (${m1[3]})`);
600
+ }
601
+ s1 = sb1.join('');
602
+ }
603
+ }
604
+ }
605
+ date.setStartPoint(Datation.parse(s1, options));
606
+ date.setEndPoint(Datation.parse(s2, options));
607
+ }
608
+ else {
609
+ // here we have a s2, even if empty. When empty, it represents
610
+ // an unknown point in a terminus ante/post, and as such we
611
+ // must set B=null. When B=undefined, it's not a range but a point.
612
+ const d = Datation.parse(s1, options);
613
+ if (d && !d.isUndefined()) {
614
+ date.setSinglePoint(d);
615
+ }
616
+ }
617
+ return date;
618
+ }
619
+ getStartPoint() {
620
+ return this.getDateType() === HistoricalDateType.range ? this.a : undefined;
621
+ }
622
+ setStartPoint(value) {
623
+ this.a = new Datation(value);
624
+ // it's a range, ensure max is not null
625
+ if (!this.b) {
626
+ this.b = new Datation();
627
+ }
628
+ }
629
+ getEndPoint() {
630
+ return this.getDateType() === HistoricalDateType.range ? this.b : undefined;
631
+ }
632
+ setEndPoint(value) {
633
+ this.b = new Datation(value);
634
+ }
635
+ getSinglePoint() {
636
+ return this.getDateType() === HistoricalDateType.point ? this.a : undefined;
637
+ }
638
+ setSinglePoint(value) {
639
+ this.a = new Datation(value);
640
+ // it's a point, ensure max is undefined
641
+ this.b = undefined;
642
+ }
643
+ /**
644
+ * True if this date is undefined.
645
+ */
646
+ isUndefined() {
647
+ return (!this.a || (this.a.isUndefined() && (!this.b || this.b.isUndefined())));
648
+ }
649
+ /**
650
+ * Get the type of this date.
651
+ */
652
+ getDateType() {
653
+ if (this.isUndefined()) {
654
+ return HistoricalDateType.undefined;
655
+ }
656
+ return this.b ? HistoricalDateType.range : HistoricalDateType.point;
657
+ }
658
+ /**
659
+ * Validate this date.
660
+ * @returns Error message if invalid, or null if valid.
661
+ */
662
+ validate() {
663
+ if (!this.a) {
664
+ return 'Missing point A';
665
+ }
666
+ if (this.getDateType() === HistoricalDateType.range) {
667
+ const av = this.a.getSortValue();
668
+ const bv = this.b.getSortValue();
669
+ if (av && bv && av >= bv) {
670
+ return 'Point A is past point B';
671
+ }
672
+ }
673
+ return null;
674
+ }
675
+ /**
676
+ * Get the sort value for this date.
677
+ */
678
+ getSortValue() {
679
+ switch (this.getDateType()) {
680
+ case HistoricalDateType.point:
681
+ return this.a.getSortValue();
682
+ case HistoricalDateType.range:
683
+ if (this.a.isUndefined()) {
684
+ return this.b.getSortValue() - APPROX_DELTA;
685
+ }
686
+ if (this.b.isUndefined()) {
687
+ return this.a.getSortValue() + APPROX_DELTA;
688
+ }
689
+ return (this.a.getSortValue() + this.b.getSortValue()) / 2;
690
+ default:
691
+ return 0;
692
+ }
693
+ }
694
+ /**
695
+ * Build a textual representation of this date.
696
+ * @param format The format string.
697
+ * @param options The formatter options.
698
+ */
699
+ toString(format = 'G', options = DATATION_FORMAT_OPTIONS) {
700
+ const sb = [];
701
+ switch (this.getDateType()) {
702
+ case HistoricalDateType.point:
703
+ sb.push(this.a.toString(format, options));
704
+ break;
705
+ case HistoricalDateType.range:
706
+ // if both terms are present and belong to same era, omit it in 1st
707
+ if (!this.a.isUndefined() &&
708
+ this.b &&
709
+ !this.b.isUndefined() &&
710
+ this.a.value * this.b.value > 0) {
711
+ sb.push(this.a.toString(Datation.stripFormatStringEra(format), options));
712
+ sb.push(' -- ');
713
+ sb.push(this.b.toString(format, options));
714
+ break;
715
+ }
716
+ if (!this.a.isUndefined()) {
717
+ sb.push(this.a.toString(format, options) + ' ');
718
+ }
719
+ sb.push('--');
720
+ if (this.b && !this.b.isUndefined()) {
721
+ sb.push(this.b.toString(format, options));
722
+ }
723
+ break;
724
+ }
725
+ return sb.join('');
726
+ }
727
+ /**
728
+ * Get the approximate year value from the specified century value.
729
+ * @param century The century number, negative if B.C.
730
+ */
731
+ centuryToYear(century) {
732
+ return century * 100 + (century < 0 ? 50 : -50);
733
+ }
734
+ /**
735
+ * Convert this date into a single approximate year value.
736
+ * For centuries, the central century year is returned (e.g. -350 for IV B.C.
737
+ * and +350 for IV A.D.); when the date is a range with a single boundary only
738
+ * (max or min) the corresponding year minus or plus a predefined delta value
739
+ * (10) is returned; if it's a range with both boundaries (max and min),
740
+ * the middle year between them is returned.
741
+ * @param useTerminusSpan True to add or remove the predefined span from
742
+ * a terminus ante or post.
743
+ */
744
+ toYear(useTerminusSpan = true) {
745
+ let year = 0;
746
+ switch (this.getDateType()) {
747
+ case HistoricalDateType.point:
748
+ year = Math.trunc(this.a.isCentury ? this.centuryToYear(this.a.value) : this.a.value);
749
+ break;
750
+ case HistoricalDateType.range:
751
+ // min is missing: terminus ante
752
+ if (this.a.isUndefined()) {
753
+ year = Math.trunc((this.b.isCentury
754
+ ? this.centuryToYear(this.b.value)
755
+ : this.b.value) - (useTerminusSpan ? APPROX_DELTA : 0));
756
+ break;
757
+ }
758
+ // max is missing: terminus post
759
+ if (!this.b || this.b.isUndefined()) {
760
+ year = Math.trunc((this.a.isCentury
761
+ ? this.centuryToYear(this.a.value)
762
+ : this.a.value) + (useTerminusSpan ? APPROX_DELTA : 0));
763
+ break;
764
+ }
765
+ // both min and max
766
+ const min = this.a.isCentury
767
+ ? this.centuryToYear(this.a.value)
768
+ : this.a.value;
769
+ const max = this.b.isCentury
770
+ ? this.centuryToYear(this.b.value)
771
+ : this.b.value;
772
+ year = Math.trunc((max - min) / 2 + min);
773
+ if (year === 0) {
774
+ year = 1;
775
+ }
776
+ break;
777
+ }
778
+ return year;
779
+ }
780
+ /**
781
+ * True if any value (either in point or in range) has an about flag.
782
+ */
783
+ isAbout() {
784
+ let about = false;
785
+ switch (this.getDateType()) {
786
+ case HistoricalDateType.point:
787
+ about = this.a.isApproximate;
788
+ break;
789
+ case HistoricalDateType.range:
790
+ if (!this.a.isUndefined()) {
791
+ about = this.a.isApproximate;
792
+ break;
793
+ }
794
+ if (!this.b.isUndefined()) {
795
+ about = this.b.isApproximate;
796
+ }
797
+ break;
798
+ }
799
+ return about;
800
+ }
801
+ /**
802
+ * True if any value (either in point or in range) has an about flag.
803
+ */
804
+ isDubious() {
805
+ let dubious = false;
806
+ switch (this.getDateType()) {
807
+ case HistoricalDateType.point:
808
+ dubious = this.a.isDubious;
809
+ break;
810
+ case HistoricalDateType.range:
811
+ if (!this.a.isUndefined()) {
812
+ dubious = this.a.isDubious;
813
+ break;
814
+ }
815
+ if (!this.b.isUndefined()) {
816
+ dubious = this.b.isDubious;
817
+ }
818
+ break;
819
+ }
820
+ return dubious;
821
+ }
822
+ }
823
+
824
+ /**
825
+ * Data pin value type in a DataPinDefinition.
826
+ */
827
+ var DataPinValueType;
828
+ (function (DataPinValueType) {
829
+ DataPinValueType[DataPinValueType["string"] = 0] = "string";
830
+ DataPinValueType[DataPinValueType["boolean"] = 1] = "boolean";
831
+ DataPinValueType[DataPinValueType["integer"] = 2] = "integer";
832
+ DataPinValueType[DataPinValueType["decimal"] = 3] = "decimal";
833
+ })(DataPinValueType || (DataPinValueType = {}));
834
+
835
+ /**
836
+ * A simple text range, expressed as start character index and characters
837
+ * length. This is used for misspellings operations.
838
+ */
839
+ class TextRange {
840
+ constructor(start, length) {
841
+ if (start < 0)
842
+ throw new RangeError('TextRange start less than 0');
843
+ if (length < 0)
844
+ throw new RangeError('TextRange length less than 0');
845
+ this.start = start;
846
+ this.length = length;
847
+ }
848
+ /**
849
+ * Parse the specified text representing a range, in the form "startxlength"
850
+ * or just "start" when length is 1.
851
+ *
852
+ * @param text The text.
853
+ */
854
+ static parse(text) {
855
+ if (!text) {
856
+ return null;
857
+ }
858
+ // [1]=start, ([2]=length)
859
+ const m = new RegExp('(\\d+)(?:[×x](\\d+))?', 'gm').exec(text);
860
+ if (!m) {
861
+ return null;
862
+ }
863
+ return new TextRange(parseInt(m[1], 10), m[2] ? parseInt(m[2], 10) : 1);
864
+ }
865
+ /**
866
+ * Get the inclusive end of the range.
867
+ */
868
+ end() {
869
+ const n = this.start + this.length;
870
+ return n > 0 ? n - 1 : 0;
871
+ }
872
+ /**
873
+ * True if this range value is equal to the other range value.
874
+ * @param other The other range.
875
+ */
876
+ isEqual(other) {
877
+ if (!other) {
878
+ return false;
879
+ }
880
+ return this.start === other.start && this.length === other.length;
881
+ }
882
+ /**
883
+ * Get a parsable textual representation of this range.
884
+ * @returns Text.
885
+ */
886
+ toString() {
887
+ return this.length === 1
888
+ ? this.start.toString()
889
+ : `${this.start}×${this.length}`;
890
+ }
891
+ }
892
+
893
+ /**
894
+ * A single point in a token-based textual location.
895
+ */
896
+ class TokenPoint {
897
+ constructor(y, x, at = 0, run = 0) {
898
+ this.y = y;
899
+ this.x = x;
900
+ this.at = at;
901
+ this.run = run;
902
+ }
903
+ /**
904
+ * Parse the specified text representing a token-based point location.
905
+ * @param text The text to parse, in the forms Y.X or Y.X@AxR or
906
+ * Y.X@A, where R=1.
907
+ */
908
+ static parse(text) {
909
+ const r = new RegExp('^(\\d+)\\.(\\d+)(?:@(\\d+)(?:x(\\d+))?)?$', 'g');
910
+ const m = r.exec(text);
911
+ if (!m) {
912
+ return null;
913
+ }
914
+ const pt = new TokenPoint(parseInt(m[1], 10), parseInt(m[2], 10), m[3] ? parseInt(m[3], 10) : 0);
915
+ if (m[3]) {
916
+ if (m[4]) {
917
+ pt.run = m[4] ? parseInt(m[4], 10) : 1;
918
+ }
919
+ else {
920
+ pt.run = 1;
921
+ }
922
+ }
923
+ return pt;
924
+ }
925
+ toString() {
926
+ let s = `${this.y}.${this.x}`;
927
+ if (this.at > 0 && this.run > 0) {
928
+ s += `@${this.at}`;
929
+ if (this.run !== 1) {
930
+ s += `x${this.run}`;
931
+ }
932
+ }
933
+ return s;
934
+ }
935
+ compareTo(other) {
936
+ if (this.y !== other.y) {
937
+ return this.y - other.y;
938
+ }
939
+ if (this.x !== other.x) {
940
+ return this.x - other.x;
941
+ }
942
+ if (this.at !== other.at) {
943
+ return this.at - other.at;
944
+ }
945
+ return this.run - other.run;
946
+ }
947
+ integralCompareTo(other) {
948
+ if (this.y !== other.y) {
949
+ return this.y - other.y;
950
+ }
951
+ if (this.x !== other.x) {
952
+ return this.x - other.x;
953
+ }
954
+ return 0;
955
+ }
956
+ }
957
+
958
+ class TokenLocation {
959
+ constructor(primary, secondary = null) {
960
+ this.primary = primary;
961
+ this.secondary = secondary;
962
+ }
963
+ /**
964
+ * Parse the text representing a token-based location,
965
+ * which has the form "primary-secondary", or just "primary",
966
+ * where each of these points has the format required by
967
+ * TokenPoint.parse (e.g. Y.X or Y.X@AxR or Y.X@A, where R=1).
968
+ * @param text The text to parse.
969
+ */
970
+ static parse(text) {
971
+ if (!text) {
972
+ return null;
973
+ }
974
+ const pair = text.split('-', 2);
975
+ if (pair.length === 0) {
976
+ return null;
977
+ }
978
+ return new TokenLocation(TokenPoint.parse(pair[0]), pair.length > 1 ? TokenPoint.parse(pair[1]) : null);
979
+ }
980
+ isRange() {
981
+ // note that != checks for both null and undefined, whereas !== does not
982
+ return this.secondary != null;
983
+ }
984
+ toString() {
985
+ return this.secondary
986
+ ? `${this.primary.toString()}-${this.secondary.toString()}`
987
+ : this.primary.toString();
988
+ }
989
+ compareTo(other) {
990
+ const n1 = this.primary.compareTo(other.primary);
991
+ if (n1 !== 0) {
992
+ return n1;
993
+ }
994
+ if (this.secondary && other.secondary) {
995
+ return this.secondary.compareTo(other.secondary);
996
+ }
997
+ if (!this.secondary && !other.secondary) {
998
+ return 0;
999
+ }
1000
+ return this.secondary ? 1 : -1;
1001
+ }
1002
+ overlaps(other) {
1003
+ // empty coords never overlaps
1004
+ if (!other.primary) {
1005
+ return false;
1006
+ }
1007
+ // (in the following comments A=this and B=other)
1008
+ // 1) if B is a point, cases are:
1009
+ // 1.1. A is a point: A overlaps with B (both points) if they're equal.
1010
+ // 1.2. A is a range: A (range) overlaps with B (point)
1011
+ // when A-left is <= B-left and A-right is >= B-right.
1012
+ if (other.secondary == null) {
1013
+ return !this.secondary
1014
+ ? this.primary.integralCompareTo(other.primary) === 0
1015
+ : this.primary.compareTo(other.primary) <= 0 &&
1016
+ this.secondary.compareTo(other.primary) >= 0;
1017
+ }
1018
+ // 2) if B is a range, cases are:
1019
+ // 2.1. A is a point: A (point) overlaps with B (range) when B-left <= A and
1020
+ // B-right >= A
1021
+ // 2.2. A is a range: A (range) overlaps with B (range)
1022
+ // when B-right >= A-left and B-left <= A-right
1023
+ return !this.secondary
1024
+ ? other.primary.compareTo(this.primary) <= 0 &&
1025
+ other.secondary.compareTo(this.primary) >= 0
1026
+ : other.secondary.compareTo(this.primary) >= 0 &&
1027
+ other.primary.compareTo(this.secondary) <= 0;
1028
+ }
1029
+ }
1030
+
1031
+ class PendingChangesGuard {
1032
+ canDeactivate(component) {
1033
+ // if there are no pending changes, just allow deactivation; else confirm first
1034
+ return !component || component.canDeactivate()
1035
+ ? true
1036
+ : // NOTE: this warning message will only be shown when navigating
1037
+ // elsewhere within your angular app; when navigating away from your
1038
+ // angular app, the browser will show a generic warning message.
1039
+ // see http://stackoverflow.com/a/42207299/7307355
1040
+ confirm('Warning: your changes have not been saved. ' +
1041
+ 'Press Cancel to go back and save, OK to continue.');
1042
+ }
1043
+ }
1044
+ PendingChangesGuard.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "13.0.2", ngImport: i0, type: PendingChangesGuard, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
1045
+ PendingChangesGuard.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "13.0.2", ngImport: i0, type: PendingChangesGuard, providedIn: 'root' });
1046
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "13.0.2", ngImport: i0, type: PendingChangesGuard, decorators: [{
1047
+ type: Injectable,
1048
+ args: [{
1049
+ providedIn: 'root'
1050
+ }]
1051
+ }] });
1052
+
1053
+ /**
1054
+ * Sort pipe. Use like *ngFor="let i of items | sort:'propname'".
1055
+ */
1056
+ class SortPipe {
1057
+ transform(value, propName) {
1058
+ if (!value || !Array.isArray(value)) {
1059
+ return value;
1060
+ }
1061
+ return [...value].sort((a, b) => {
1062
+ if (!a && !b) {
1063
+ return 0;
1064
+ }
1065
+ if (!a && b) {
1066
+ return -1;
1067
+ }
1068
+ if (a && !b) {
1069
+ return 1;
1070
+ }
1071
+ if (a[propName] < b[propName]) {
1072
+ return -1;
1073
+ }
1074
+ else if (a[propName] === b[propName]) {
1075
+ return 0;
1076
+ }
1077
+ else if (a[propName] > b[propName]) {
1078
+ return 1;
1079
+ }
1080
+ });
1081
+ }
1082
+ }
1083
+ SortPipe.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "13.0.2", ngImport: i0, type: SortPipe, deps: [], target: i0.ɵɵFactoryTarget.Pipe });
1084
+ SortPipe.ɵpipe = i0.ɵɵngDeclarePipe({ minVersion: "12.0.0", version: "13.0.2", ngImport: i0, type: SortPipe, name: "sort" });
1085
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "13.0.2", ngImport: i0, type: SortPipe, decorators: [{
1086
+ type: Pipe,
1087
+ args: [{
1088
+ name: 'sort',
1089
+ }]
1090
+ }] });
1091
+
1092
+ // npm i gravatar --save
1093
+ // npm i @types/gravatar --save
1094
+ class GravatarService {
1095
+ /**
1096
+ * Builds the URL to the Gravatar avatar corresponding to the specified email
1097
+ * address.
1098
+ * @param email: The email address.
1099
+ * @param size The required size in pixels (1-512).
1100
+ */
1101
+ buildGravatarUrl(email, size = 80) {
1102
+ if (!email) {
1103
+ return null;
1104
+ }
1105
+ return gravatar.url(email, { s: size.toString() });
1106
+ // const hash = this._hash.getMd5(email.trim().toLowerCase());
1107
+ // return this.buildGravatarUrlFromHash(hash, size);
1108
+ }
1109
+ }
1110
+ GravatarService.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "13.0.2", ngImport: i0, type: GravatarService, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
1111
+ GravatarService.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "13.0.2", ngImport: i0, type: GravatarService, providedIn: 'root' });
1112
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "13.0.2", ngImport: i0, type: GravatarService, decorators: [{
1113
+ type: Injectable,
1114
+ args: [{
1115
+ providedIn: 'root'
1116
+ }]
1117
+ }] });
1118
+
1119
+ /**
1120
+ * Library route service.
1121
+ * This service is used to build routes to part and fragment editors,
1122
+ * which are hosted in an open list of library modules in the Cadmus
1123
+ * application.
1124
+ * This architecture allows lazy-loading part- and fragment-editors
1125
+ * only when they are required.
1126
+ * Each part type with its dumb UI editor component is located in a
1127
+ * library, named after the name of the group the part belongs to. For
1128
+ * instance, the model and dumb UI editor component for a part belonging
1129
+ * to the "general" group are located in the "parts/general/general-ui"
1130
+ * library.
1131
+ * In turn, the feature UI editor component for the same part is located
1132
+ * in the "parts/general/general-feature" library. This library has
1133
+ * a route for each part editor. For instance, the NotePart editor
1134
+ * component route is "items/:iid/general/it.vedph.note/:pid", where
1135
+ * ":iid" is the item ID and ":pid" the part ID.
1136
+ */
1137
+ class LibraryRouteService {
1138
+ constructor(_partEditorKeys) {
1139
+ this._partEditorKeys = _partEditorKeys;
1140
+ }
1141
+ /**
1142
+ * Strip the eventual fragment-role ID from the specified part's role ID.
1143
+ * For instance, a part's role ID like "fr.it.vedph.comment:scholarly"
1144
+ * becomes "fr.it.vedph.comment".
1145
+ *
1146
+ * @param roleId The part's role ID.
1147
+ */
1148
+ stripFragmentRoleId(roleId) {
1149
+ // remove the optional :fr-role from roleId
1150
+ const i = roleId.lastIndexOf(':');
1151
+ if (i > -1) {
1152
+ roleId = roleId.substring(0, i);
1153
+ }
1154
+ return roleId;
1155
+ }
1156
+ /**
1157
+ * Get the fragment type and role from the part's role ID. This starts
1158
+ * with "fr.", and might be followed by the role proper, introduced
1159
+ * by the first dot if any. For instance, "fr.it.vedph.comment" would just
1160
+ * return "fr.it.vedph.comment", while "fr.it.vedph.comment:scholarly"
1161
+ * would return "fr.it.vedph.comment". This is required to navigate to
1162
+ * the correct fragment editor, which is the same for each fragment type,
1163
+ * independently from its role.
1164
+ * @param role The part role ID.
1165
+ * @returns An object where frTypeId=fragment type ID and frRoleId=fragment role
1166
+ * ID, or null.
1167
+ */
1168
+ getFragmentTypeAndRole(roleId) {
1169
+ if (!roleId || !roleId.startsWith('fr.')) {
1170
+ return null;
1171
+ }
1172
+ const i = roleId.indexOf(':');
1173
+ if (i > -1) {
1174
+ return {
1175
+ frTypeId: roleId.substring(0, i),
1176
+ frRoleId: roleId.substring(i + 1)
1177
+ };
1178
+ }
1179
+ else {
1180
+ return {
1181
+ frTypeId: roleId,
1182
+ frRoleId: null
1183
+ };
1184
+ }
1185
+ }
1186
+ /**
1187
+ * Find among the specified parts definitions the one matching the specified
1188
+ * type ID, and eventually role ID when specified.
1189
+ *
1190
+ * @param partDefs The parts definitions.
1191
+ * @param typeId The type ID.
1192
+ * @param roleId The role ID or null.
1193
+ * @returns Part definition or null if not found.
1194
+ */
1195
+ findPartDefinition(partDefs, typeId, roleId = null) {
1196
+ if (!partDefs) {
1197
+ return null;
1198
+ }
1199
+ // if role ID is specified, find both type and role
1200
+ if (roleId) {
1201
+ const reqRoleId = this.stripFragmentRoleId(roleId);
1202
+ return partDefs.find(d => {
1203
+ return (d.typeId === typeId &&
1204
+ this.stripFragmentRoleId(d.roleId) === reqRoleId);
1205
+ });
1206
+ }
1207
+ // else just find type ID
1208
+ return partDefs.find(d => {
1209
+ return d.typeId === typeId;
1210
+ });
1211
+ }
1212
+ /**
1213
+ * Get the library editor key from the specified part type, looking up
1214
+ * the specified parts definitions.
1215
+ *
1216
+ * @param typeId The part's type ID.
1217
+ * @param roleId The part's role ID.
1218
+ */
1219
+ getEditorKeyFromPartType(typeId, roleId = null) {
1220
+ // find the part type ID
1221
+ const partGroupKey = this._partEditorKeys[typeId];
1222
+ if (!partGroupKey) {
1223
+ return {
1224
+ partKey: 'default'
1225
+ };
1226
+ }
1227
+ // additionally find the role ID if specified
1228
+ if (roleId) {
1229
+ const reqRoleId = this.stripFragmentRoleId(roleId);
1230
+ return {
1231
+ partKey: partGroupKey.part,
1232
+ frKey: partGroupKey.fragments[reqRoleId]
1233
+ };
1234
+ }
1235
+ return {
1236
+ partKey: partGroupKey.part
1237
+ };
1238
+ }
1239
+ /**
1240
+ * Decompose the specified editor key into part and fragment.
1241
+ * A simple editor key will just provide the same value for both.
1242
+ *
1243
+ * @param key The editor key to decompose.
1244
+ */
1245
+ decomposeEditorKey(key) {
1246
+ const i = key.indexOf(' ');
1247
+ if (i > -1) {
1248
+ return {
1249
+ partKey: key.substr(0, i),
1250
+ frKey: key.substr(i + 1)
1251
+ };
1252
+ }
1253
+ else {
1254
+ return {
1255
+ partKey: key,
1256
+ frKey: key
1257
+ };
1258
+ }
1259
+ }
1260
+ /**
1261
+ * Build the route to the part editor corresponding to the specified
1262
+ * part.
1263
+ *
1264
+ * A part editing route is like
1265
+ * "/items/<id>/<part-group>/<part-typeid>/<part-id>?rid=<role-id>",
1266
+ * where the role ID is optional, and may include the fragment role ID
1267
+ * as a suffix preceded by a colon.
1268
+ *
1269
+ * A fragment editing route is like
1270
+ * "/items/<id>/<part-group>/fragment/<part-id>/<fr-typeid>/<loc>?rid=<role-id>",
1271
+ * where the role ID is as above, and the fragment's type ID is derived
1272
+ * from the part's role ID, stripping the eventual fragment's role ID out.
1273
+ *
1274
+ * @param itemId The ID of the item the parts belongs to.
1275
+ * @param partId The part's ID.
1276
+ * @param typeId The part's type ID.
1277
+ * @param roleId The optional part's role ID.
1278
+ * @returns Object with a route property and an optional rid property
1279
+ * representing the role ID, which will be rendered as a query parameter.
1280
+ */
1281
+ buildPartEditorRoute(itemId, partId, typeId, roleId) {
1282
+ let route;
1283
+ const editorKey = this.getEditorKeyFromPartType(typeId);
1284
+ // /items/<id>/<part-group>/<part-typeid>/<part-id>?rid=<role-id>
1285
+ route = `/items/${itemId}/${editorKey.partKey}/${typeId}/${partId}`;
1286
+ return {
1287
+ route: route,
1288
+ rid: roleId
1289
+ };
1290
+ }
1291
+ /**
1292
+ * Build the route to the fragment editor corresponding to the specified
1293
+ * layers part and location.
1294
+ *
1295
+ * @param partDefs The parts definitions.
1296
+ * @param itemId The ID of the item the parts belongs to.
1297
+ * @param partId The part's ID.
1298
+ * @param typeId The part's type ID.
1299
+ * @param roleId The part's role ID.
1300
+ * @param loc The fragment's location.
1301
+ * @returns Object with a route property and an optional rid property
1302
+ * representing the role ID, which will be rendered as a query parameter.
1303
+ */
1304
+ buildFragmentEditorRoute(partDefs, itemId, partId, typeId, roleId, loc) {
1305
+ let route;
1306
+ const editorKey = this.getEditorKeyFromPartType(typeId, roleId);
1307
+ const { frTypeId, frRoleId } = this.getFragmentTypeAndRole(roleId);
1308
+ route = `/items/${itemId}/${editorKey.frKey}/fragment/${partId}/${frTypeId}/${loc}`;
1309
+ return {
1310
+ route: route,
1311
+ rid: frRoleId
1312
+ };
1313
+ }
1314
+ }
1315
+ LibraryRouteService.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "13.0.2", ngImport: i0, type: LibraryRouteService, deps: [{ token: 'partEditorKeys' }], target: i0.ɵɵFactoryTarget.Injectable });
1316
+ LibraryRouteService.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "13.0.2", ngImport: i0, type: LibraryRouteService, providedIn: 'root' });
1317
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "13.0.2", ngImport: i0, type: LibraryRouteService, decorators: [{
1318
+ type: Injectable,
1319
+ args: [{
1320
+ providedIn: 'root'
1321
+ }]
1322
+ }], ctorParameters: function () { return [{ type: undefined, decorators: [{
1323
+ type: Inject,
1324
+ args: ['partEditorKeys']
1325
+ }] }]; } });
1326
+
1327
+ class TextLayerService {
1328
+ constructor() {
1329
+ this._wsRegex = new RegExp('^\\s$', 'g');
1330
+ }
1331
+ isWhitespace(c) {
1332
+ if (!c) {
1333
+ return false;
1334
+ }
1335
+ if (c.length !== 1) {
1336
+ c = c.charAt(0);
1337
+ }
1338
+ return this._wsRegex.test(c);
1339
+ }
1340
+ /**
1341
+ * Extract the lines with their tokens from the specified text.
1342
+ * @param text the source text.
1343
+ * @returns lines.
1344
+ */
1345
+ getLines(text) {
1346
+ const results = [];
1347
+ if (!text) {
1348
+ return results;
1349
+ }
1350
+ const lines = text.split('\n');
1351
+ for (let y = 0; y < lines.length; y++) {
1352
+ const line = lines[y].trim();
1353
+ const l = {
1354
+ y: y + 1,
1355
+ tokens: [],
1356
+ };
1357
+ let x = 0;
1358
+ let xBeg = 0;
1359
+ while (x < line.length) {
1360
+ if (this.isWhitespace(line.charAt(x))) {
1361
+ l.tokens.push(line.substr(xBeg, x - xBeg));
1362
+ x++;
1363
+ while (x < line.length && this.isWhitespace(line.charAt(x))) {
1364
+ x++;
1365
+ }
1366
+ xBeg = x;
1367
+ }
1368
+ else {
1369
+ x++;
1370
+ }
1371
+ }
1372
+ if (xBeg < x) {
1373
+ l.tokens.push(line.substr(xBeg));
1374
+ }
1375
+ results.push(l);
1376
+ }
1377
+ return results;
1378
+ }
1379
+ /*
1380
+ * Rendition: HTML rendering from a base text and a set of fragments locations.
1381
+ * Each line in the base text is rendered with p; each token in a line is
1382
+ * rendered with its text value, and tokens are separated by space. Layer
1383
+ * fragments are rendered inside a span, with an id equal to the fragment location
1384
+ * plus a suffix beginning with _, added only for the purpose of ensuring unique
1385
+ * IDs in the rendered HTML code. Example:
1386
+ * <div>
1387
+ * <p id="y1">this is line 1.</p>
1388
+ * <p id="y2">here's a <span id="f2.3_0">fragment</span>.</p>
1389
+ * </div>
1390
+ */
1391
+ /**
1392
+ * Render the opening span for a layer fragment.
1393
+ * @param loc location.
1394
+ * @param locPortion the index of the token's portion (0-N). This is used
1395
+ * to build a unique ID for each HTML span rendering a layer fragment.
1396
+ * @param sb the target strings array.
1397
+ * @param isSelected true if selected.
1398
+ */
1399
+ renderOpeningSpan(loc, locPortion, sb, isSelected) {
1400
+ sb.push(`<span id="f${loc.toString()}_${locPortion}" class="fr${isSelected ? 'fr-sel' : ''}">`);
1401
+ }
1402
+ /**
1403
+ * Render the specified token intersecting the specified end-fragment location.
1404
+ * @param pt The point.
1405
+ * @param token The token.
1406
+ * @param sb The target array.
1407
+ */
1408
+ renderTokenAtEnd(pt, token, sb) {
1409
+ if (pt.at > 0) {
1410
+ // ...to]
1411
+ sb.push(token.substr(pt.at - 1, pt.run));
1412
+ sb.push('</span>');
1413
+ // ...ken
1414
+ if (pt.at - 1 + pt.run < token.length) {
1415
+ sb.push(token.substr(pt.at - 1 + pt.run));
1416
+ }
1417
+ }
1418
+ else {
1419
+ // ...token]
1420
+ sb.push(token);
1421
+ sb.push('</span>');
1422
+ }
1423
+ }
1424
+ /**
1425
+ * Render the specified token intersecting the specified single-point location.
1426
+ * The received token starts and ends a single-token range.
1427
+ * @param loc location.
1428
+ * @param token token.
1429
+ * @param sb target strings array.
1430
+ * @param isSelected True if the token is selected.
1431
+ */
1432
+ renderTokenAtPointStart(loc, token, sb, isSelected) {
1433
+ // 1.token's left-part
1434
+ if (loc.primary.at > 0) {
1435
+ // to...
1436
+ sb.push(token.substr(0, loc.primary.at - 1));
1437
+ }
1438
+ // 2.span: [
1439
+ this.renderOpeningSpan(loc, 0, sb, isSelected);
1440
+ // 3.token's right-part (...ken]/...ke]n or ...token])
1441
+ this.renderTokenAtEnd(loc.primary, token, sb);
1442
+ }
1443
+ /**
1444
+ * Render the specified token intersecting the specified range start location.
1445
+ * The received token starts a multi-tokens range.
1446
+ * @param loc location.
1447
+ * @param locPortion the index of the token's portion (0-N). This is used
1448
+ * to build a unique ID for each HTML span rendering a layer fragment.
1449
+ * @param token token.
1450
+ * @param sb target strings array.
1451
+ * @param isSelected True if the token is selected.
1452
+ */
1453
+ renderTokenAtRangeStart(loc, token, sb, isSelected) {
1454
+ // 1.token's left-part (=before at)
1455
+ if (loc.primary.at > 0) {
1456
+ // to...
1457
+ sb.push(token.substr(0, loc.primary.at - 1));
1458
+ }
1459
+ // 2.span: [
1460
+ this.renderOpeningSpan(loc, 0, sb, isSelected);
1461
+ // 3.token's right-part (...ken or ...token)
1462
+ if (loc.primary.at > 0) {
1463
+ // ...ken
1464
+ sb.push(token.substr(loc.primary.at - 1));
1465
+ }
1466
+ else {
1467
+ // ...token
1468
+ sb.push(token);
1469
+ }
1470
+ }
1471
+ renderTokenAtStart(loc, token, sb, isSelected) {
1472
+ if (!loc.secondary) {
1473
+ // single
1474
+ this.renderTokenAtPointStart(loc, token, sb, isSelected);
1475
+ return false;
1476
+ }
1477
+ else {
1478
+ // range
1479
+ this.renderTokenAtRangeStart(loc, token, sb, isSelected);
1480
+ return true;
1481
+ }
1482
+ }
1483
+ /**
1484
+ * Render to HTML the base text decorated with its layer fragments.
1485
+ * @param text The base text.
1486
+ * @param locations The locations of all the fragments
1487
+ * of the same type to be rendered on top of the base text.
1488
+ * @param selectedLoc The optional location of the selected
1489
+ * fragment if any. The selected fragment gets decorated with an additional
1490
+ * class value.
1491
+ */
1492
+ render(text, locations, selectedLoc = null) {
1493
+ if (!text) {
1494
+ return '<div></div>';
1495
+ }
1496
+ // get lines from text
1497
+ const sb = [];
1498
+ const lines = this.getLines(text);
1499
+ let loc = null;
1500
+ let tokenSelected = false;
1501
+ if (!locations) {
1502
+ locations = [];
1503
+ }
1504
+ // for each line in text
1505
+ sb.push('<div>');
1506
+ for (let y = 0; y < lines.length; y++) {
1507
+ sb.push(`<p id="y${y + 1}">`);
1508
+ // reopen a span if continuing a fragment from prev line
1509
+ if (loc) {
1510
+ this.renderOpeningSpan(loc, y + 1 - loc.primary.y, sb, tokenSelected);
1511
+ }
1512
+ // for each token in line
1513
+ const line = lines[y];
1514
+ for (let x = 0; x < line.tokens.length; x++) {
1515
+ // add separator if required
1516
+ if (x > 0) {
1517
+ sb.push(' ');
1518
+ }
1519
+ const token = line.tokens[x];
1520
+ // if inside a fragment, check if this token is the last
1521
+ if (loc && loc.secondary) {
1522
+ if (loc.secondary.y === y + 1 && loc.secondary.x === x + 1) {
1523
+ this.renderTokenAtEnd(loc.secondary, token, sb);
1524
+ loc = null;
1525
+ }
1526
+ else {
1527
+ sb.push(token);
1528
+ }
1529
+ }
1530
+ else {
1531
+ // else, check if this token starts a fragment
1532
+ loc = locations.find((l) => {
1533
+ return l.primary.y === y + 1 && l.primary.x === x + 1;
1534
+ });
1535
+ if (loc) {
1536
+ tokenSelected = selectedLoc ? loc.overlaps(selectedLoc) : false;
1537
+ if (!this.renderTokenAtStart(loc, token, sb, tokenSelected)) {
1538
+ loc = null;
1539
+ }
1540
+ }
1541
+ else {
1542
+ sb.push(token);
1543
+ }
1544
+ }
1545
+ }
1546
+ // close a span if pending at p end
1547
+ if (loc) {
1548
+ sb.push('</span>');
1549
+ }
1550
+ sb.push('</p>');
1551
+ }
1552
+ sb.push('</div>');
1553
+ return sb.join('');
1554
+ }
1555
+ /*
1556
+ Location: starting from user selection on a rendered text, get the corresponding
1557
+ layer fragment location. This differs according to the purpose of the location
1558
+ to be got: if getting a location for an existing fragment, at least 1 decorated
1559
+ text (span) should be included in the selection, which does not require to be
1560
+ exact; if getting a location for a new fragment, no decorated text (span) can be
1561
+ included in the selection (two fragments in the same layer can never overlap),
1562
+ which must be exact.
1563
+ */
1564
+ /**
1565
+ * Get the Y bounds from the specified selection.
1566
+ * @param range The selection range.
1567
+ * @param forNew True if getting bounds for a new fragment.
1568
+ * @returns Range, inclusive.
1569
+ */
1570
+ getYBoundsFromRange(range, forNew) {
1571
+ let p = null;
1572
+ switch (range.commonAncestorContainer.nodeType) {
1573
+ case Node.TEXT_NODE:
1574
+ // single-p selection, parent=p
1575
+ p = range.commonAncestorContainer.parentElement;
1576
+ if (forNew && (p.nodeName !== 'P' || !p.hasAttribute('id'))) {
1577
+ return null;
1578
+ }
1579
+ if (p.nodeName === 'SPAN') {
1580
+ p = p.parentElement;
1581
+ }
1582
+ const y = parseInt(p.getAttribute('id').substr(1), 10);
1583
+ // return [y, y];
1584
+ return { start: y, end: y };
1585
+ case Node.ELEMENT_NODE:
1586
+ // div only is allowed; in this case, it's a multi-p range
1587
+ if (range.commonAncestorContainer.nodeName !== 'DIV') {
1588
+ return null;
1589
+ }
1590
+ // for each div's child p element:
1591
+ let yMin = 0;
1592
+ let yMax = 0;
1593
+ let inside = false;
1594
+ for (let i = 0; i < range.commonAncestorContainer.childNodes.length; i++) {
1595
+ const child = range.commonAncestorContainer.childNodes[i];
1596
+ if (child.nodeType !== Node.ELEMENT_NODE || child.nodeName !== 'P') {
1597
+ continue;
1598
+ }
1599
+ // check if we're entering the start-p
1600
+ if (!inside && child.contains(range.startContainer)) {
1601
+ inside = true;
1602
+ }
1603
+ // collect y if inside
1604
+ if (inside) {
1605
+ const iy = parseInt(child.getAttribute('id').substr(1), 10);
1606
+ if (!yMin || iy < yMin) {
1607
+ yMin = iy;
1608
+ }
1609
+ if (!yMax || iy > yMax) {
1610
+ yMax = iy;
1611
+ }
1612
+ // check if we have exited the last p
1613
+ if (child.contains(range.endContainer)) {
1614
+ break;
1615
+ }
1616
+ }
1617
+ }
1618
+ return {
1619
+ start: yMin,
1620
+ end: yMax,
1621
+ };
1622
+ }
1623
+ }
1624
+ locatePrevSpace(line, index) {
1625
+ while (index > -1 && line.charAt(index) !== ' ') {
1626
+ index--;
1627
+ }
1628
+ return index;
1629
+ }
1630
+ locateNextSpace(line, index) {
1631
+ while (index < line.length && line.charAt(index) !== ' ') {
1632
+ index++;
1633
+ }
1634
+ return index === line.length ? -1 : index;
1635
+ }
1636
+ /**
1637
+ * Get the bounds of the token any character of which is indexed
1638
+ * by index.
1639
+ * @param line The text line.
1640
+ * @param index The index to the text line to start from.
1641
+ * @returns Bounds where start=index of the first character of the token,
1642
+ * and end=index of the character past the token's last character;
1643
+ * or null if index was not valid.
1644
+ */
1645
+ getTokenBounds(line, index) {
1646
+ if (line.charAt(index) === ' ') {
1647
+ return null;
1648
+ }
1649
+ let start = this.locatePrevSpace(line, index);
1650
+ if (start === -1) {
1651
+ start = 0;
1652
+ }
1653
+ else {
1654
+ start++;
1655
+ }
1656
+ let end = this.locateNextSpace(line, index);
1657
+ if (end === -1) {
1658
+ end = line.length;
1659
+ }
1660
+ // return [start, end];
1661
+ return {
1662
+ start,
1663
+ end,
1664
+ };
1665
+ }
1666
+ /**
1667
+ * Return the received selection bounds, adjusted to exclude spaces.
1668
+ */
1669
+ getAdjustedSelectionBounds(selStart, selEnd, line) {
1670
+ // corner case: if on space, move to right
1671
+ if (line.charAt(selStart) === ' ') {
1672
+ selStart++;
1673
+ }
1674
+ // corner case: if included trailing space, move to left
1675
+ if (selEnd > 0 && line.charAt(selEnd - 1) === ' ') {
1676
+ selEnd--;
1677
+ }
1678
+ // return [selStart, selEnd];
1679
+ return {
1680
+ start: selStart,
1681
+ end: selEnd,
1682
+ };
1683
+ }
1684
+ /**
1685
+ * Get the start coordinates for the selected range and line.
1686
+ * @param range The selected range.
1687
+ * @param line The reference text line.
1688
+ */
1689
+ getStartCoordsFromRange(selStart, selEnd, line) {
1690
+ // get adjusted selection bounds
1691
+ const selBounds = this.getAdjustedSelectionBounds(selStart, selEnd, line);
1692
+ // get the bounds of the first selected token
1693
+ const tokBounds = this.getTokenBounds(line, selBounds.start);
1694
+ // calculate x by counting the tokens before the target token
1695
+ let x = 1;
1696
+ let j = tokBounds.start - 1;
1697
+ while (j > -1) {
1698
+ if (line.charAt(j) === ' ') {
1699
+ x++;
1700
+ }
1701
+ j--;
1702
+ }
1703
+ // calculate at,run only when either of these is true:
1704
+ // (a) selection starts past the 1st char of the token (al[pha);
1705
+ // (b) selection ends before the last char of the token (al]pha);
1706
+ // run is calculated only if (b) is true.
1707
+ let at = 0;
1708
+ let run = 0;
1709
+ if (selBounds.start > tokBounds.start || selBounds.end < tokBounds.end) {
1710
+ at = 1 + selBounds.start - tokBounds.start;
1711
+ run =
1712
+ (selBounds.end < tokBounds.end
1713
+ ? selBounds.end // al]pha
1714
+ : tokBounds.end) - // alpha]
1715
+ Math.max(tokBounds.start, selBounds.start);
1716
+ }
1717
+ return {
1718
+ y: 0,
1719
+ x,
1720
+ at,
1721
+ run,
1722
+ };
1723
+ }
1724
+ getEndCoordsFromRange(selStart, selEnd, line) {
1725
+ // get adjusted selection bounds
1726
+ const selBounds = this.getAdjustedSelectionBounds(selStart, selEnd, line);
1727
+ // get the bounds of the last selected token
1728
+ const tokBounds = this.getTokenBounds(line, selBounds.end - 1);
1729
+ // calculate x by counting the tokens before the target token
1730
+ let x = 1;
1731
+ let j = selBounds.end - 1;
1732
+ while (j > -1) {
1733
+ if (line.charAt(j) === ' ') {
1734
+ x++;
1735
+ }
1736
+ j--;
1737
+ }
1738
+ // calculate at,run only when selection ends before the 1st char of the token
1739
+ // (al]pha); run is calculated only if at is calculated.
1740
+ let at = 0;
1741
+ let run = 0;
1742
+ if (selBounds.end < tokBounds.end) {
1743
+ at =
1744
+ selBounds.start > tokBounds.start
1745
+ ? 1 + selBounds.start - tokBounds.start
1746
+ : 1;
1747
+ run = selBounds.end - tokBounds.start;
1748
+ }
1749
+ return {
1750
+ y: 0,
1751
+ x,
1752
+ at,
1753
+ run,
1754
+ };
1755
+ }
1756
+ getSpanLocFromId(id) {
1757
+ if (!id) {
1758
+ return null;
1759
+ }
1760
+ const r = new RegExp('^f([-\\d+.@x]+)', 'g');
1761
+ const m = r.exec(id);
1762
+ if (!m) {
1763
+ return null;
1764
+ }
1765
+ return TokenLocation.parse(m[1]);
1766
+ }
1767
+ visitNodes(node, visitor) {
1768
+ if (!visitor(node)) {
1769
+ return;
1770
+ }
1771
+ if (node.nodeType === Node.ELEMENT_NODE) {
1772
+ for (let i = 0; i < node.childNodes.length; i++) {
1773
+ const child = node.childNodes[i];
1774
+ this.visitNodes(child, visitor);
1775
+ }
1776
+ }
1777
+ }
1778
+ findFirstDescendantSpan(range) {
1779
+ let inside = false;
1780
+ let span = null;
1781
+ this.visitNodes(range.commonAncestorContainer, (current) => {
1782
+ if (current === range.startContainer) {
1783
+ inside = true;
1784
+ }
1785
+ if (current.nodeType === Node.ELEMENT_NODE &&
1786
+ current.nodeName === 'SPAN') {
1787
+ span = current;
1788
+ return false;
1789
+ }
1790
+ if (current === range.endContainer) {
1791
+ inside = false;
1792
+ }
1793
+ return true;
1794
+ });
1795
+ return span;
1796
+ }
1797
+ /**
1798
+ * Get the base offset for the specified node. This is used
1799
+ * when the start container of the selected range has any
1800
+ * preceding sibling node, which happens only when you have
1801
+ * any spans in the p element (=the line). In this case,
1802
+ * the selection offset starts from the start container node,
1803
+ * which is preceded by other nodes including other text.
1804
+ * As we must get the line-based offset, we have to start
1805
+ * from a base offset equal to the sum of the lengths of
1806
+ * all the preceding siblings.
1807
+ */
1808
+ getNodeBaseOffset(node) {
1809
+ let offset = 0;
1810
+ node = node.previousSibling;
1811
+ while (node) {
1812
+ offset +=
1813
+ node.nodeType === Node.ELEMENT_NODE
1814
+ ? node.innerText?.length || 0
1815
+ : node.textContent?.length || 0;
1816
+ node = node.previousSibling;
1817
+ }
1818
+ return offset;
1819
+ }
1820
+ /**
1821
+ * Get the location corresponding to the user selection,
1822
+ * for editing the first fragment included in it.
1823
+ * @param range The selected range. You can get it from the
1824
+ * current selection using getSelectedRange().
1825
+ * @returns The token location or null.
1826
+ */
1827
+ getSelectedLocationForEdit(range) {
1828
+ if (!range) {
1829
+ return null;
1830
+ }
1831
+ // just find the first descendant span in selection
1832
+ let span = null;
1833
+ switch (range.commonAncestorContainer.nodeType) {
1834
+ case Node.ELEMENT_NODE:
1835
+ span = range.commonAncestorContainer;
1836
+ if (span.nodeName !== 'SPAN') {
1837
+ span = this.findFirstDescendantSpan(range);
1838
+ }
1839
+ break;
1840
+ case Node.TEXT_NODE:
1841
+ span = range.commonAncestorContainer.parentElement;
1842
+ if (span &&
1843
+ (span.nodeType !== Node.ELEMENT_NODE || span.nodeName !== 'SPAN')) {
1844
+ span = null;
1845
+ }
1846
+ break;
1847
+ }
1848
+ return span ? this.getSpanLocFromId(span.getAttribute('id')) : null;
1849
+ }
1850
+ textLineToString(line) {
1851
+ if (!line || !line.tokens) {
1852
+ return '';
1853
+ }
1854
+ return line.tokens.join(' ');
1855
+ }
1856
+ buildCoords(start, end, singleToken) {
1857
+ const sb = [];
1858
+ // start: y.x
1859
+ sb.push(`${start.y}.${start.x}`);
1860
+ if (singleToken) {
1861
+ // single token: check for at,run
1862
+ if (start.at) {
1863
+ sb.push(`@${start.at}`);
1864
+ if (start.run > 1) {
1865
+ sb.push(`x${start.run}`);
1866
+ }
1867
+ }
1868
+ }
1869
+ else {
1870
+ // not a single token
1871
+ // first token
1872
+ if (start.at) {
1873
+ sb.push(`@${start.at}x${start.run}`);
1874
+ }
1875
+ // last token
1876
+ sb.push(`-${end.y}.${end.x}`);
1877
+ if (end.at) {
1878
+ sb.push(`@1x${end.run}`);
1879
+ }
1880
+ }
1881
+ return sb.join('');
1882
+ }
1883
+ /**
1884
+ * Recursively find the node matching the specified matcher
1885
+ * function, starting from the specified node (included).
1886
+ *
1887
+ * @param node The node to start from.
1888
+ * @param matcher The matcher function, which receives a node
1889
+ * to match, and returns 1=match, 0=no match, -1=stop the
1890
+ * find operation with a no match.
1891
+ */
1892
+ findNode(node, matcher) {
1893
+ // self
1894
+ const n = matcher(node);
1895
+ if (n === 1) {
1896
+ return node;
1897
+ }
1898
+ if (n === -1) {
1899
+ return null;
1900
+ }
1901
+ // children
1902
+ if (node.hasChildNodes()) {
1903
+ for (let i = 0; i < node.childNodes.length; i++) {
1904
+ const child = node.childNodes[i];
1905
+ const found = this.findNode(child, matcher);
1906
+ if (found) {
1907
+ return found;
1908
+ }
1909
+ }
1910
+ }
1911
+ return null;
1912
+ }
1913
+ selHasAnySpan(range) {
1914
+ let inside = false;
1915
+ if (
1916
+ // the selected text node must not be child of a span
1917
+ range.startContainer.parentElement.tagName === 'SPAN' ||
1918
+ range.startContainer.parentElement.tagName === 'SPAN' ||
1919
+ // the nodes tree from the common ancestor, from the start node
1920
+ // up to the end node, must not include any span
1921
+ this.findNode(range.commonAncestorContainer, (node) => {
1922
+ // start checking only when start node reached
1923
+ if (node === range.startContainer) {
1924
+ inside = true;
1925
+ }
1926
+ if (!inside) {
1927
+ return 0;
1928
+ }
1929
+ // stop checking when end node reached
1930
+ if (node === range.endContainer) {
1931
+ return -1;
1932
+ }
1933
+ // node cannot be a span
1934
+ if (node.nodeType === Node.ELEMENT_NODE &&
1935
+ node.tagName === 'SPAN') {
1936
+ return 1;
1937
+ }
1938
+ return 0;
1939
+ })) {
1940
+ return true;
1941
+ }
1942
+ return false;
1943
+ }
1944
+ /**
1945
+ * Get the location corresponding to the user selection,
1946
+ * for adding a new fragment with the same extension.
1947
+ * @param range The selected range. You can get it from the
1948
+ * current selection using getSelectedRange().
1949
+ * @param text The full base text.
1950
+ * @returns TokenLocation The token location or null.
1951
+ */
1952
+ getSelectedLocationForNew(range, text) {
1953
+ if (!range || this.selHasAnySpan(range)) {
1954
+ return null;
1955
+ }
1956
+ // get y bounds (min, max; equal if single-line)
1957
+ const yBounds = this.getYBoundsFromRange(range, true);
1958
+ if (!yBounds) {
1959
+ return null;
1960
+ }
1961
+ // get lines and calculate start/end coords
1962
+ const lines = this.getLines(text);
1963
+ const startLine = this.textLineToString(lines[yBounds.start - 1]);
1964
+ const endLine = this.textLineToString(lines[yBounds.end - 1]);
1965
+ // get the base offsets
1966
+ const startBaseOffset = this.getNodeBaseOffset(range.startContainer);
1967
+ const endBaseOffset = this.getNodeBaseOffset(range.endContainer);
1968
+ // get the start (including the base offset)
1969
+ const startLineEndOffset = yBounds.start !== yBounds.end
1970
+ ? startLine.length
1971
+ : range.endOffset + startBaseOffset;
1972
+ const start = this.getStartCoordsFromRange(range.startOffset + startBaseOffset, startLineEndOffset, startLine);
1973
+ start.y = yBounds.start;
1974
+ // get the end (including the base offset)
1975
+ const end = yBounds.start !== yBounds.end
1976
+ ? this.getEndCoordsFromRange(0, range.endOffset + endBaseOffset, endLine)
1977
+ : this.getEndCoordsFromRange(range.startOffset + endBaseOffset, range.endOffset + endBaseOffset, endLine);
1978
+ end.y = yBounds.end;
1979
+ const singleLine = start.y === end.y;
1980
+ const singleToken = singleLine && start.x === end.x;
1981
+ const coords = this.buildCoords(start, end, singleToken);
1982
+ return TokenLocation.parse(coords);
1983
+ }
1984
+ /**
1985
+ * Get the currently selected range in the browser's document.
1986
+ * This uses the rangy library.
1987
+ */
1988
+ getSelectedRange() {
1989
+ const sel = rangy.getSelection();
1990
+ if (sel.isCollapsed) {
1991
+ return null;
1992
+ }
1993
+ return sel.getRangeAt(0);
1994
+ }
1995
+ }
1996
+ TextLayerService.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "13.0.2", ngImport: i0, type: TextLayerService, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
1997
+ TextLayerService.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "13.0.2", ngImport: i0, type: TextLayerService, providedIn: 'root' });
1998
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "13.0.2", ngImport: i0, type: TextLayerService, decorators: [{
1999
+ type: Injectable,
2000
+ args: [{ providedIn: 'root' }]
2001
+ }], ctorParameters: function () { return []; } });
2002
+
2003
+ // https://github.com/angular/angular/blob/3b7d4ebbd6445364889d61b7b1b1c65206534d34/packages/forms/src/validators.ts
2004
+ // https://indepth.dev/posts/1319/the-best-way-to-implement-custom-validators
2005
+ /**
2006
+ * Cadmus general-purpose custom validators.
2007
+ */
2008
+ // @dynamic
2009
+ class CadmusValidators {
2010
+ static hasValidLength(value) {
2011
+ // non-strict comparison is intentional,
2012
+ // to check for both `null` and `undefined` values
2013
+ return value != null && typeof value.length === 'number';
2014
+ }
2015
+ /**
2016
+ * Validate an array or string for a minimum required length.
2017
+ * Differently from the standard minLength validator, this does
2018
+ * not exclude 0 from the values to be checked. The standard
2019
+ * validator instead does not validate the value if this is 0.
2020
+ *
2021
+ * @param minLength Minimum length required.
2022
+ * @returns Null if valid, else an object with minlength with
2023
+ * requiredLength and actualLength.
2024
+ */
2025
+ static strictMinLengthValidator(minLength) {
2026
+ return (control) => {
2027
+ // don't validate values without `length` property
2028
+ if (!this.hasValidLength(control.value)) {
2029
+ return null;
2030
+ }
2031
+ return control.value.length < minLength
2032
+ ? {
2033
+ minlength: {
2034
+ requiredLength: minLength,
2035
+ actualLength: control.value.length,
2036
+ },
2037
+ }
2038
+ : null;
2039
+ };
2040
+ }
2041
+ /**
2042
+ * Conditionally validate using the specified validator
2043
+ * when predicate is true.
2044
+ * See https://medium.com/ngx/3-ways-to-implement-conditional-validation-of-reactive-forms-c59ed6fc3325.
2045
+ *
2046
+ * @param predicate The predicate function to use when determining
2047
+ * if the validator should be used.
2048
+ * @param validator The conditional validator to use.
2049
+ * @returns Validation results.
2050
+ */
2051
+ static conditionalValidator(predicate, validator) {
2052
+ return (control) => {
2053
+ if (!control.parent) {
2054
+ return null;
2055
+ }
2056
+ if (predicate()) {
2057
+ return validator(control);
2058
+ }
2059
+ return null;
2060
+ };
2061
+ }
2062
+ }
2063
+
2064
+ class PasswordValidator {
2065
+ static isValidPassword(control) {
2066
+ if (!control.value) {
2067
+ return null;
2068
+ }
2069
+ if (control.value.length < 8) {
2070
+ return {
2071
+ passwordTooShort: true
2072
+ };
2073
+ }
2074
+ if (!/.*[A-Z].*/.test(control.value)) {
2075
+ return {
2076
+ noUpperInPassword: true
2077
+ };
2078
+ }
2079
+ if (!/.*[a-z].*/.test(control.value)) {
2080
+ return {
2081
+ noLowerInPassword: true
2082
+ };
2083
+ }
2084
+ if (!/.*[A-Z].*/.test(control.value)) {
2085
+ return {
2086
+ noUpperInPassword: true
2087
+ };
2088
+ }
2089
+ if (!/.*[-`~!@#$%^&*()_+=\[\]{};:'",.<>/?|\\].*/.test(control.value)) {
2090
+ return {
2091
+ noSymbolInPassword: true
2092
+ };
2093
+ }
2094
+ return null;
2095
+ }
2096
+ }
2097
+
2098
+ class CadmusCoreModule {
2099
+ }
2100
+ CadmusCoreModule.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "13.0.2", ngImport: i0, type: CadmusCoreModule, deps: [], target: i0.ɵɵFactoryTarget.NgModule });
2101
+ CadmusCoreModule.ɵmod = i0.ɵɵngDeclareNgModule({ minVersion: "12.0.0", version: "13.0.2", ngImport: i0, type: CadmusCoreModule, declarations: [SortPipe], imports: [CommonModule, HttpClientModule, NgToolsModule], exports: [SortPipe] });
2102
+ CadmusCoreModule.ɵinj = i0.ɵɵngDeclareInjector({ minVersion: "12.0.0", version: "13.0.2", ngImport: i0, type: CadmusCoreModule, imports: [[CommonModule, HttpClientModule, NgToolsModule]] });
2103
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "13.0.2", ngImport: i0, type: CadmusCoreModule, decorators: [{
2104
+ type: NgModule,
2105
+ args: [{
2106
+ imports: [CommonModule, HttpClientModule, NgToolsModule],
2107
+ declarations: [SortPipe],
2108
+ exports: [SortPipe],
2109
+ }]
2110
+ }] });
2111
+
2112
+ /*
2113
+ * Public API Surface of cadmus-core
2114
+ */
2115
+
2116
+ /**
2117
+ * Generated bundle index. Do not edit.
2118
+ */
2119
+
2120
+ export { CadmusCoreModule, CadmusValidators, DATATION_FORMAT_OPTIONS, DataPinValueType, Datation, GravatarService, HistoricalDate, HistoricalDateType, LibraryRouteService, PasswordValidator, PendingChangesGuard, SortPipe, TextLayerService, TextRange, TokenLocation, TokenPoint };