-
-
Notifications
You must be signed in to change notification settings - Fork 51
/
cfi.ts
430 lines (405 loc) 路 10.6 KB
/
cfi.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
/**
* Copyright 2013 Google, Inc.
* Copyright 2015 Daishinsha Inc.
* Copyright 2019 Vivliostyle Foundation
*
* Vivliostyle.js is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Vivliostyle.js is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Vivliostyle.js. If not, see <http://www.gnu.org/licenses/>.
*
* @fileoverview Cfi - Support for EPUB Canonical Fragment Identifiers.
*/
import * as Base from "./base";
import * as Logging from "./logging";
export type Position = {
node: Node;
offset: number;
after: boolean;
sideBias: string | null;
ref: Fragment;
};
export function getId(node: Node): string | null {
if (node.nodeType == 1) {
const idtxt = (node as Element).getAttribute("id");
if (idtxt) {
return idtxt;
}
}
return null;
}
export function escapeChar(ch: string): string {
return `^${ch}`;
}
export function escape(str: string): string {
return str.replace(/[\[\]\(\),=;^]/g, escapeChar);
}
export function unescapeChar(str: string): string {
return str.substr(1);
}
export function unescape(str: string): string {
if (!str) {
return str;
}
return str.replace(/\^[\[\]\(\),=;^]/g, unescapeChar);
}
export function parseExtVal(extstr: string): string | string[] {
const result = [];
do {
const r = extstr.match(/^(\^,|[^,])*/);
const p = unescape(r[0]);
extstr = extstr.substr(r[0].length + 1);
if (!extstr && !result.length) {
return p;
}
result.push(p);
} while (extstr);
return result;
}
export function parseExt(extstr: string): { [key: string]: string | string[] } {
const ext = {};
while (extstr) {
const r = extstr.match(/^;([^;=]+)=(([^;]|\^;)*)/);
if (!r) {
return ext;
}
ext[r[1]] = parseExtVal(r[2]);
extstr = extstr.substr(r[0].length);
}
return ext;
}
export interface Step {
appendTo(sb: Base.StringBuffer): void;
applyTo(pos: Position): boolean;
}
export class RefStep implements Step {
appendTo(sb: Base.StringBuffer) {
sb.append("!");
}
/** @override */
applyTo(pos: Position): boolean {
return false;
}
}
export class ChildStep implements Step {
constructor(
public readonly index: number,
public readonly id: string | null,
public readonly sideBias: string | null,
) {}
/** @override */
appendTo(sb: Base.StringBuffer): void {
sb.append("/");
sb.append(this.index.toString());
if (this.id || this.sideBias) {
sb.append("[");
if (this.id) {
sb.append(this.id);
}
if (this.sideBias) {
sb.append(";s=");
sb.append(this.sideBias);
}
sb.append("]");
}
}
/** @override */
applyTo(pos: Position): boolean {
if (pos.node.nodeType != 1) {
throw new Error("E_CFI_NOT_ELEMENT");
}
const elem = pos.node as Element;
const childElements = elem.children;
const childElementCount = childElements.length;
let child: Node;
const childIndex = Math.floor(this.index / 2) - 1;
if (childIndex < 0 || childElementCount == 0) {
child = elem.firstChild;
pos.node = child || elem;
} else {
child = childElements[Math.min(childIndex, childElementCount - 1)];
if (this.index & 1) {
const next = child.nextSibling;
if (!next || next.nodeType == 1) {
pos.after = true;
} else {
child = next;
}
}
pos.node = child;
}
if (this.id && (pos.after || this.id != getId(pos.node))) {
const movedNode = elem.ownerDocument.getElementById(this.id);
if (movedNode) {
pos.node = movedNode;
} else {
Logging.logger.warn("E_CFI_ID_MISMATCH:", this.id);
}
}
pos.sideBias = this.sideBias;
return true;
}
}
export class OffsetStep implements Step {
constructor(
public readonly offset: number,
public readonly textBefore: string | null,
public readonly textAfter: string | null,
public readonly sideBias: string | null,
) {}
applyTo(pos: Position): boolean {
if (this.offset > 0 && !pos.after) {
let offset = this.offset;
let node = pos.node;
while (true) {
const nodeType = node.nodeType;
if (nodeType == 1) {
break;
}
const next = node.nextSibling;
if (3 <= nodeType && nodeType <= 5) {
const textLength = node.textContent.length;
if (offset <= textLength) {
break;
}
if (!next) {
offset = textLength;
break;
}
offset -= textLength;
}
if (!next) {
offset = 0;
break;
}
node = next;
}
pos.node = node;
pos.offset = offset;
}
pos.sideBias = this.sideBias;
return true;
}
/** @override */
appendTo(sb: Base.StringBuffer): void {
sb.append(":");
sb.append(this.offset.toString());
if (this.textBefore || this.textAfter || this.sideBias) {
sb.append("[");
if (this.textBefore || this.textAfter) {
if (this.textBefore) {
sb.append(escape(this.textBefore));
}
sb.append(",");
if (this.textAfter) {
sb.append(escape(this.textAfter));
}
}
if (this.sideBias) {
sb.append(";s=");
sb.append(this.sideBias);
}
sb.append("]");
}
}
}
export class Fragment {
steps: Step[] = null;
fromString(fragstr: string): void {
let r = fragstr.match(/^#?epubcfi\((.*)\)$/);
if (!r) {
throw new Error("E_CFI_NOT_CFI");
}
const str = decodeURIComponent(r[1]);
let i = 0;
const steps = [];
while (true) {
let ext: {
[key: string]: string | string[];
};
switch (str.charAt(i)) {
case "/": {
i++;
r = str
.substr(i)
.match(/^(0|[1-9][0-9]*)(\[(.*?)(;([^\]]|\^\])*)?\])?/);
if (!r) {
throw new Error("E_CFI_NUMBER_EXPECTED");
}
i += r[0].length;
const index = parseInt(r[1], 10);
const id = r[3];
ext = parseExt(r[4]);
steps.push(new ChildStep(index, id, Base.asString(ext["s"])));
break;
}
case ":": {
i++;
r = str
.substr(i)
.match(
/^(0|[1-9][0-9]*)(\[((([^\];,]|\^[\];,])*)(,(([^\];,]|\^[\];,])*))?)(;([^]]|\^\])*)?\])?/,
);
if (!r) {
throw new Error("E_CFI_NUMBER_EXPECTED");
}
i += r[0].length;
const offset = parseInt(r[1], 10);
let textBefore = r[4];
if (textBefore) {
textBefore = unescape(textBefore);
}
let textAfter = r[7];
if (textAfter) {
textAfter = unescape(textAfter);
}
ext = parseExt(r[10]);
steps.push(
new OffsetStep(
offset,
textBefore,
textAfter,
Base.asString(ext["s"]),
),
);
break;
}
case "!":
i++;
steps.push(new RefStep());
break;
case "~":
case "@":
// Time/space terminus; only useful for highlights/selections which are
// not yet supported, skip for now. fall through
case "":
this.steps = steps;
return;
default:
throw new Error("E_CFI_PARSE_ERROR");
}
}
}
navigate(doc: Document): Position {
const pos = {
node: doc.documentElement,
offset: 0,
after: false,
sideBias: null,
ref: null,
};
for (let i = 0; i < this.steps.length; i++) {
if (!this.steps[i].applyTo(pos)) {
pos.ref = new Fragment();
pos.ref.steps = this.steps.slice(i + 1);
break;
}
}
return pos;
}
trim(text: string, after: boolean): string {
return text
.replace(/\s+/g, " ")
.match(
after
? /^[ -\uD7FF\uE000-\uFFFF]{0,8}/
: /[ -\uD7FF\uE000-\uFFFF]{0,8}$/,
)[0]
.replace(/^\s/, "")
.replace(/\s$/, "");
}
/**
* Initialize from a node and an offset.
*/
prependPathFromNode(
node: Node,
offset: number,
after: boolean,
sideBias: string | null,
) {
const steps = [];
let parent = node.parentNode;
let textBefore = "";
let textAfter = "";
while (node) {
switch (node.nodeType) {
case 3: // Text nodes
case 4:
case 5: {
const text = node.textContent;
const textLength = text.length;
if (after) {
offset += textLength;
if (!textBefore) {
textBefore = text;
}
} else {
if (offset > textLength) {
offset = textLength;
}
after = true;
textBefore = text.substr(0, offset);
textAfter = text.substr(offset);
}
node = node.previousSibling;
continue;
}
case 8: // Comment Node
node = node.previousSibling;
continue;
}
break;
}
if (offset > 0 || textBefore || textAfter) {
textBefore = this.trim(textBefore, false);
textAfter = this.trim(textAfter, true);
steps.push(new OffsetStep(offset, textBefore, textAfter, sideBias));
sideBias = null;
}
while (parent) {
if (!parent || parent.nodeType == 9) {
break;
}
const id = after ? null : getId(node);
let index = after ? 1 : 0;
while (node) {
if (node.nodeType == 1) {
index += 2;
}
node = node.previousSibling;
}
steps.push(new ChildStep(index, id, sideBias));
sideBias = null;
node = parent;
parent = parent.parentNode;
after = false;
}
steps.reverse();
if (this.steps) {
steps.push(new RefStep());
this.steps = steps.concat(this.steps);
} else {
this.steps = steps;
}
}
toString(): string {
if (!this.steps) {
return "";
}
const sb = new Base.StringBuffer();
sb.append("epubcfi(");
for (let i = 0; i < this.steps.length; i++) {
this.steps[i].appendTo(sb);
}
sb.append(")");
return sb.toString().replace(/%/g, "%25");
}
}