This repository has been archived by the owner on Feb 1, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathjsapi.js
1403 lines (1306 loc) · 37.3 KB
/
jsapi.js
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
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Handy JavaScript API for Parsoid DOM, inspired by the
* python `mwparserfromhell` package.
* @module
*/
'use strict';
require('parsoid/core-upgrade.js');
// TO DO:
// extension
// PExtLink#url PWikiLink#title should handle mw:ExpandedAttrs
const DOMImpl = require('domino').impl;
const { Node, NodeFilter } = DOMImpl;
const DU = require('parsoid/lib/utils/DOMUtils.js').DOMUtils;
const Promise = require('parsoid/lib/utils/promise.js');
// Note that the JSAPI exposes data-mw directly as a DOM attribute to
// allow clients to easily edit it.
// WTS helper
const wts = Promise.async(function *(env, nodes) {
let body;
if (nodes.length === 0) {
return '';
} else if (nodes.length === 1 && DU.isBody(nodes[0])) {
body = nodes[0];
} else {
body = nodes[0].ownerDocument.createElement('body');
for (var i = 0; i < nodes.length; i++) {
body.appendChild(nodes[i].cloneNode(true));
}
}
return (yield env.getContentHandler().fromHTML(env, body, false));
});
// toString helper
const toStringHelper = function(nodes, sizeLimit) {
let out;
if (sizeLimit === undefined) { sizeLimit = 80; /* characters */ }
if (nodes.length === 0) {
return '';
} else if (nodes.length === 1) {
const body = nodes[0].ownerDocument.createElement('body');
body.appendChild(nodes[0].cloneNode(true));
out = DU.normalizeOut(body, 'parsoidOnly');
if (out.length <= sizeLimit || !DU.isElt(nodes[0])) { return out; }
body.firstChild.innerHTML = '...';
out = DU.normalizeOut(body, 'parsoidOnly');
if (out.length <= sizeLimit) { return out; }
const name = nodes[0].nodeName.toLowerCase();
const children = nodes[0].childNodes;
if (children.length === 0) {
return '<' + name + ' .../>';
} else {
return '<' + name + ' ...>...</' + name + '>';
}
} else {
out = '';
for (let i = 0; i < nodes.length; i++) {
out += toStringHelper(
[nodes[i]],
(sizeLimit - out.length) / (nodes.length - i)
);
}
return out;
}
};
// HTML escape helper
const toHtmlStr = function(node, v) {
if (typeof v === 'string') {
const div = node.ownerDocument.createElement('div');
div.textContent = v;
return div.innerHTML;
} else if (v instanceof PNodeList) {
return v.container.innerHTML;
} else {
return v.outerHTML;
}
};
/**
* The PNodeList class wraps a collection of DOM {@link Node}s.
* It provides methods that can be used to extract data from or
* modify the nodes. The `filter()` series of functions is very
* useful for extracting and iterating over, for example, all
* of the templates in the project (via {@link #filterTemplates}).
*/
class PNodeList {
/**
* @private
* @param {PDoc} pdoc The parent document for this {@link PNodeList}.
* @param {PNode|null} parent A {@link PNode} which will receive updates
* when this {@link PNodeList} is mutated.
* @param {Node} container A DOM {@link Node} which is the parent of all
* of the DOM {@link Node}s in this {@link PNodeList}. The container
* element itself is *not* considered part of the list.
* @param {Object} [opts]
* @param {Function} [opts.update]
* A function which will be invoked when {@link #update} is called.
*/
constructor(pdoc, parent, container, opts) {
this.pdoc = pdoc;
this.parent = parent;
this.container = container;
this._update = (opts && opts.update);
this._cachedPNodes = null;
}
/**
* Returns an {@link Array} of the DOM {@link Node}s represented
* by this {@link PNodeList}.
* @prop {Node[]}
*/
get nodes() {
return Array.from(this.container.childNodes);
}
/**
* Call {@link #update} after manually mutating any of the DOM
* {@link Node}s represented by this {@link PNodeList} in order to
* ensure that any containing templates are refreshed with their
* updated contents.
*
* The mutation methods in the {@link PDoc}/{@link PNodeList} API
* automatically call {@link #update} for you when required.
*/
update() {
this._cachedPNodes = null;
if (this._update) { this._update(); }
if (this.parent) { this.parent.update(); }
}
_querySelectorAll(selector) {
const tweakedSelector = ',' + selector + ',';
if (!(/,(COMMENT|TEXT),/.test(tweakedSelector))) {
// Use fast native querySelectorAll
return Array.from(this.container.querySelectorAll(selector));
}
// Implement comment/text node selector the hard way
/* eslint-disable no-bitwise */
let whatToShow = NodeFilter.SHOW_ELEMENT; // always show templates
if (/,COMMENT,/.test(tweakedSelector)) {
whatToShow |= NodeFilter.SHOW_COMMENT;
}
if (/,TEXT,/.test(tweakedSelector)) {
whatToShow |= NodeFilter.SHOW_TEXT;
}
/* eslint-enable no-bitwise */
const nodeFilter = (node) => {
if (node.nodeType !== Node.ELEMENT_NODE) {
return NodeFilter.FILTER_ACCEPT;
}
if (node.matches(PTemplate._selector)) {
return NodeFilter.FILTER_ACCEPT;
}
return NodeFilter.FILTER_SKIP;
};
const result = [];
const includeTemplates =
/,\[typeof~="mw:Transclusion"\],/.test(tweakedSelector);
const treeWalker = this.pdoc.document.createTreeWalker(
this.container, whatToShow, nodeFilter, false
);
while (treeWalker.nextNode()) {
const node = treeWalker.currentNode;
// We don't need the extra test for ELEMENT_NODEs yet, since
// non-template element nodes will be skipped by the nodeFilter
// above. But if we ever extend filter() to be fully generic,
// we might need the commented-out portion of this test.
if (
node.nodeType === Node.ELEMENT_NODE /* &&
node.matches(PTemplate._selector) */
) {
treeWalker.lastChild(); // always skip over all children
if (!includeTemplates) {
continue; // skip template itself
}
}
result.push(node);
}
return result;
}
_templatesForNode(node) {
// each Transclusion node could represent multiple templates.
const parent = this;
const result = [];
const parts = DU.getJSONAttribute(node, 'data-mw', {}).parts || [];
parts.forEach((part, i) => {
if (part.template) {
result.push(new PTemplate(parent.pdoc, parent, node, i));
}
});
return result;
}
/**
* @private
* @param {Array} result
* A result array to append new items to as they are found
* @param {string} selector
* CSS-style selector for the nodes of interest
* @param {Function} func
* Function to apply to every non-template match
* @param {Object} [opts]
* @param {boolean} [opts.recursive]
* Set to `false` to avoid recursing into templates.
*/
_filter(result, selector, func, opts) {
const recursive = (opts && opts.recursive) !== false;
let tSelector = PTemplate._selector;
if (selector) {
tSelector += ',' + selector;
}
this._querySelectorAll(tSelector).forEach((node) => {
const isTemplate = node.nodeType === Node.ELEMENT_NODE &&
node.matches(PTemplate._selector);
if (isTemplate) {
this._templatesForNode(node).forEach((t) => {
if (!selector) {
result.push(t);
}
if (recursive) {
t.params.forEach((k) => {
const td = t.get(k);
['key', 'value'].forEach((prop) => {
if (td[prop]) {
td[prop]._filter(result, selector, func, opts);
}
});
});
}
});
} else {
func(result, this, node, opts);
}
});
return result;
}
/**
* Return an array of {@link PComment} representing comments
* found in this {@link PNodeList}.
* @param {Object} [opts]
* @param {boolean} [opts.recursive]
* Set to `false` to avoid recursing into templates.
* @return {PComment[]}
*/
filterComments(opts) {
return this._filter([], PComment._selector, (r, parent, node) => {
r.push(new PComment(parent.pdoc, parent, node));
}, opts);
}
/**
* Return an array of {@link PExtLink} representing external links
* found in this {@link PNodeList}.
* @param {Object} [opts]
* @param {boolean} [opts.recursive]
* Set to `false` to avoid recursing into templates.
* @return {PExtLink[]}
*/
filterExtLinks(opts) {
return this._filter([], PExtLink._selector, (r, parent, node) => {
r.push(new PExtLink(parent.pdoc, parent, node));
}, opts);
}
/**
* Return an array of {@link PHeading} representing headings
* found in this {@link PNodeList}.
* @param {Object} [opts]
* @param {boolean} [opts.recursive]
* Set to `false` to avoid recursing into templates.
* @return {PHeading[]}
*/
filterHeadings(opts) {
return this._filter([], PHeading._selector, (r, parent, node) => {
r.push(new PHeading(parent.pdoc, parent, node));
}, opts);
}
/**
* Return an array of {@link PHtmlEntity} representing HTML entities
* found in this {@link PNodeList}.
* @param {Object} [opts]
* @param {boolean} [opts.recursive]
* Set to `false` to avoid recursing into templates.
* @return {PHtmlEntity[]}
*/
filterHtmlEntities(opts) {
return this._filter([], PHtmlEntity._selector, (r, parent, node) => {
r.push(new PHtmlEntity(parent.pdoc, parent, node));
}, opts);
}
/**
* Return an array of {@link PMedia} representing images or other
* media content found in this {@link PNodeList}.
* @param {Object} [opts]
* @param {boolean} [opts.recursive]
* Set to `false` to avoid recursing into templates.
* @return {PMedia[]}
*/
filterMedia(opts) {
return this._filter([], PMedia._selector, (r, parent, node) => {
r.push(new PMedia(parent.pdoc, parent, node));
}, opts);
}
/**
* Return an array of {@link PSection} representing sections
* found in this {@link PNodeList}.
* @param {Object} [opts]
* @param {boolean} [opts.recursive]
* Set to `false` to avoid recursing into templates.
* @return {PSection[]}
*/
filterSections(opts) {
return this._filter([], PSection._selector, (r, parent, node) => {
r.push(new PSection(parent.pdoc, parent, node));
}, opts);
}
/**
* Return an array of {@link PTemplate} representing templates
* found in this {@link PNodeList}.
* @param {Object} [opts]
* @param {boolean} [opts.recursive]
* Set to `false` to avoid recursing into templates.
* @return {PTemplate[]}
*/
filterTemplates(opts) {
return this._filter([], null, null, opts);
}
/**
* Return an array of {@link PText} representing plain text
* found in this {@link PNodeList}.
* @param {Object} [opts]
* @param {boolean} [opts.recursive]
* Set to `false` to avoid recursing into templates.
* @return {PText[]}
*/
filterText(opts) {
return this._filter([], PText._selector, (r, parent, node) => {
r.push(new PText(parent.pdoc, parent, node));
}, opts);
}
/**
* Return an array of {@link PWikiLink} representing wiki links
* found in this {@link PNodeList}.
* @param {Object} [opts]
* @param {boolean} [opts.recursive]
* Set to `false` to avoid recursing into templates.
* @return {PWikiLink[]}
*/
filterWikiLinks(opts) {
return this._filter([], PWikiLink._selector, (r, parent, node) => {
r.push(new PWikiLink(parent.pdoc, parent, node));
}, opts);
}
/**
* Internal list of PNodes in this list.
* @prop {PNode[]}
* @private
*/
get pnodes() {
if (this._cachedPNodes !== null) {
return this._cachedPNodes;
}
const templates = new Set();
const result = [];
/* eslint-disable no-labels */
OUTER: for (let i = 0; i < this.container.childNodes.length; i++) {
const node = this.container.childNodes.item(i);
if (node.nodeType === Node.TEXT_NODE) {
result.push(new PText(this.pdoc, this, node));
continue;
}
if (node.nodeType === Node.COMMENT_NODE) {
result.push(new PComment(this.pdoc, this, node));
continue;
}
if (node.nodeType === Node.ELEMENT_NODE) {
// Note: multiple PTemplates per Node, and possibly
// multiple Nodes per PTemplate.
if (node.matches(PTemplate._selector)) {
templates.add(node.getAttribute('about'));
this._templatesForNode(node).forEach((t) => {
result.push(t);
});
continue;
} else if (templates.has(node.getAttribute('about'))) {
continue;
}
// PTag is the catch-all; it should always be last.
const which = [
PExtLink, PHeading, PHtmlEntity, PMedia,
PSection, PWikiLink,
PTag,
];
for (let j = 0; j < which.length; j++) {
const Ty = which[j];
if (node.matches(Ty._selector)) {
result.push(new Ty(this.pdoc, this, node));
continue OUTER;
}
}
}
// Unknown type.
result.push(new PNode(this.pdoc, this, node));
}
/* eslint-enable no-labels */
return (this._cachedPNodes = result);
}
/**
* The number of nodes within the node list.
* @prop {number}
*/
get length() { return this.pnodes.length; }
/**
* Return the `index`th node within the node list.
* @param {number} index
* @return {PNode}
*/
get(index) { return this.pnodes[index]; }
/**
* Return the index of `target` in the list of nodes, or `-1` if
* the target was not found.
*
* If `recursive` is true, we will look in all nodes of ours and
* their descendants, and return the index of our direct descendant
* node which contains the target. Otherwise, the search is done
* only on direct descendants.
*
* If `fromIndex` is provided, it is the index to start the search
* at.
* @param {PNode|Node} target
* @param {Object} [options]
* @param {boolean} [options.recursive=false]
* @param {number} [options.fromIndex=0]
*/
indexOf(target, options) {
const recursive = Boolean(options && options.recursive);
const fromIndex = Number(options && options.fromIndex) || 0;
let child, children;
let i, j;
if (target instanceof PNode) {
target = target.node;
}
for (i = fromIndex; i < this.length; i++) {
child = this.get(i);
if (child.matches(target)) {
return i;
}
if (recursive) {
children = child._children();
for (j = 0; j < children.length; j++) {
if (children[j].indexOf(target, options) !== -1) {
return i;
}
}
}
}
return -1;
}
/**
* Return a string representing the contents of this object
* as HTML conforming to the
* [MediaWiki DOM specification](https://www.mediawiki.org/wiki/Parsoid/MediaWiki_DOM_spec).
* @return {string}
*/
toHtml() {
return this.container.innerHTML;
}
/**
* Return a promise for a string representing the contents of this
* object as wikitext.
* @return {Promise}
*/
toWikitext() {
return wts(this.pdoc.env, this.nodes);
}
/**
* Return a string representing the contents of this object for
* debugging. Some contents may be elided.
* @return {string}
*/
toString() {
return toStringHelper(this.nodes);
}
/**
* Create a {@link PNodeList} from a string containing HTML.
* @return {PNodeList}
*/
static fromHTML(pdoc, html) {
const div = pdoc.document.createElement('div');
div.innerHTML = html;
return new PNodeList(pdoc, null, div);
}
/**
* Create a {@link PNodeList} belonging to the given {@link PDoc}
* from a string containing wikitext.
* @param {PDoc} pdoc
* The {@link PDoc} which will own the result.
* @param {string} wikitext
* The wikitext to convert.
* @param {Object} options
* Options which are passed to {@link Parsoid#parse}.
* @return {Promise}
* Fulfilled by a {@link PNodeList} representing the given wikitext.
*/
static fromWikitext(pdoc, wikitext, options) {
throw new Error("Implemented elsewhere.");
}
}
/**
* A PNode represents a specific DOM {@link Node}. Its subclasses provide
* specific accessors and mutators for associated semantic information.
*
* Useful subclasses of {@link PNode} include:
*
* - {@link PComment}: comments, like `<!-- example -->`
* - {@link PExtLink}: external links, like `[http://example.com Example]`
* - {@link PHeading}: headings, like `== Section 1 ==`
* - {@link PHtmlEntity}: html entities, like ` `
* - {@link PMedia}: images and media, like `[[File:Foo.jpg|caption]]`
* - {@link PSection}: section; wraps a PHeading and its contents
* - {@link PTag}: other HTML tags, like `<span>`
* - {@link PTemplate}: templates, like `{{foo|bar}}`
* - {@link PText}: unformatted text, like `foo`
* - {@link PWikiLink}: wiki links, like `[[Foo|bar]]`
*/
class PNode {
/**
* @private
* @param {PDoc} pdoc The parent document for this PNode.
* @param {PNodeList|null} parent A containing node list which will receive
* updates when this {@link PNode} is mutated.
* @param {Node} node The DOM node.
* @param {Object} [opts]
* @param {Function} [opts.update]
* A function which will be invoked when {@link #update} is called.
* @param {Function} [opts.wtsNodes]
* A function returning an array of {@link Node}s which can tweak the
* portion of the document serialized by {@link #toWikitext}.
*/
constructor(pdoc, parent, node, opts) {
/** @prop {PDoc} pdoc The parent document for this {@link PNode}. */
this.pdoc = pdoc;
this.parent = parent;
/** @prop {Node} node The underlying DOM {@link Node}. */
this.node = node;
this._update = (opts && opts.update);
this._wtsNodes = (opts && opts.wtsNodes);
}
get ownerDocument() { return this.node.ownerDocument; }
get dataMw() {
return DU.getJSONAttribute(this.node, 'data-mw', {});
}
set dataMw(v) {
DU.setJSONAttribute(this.node, 'data-mw', v);
this.update();
}
/**
* Internal helper: enumerate all PNodeLists contained within this node.
* @private
* @return {PNodeList[]}
*/
_children() { return []; }
/**
* Call {@link #update} after manually mutating the DOM {@link Node}
* associated with this {@link PNode} in order to ensure that any
* containing templates are refreshed with their updated contents.
*
* The mutation methods in the API automatically call {@link #update}
* for you when required.
*/
update() {
if (this._update) { this._update(); }
if (this.parent) { this.parent.update(); }
}
/**
* Returns true if the `target` matches this node. By default a
* node matches only if its #node is strictly equal to the target
* or the target's #node. Subclasses can override this to provide
* more flexible matching: for example see {@link PText#matches}.
* @param {Node|PNode} target
* @return {boolean} true if the target matches this node, false otherwise.
*/
matches(target) {
return (target === this) || (target === this.node) ||
(target instanceof PNode && target.node === this.node);
}
/**
* @inheritdoc
*/
toHtml() {
const nodes = this._wtsNodes ? this._wtsNodes() : [ this.node ];
return nodes.map(function(n) { return n.outerHTML; }).join('');
}
/**
* @inheritdoc
*/
toWikitext() {
const nodes = this._wtsNodes ? this._wtsNodes() : [ this.node ];
return wts(this.pdoc.env, nodes);
}
/**
* @inheritdoc
*/
toString() {
const nodes = this._wtsNodes ? this._wtsNodes() : [ this.node ];
return toStringHelper(nodes);
}
}
// Helper: getter and setter for the inner contents of a node.
const innerAccessorGet = function(self) {
return new PNodeList(self.pdoc, self, self.node);
};
const innerAccessorSet = function(self, v) {
self.node.innerHTML = toHtmlStr(self.node, v);
self.update();
};
/**
* PTag represents any otherwise-unmatched tag. This includes
* HTML-style tags in wikicode, like `<span>`, as well as some
* "invisible" tags like `<p>`.
* @extends PNode
*/
class PTag extends PNode {
/**
* The name of the tag, in lowercase.
*/
get tagName() { return this.node.tagName.toLowerCase(); }
/**
* The contents of the tag, as a {@PNodeList} object.
* You can assign a String, Node, or PNodeList to mutate the contents.
* @prop {PNodeList}
*/
get contents() { return innerAccessorGet(this); }
set contents(v) { innerAccessorSet(this, v); }
_children() { return [this.contents]; }
}
/**
* @ignore
* @static
* @private
*/
PTag._selector = '*'; // any otherwise-unmatched element
/**
* PComment represents a hidden HTML comment, like `<!-- fobar -->`.
* @extends PNode
*/
class PComment extends PNode {
/**
* The hidden text contained between `<!--` and `-->`.
* @prop {string}
*/
get contents() {
return DU.decodeComment(this.node.data);
}
set contents(v) {
this.node.data = DU.encodeComment(v);
this.update();
}
}
/**
* @ignore
* @static
* @private
*/
PComment._selector = 'COMMENT'; // non-standard selector
/**
* PExtLink represents an external link, like `[http://example.com Example]`.
* @extends PNode
*/
class PExtLink extends PNode {
/**
* The name of the tag, in lowercase.
*/
get tagName() { return this.node.tagName.toLowerCase(); }
/**
* The URL of the link target.
* @prop {string}
*/
get url() {
// XXX url should be a PNodeList, but that requires handling
// typeof="mw:ExpandedAttrs"
return this.node.getAttribute('href');
}
set url(v) {
this.node.setAttribute('href', v);
}
/**
* The link title, as a {@link PNodeList}.
* You can assign a String, Node, or PNodeList to mutate the title.
* @prop {PNodeList}
*/
get title() { return innerAccessorGet(this); }
set title(v) { innerAccessorSet(this, v); }
// XXX include this.url, once it is a PNodeList
_children() { return [this.title]; }
}
/**
* @ignore
* @static
* @private
*/
PExtLink._selector = 'a[rel="mw:ExtLink"]';
/**
* PHeading represents a section heading in wikitext, like `== Foo ==`.
* @extends PNode
*/
class PHeading extends PNode {
/**
* The name of the tag, in lowercase.
*/
get tagName() { return this.node.tagName.toLowerCase(); }
/**
* The heading level, as an integer between 1 and 6 inclusive.
* @prop {number}
*/
get level() {
return +this.node.nodeName.slice(1);
}
set level(v) {
v = +v;
if (v === this.level) {
return;
} else if (v >= 1 && v <= 6) {
const nh = this.ownerDocument.createElement('h' + v);
while (this.node.firstChild !== null) {
nh.appendChild(this.node.firstChild);
}
this.node.parentNode.replaceChild(nh, this.node);
this.node = nh;
this.update();
} else {
throw new Error("Level must be between 1 and 6, inclusive.");
}
}
/**
* The title of the heading, as a {@link PNodeList}.
* You can assign a String, Node, or PNodeList to mutate the title.
* @prop {PNodeList}
*/
get title() { return innerAccessorGet(this); }
set title(v) { innerAccessorSet(this, v); }
_children() { return [this.title]; }
}
/**
* @ignore
* @static
* @private
*/
PHeading._selector = 'h1,h2,h3,h4,h5,h6';
/**
* PHtmlEntity represents an HTML entity, like ` `.
* @extends PNode
*/
class PHtmlEntity extends PNode {
/**
* The character represented by the HTML entity.
* @prop {string}
*/
get normalized() { return this.node.textContent; }
set normalized(v) {
this.node.textContent = v;
this.node.removeAttribute('data-parsoid');
this.update();
}
/**
* Extends {@link PNode#matches} to allow a target string to match
* if it matches this node's #normalized character.
* @inheritdoc
* @param {Node|PNode|string} target
*/
matches(target) {
return super.matches(target) || this.normalized === target;
}
}
/**
* @ignore
* @static
* @private
*/
PHtmlEntity._selector = '[typeof="mw:Entity"]';
/**
* PMedia represents an image or audio/video element in wikitext,
* like `[[File:Foobar.jpg|caption]]`.
* @extends PNode
*/
class PMedia extends PNode {
/**
* The name of the tag, in lowercase.
*/
get tagName() { return this.node.tagName.toLowerCase(); }
// Internal helper: is the outer element a <figure> or a <span>?
get _isBlock() { return this.node.tagName === 'FIGURE'; }
// Internal helper: get at the 'caption' property in the dataMw
get _caption() {
const c = this.dataMw.caption;
return c === undefined ? null : c;
}
set _caption(v) {
const dmw = this.dataMw;
if (v === undefined || v === null) {
delete dmw.caption;
} else {
dmw.caption = v;
}
this.dataMw = dmw;
}
/**
* The caption of the image or media file, or `null` if not present.
* You can assign `null`, a String, Node, or PNodeList to mutate the
* contents.
* @prop {PNodeList|null}
*/
get caption() {
let c, captionDiv;
// Note that _cachedNodeList is null if caption is missing.
if (this._cachedNodeList === undefined) {
if (this._isBlock) {
c = this.node.firstChild.nextSibling;
this._cachedNodeList =
c ? new PNodeList(this.pdoc, this, c) : null;
} else {
c = this._caption;
if (c === null) {
this._cachedNodeList = null;
} else {
captionDiv = this.ownerDocument.createElement('div');
captionDiv.innerHTML = c;
this._cachedNodeList = new PNodeList(
this.pdoc, this, captionDiv, {
update: function() {
this.parent._caption = this.container.innerHTML;
},
});
}
}
}
return this._cachedNodeList;
}
set caption(v) {
this._cachedNodeList = undefined;
if (this._isBlock) {
let c = this.node.firstChild.nextSibling;
if (v === null || v === undefined) {
if (c) {
this.node.removeChild(c);
this.update();
}
} else {
if (!c) {
c = this.ownerDocument.createElement('figcaption');
this.node.appendChild(c);
}
c.innerHTML = toHtmlStr(c, v);
this.update();
}
} else {
this._caption = (v === null || v === undefined) ? v :
toHtmlStr(this.node, v);
this.update();
}
}
_children() {
const c = this.caption;
return c ? [ c ] : [];
}
}
/**
* @ignore
* @static
* @private
*/
PMedia._selector = 'figure,[typeof~="mw:Image"]';
/**
* PSection represents an internal wikilink, like `[[Foo|Bar]]`.
* @extends PTag
*/
class PSection extends PTag {
/**
* The section id. 0 is the lead section, negative numbers are used for
* "pseudo-sections".
* @prop {number}
*/
get sectionId() {
return +this.node.getAttribute('data-mw-section-id');
}
}
/**
* @ignore
* @static
* @private
*/
PSection._selector = 'section';
/**
* PTemplate represents a wikitext template, like `{{foo}}`.
* @extends PNode
*/
class PTemplate extends PNode {
/**
* @private
* @param {PDoc} pdoc The parent document for this PNode.
* @param {PNodeList|null} parent A containing node list which will receive
* updates when this {@link PNode} is mutated.
* @param {Node} node The DOM node.
* @param {number} which A single {@link Node} can represent multiple
* templates; this parameter serves to distinguish them.
*/
constructor(pdoc, parent, node, which) {
super(pdoc, parent, node, {
wtsNodes: function() {
// Templates are actually a collection of nodes.
return this.parent._querySelectorAll('[about="' + this.node.getAttribute('about') + '"]');
},
});
this.which = which;
this._cachedParams = Object.create(null);
}
get _template() {
return this.dataMw.parts[this.which];
}
set _template(v) {
const dmw = this.dataMw;
dmw.parts[this.which] = v;
this.dataMw = dmw;
}
/**
* The name of the template, as a String.
*
* See: [T107194](https://phabricator.wikimedia.org/T107194)
* @prop {string}
*/
get name() {
// This should really be a PNodeList; see T107194
return this._template.template.target.wt;
}
set name(v) {
const t = this._template;
t.template.target.wt = v;