@myrmidon/cadmus-core 0.0.24 → 1.0.0

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