Skip to content
This repository has been archived by the owner on Feb 22, 2018. It is now read-only.

Commit

Permalink
feat(probe): add ngQuery which can cross shadow root boundaries
Browse files Browse the repository at this point in the history
  • Loading branch information
mhevery committed Nov 27, 2013
1 parent 26ca46d commit 2089791
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 0 deletions.
17 changes: 17 additions & 0 deletions lib/introspection.dart
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,21 @@ Injector ngInjector(dom.Node node) => ngProbe(node).injector;
Scope ngScope(dom.Node node) => ngProbe(node).scope;


List<dom.Element> ngQuery(dom.Node element, String selector, [String containsText]) {
var list = [];
var children = [element];
while (!children.isEmpty) {
var child = children.removeAt(0);
child.queryAll(selector).forEach((e) {
if (containsText == null || e.text.contains(containsText)) list.add(e);
});
child.queryAll('*').forEach((e) {
if (e.shadowRoot != null) children.add(e.shadowRoot);
});
}
return list;
}

/**
* Return a List of directive controllers associated with a current [Element].
*
Expand All @@ -59,6 +74,8 @@ _publishToJavaScript() {
js.context.ngProbe = (dom.Node node) => _jsProbe(ngProbe(node));
js.context.ngInjector = (dom.Node node) => _jsInjector(ngInjector(node));
js.context.ngScope = (dom.Node node) => _jsScope(ngScope(node));
js.context.ngQuery = (dom.Node node, String selector, [String containsText]) =>
new JsArray.from(ngQuery(node, selector, containsText));
}

JsObject _jsProbe(ElementProbe probe) {
Expand Down
14 changes: 14 additions & 0 deletions test/introspection_spec.dart
Original file line number Diff line number Diff line change
Expand Up @@ -13,4 +13,18 @@ main() => describe('introspection', () {
expect(probe.scope).toBe(_.rootScope);
expect(ngScope(_.rootElement)).toBe(_.rootScope);
}));

toHtml(List list) => list.map((e) => e.outerHtml).join('');

it('should select elements using CSS selector', () {
var div = new Element.html('<div><p><span></span></p></div>');
var span = div.query('span');
var shadowRoot = span.createShadowRoot();
shadowRoot.innerHtml = '<ul><li>stash</li><li>secret</li><ul>';

expect(toHtml(ngQuery(div, 'li'))).toEqual('<li>stash</li><li>secret</li>');
expect(toHtml(ngQuery(div, 'li', 'stash'))).toEqual('<li>stash</li>');
expect(toHtml(ngQuery(div, 'li', 'secret'))).toEqual('<li>secret</li>');
expect(toHtml(ngQuery(div, 'li', 'xxx'))).toEqual('');
});
});

0 comments on commit 2089791

Please sign in to comment.