Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(644)

Side by Side Diff: pkg/third_party/html5lib/lib/dom.dart

Issue 22375011: move html5lib code into dart svn repo (Closed) Base URL: https://dart.googlecode.com/svn/branches/bleeding_edge/dart
Patch Set: change location of html5lib to pkg/third_party/html5lib Created 7 years, 4 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch | Annotate | Revision Log
OLDNEW
(Empty)
1 /**
2 * A simple tree API that results from parsing html. Intended to be compatible
3 * with dart:html, but right now it resembles the classic JS DOM.
4 */
5 library dom;
6
7 import 'dart:collection';
8 import 'package:source_maps/span.dart' show FileSpan;
9
10 import 'src/constants.dart';
11 import 'src/list_proxy.dart';
12 import 'src/token.dart';
13 import 'src/tokenizer.dart';
14 import 'src/treebuilder.dart';
15 import 'src/utils.dart';
16 import 'dom_parsing.dart';
17 import 'parser.dart';
18
19 // TODO(jmesserly): this needs to be replaced by an AttributeMap for attributes
20 // that exposes namespace info.
21 class AttributeName implements Comparable {
22 /** The namespace prefix, e.g. `xlink`. */
23 final String prefix;
24
25 /** The attribute name, e.g. `title`. */
26 final String name;
27
28 /** The namespace url, e.g. `http://www.w3.org/1999/xlink` */
29 final String namespace;
30
31 const AttributeName(this.prefix, this.name, this.namespace);
32
33 String toString() {
34 // Implement:
35 // http://www.whatwg.org/specs/web-apps/current-work/multipage/the-end.html# serializing-html-fragments
36 // If we get here we know we are xml, xmlns, or xlink, because of
37 // [HtmlParser.adjustForeignAttriubtes] is the only place we create
38 // an AttributeName.
39 return prefix != null ? '$prefix:$name' : name;
40 }
41
42 int get hashCode {
43 int h = prefix.hashCode;
44 h = 37 * (h & 0x1FFFFF) + name.hashCode;
45 h = 37 * (h & 0x1FFFFF) + namespace.hashCode;
46 return h & 0x3FFFFFFF;
47 }
48
49 int compareTo(other) {
50 // Not sure about this sort order
51 if (other is! AttributeName) return 1;
52 int cmp = (prefix != null ? prefix : "").compareTo(
53 (other.prefix != null ? other.prefix : ""));
54 if (cmp != 0) return cmp;
55 cmp = name.compareTo(other.name);
56 if (cmp != 0) return cmp;
57 return namespace.compareTo(other.namespace);
58 }
59
60 bool operator ==(x) {
61 if (x is! AttributeName) return false;
62 return prefix == x.prefix && name == x.name && namespace == x.namespace;
63 }
64 }
65
66 /** Really basic implementation of a DOM-core like Node. */
67 abstract class Node {
68 static const int ATTRIBUTE_NODE = 2;
69 static const int CDATA_SECTION_NODE = 4;
70 static const int COMMENT_NODE = 8;
71 static const int DOCUMENT_FRAGMENT_NODE = 11;
72 static const int DOCUMENT_NODE = 9;
73 static const int DOCUMENT_TYPE_NODE = 10;
74 static const int ELEMENT_NODE = 1;
75 static const int ENTITY_NODE = 6;
76 static const int ENTITY_REFERENCE_NODE = 5;
77 static const int NOTATION_NODE = 12;
78 static const int PROCESSING_INSTRUCTION_NODE = 7;
79 static const int TEXT_NODE = 3;
80
81 // TODO(jmesserly): this should be on Element
82 /** The tag name associated with the node. */
83 final String tagName;
84
85 /** The parent of the current node (or null for the document node). */
86 Node parent;
87
88 // TODO(jmesserly): should move to Element.
89 /**
90 * A map holding name, value pairs for attributes of the node.
91 *
92 * Note that attribute order needs to be stable for serialization, so we use a
93 * LinkedHashMap. Each key is a [String] or [AttributeName].
94 */
95 LinkedHashMap<dynamic, String> attributes = new LinkedHashMap();
96
97 /**
98 * A list of child nodes of the current node. This must
99 * include all elements but not necessarily other node types.
100 */
101 final NodeList nodes = new NodeList._();
102
103 List<Element> _elements;
104
105 // TODO(jmesserly): consider using an Expando for this, and put it in
106 // dom_parsing. Need to check the performance affect.
107 /** The source span of this node, if it was created by the [HtmlParser]. */
108 FileSpan sourceSpan;
109
110 /** The attribute spans if requested. Otherwise null. */
111 LinkedHashMap<dynamic, FileSpan> _attributeSpans;
112 LinkedHashMap<dynamic, FileSpan> _attributeValueSpans;
113
114 Node(this.tagName) {
115 nodes._parent = this;
116 }
117
118 /**
119 * If [sourceSpan] is available, this contains the spans of each attribute.
120 * The span of an attribute is the entire attribute, including the name and
121 * quotes (if any). For example, the span of "attr" in `<a attr="value">`
122 * would be the text `attr="value"`.
123 */
124 LinkedHashMap<dynamic, FileSpan> get attributeSpans {
125 _ensureAttributeSpans();
126 return _attributeSpans;
127 }
128
129 /**
130 * If [sourceSpan] is available, this contains the spans of each attribute's
131 * value. Unlike [attributeSpans], this span will inlcude only the value.
132 * For example, the value span of "attr" in `<a attr="value">` would be the
133 * text `value`.
134 */
135 LinkedHashMap<dynamic, FileSpan> get attributeValueSpans {
136 _ensureAttributeSpans();
137 return _attributeValueSpans;
138 }
139
140 List<Element> get children {
141 if (_elements == null) {
142 _elements = new FilteredElementList(this);
143 }
144 return _elements;
145 }
146
147 // TODO(jmesserly): needs to support deep clone.
148 /**
149 * Return a shallow copy of the current node i.e. a node with the same
150 * name and attributes but with no parent or child nodes.
151 */
152 Node clone();
153
154 String get namespace => null;
155
156 // TODO(jmesserly): do we need this here?
157 /** The value of the current node (applies to text nodes and comments). */
158 String get value => null;
159
160 // TODO(jmesserly): this is a workaround for http://dartbug.com/4754
161 int get $dom_nodeType => nodeType;
162
163 int get nodeType;
164
165 String get outerHtml {
166 var str = new StringBuffer();
167 _addOuterHtml(str);
168 return str.toString();
169 }
170
171 String get innerHtml {
172 var str = new StringBuffer();
173 _addInnerHtml(str);
174 return str.toString();
175 }
176
177 set innerHtml(String value) {
178 nodes.clear();
179 // TODO(jmesserly): should be able to get the same effect by adding the
180 // fragment directly.
181 nodes.addAll(parseFragment(value, container: tagName).nodes);
182 }
183
184 void _addOuterHtml(StringBuffer str);
185
186 void _addInnerHtml(StringBuffer str) {
187 for (Node child in nodes) child._addOuterHtml(str);
188 }
189
190 String toString() => tagName;
191
192 Node remove() {
193 // TODO(jmesserly): is parent == null an error?
194 if (parent != null) {
195 parent.nodes.remove(this);
196 }
197 return this;
198 }
199
200 /**
201 * Insert [node] as a child of the current node, before [refNode] in the
202 * list of child nodes. Raises [UnsupportedOperationException] if [refNode]
203 * is not a child of the current node. If refNode is null, this adds to the
204 * end of the list.
205 */
206 void insertBefore(Node node, Node refNode) {
207 if (refNode == null) {
208 nodes.add(node);
209 } else {
210 nodes.insert(nodes.indexOf(refNode), node);
211 }
212 }
213
214 /** Replaces this node with another node. */
215 Node replaceWith(Node otherNode) {
216 if (parent == null) {
217 throw new UnsupportedError('Node must have a parent to replace it.');
218 }
219 parent.nodes[parent.nodes.indexOf(this)] = otherNode;
220 return this;
221 }
222
223 // TODO(jmesserly): should this be a property or remove?
224 /** Return true if the node has children or text. */
225 bool hasContent() => nodes.length > 0;
226
227 Pair<String, String> get nameTuple {
228 var ns = namespace != null ? namespace : Namespaces.html;
229 return new Pair(ns, tagName);
230 }
231
232 /**
233 * Move all the children of the current node to [newParent].
234 * This is needed so that trees that don't store text as nodes move the
235 * text in the correct way.
236 */
237 void reparentChildren(Node newParent) {
238 newParent.nodes.addAll(nodes);
239 nodes.clear();
240 }
241
242 /**
243 * Seaches for the first descendant node matching the given selectors, using a
244 * preorder traversal. NOTE: right now, this supports only a single type
245 * selectors, e.g. `node.query('div')`.
246 */
247 Element query(String selectors) => _queryType(_typeSelector(selectors));
248
249 /**
250 * Returns all descendant nodes matching the given selectors, using a
251 * preorder traversal. NOTE: right now, this supports only a single type
252 * selectors, e.g. `node.queryAll('div')`.
253 */
254 List<Element> queryAll(String selectors) {
255 var results = new List<Element>();
256 _queryAllType(_typeSelector(selectors), results);
257 return results;
258 }
259
260 bool hasChildNodes() => !nodes.isEmpty;
261
262 bool contains(Node node) => nodes.contains(node);
263
264 String _typeSelector(String selectors) {
265 selectors = selectors.trim();
266 if (!_isTypeSelector(selectors)) {
267 throw new UnimplementedError('only type selectors are implemented');
268 }
269 return selectors;
270 }
271
272 /**
273 * Checks if this is a type selector.
274 * See <http://www.w3.org/TR/CSS2/grammar.html>.
275 * Note: this doesn't support '*', the universal selector, non-ascii chars or
276 * escape chars.
277 */
278 bool _isTypeSelector(String selector) {
279 // Parser:
280
281 // element_name
282 // : IDENT | '*'
283 // ;
284
285 // Lexer:
286
287 // nmstart [_a-z]|{nonascii}|{escape}
288 // nmchar [_a-z0-9-]|{nonascii}|{escape}
289 // ident -?{nmstart}{nmchar}*
290 // nonascii [\240-\377]
291 // unicode \\{h}{1,6}(\r\n|[ \t\r\n\f])?
292 // escape {unicode}|\\[^\r\n\f0-9a-f]
293
294 // As mentioned above, no nonascii or escape support yet.
295 int len = selector.length;
296 if (len == 0) return false;
297
298 int i = 0;
299 const int DASH = 45;
300 if (selector.codeUnitAt(i) == DASH) i++;
301
302 if (i >= len || !isLetter(selector[i])) return false;
303 i++;
304
305 for (; i < len; i++) {
306 if (!isLetterOrDigit(selector[i]) && selector.codeUnitAt(i) != DASH) {
307 return false;
308 }
309 }
310
311 return true;
312 }
313
314 Element _queryType(String tag) {
315 for (var node in nodes) {
316 if (node is! Element) continue;
317 if (node.tagName == tag) return node;
318 var result = node._queryType(tag);
319 if (result != null) return result;
320 }
321 return null;
322 }
323
324 void _queryAllType(String tag, List<Element> results) {
325 for (var node in nodes) {
326 if (node is! Element) continue;
327 if (node.tagName == tag) results.add(node);
328 node._queryAllType(tag, results);
329 }
330 }
331
332 /** Initialize [attributeSpans] using [sourceSpan]. */
333 void _ensureAttributeSpans() {
334 if (_attributeSpans != null) return;
335
336 _attributeSpans = new LinkedHashMap<dynamic, FileSpan>();
337 _attributeValueSpans = new LinkedHashMap<dynamic, FileSpan>();
338
339 if (sourceSpan == null) return;
340
341 var tokenizer = new HtmlTokenizer(sourceSpan.text, generateSpans: true,
342 attributeSpans: true);
343
344 tokenizer.moveNext();
345 var token = tokenizer.current as StartTagToken;
346
347 if (token.attributeSpans == null) return; // no attributes
348
349 for (var attr in token.attributeSpans) {
350 var offset = sourceSpan.start.offset;
351 _attributeSpans[attr.name] = sourceSpan.file.span(
352 offset + attr.start, offset + attr.end);
353 if (attr.startValue != null) {
354 _attributeValueSpans[attr.name] = sourceSpan.file.span(
355 offset + attr.startValue, offset + attr.endValue);
356 }
357 }
358 }
359 }
360
361 class Document extends Node {
362 Document() : super(null);
363 factory Document.html(String html) => parse(html);
364
365 int get nodeType => Node.DOCUMENT_NODE;
366
367 // TODO(jmesserly): optmize this if needed
368 Element get head => query('html').query('head');
369 Element get body => query('html').query('body');
370
371 String toString() => "#document";
372
373 void _addOuterHtml(StringBuffer str) => _addInnerHtml(str);
374
375 Document clone() => new Document();
376 }
377
378 class DocumentFragment extends Document {
379 DocumentFragment();
380 factory DocumentFragment.html(String html) => parseFragment(html);
381
382 int get nodeType => Node.DOCUMENT_FRAGMENT_NODE;
383
384 String toString() => "#document-fragment";
385
386 DocumentFragment clone() => new DocumentFragment();
387 }
388
389 class DocumentType extends Node {
390 final String publicId;
391 final String systemId;
392
393 DocumentType(String name, this.publicId, this.systemId) : super(name);
394
395 int get nodeType => Node.DOCUMENT_TYPE_NODE;
396
397 String toString() {
398 if (publicId != null || systemId != null) {
399 // TODO(jmesserly): the html5 serialization spec does not add these. But
400 // it seems useful, and the parser can handle it, so for now keeping it.
401 var pid = publicId != null ? publicId : '';
402 var sid = systemId != null ? systemId : '';
403 return '<!DOCTYPE $tagName "$pid" "$sid">';
404 } else {
405 return '<!DOCTYPE $tagName>';
406 }
407 }
408
409
410 void _addOuterHtml(StringBuffer str) {
411 str.write(toString());
412 }
413
414 DocumentType clone() => new DocumentType(tagName, publicId, systemId);
415 }
416
417 class Text extends Node {
418 // TODO(jmesserly): this should be text?
419 String value;
420
421 Text(this.value) : super(null);
422
423 int get nodeType => Node.TEXT_NODE;
424
425 String toString() => '"$value"';
426
427 void _addOuterHtml(StringBuffer str) {
428 // Don't escape text for certain elements, notably <script>.
429 if (rcdataElements.contains(parent.tagName) ||
430 parent.tagName == 'plaintext') {
431 str.write(value);
432 } else {
433 str.write(htmlSerializeEscape(value));
434 }
435 }
436
437 Text clone() => new Text(value);
438 }
439
440 class Element extends Node {
441 final String namespace;
442
443 // TODO(jmesserly): deprecate in favor of Element.tag? Or rename?
444 Element(String name, [this.namespace]) : super(name);
445
446 Element.tag(String name) : namespace = null, super(name);
447
448 static final _START_TAG_REGEXP = new RegExp('<(\\w+)');
449
450 static final _CUSTOM_PARENT_TAG_MAP = const {
451 'body': 'html',
452 'head': 'html',
453 'caption': 'table',
454 'td': 'tr',
455 'colgroup': 'table',
456 'col': 'colgroup',
457 'tr': 'tbody',
458 'tbody': 'table',
459 'tfoot': 'table',
460 'thead': 'table',
461 'track': 'audio',
462 };
463
464 // TODO(jmesserly): this is from dart:html _ElementFactoryProvider...
465 // TODO(jmesserly): have a look at fixing some things in dart:html, in
466 // particular: is the parent tag map complete? Is it faster without regexp?
467 // TODO(jmesserly): for our version we can do something smarter in the parser.
468 // All we really need is to set the correct parse state.
469 factory Element.html(String html) {
470
471 // TODO(jacobr): this method can be made more robust and performant.
472 // 1) Cache the dummy parent elements required to use innerHTML rather than
473 // creating them every call.
474 // 2) Verify that the html does not contain leading or trailing text nodes.
475 // 3) Verify that the html does not contain both <head> and <body> tags.
476 // 4) Detatch the created element from its dummy parent.
477 String parentTag = 'div';
478 String tag;
479 final match = _START_TAG_REGEXP.firstMatch(html);
480 if (match != null) {
481 tag = match.group(1).toLowerCase();
482 if (_CUSTOM_PARENT_TAG_MAP.containsKey(tag)) {
483 parentTag = _CUSTOM_PARENT_TAG_MAP[tag];
484 }
485 }
486
487 var fragment = parseFragment(html, container: parentTag);
488 Element element;
489 if (fragment.children.length == 1) {
490 element = fragment.children[0];
491 } else if (parentTag == 'html' && fragment.children.length == 2) {
492 // You'll always get a head and a body when starting from html.
493 element = fragment.children[tag == 'head' ? 0 : 1];
494 } else {
495 throw new ArgumentError('HTML had ${fragment.children.length} '
496 'top level elements but 1 expected');
497 }
498 element.remove();
499 return element;
500 }
501
502 int get nodeType => Node.ELEMENT_NODE;
503
504 String toString() {
505 if (namespace == null) return "<$tagName>";
506 return "<${Namespaces.getPrefix(namespace)} $tagName>";
507 }
508
509 void _addOuterHtml(StringBuffer str) {
510 // http://www.whatwg.org/specs/web-apps/current-work/multipage/the-end.html# serializing-html-fragments
511 // Element is the most complicated one.
512 if (namespace == null ||
513 namespace == Namespaces.html ||
514 namespace == Namespaces.mathml ||
515 namespace == Namespaces.svg) {
516 str.write('<$tagName');
517 } else {
518 // TODO(jmesserly): the spec doesn't define "qualified name".
519 // I'm not sure if this is correct, but it should parse reasonably.
520 str.write('<${Namespaces.getPrefix(namespace)}:$tagName');
521 }
522
523 if (attributes.length > 0) {
524 attributes.forEach((key, v) {
525 // Note: AttributeName.toString handles serialization of attribute
526 // namespace, if needed.
527 str.write(' $key="${htmlSerializeEscape(v, attributeMode: true)}"');
528 });
529 }
530
531 str.write('>');
532
533 if (nodes.length > 0) {
534 if (tagName == 'pre' || tagName == 'textarea' || tagName == 'listing') {
535 if (nodes[0] is Text && nodes[0].value.startsWith('\n')) {
536 // These nodes will remove a leading \n at parse time, so if we still
537 // have one, it means we started with two. Add it back.
538 str.write('\n');
539 }
540 }
541
542 _addInnerHtml(str);
543 }
544
545 // void elements must not have an end tag
546 // http://dev.w3.org/html5/markup/syntax.html#void-elements
547 if (!isVoidElement(tagName)) str.write('</$tagName>');
548 }
549
550 Element clone() => new Element(tagName, namespace)
551 ..attributes = new LinkedHashMap.from(attributes);
552
553 String get id {
554 var result = attributes['id'];
555 return result != null ? result : '';
556 }
557
558 set id(String value) {
559 if (value == null) {
560 attributes.remove('id');
561 } else {
562 attributes['id'] = value;
563 }
564 }
565 }
566
567 class Comment extends Node {
568 final String data;
569
570 Comment(this.data) : super(null);
571
572 int get nodeType => Node.COMMENT_NODE;
573
574 String toString() => "<!-- $data -->";
575
576 void _addOuterHtml(StringBuffer str) {
577 str.write("<!--$data-->");
578 }
579
580 Comment clone() => new Comment(data);
581 }
582
583
584 // TODO(jmesserly): fix this to extend one of the corelib classes if possible.
585 // (The requirement to remove the node from the old node list makes it tricky.)
586 // TODO(jmesserly): is there any way to share code with the _NodeListImpl?
587 class NodeList extends ListProxy<Node> {
588 // Note: this is conceptually final, but because of circular reference
589 // between Node and NodeList we initialize it after construction.
590 Node _parent;
591
592 NodeList._();
593
594 Node get first => this[0];
595
596 Node _setParent(Node node) {
597 // Note: we need to remove the node from its previous parent node, if any,
598 // before updating its parent pointer to point at our parent.
599 node.remove();
600 node.parent = _parent;
601 return node;
602 }
603
604 void add(Node value) {
605 super.add(_setParent(value));
606 }
607
608 void addLast(Node value) => add(value);
609
610 void addAll(Iterable<Node> collection) {
611 // Note: we need to be careful if collection is another NodeList.
612 // In particular:
613 // 1. we need to copy the items before updating their parent pointers,
614 // 2. we should update parent pointers in reverse order. That way they
615 // are removed from the original NodeList (if any) from the end, which
616 // is faster.
617 var list = (collection is NodeList || collection is! List)
618 ? collection.toList() : collection as List;
619 for (var node in list.reversed) _setParent(node);
620 super.addAll(list);
621 }
622
623 void insert(int index, Node value) {
624 super.insert(index, _setParent(value));
625 }
626
627 Node removeLast() => super.removeLast()..parent = null;
628
629 Node removeAt(int i) => super.removeAt(i)..parent = null;
630
631 void clear() {
632 for (var node in this) node.parent = null;
633 super.clear();
634 }
635
636 void operator []=(int index, Node value) {
637 this[index].parent = null;
638 super[index] = _setParent(value);
639 }
640
641 // TODO(jmesserly): These aren't implemented in DOM _NodeListImpl, see
642 // http://code.google.com/p/dart/issues/detail?id=5371
643 void setRange(int start, int rangeLength, List<Node> from,
644 [int startFrom = 0]) {
645 if (from is NodeList) {
646 // Note: this is presumed to make a copy
647 from = from.sublist(startFrom, startFrom + rangeLength);
648 }
649 // Note: see comment in [addAll]. We need to be careful about the order of
650 // operations if [from] is also a NodeList.
651 for (int i = rangeLength - 1; i >= 0; i--) {
652 this[start + i].parent = null;
653 super[start + i] = _setParent(from[startFrom + i]);
654 }
655 }
656
657 void replaceRange(int start, int end, Iterable<Node> newContents) {
658 removeRange(start, end);
659 insertAll(start, newContents);
660 }
661
662 void removeRange(int start, int rangeLength) {
663 for (int i = start; i < rangeLength; i++) this[i].parent = null;
664 super.removeRange(start, rangeLength);
665 }
666
667 void removeWhere(bool test(Element e)) {
668 for (var node in where(test)) {
669 node.parent = null;
670 }
671 super.removeWhere(test);
672 }
673
674 void retainWhere(bool test(Element e)) {
675 for (var node in where((n) => !test(n))) {
676 node.parent = null;
677 }
678 super.retainWhere(test);
679 }
680
681 void insertAll(int index, List<Node> nodes) {
682 for (var node in nodes) _setParent(node);
683 super.insertAll(index, nodes);
684 }
685 }
686
687
688 /**
689 * An indexable collection of a node's descendants in the document tree,
690 * filtered so that only elements are in the collection.
691 */
692 // TODO(jmesserly): this was copied from dart:html
693 // TODO(jmesserly): "implements List<Element>" is a workaround for analyzer bug.
694 class FilteredElementList extends IterableBase<Element> with ListMixin<Element>
695 implements List<Element> {
696
697 final Node _node;
698 final List<Node> _childNodes;
699
700 /**
701 * Creates a collection of the elements that descend from a node.
702 *
703 * Example usage:
704 *
705 * var filteredElements = new FilteredElementList(query("#container"));
706 * // filteredElements is [a, b, c].
707 */
708 FilteredElementList(Node node): _childNodes = node.nodes, _node = node;
709
710 // We can't memoize this, since it's possible that children will be messed
711 // with externally to this class.
712 //
713 // TODO(nweiz): we don't always need to create a new list. For example
714 // forEach, every, any, ... could directly work on the _childNodes.
715 List<Element> get _filtered =>
716 new List<Element>.from(_childNodes.where((n) => n is Element));
717
718 void forEach(void f(Element element)) {
719 _filtered.forEach(f);
720 }
721
722 void operator []=(int index, Element value) {
723 this[index].replaceWith(value);
724 }
725
726 void set length(int newLength) {
727 final len = this.length;
728 if (newLength >= len) {
729 return;
730 } else if (newLength < 0) {
731 throw new ArgumentError("Invalid list length");
732 }
733
734 removeRange(newLength, len);
735 }
736
737 String join([String separator = ""]) => _filtered.join(separator);
738
739 void add(Element value) {
740 _childNodes.add(value);
741 }
742
743 void addAll(Iterable<Element> iterable) {
744 for (Element element in iterable) {
745 add(element);
746 }
747 }
748
749 bool contains(Element element) {
750 return element is Element && _childNodes.contains(element);
751 }
752
753 Iterable<Element> get reversed => _filtered.reversed;
754
755 void sort([int compare(Element a, Element b)]) {
756 throw new UnsupportedError('TODO(jacobr): should we impl?');
757 }
758
759 void setRange(int start, int end, Iterable<Element> iterable,
760 [int skipCount = 0]) {
761 throw new UnimplementedError();
762 }
763
764 void fillRange(int start, int end, [Element fillValue]) {
765 throw new UnimplementedError();
766 }
767
768 void replaceRange(int start, int end, Iterable<Element> iterable) {
769 throw new UnimplementedError();
770 }
771
772 void removeRange(int start, int end) {
773 _filtered.sublist(start, end).forEach((el) => el.remove());
774 }
775
776 void clear() {
777 // Currently, ElementList#clear clears even non-element nodes, so we follow
778 // that behavior.
779 _childNodes.clear();
780 }
781
782 Element removeLast() {
783 final result = this.last;
784 if (result != null) {
785 result.remove();
786 }
787 return result;
788 }
789
790 Iterable map(f(Element element)) => _filtered.map(f);
791 Iterable<Element> where(bool f(Element element)) => _filtered.where(f);
792 Iterable expand(Iterable f(Element element)) => _filtered.expand(f);
793
794 void insert(int index, Element value) {
795 _childNodes.insert(index, value);
796 }
797
798 void insertAll(int index, Iterable<Element> iterable) {
799 _childNodes.insertAll(index, iterable);
800 }
801
802 Element removeAt(int index) {
803 final result = this[index];
804 result.remove();
805 return result;
806 }
807
808 bool remove(Object element) {
809 if (element is! Element) return false;
810 for (int i = 0; i < length; i++) {
811 Element indexElement = this[i];
812 if (identical(indexElement, element)) {
813 indexElement.remove();
814 return true;
815 }
816 }
817 return false;
818 }
819
820 Element reduce(Element combine(Element value, Element element)) {
821 return _filtered.reduce(combine);
822 }
823
824 dynamic fold(dynamic initialValue,
825 dynamic combine(dynamic previousValue, Element element)) {
826 return _filtered.fold(initialValue, combine);
827 }
828
829 bool every(bool f(Element element)) => _filtered.every(f);
830 bool any(bool f(Element element)) => _filtered.any(f);
831 List<Element> toList({ bool growable: true }) =>
832 new List<Element>.from(this, growable: growable);
833 Set<Element> toSet() => new Set<Element>.from(this);
834 Element firstWhere(bool test(Element value), {Element orElse()}) {
835 return _filtered.firstWhere(test, orElse: orElse);
836 }
837
838 Element lastWhere(bool test(Element value), {Element orElse()}) {
839 return _filtered.lastWhere(test, orElse: orElse);
840 }
841
842 Element singleWhere(bool test(Element value)) {
843 return _filtered.singleWhere(test);
844 }
845
846 Element elementAt(int index) {
847 return this[index];
848 }
849
850 bool get isEmpty => _filtered.isEmpty;
851 int get length => _filtered.length;
852 Element operator [](int index) => _filtered[index];
853 Iterator<Element> get iterator => _filtered.iterator;
854 List<Element> sublist(int start, [int end]) =>
855 _filtered.sublist(start, end);
856 Iterable<Element> getRange(int start, int end) =>
857 _filtered.getRange(start, end);
858 int indexOf(Element element, [int start = 0]) =>
859 _filtered.indexOf(element, start);
860
861 int lastIndexOf(Element element, [int start = null]) {
862 if (start == null) start = length - 1;
863 return _filtered.lastIndexOf(element, start);
864 }
865
866 Element get first => _filtered.first;
867
868 Element get last => _filtered.last;
869
870 Element get single => _filtered.single;
871 }
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698