Return navigation for files when subscriptions change
diff --git a/angular_analyzer_plugin/lib/plugin.dart b/angular_analyzer_plugin/lib/plugin.dart index 1b0575a..5bc155d 100644 --- a/angular_analyzer_plugin/lib/plugin.dart +++ b/angular_analyzer_plugin/lib/plugin.dart
@@ -187,39 +187,24 @@ _handleResultNavigation(result, driver, isHtml: isHtml); } - void sendNotificationForSubscription( - String fileName, plugin.AnalysisService service, AnalysisResult result) { - switch (service) { - case plugin.AnalysisService.FOLDING: - // TODO(brianwilkerson) Implement this. - break; - case plugin.AnalysisService.HIGHLIGHTS: - // TODO(brianwilkerson) Implement this. - break; - case plugin.AnalysisService.NAVIGATION: - // TODO(brianwilkerson) Implement this. - break; - case plugin.AnalysisService.OCCURRENCES: - // TODO(brianwilkerson) Implement this. - break; - case plugin.AnalysisService.OUTLINE: - // TODO(brianwilkerson) Implement this. - break; - default: - // Ignore unhandled service types. - break; - } - } - + /// This method is used when the set of subscribed notifications has been + /// changed and notifications need to be sent even when the specified files + /// have already been analyzed. @override void sendNotificationsForSubscriptions( Map<String, List<plugin.AnalysisService>> subscriptions) { subscriptions.forEach((filePath, services) { - // TODO(brianwilkerson) Get the results for this file. - AnalysisResult result; - for (final service in services) { - sendNotificationForSubscription(filePath, service, result); + final driver = angularDriverForPath(filePath); + if (driver == null) { + return; } + + // Kick off a full reanalysis of files with subscriptions. This will add + // a resolved result to the stream which will send the new necessary + // notifications. + filePath.endsWith('.dart') + ? driver.requestDartResult(filePath) + : driver.requestHtmlResult(filePath); }); }
diff --git a/angular_analyzer_plugin/test/abstract_angular.dart b/angular_analyzer_plugin/test/abstract_angular.dart index cc4640b..250f392 100644 --- a/angular_analyzer_plugin/test/abstract_angular.dart +++ b/angular_analyzer_plugin/test/abstract_angular.dart
@@ -24,6 +24,7 @@ import 'package:mockito/mockito.dart'; import 'package:test/test.dart'; +import 'mock_angular.dart'; import 'mock_sdk.dart'; void assertComponentReference( @@ -222,209 +223,7 @@ ngOptions); errorListener = new GatheringErrorListener(); - _addAngularSources(); - } - - void _addAngularSources() { - newSource('/angular2/angular2.dart', r''' -library angular2; - -export 'package:angular/angular.dart'; -'''); - newSource('/angular2/security.dart', r''' -library angular2.security; - -export 'package:angular/security.dart'; -'''); - newSource('/angular/angular.dart', r''' -library angular; - -export 'src/core/async.dart'; -export 'src/core/metadata.dart'; -export 'src/core/ng_if.dart'; -export 'src/core/ng_for.dart'; -export 'src/core/change_detection.dart'; -'''); - newSource('/angular/security.dart', r''' -library angular.security; -export 'src/security/dom_sanitization_service.dart'; -'''); - newSource( - '/angular/src/core/metadata.dart', - r''' -import 'dart:async'; - -abstract class Directive { - const Directive( - {String selector, - Map<String, String> host, - @Deprecated('Use `providers` instead') List bindings, - List providers, - String exportAs, - String moduleId, - Map<String, dynamic> queries}) - : super( - selector: selector, - properties: properties, - events: events, - host: host, - bindings: bindings, - providers: providers, - exportAs: exportAs, - moduleId: moduleId, - queries: queries); -} - -class Component extends Directive { - final List<Object> directives; - const Component( - {String selector, - Map<String, String> host, - @Deprecated('Use `providers` instead') List bindings, - List providers, - String exportAs, - String moduleId, - Map<String, dynamic> queries, - @Deprecated('Use `viewProviders` instead') List viewBindings, - List viewProviders, - ChangeDetectionStrategy changeDetection, - String templateUrl, - String template, - this.directives, - dynamic pipes, - ViewEncapsulation encapsulation, - List exports, - List<String> styles, - List<String> styleUrls}); -} - -class Pipe { - final String name; - final bool _pure; - const Pipe(this.name, {bool pure}); -} - -class Input { - final String bindingPropertyName; - const Input([this.bindingPropertyName]); -} - -class Output { - final String bindingPropertyName; - const Output([this.bindingPropertyName]); -} - -class Attribute { - final String attributeName; - const Attribute(this.attributeName); -} - -class ContentChild extends Query { - const ContentChild(dynamic /* Type | String */ selector, - {dynamic read: null}) : super(selector, read: read); -} - -class ContentChildren extends Query { - const ContentChildren(dynamic /* Type | String */ selector, - {dynamic read: null}) : super(selector, read: read); -} - -class Query extends DependencyMetadata { - final dynamic /* Type | String */ selector; - final dynamic /* String | Function? */ read; - const DependencyMetadata(this.selector, {this.read}) : super(); -} - -class DependencyMetadata { - const DependencyMetadata(); -} - -class TemplateRef {} -class ElementRef {} -''' + - (includeQueryList - ? r''' -class QueryList<T> implements Iterable<T> {} -''' - : '') + - r''' -class ViewContainerRef {} -class PipeTransform {} -'''); - newSource('/angular/src/core/async.dart', r''' -import 'dart:async'; - -class EventEmitter<T> extends Stream<T> { - StreamController<dynamic> _controller; - - /** - * Creates an instance of [EventEmitter], which depending on [isAsync], - * delivers events synchronously or asynchronously. - */ - EventEmitter([bool isAsync = true]) { - _controller = new StreamController.broadcast(sync: !isAsync); - } - - StreamSubscription listen(void onData(dynamic line), - {void onError(Error error), void onDone(), bool cancelOnError}) { - return _controller.stream.listen(onData, - onError: onError, onDone: onDone, cancelOnError: cancelOnError); - } - - void add(value) { - _controller.add(value); - } - - void addError(error) { - _controller.addError(error); - } - - void close() { - _controller.close(); - } -} -'''); - newSource('/angular/src/core/ng_if.dart', r''' -import 'metadata.dart'; - -@Directive(selector: "[ngIf]") -class NgIf { - @Input() - NgIf(TemplateRef tpl); - - @Input() - set ngIf(newCondition) {} -} -'''); - newSource('/angular/src/core/ng_for.dart', r''' -import 'metadata.dart'; - -@Directive( - selector: "[ngFor][ngForOf]") -class NgFor { - @Input() - NgFor(TemplateRef tpl); - @Input() - set ngForOf(dynamic value) {} - @Input() - set ngForTrackBy(TrackByFn value) {} -} - -typedef dynamic TrackByFn(num index, dynamic item); -'''); - newSource('/angular/src/security/dom_sanitization_service.dart', r''' -class SafeValue {} - -abstract class SafeHtml extends SafeValue {} - -abstract class SafeStyle extends SafeValue {} - -abstract class SafeScript extends SafeValue {} - -abstract class SafeUrl extends SafeValue {} - -abstract class SafeResourceUrl extends SafeValue {} -'''); + addAngularSources(newSource); } }
diff --git a/angular_analyzer_plugin/test/mock_angular.dart b/angular_analyzer_plugin/test/mock_angular.dart new file mode 100644 index 0000000..abadf0c --- /dev/null +++ b/angular_analyzer_plugin/test/mock_angular.dart
@@ -0,0 +1,202 @@ +void addAngularSources(Function(String, [String]) newSource, + {bool includeQueryList: false}) { + newSource('/angular2/angular2.dart', r''' +library angular2; + +export 'package:angular/angular.dart'; +'''); + newSource('/angular2/security.dart', r''' +library angular2.security; + +export 'package:angular/security.dart'; +'''); + newSource('/angular/angular.dart', r''' +library angular; + +export 'src/core/async.dart'; +export 'src/core/metadata.dart'; +export 'src/core/ng_if.dart'; +export 'src/core/ng_for.dart'; +export 'src/core/change_detection.dart'; +'''); + newSource('/angular/security.dart', r''' +library angular.security; +export 'src/security/dom_sanitization_service.dart'; +'''); + newSource( + '/angular/src/core/metadata.dart', + r''' +import 'dart:async'; + +abstract class Directive { + const Directive( + {String selector, + Map<String, String> host, + @Deprecated('Use `providers` instead') List bindings, + List providers, + String exportAs, + String moduleId, + Map<String, dynamic> queries}) + : super( + selector: selector, + properties: properties, + events: events, + host: host, + bindings: bindings, + providers: providers, + exportAs: exportAs, + moduleId: moduleId, + queries: queries); +} + +class Component extends Directive { + final List<Object> directives; + const Component( + {String selector, + Map<String, String> host, + @Deprecated('Use `providers` instead') List bindings, + List providers, + String exportAs, + String moduleId, + Map<String, dynamic> queries, + @Deprecated('Use `viewProviders` instead') List viewBindings, + List viewProviders, + ChangeDetectionStrategy changeDetection, + String templateUrl, + String template, + this.directives, + dynamic pipes, + ViewEncapsulation encapsulation, + List exports, + List<String> styles, + List<String> styleUrls}); +} + +class Pipe { + final String name; + final bool _pure; + const Pipe(this.name, {bool pure}); +} + +class Input { + final String bindingPropertyName; + const Input([this.bindingPropertyName]); +} + +class Output { + final String bindingPropertyName; + const Output([this.bindingPropertyName]); +} + +class Attribute { + final String attributeName; + const Attribute(this.attributeName); +} + +class ContentChild extends Query { + const ContentChild(dynamic /* Type | String */ selector, + {dynamic read: null}) : super(selector, read: read); +} + +class ContentChildren extends Query { + const ContentChildren(dynamic /* Type | String */ selector, + {dynamic read: null}) : super(selector, read: read); +} + +class Query extends DependencyMetadata { + final dynamic /* Type | String */ selector; + final dynamic /* String | Function? */ read; + const DependencyMetadata(this.selector, {this.read}) : super(); +} + +class DependencyMetadata { + const DependencyMetadata(); +} + +class TemplateRef {} +class ElementRef {} +''' + + (includeQueryList + ? r''' +class QueryList<T> implements Iterable<T> {} +''' + : '') + + r''' +class ViewContainerRef {} +class PipeTransform {} +'''); + newSource('/angular/src/core/async.dart', r''' +import 'dart:async'; + +class EventEmitter<T> extends Stream<T> { + StreamController<dynamic> _controller; + + /** + * Creates an instance of [EventEmitter], which depending on [isAsync], + * delivers events synchronously or asynchronously. + */ + EventEmitter([bool isAsync = true]) { + _controller = new StreamController.broadcast(sync: !isAsync); + } + + StreamSubscription listen(void onData(dynamic line), + {void onError(Error error), void onDone(), bool cancelOnError}) { + return _controller.stream.listen(onData, + onError: onError, onDone: onDone, cancelOnError: cancelOnError); + } + + void add(value) { + _controller.add(value); + } + + void addError(error) { + _controller.addError(error); + } + + void close() { + _controller.close(); + } +} +'''); + newSource('/angular/src/core/ng_if.dart', r''' +import 'metadata.dart'; + +@Directive(selector: "[ngIf]") +class NgIf { + @Input() + NgIf(TemplateRef tpl); + + @Input() + set ngIf(newCondition) {} +} +'''); + newSource('/angular/src/core/ng_for.dart', r''' +import 'metadata.dart'; + +@Directive( + selector: "[ngFor][ngForOf]") +class NgFor { + @Input() + NgFor(TemplateRef tpl); + @Input() + set ngForOf(dynamic value) {} + @Input() + set ngForTrackBy(TrackByFn value) {} +} + +typedef dynamic TrackByFn(num index, dynamic item); +'''); + newSource('/angular/src/security/dom_sanitization_service.dart', r''' +class SafeValue {} + +abstract class SafeHtml extends SafeValue {} + +abstract class SafeStyle extends SafeValue {} + +abstract class SafeScript extends SafeValue {} + +abstract class SafeUrl extends SafeValue {} + +abstract class SafeResourceUrl extends SafeValue {} +'''); +}
diff --git a/angular_analyzer_plugin/test/mock_sdk.dart b/angular_analyzer_plugin/test/mock_sdk.dart index 057ad13..99cf448 100644 --- a/angular_analyzer_plugin/test/mock_sdk.dart +++ b/angular_analyzer_plugin/test/mock_sdk.dart
@@ -321,9 +321,145 @@ '''); const _LIB_HTML_DART2JS = const _MockSdkLibrary( - 'dart:html', '$sdkRoot/lib/html/dartium/html_dartium.dart', ''' + 'dart:html', '$sdkRoot/lib/html/dart2js/html_dart2js.dart', ''' library dart.html; -class HtmlElement {} +import 'dart:async'; + +class Event {} +class MouseEvent extends Event {} +class FocusEvent extends Event {} +class KeyEvent extends Event {} + +abstract class ElementStream<T extends Event> implements Stream<T> {} + +abstract class Element { + /// Stream of `cut` events handled by this [Element]. + ElementStream<Event> get onCut => null; + + String get id => null; + + set id(String value) => null; +} + +class HtmlElement extends Element { + int tabIndex; + ElementStream<Event> get onChange => null; + ElementStream<MouseEvent> get onClick => null; + ElementStream<KeyEvent> get onKeyUp => null; + ElementStream<KeyEvent> get onKeyDown => null; + + bool get hidden => null; + set hidden(bool value) => null; + + void set className(String s){} + void set readOnly(bool b){} + void set tabIndex(int i){} + + String _innerHtml; + String get innerHtml { + throw 'not the real implementation'; + } + set innerHtml(String value) { + // stuff + } + +} + +dynamic JS(a, b, c, d) {} + +class AnchorElement extends HtmlElement { + factory AnchorElement({String href}) { + AnchorElement e = JS('returns:AnchorElement;creates:AnchorElement;new:true', + '#.createElement(#)', document, "a"); + if (href != null) e.href = href; + return e; + } + String href; + String _privateField; +} + +class BodyElement extends HtmlElement { + factory BodyElement() => document.createElement("body"); + + ElementStream<Event> get onUnload => null; +} + +class ButtonElement extends HtmlElement { + factory ButtonElement._() { throw new UnsupportedError("Not supported"); } + factory ButtonElement() => document.createElement("button"); + bool autofocus; +} + +class HeadingElement extends HtmlElement { + factory HeadingElement._() { throw new UnsupportedError("Not supported"); } + factory HeadingElement.h1() => document.createElement("h1"); + factory HeadingElement.h2() => document.createElement("h2"); + factory HeadingElement.h3() => document.createElement("h3"); +} + +class InputElement extends HtmlElement { + factory InputElement._() { throw new UnsupportedError("Not supported"); } + factory InputElement() => document.createElement("input"); + String value; + String validationMessage; +} + +class IFrameElement extends HtmlElement { + factory IFrameElement._() { throw new UnsupportedError("Not supported"); } + factory IFrameElement() => JS( + 'returns:IFrameElement;creates:IFrameElement;new:true', + '#.createElement(#)', + document, + "iframe"); + String src; +} + +class OptionElement extends HtmlElement { + factory OptionElement({String data: '', String value : '', bool selected: false}) { + } + + factory OptionElement._([String data, String value, bool defaultSelected, bool selected]) { + } +} + +class TableSectionElement extends HtmlElement { + + List<TableRowElement> get rows => null; + + TableRowElement addRow() { + } + + TableRowElement insertRow(int index) => null; + + factory TableSectionElement._() { throw new UnsupportedError("Not supported"); } + + @Deprecated("Internal Use Only") + external static Type get instanceRuntimeType; + + @Deprecated("Internal Use Only") + TableSectionElement.internal_() : super.internal_(); +} + +class TemplateElement extends HtmlElement { + factory TemplateElement._() { throw new UnsupportedError("Not supported"); } + factory TemplateElement() => document.createElement("template"); +} + +class AudioElement extends MediaElement { + factory AudioElement._([String src]) { + if (src != null) { + return AudioElement._create_1(src); + } + return AudioElement._create_2(); + } + static AudioElement _create_1(src) => JS('AudioElement', 'new Audio(#)', src); + static AudioElement _create_2() => JS('AudioElement', 'new Audio()'); + AudioElement.created() : super.created(); + + factory AudioElement([String src]) => new AudioElement._(src); +} + +class MediaElement extends Element {} '''); const _LIB_HTML_DARTIUM = const _MockSdkLibrary(
diff --git a/angular_analyzer_plugin/test/plugin_test.dart b/angular_analyzer_plugin/test/plugin_test.dart index 112bbed..f5c479f 100644 --- a/angular_analyzer_plugin/test/plugin_test.dart +++ b/angular_analyzer_plugin/test/plugin_test.dart
@@ -1,5 +1,10 @@ +import 'dart:async'; +import 'dart:developer'; + import 'package:analyzer/file_system/file_system.dart'; import 'package:analyzer/file_system/memory_file_system.dart'; +import 'package:analyzer_plugin/channel/channel.dart'; +import 'package:analyzer_plugin/protocol/protocol.dart' as protocol; import 'package:analyzer_plugin/protocol/protocol_common.dart' as protocol; import 'package:analyzer_plugin/protocol/protocol_generated.dart' as protocol; import 'package:angular_analyzer_plugin/plugin.dart'; @@ -8,22 +13,20 @@ import 'package:test/test.dart'; import 'package:test_reflective_loader/test_reflective_loader.dart'; +import 'mock_angular.dart'; import 'mock_sdk.dart'; void main() { defineReflectiveSuite(() { defineReflectiveTests(PluginIntegrationTest); + defineReflectiveTests(PluginCreateDriverTest); defineReflectiveTests(AnalysisOptionsUtilsTest); }); } /// Unfortunately, package:yaml doesn't support dumping to yaml. So this is /// what we are stuck with, for now. Put it in a base class so we can test it -class AnalysisOptionsUtilsBase { - AngularAnalyzerPlugin plugin; - MemoryResourceProvider resourceProvider; - protocol.ContextRoot root; - +class AnalysisOptionsUtilsBase extends PluginIntegrationTestBase { String optionsHeader = ''' analyzer: plugins: @@ -47,17 +50,6 @@ void setOptionsFileContent(String content) { resourceProvider.newFile('/test/analysis_options.yaml', content); } - - void setUp() { - resourceProvider = new MemoryResourceProvider(); - new MockSdk(resourceProvider: resourceProvider); - plugin = new AngularAnalyzerPlugin(resourceProvider); - final versionCheckParams = new protocol.PluginVersionCheckParams( - "~/.dartServer/.analysis-driver", "/sdk", "1.0.0"); - plugin.handlePluginVersionCheck(versionCheckParams); - root = new protocol.ContextRoot("/test", [], - optionsFile: '/test/analysis_options.yaml'); - } } /// Since our yaml generation is...not ideal, let's test it. @@ -132,10 +124,35 @@ } } +class MockPluginCommunicationChannel extends Mock + implements PluginCommunicationChannel {} + class MockResourceProvider extends Mock implements ResourceProvider {} +class NamedNavigationNotificationMatcher implements Matcher { + final String filename; + + NamedNavigationNotificationMatcher(this.filename); + + @override + Description describe(Description description) => + description..add('that is a navigation notification for file $filename'); + + @override + Description describeMismatch(item, Description mismatchDescription, + Map matchState, bool verbose) => + mismatchDescription + ..add('is not a navigation notification for file $filename'); + + @override + bool matches(item, Map matchState) => + item is protocol.Notification && + item.event == 'analysis.navigation' && + item.params['file'] == filename; +} + @reflectiveTest -class PluginIntegrationTest extends AnalysisOptionsUtilsBase { +class PluginCreateDriverTest extends AnalysisOptionsUtilsBase { // ignore: non_constant_identifier_names void test_createAnalysisDriver() { enableAnalyzerPluginsAngular(); @@ -202,3 +219,88 @@ expect(driver.options.customTagNames, isEmpty); } } + +@reflectiveTest +class PluginIntegrationTest extends PluginIntegrationTestBase { + @override + void setUp() async { + super.setUp(); + + addAngularSources((filename, [contents = ""]) => + resourceProvider.newFile(filename, contents)); + resourceProvider.newFile('/test/.packages', 'angular:/angular/'); + plugin.start(mockChannel); + await plugin.handleAnalysisSetContextRoots( + new protocol.AnalysisSetContextRootsParams([root])); + } + + // ignore: non_constant_identifier_names + void test_navigation_dart() async { + resourceProvider.newFile('/test/test.dart', r''' +import 'package:angular/angular.dart'; +@Component( + selector: 'foo' +) +class MyComponent {} +'''); + + await (plugin.driverForPath('/test/test.dart') as AngularDriver) + .requestDartResult('/test/test.dart'); + verifyNever(mockChannel.sendNotification( + argThat(new NamedNavigationNotificationMatcher('/test/test.dart')))); + + await plugin.handleAnalysisSetSubscriptions( + new protocol.AnalysisSetSubscriptionsParams({ + protocol.AnalysisService.NAVIGATION: ['/test/test.dart'] + })); + + await Future.delayed(const Duration(milliseconds: 300)); + verify(mockChannel.sendNotification( + argThat(new NamedNavigationNotificationMatcher('/test/test.dart')))); + } + + // ignore: non_constant_identifier_names + void test_navigation_html() async { + resourceProvider..newFile('/test/test.dart', r''' +import 'package:angular/angular.dart'; +@Component( + selector: 'foo' + templateUrl: 'test.html'; +) +class MyComponent {} +''')..newFile('/test/test.html', ''); + + final driver = (plugin.driverForPath('/test/test.dart') as AngularDriver); + await driver.requestDartResult('/test/test.dart'); + await driver.requestHtmlResult('/test/test.html'); + verifyNever(mockChannel.sendNotification( + argThat(new NamedNavigationNotificationMatcher('/test/test.html')))); + + await plugin.handleAnalysisSetSubscriptions( + new protocol.AnalysisSetSubscriptionsParams({ + protocol.AnalysisService.NAVIGATION: ['/test/test.html'] + })); + + await Future.delayed(const Duration(milliseconds: 300)); + verify(mockChannel.sendNotification( + argThat(new NamedNavigationNotificationMatcher('/test/test.html')))); + } +} + +class PluginIntegrationTestBase { + AngularAnalyzerPlugin plugin; + MemoryResourceProvider resourceProvider; + PluginCommunicationChannel mockChannel; + protocol.ContextRoot root; + void setUp() { + resourceProvider = new MemoryResourceProvider(); + new MockSdk(resourceProvider: resourceProvider); + plugin = new AngularAnalyzerPlugin(resourceProvider); + final versionCheckParams = new protocol.PluginVersionCheckParams( + "~/.dartServer/.analysis-driver", "/sdk", "1.0.0"); + plugin.handlePluginVersionCheck(versionCheckParams); + root = new protocol.ContextRoot("/test", [], + optionsFile: '/test/analysis_options.yaml'); + mockChannel = new MockPluginCommunicationChannel(); + } +}