From 60727c4d2ba1e4b0b9455c767d0ef152bcedc7c2 Mon Sep 17 00:00:00 2001 From: Alex Rickabaugh Date: Tue, 12 Apr 2016 09:40:37 -0700 Subject: [PATCH] revert(format): Revert "chore(format): update to latest formatter" This reverts commit 03627aa84d90f7f1d8d62f160997b783fdf9eaa4. --- gulpfile.js | 718 ++-- modules/angular1_router/src/ng_outlet.ts | 29 +- modules/angular2/core.ts | 8 +- .../core/di/ts/forward_ref/forward_ref.ts | 6 +- .../pipes/ts/async_pipe/async_pipe_example.ts | 4 +- .../ts/can_activate/can_activate_example.ts | 8 +- .../can_deactivate/can_deactivate_example.ts | 9 +- .../ts/on_activate/on_activate_example.ts | 8 +- .../ts/on_deactivate/on_deactivate_example.ts | 11 +- .../examples/router/ts/reuse/reuse_example.ts | 15 +- .../angular2/examples/testing/ts/testing.ts | 25 +- modules/angular2/http.ts | 38 +- modules/angular2/instrumentation.ts | 8 +- modules/angular2/platform/browser.ts | 21 +- modules/angular2/platform/browser_static.ts | 23 +- modules/angular2/platform/common_dom.ts | 6 +- modules/angular2/platform/testing/browser.ts | 5 +- .../platform/testing/browser_static.ts | 15 +- modules/angular2/platform/testing/server.ts | 18 +- modules/angular2/platform/worker_app.ts | 18 +- modules/angular2/platform/worker_render.ts | 20 +- modules/angular2/src/animate/animation.ts | 32 +- .../src/common/directives/core_directives.ts | 10 +- .../src/common/directives/ng_class.ts | 39 +- .../angular2/src/common/directives/ng_for.ts | 44 +- .../src/common/directives/ng_plural.ts | 18 +- .../src/common/directives/ng_style.ts | 15 +- .../src/common/directives/ng_switch.ts | 8 +- modules/angular2/src/common/forms.ts | 13 +- .../angular2/src/common/forms/directives.ts | 51 +- .../directives/control_value_accessor.ts | 2 +- .../forms/directives/ng_control_group.ts | 20 +- .../forms/directives/ng_control_name.ts | 71 +- .../src/common/forms/directives/ng_form.ts | 16 +- .../forms/directives/ng_form_control.ts | 70 +- .../common/forms/directives/ng_form_model.ts | 18 +- .../src/common/forms/directives/ng_model.ts | 65 +- .../forms/directives/normalize_validator.ts | 2 +- .../radio_control_value_accessor.ts | 25 +- .../select_control_value_accessor.ts | 30 +- .../src/common/forms/directives/shared.ts | 34 +- .../src/common/forms/directives/validators.ts | 8 +- .../angular2/src/common/forms/form_builder.ts | 23 +- modules/angular2/src/common/forms/model.ts | 56 +- .../angular2/src/common/forms/validators.ts | 28 +- .../angular2/src/common/pipes/async_pipe.ts | 17 +- .../angular2/src/common/pipes/common_pipes.ts | 14 +- .../angular2/src/common/pipes/date_pipe.ts | 11 +- .../src/common/pipes/i18n_plural_pipe.ts | 8 +- .../angular2/src/common/pipes/number_pipe.ts | 20 +- .../angular2/src/common/pipes/replace_pipe.ts | 9 +- .../src/compiler/change_definition_factory.ts | 73 +- .../src/compiler/change_detector_compiler.ts | 35 +- modules/angular2/src/compiler/compiler.ts | 31 +- modules/angular2/src/compiler/css/lexer.ts | 122 +- modules/angular2/src/compiler/css/parser.ts | 101 +- .../src/compiler/directive_metadata.ts | 152 +- modules/angular2/src/compiler/html_ast.ts | 7 +- modules/angular2/src/compiler/html_lexer.ts | 31 +- modules/angular2/src/compiler/html_parser.ts | 40 +- modules/angular2/src/compiler/html_tags.ts | 58 +- .../angular2/src/compiler/legacy_template.ts | 45 +- modules/angular2/src/compiler/parse_util.ts | 11 +- .../src/compiler/proto_view_compiler.ts | 225 +- .../angular2/src/compiler/runtime_metadata.ts | 20 +- .../schema/dom_element_schema_registry.ts | 4 +- modules/angular2/src/compiler/selector.ts | 53 +- modules/angular2/src/compiler/shadow_css.ts | 67 +- .../angular2/src/compiler/static_reflector.ts | 254 +- .../angular2/src/compiler/style_compiler.ts | 32 +- .../src/compiler/style_url_resolver.ts | 4 +- modules/angular2/src/compiler/template_ast.ts | 65 +- .../src/compiler/template_compiler.ts | 199 +- .../src/compiler/template_normalizer.ts | 34 +- .../angular2/src/compiler/template_parser.ts | 312 +- .../src/compiler/template_preparser.ts | 5 +- modules/angular2/src/compiler/url_resolver.ts | 69 +- modules/angular2/src/compiler/util.ts | 17 +- .../angular2/src/compiler/view_compiler.ts | 335 +- .../src/core/application_common_providers.ts | 34 +- modules/angular2/src/core/application_ref.ts | 125 +- .../angular2/src/core/application_tokens.ts | 6 +- modules/angular2/src/core/change_detection.ts | 22 +- .../abstract_change_detector.ts | 35 +- .../core/change_detection/binding_record.ts | 93 +- .../core/change_detection/change_detection.ts | 46 +- .../change_detection_jit_generator.ts | 63 +- .../change_detection/change_detection_util.ts | 36 +- .../src/core/change_detection/coalesce.ts | 37 +- .../change_detection/codegen_logic_util.ts | 37 +- .../change_detection/codegen_name_util.ts | 27 +- .../src/core/change_detection/constants.ts | 19 +- .../differs/default_iterable_differ.ts | 52 +- .../differs/default_keyvalue_differ.ts | 18 +- .../core/change_detection/directive_record.ts | 31 +- .../dynamic_change_detector.ts | 56 +- .../core/change_detection/event_binding.ts | 5 +- .../src/core/change_detection/exceptions.ts | 12 +- .../src/core/change_detection/interfaces.ts | 17 +- .../jit_proto_change_detector.ts | 4 +- .../src/core/change_detection/parser/ast.ts | 19 +- .../src/core/change_detection/parser/lexer.ts | 59 +- .../core/change_detection/parser/parser.ts | 85 +- .../change_detection/proto_change_detector.ts | 159 +- .../src/core/change_detection/proto_record.ts | 14 +- modules/angular2/src/core/debug/debug_node.ts | 8 +- .../angular2/src/core/debug/debug_renderer.ts | 16 +- modules/angular2/src/core/di.ts | 33 +- modules/angular2/src/core/di/decorators.ts | 9 +- modules/angular2/src/core/di/exceptions.ts | 26 +- modules/angular2/src/core/di/injector.ts | 89 +- modules/angular2/src/core/di/metadata.ts | 2 +- modules/angular2/src/core/di/provider.ts | 53 +- modules/angular2/src/core/linker.ts | 11 +- .../src/core/linker/directive_resolver.ts | 25 +- .../core/linker/dynamic_component_loader.ts | 46 +- modules/angular2/src/core/linker/element.ts | 132 +- .../angular2/src/core/linker/interfaces.ts | 9 +- modules/angular2/src/core/linker/view.ts | 94 +- .../src/core/linker/view_container_ref.ts | 27 +- .../angular2/src/core/linker/view_manager.ts | 85 +- .../angular2/src/core/linker/view_resolver.ts | 14 +- modules/angular2/src/core/metadata.ts | 92 +- modules/angular2/src/core/metadata/di.ts | 18 +- .../angular2/src/core/metadata/directives.ts | 60 +- modules/angular2/src/core/metadata/view.ts | 8 +- .../angular2/src/core/pipes/pipe_provider.ts | 9 +- modules/angular2/src/core/pipes/pipes.ts | 9 +- .../src/core/platform_common_providers.ts | 6 +- .../src/core/platform_directives_and_pipes.ts | 8 +- modules/angular2/src/core/profile/profile.ts | 8 +- .../reflection/reflection_capabilities.ts | 33 +- .../angular2/src/core/reflection/reflector.ts | 14 +- modules/angular2/src/core/render/api.ts | 18 +- modules/angular2/src/core/render/util.ts | 8 +- .../src/core/testability/testability.ts | 8 +- modules/angular2/src/core/util/decorators.ts | 6 +- .../angular2/src/core/zone/ng_zone_impl.ts | 2 +- modules/angular2/src/facade/async.ts | 9 +- modules/angular2/src/facade/collection.ts | 13 +- .../angular2/src/facade/exception_handler.ts | 10 +- modules/angular2/src/facade/exceptions.ts | 7 +- modules/angular2/src/facade/intl.ts | 21 +- modules/angular2/src/facade/lang.ts | 46 +- modules/angular2/src/facade/promise.ts | 13 +- .../src/http/backends/jsonp_backend.ts | 4 +- .../src/http/backends/mock_backend.ts | 4 +- .../angular2/src/http/base_request_options.ts | 14 +- .../src/http/base_response_options.ts | 2 +- modules/angular2/src/http/headers.ts | 22 +- modules/angular2/src/http/http.ts | 42 +- modules/angular2/src/http/http_utils.ts | 5 +- modules/angular2/src/http/interfaces.ts | 9 +- modules/angular2/src/http/static_request.ts | 8 +- modules/angular2/src/http/static_response.ts | 4 +- modules/angular2/src/i18n/i18n_html_parser.ts | 76 +- modules/angular2/src/i18n/message.ts | 4 +- .../angular2/src/i18n/message_extractor.ts | 21 +- modules/angular2/src/i18n/shared.ts | 53 +- modules/angular2/src/i18n/xmb_serializer.ts | 25 +- modules/angular2/src/mock/location_mock.ts | 5 +- .../angular2/src/mock/mock_application_ref.ts | 2 +- .../src/platform/browser/browser_adapter.ts | 14 +- .../browser/generic_browser_adapter.ts | 4 +- .../src/platform/browser/testability.ts | 12 +- .../angular2/src/platform/browser_common.ts | 48 +- modules/angular2/src/platform/dom/debug/by.ts | 4 +- .../src/platform/dom/debug/ng_probe.ts | 6 +- .../angular2/src/platform/dom/dom_renderer.ts | 47 +- .../src/platform/dom/events/event_manager.ts | 6 +- .../platform/dom/events/hammer_gestures.ts | 2 +- .../src/platform/dom/events/key_events.ts | 16 +- modules/angular2/src/platform/dom/util.ts | 8 +- .../src/platform/server/parse5_adapter.ts | 476 +-- modules/angular2/src/platform/worker_app.ts | 11 +- .../src/platform/worker_app_common.ts | 37 +- .../angular2/src/platform/worker_render.ts | 28 +- .../src/platform/worker_render_common.ts | 47 +- .../directives/router_link_transform.ts | 40 +- .../src/router/directives/router_outlet.ts | 21 +- modules/angular2/src/router/instruction.ts | 35 +- modules/angular2/src/router/interfaces.ts | 24 +- .../router/lifecycle/lifecycle_annotations.ts | 14 +- .../lifecycle/lifecycle_annotations_impl.ts | 10 +- .../lifecycle/route_lifecycle_reflector.ts | 2 +- .../router/location/hash_location_strategy.ts | 12 +- .../angular2/src/router/location/location.ts | 5 +- .../router/location/path_location_strategy.ts | 12 +- .../route_config/route_config_normalizer.ts | 8 +- .../angular2/src/router/route_definition.ts | 2 +- modules/angular2/src/router/route_registry.ts | 63 +- modules/angular2/src/router/router.ts | 122 +- .../src/router/router_providers_common.ts | 21 +- .../rules/route_paths/param_route_path.ts | 2 +- .../router/rules/route_paths/route_path.ts | 5 +- modules/angular2/src/router/rules/rule_set.ts | 12 +- modules/angular2/src/router/rules/rules.ts | 18 +- modules/angular2/src/router/url_parser.ts | 15 +- modules/angular2/src/testing/matchers.ts | 6 +- modules/angular2/src/testing/perf_util.ts | 62 +- .../src/testing/test_component_builder.ts | 21 +- modules/angular2/src/testing/test_injector.ts | 18 +- modules/angular2/src/testing/testing.ts | 56 +- .../angular2/src/testing/testing_internal.ts | 9 +- modules/angular2/src/testing/utils.ts | 12 +- .../change_detector_codegen.ts | 8 +- modules/angular2/src/upgrade/angular_js.ts | 35 +- .../src/upgrade/downgrade_ng2_adapter.ts | 28 +- .../angular2/src/upgrade/upgrade_adapter.ts | 76 +- .../src/upgrade/upgrade_ng1_adapter.ts | 47 +- .../angular2/src/web_workers/shared/api.ts | 4 +- .../shared/client_message_broker.ts | 35 +- .../src/web_workers/shared/messaging_api.ts | 8 +- .../web_workers/shared/post_message_bus.ts | 16 +- .../src/web_workers/shared/render_store.ts | 2 +- .../web_workers/shared/serialized_types.ts | 7 +- .../src/web_workers/shared/serializer.ts | 27 +- .../shared/service_message_broker.ts | 15 +- .../src/web_workers/ui/event_dispatcher.ts | 150 +- .../src/web_workers/ui/event_serializer.ts | 31 +- .../src/web_workers/ui/platform_location.ts | 34 +- .../angular2/src/web_workers/ui/renderer.ts | 146 +- .../src/web_workers/ui/router_providers.ts | 9 +- .../angular2/src/web_workers/ui/xhr_impl.ts | 2 +- .../web_workers/worker/event_deserializer.ts | 4 +- .../web_workers/worker/platform_location.ts | 48 +- .../src/web_workers/worker/renderer.ts | 66 +- .../web_workers/worker/router_providers.ts | 16 +- .../src/web_workers/worker/xhr_impl.ts | 9 +- .../test/animate/animation_builder_spec.ts | 2 +- .../test/common/directives/ng_class_spec.ts | 17 +- .../test/common/directives/ng_for_spec.ts | 55 +- .../test/common/directives/ng_if_spec.ts | 255 +- .../test/common/directives/ng_plural_spec.ts | 32 +- .../test/common/directives/ng_style_spec.ts | 16 +- .../test/common/directives/ng_switch_spec.ts | 56 +- .../common/directives/non_bindable_spec.ts | 14 +- .../test/common/forms/directives_spec.ts | 278 +- .../test/common/forms/form_builder_spec.ts | 62 +- .../test/common/forms/integration_spec.ts | 868 ++--- .../angular2/test/common/forms/model_spec.ts | 545 +-- .../test/common/forms/validators_spec.ts | 142 +- .../test/common/pipes/async_pipe_spec.ts | 75 +- .../test/common/pipes/date_pipe_spec.ts | 24 +- .../common/pipes/i18n_plural_pipe_spec.ts | 34 +- .../common/pipes/i18n_select_pipe_spec.ts | 25 +- .../test/common/pipes/json_pipe_spec.ts | 38 +- .../test/common/pipes/lowercase_pipe_spec.ts | 21 +- .../test/common/pipes/number_pipe_spec.ts | 30 +- .../test/common/pipes/pipe_binding_spec.ts | 14 +- .../angular2/test/common/pipes/pipes_spec.ts | 30 +- .../test/common/pipes/replace_pipe_spec.ts | 65 +- .../test/common/pipes/slice_pipe_spec.ts | 27 +- .../test/common/pipes/uppercase_pipe_spec.ts | 21 +- .../change_definition_factory_spec.ts | 47 +- .../compiler/change_detector_compiler_spec.ts | 75 +- .../test/compiler/change_detector_mocks.ts | 7 +- .../angular2/test/compiler/css/lexer_spec.ts | 185 +- .../angular2/test/compiler/css/parser_spec.ts | 76 +- .../test/compiler/css/visitor_spec.ts | 58 +- .../test/compiler/directive_metadata_spec.ts | 69 +- .../test/compiler/eval_module_spec.ts | 23 +- .../test/compiler/html_ast_spec_utils.ts | 10 +- .../angular2/test/compiler/html_lexer_spec.ts | 644 ++-- .../test/compiler/html_parser_spec.ts | 196 +- .../test/compiler/legacy_template_spec.ts | 24 +- .../test/compiler/runtime_compiler_spec.ts | 24 +- .../test/compiler/runtime_metadata_fixture.ts | 2 +- .../test/compiler/runtime_metadata_spec.ts | 34 +- .../dom_element_schema_registry_spec.ts | 12 +- .../test/compiler/schema_registry_mock.ts | 5 +- .../angular2/test/compiler/selector_spec.ts | 47 +- .../angular2/test/compiler/shadow_css_spec.ts | 44 +- .../test/compiler/source_module_spec.ts | 14 +- .../test/compiler/static_reflector_spec.ts | 417 ++- .../test/compiler/style_compiler_spec.ts | 118 +- .../test/compiler/style_url_resolver_spec.ts | 10 +- .../test/compiler/template_compiler_spec.ts | 222 +- .../test/compiler/template_normalizer_spec.ts | 226 +- .../test/compiler/template_parser_spec.ts | 699 ++-- .../test/compiler/template_preparser_spec.ts | 21 +- .../test/compiler/url_resolver_spec.ts | 80 +- modules/angular2/test/compiler/util_spec.ts | 14 +- .../angular2/test/compiler/xhr_mock_spec.ts | 12 +- .../test/core/application_ref_spec.ts | 103 +- .../change_detector_config.ts | 131 +- .../change_detector_ref_spec.ts | 18 +- .../change_detection/change_detector_spec.ts | 214 +- .../change_detector_util_spec.ts | 27 +- .../core/change_detection/coalesce_spec.ts | 221 +- .../differs/default_iterable_differ_spec.ts | 335 +- .../differs/default_keyvalue_differ_spec.ts | 85 +- .../differs/iterable_differs_spec.ts | 31 +- .../change_detection/parser/lexer_spec.ts | 68 +- .../change_detection/parser/locals_spec.ts | 2 +- .../change_detection/parser/parser_spec.ts | 238 +- .../core/change_detection/parser/unparser.ts | 25 +- .../proto_record_builder_spec.ts | 22 +- .../change_detection/proto_record_spec.ts | 20 +- .../test/core/change_detection/util.ts | 18 +- .../test/core/debug/debug_node_spec.ts | 208 +- modules/angular2/test/core/di/binding_spec.ts | 22 +- .../angular2/test/core/di/forward_ref_spec.ts | 14 +- .../angular2/test/core/di/injector_spec.ts | 257 +- modules/angular2/test/core/di/key_spec.ts | 2 +- .../directive_lifecycle_integration_spec.ts | 86 +- .../test/core/dom/dom_adapter_spec.ts | 16 +- modules/angular2/test/core/dom/shim_spec.ts | 13 +- .../test/core/facade/observable_spec.ts | 34 +- .../test/core/forward_ref_integration_spec.ts | 32 +- .../test/core/linker/compiler_spec.ts | 28 +- .../core/linker/directive_lifecycle_spec.ts | 75 +- .../core/linker/directive_resolver_spec.ts | 71 +- .../linker/dynamic_component_loader_spec.ts | 455 +-- .../angular2/test/core/linker/element_spec.ts | 118 +- .../test/core/linker/integration_spec.ts | 919 ++--- .../linker/projection_integration_spec.ts | 141 +- .../core/linker/query_integration_spec.ts | 688 ++-- .../test/core/linker/query_list_spec.ts | 29 +- .../test/core/linker/view_resolver_spec.ts | 31 +- .../test/core/metadata/decorators_spec.ts | 12 +- .../test/core/reflection/reflector_common.ts | 6 +- .../test/core/reflection/reflector_spec.ts | 223 +- modules/angular2/test/core/spies.ts | 7 +- .../test/core/testability/testability_spec.ts | 14 +- .../test/core/util/decorators_spec.ts | 50 +- .../angular2/test/core/zone/ng_zone_spec.ts | 41 +- modules/angular2/test/dev_mode_spec.ts | 15 +- modules/angular2/test/facade/async_spec.ts | 94 +- .../angular2/test/facade/collection_spec.ts | 34 +- .../test/facade/exception_handler_spec.ts | 92 +- modules/angular2/test/facade/lang_spec.ts | 74 +- .../test/http/backends/jsonp_backend_spec.ts | 32 +- .../test/http/backends/mock_backend_spec.ts | 18 +- .../test/http/backends/xhr_backend_spec.ts | 82 +- .../test/http/base_request_options_spec.ts | 12 +- modules/angular2/test/http/headers_spec.ts | 12 +- modules/angular2/test/http/http_spec.ts | 111 +- .../test/http/url_search_params_spec.ts | 36 +- .../test/i18n/i18n_html_parser_spec.ts | 163 +- .../test/i18n/message_extractor_spec.ts | 154 +- modules/angular2/test/i18n/message_spec.ts | 21 +- .../angular2/test/i18n/xmb_serializer_spec.ts | 65 +- .../test/mock/view_resolver_mock_spec.ts | 10 +- .../test/platform/browser/bootstrap_spec.ts | 104 +- .../test/platform/browser/ruler_spec.ts | 14 +- .../test/platform/browser/tools/tools_spec.ts | 12 +- .../test/platform/browser/xhr_cache_spec.ts | 38 +- .../test/platform/browser/xhr_impl_spec.ts | 12 +- .../dom/dom_renderer_integration_spec.ts | 15 +- .../platform/dom/events/event_manager_spec.ts | 14 +- .../platform/dom/events/key_events_spec.ts | 12 +- .../platform/dom/shared_styles_host_spec.ts | 18 +- modules/angular2/test/public_api_spec.ts | 264 +- .../router/directives/router_link_spec.ts | 98 +- .../directives/router_link_transform_spec.ts | 34 +- .../router/integration/async_route_spec.ts | 18 +- .../integration/auxiliary_route_spec.ts | 15 +- .../test/router/integration/bootstrap_spec.ts | 250 +- .../integration/impl/async_route_spec_impl.ts | 177 +- .../integration/impl/aux_route_spec_impl.ts | 26 +- .../integration/impl/fixture_components.ts | 23 +- .../integration/impl/sync_route_spec_impl.ts | 179 +- .../router/integration/lifecycle_hook_spec.ts | 113 +- .../router/integration/navigation_spec.ts | 40 +- .../router/integration/redirect_route_spec.ts | 25 +- .../router/integration/router_link_spec.ts | 170 +- .../router/integration/sync_route_spec.ts | 14 +- .../angular2/test/router/integration/util.ts | 26 +- .../location/hash_location_strategy_spec.ts | 14 +- .../test/router/location/location_spec.ts | 18 +- .../location/path_location_strategy_spec.ts | 21 +- .../router/route_config/route_config_spec.ts | 224 +- .../test/router/route_registry_spec.ts | 219 +- modules/angular2/test/router/router_spec.ts | 52 +- .../route_paths/param_route_path_spec.ts | 12 +- .../route_paths/regex_route_param_spec.ts | 12 +- .../test/router/rules/rule_set_spec.ts | 131 +- .../angular2/test/router/url_parser_spec.ts | 12 +- .../test/symbol_inspector/symbol_inspector.ts | 20 +- .../symbol_inspector/symbol_inspector_spec.ts | 46 +- .../angular2/test/testing/fake_async_spec.ts | 46 +- .../testing/test_component_builder_spec.ts | 30 +- .../test/testing/testing_internal_spec.ts | 81 +- .../test/testing/testing_public_spec.ts | 129 +- .../angular2/test/upgrade/metadata_spec.ts | 62 +- modules/angular2/test/upgrade/upgrade_spec.ts | 528 +-- .../web_workers/shared/message_bus_spec.ts | 48 +- .../web_workers/shared/message_bus_util.ts | 10 +- .../web_workers/shared/render_store_spec.ts | 14 +- .../shared/service_message_broker_spec.ts | 43 +- .../shared/web_worker_test_util.ts | 62 +- .../worker/platform_location_spec.ts | 67 +- .../worker/renderer_integration_spec.ts | 107 +- .../test/web_workers/worker/xhr_impl_spec.ts | 29 +- modules/angular2/web_worker/ui.ts | 7 +- .../e2e_test/change_detection_perf.ts | 18 +- .../benchmarks/e2e_test/largetable_perf.ts | 6 +- .../e2e_test/naive_infinite_scroll_perf.ts | 7 +- .../e2e_test/naive_infinite_scroll_spec.ts | 29 +- .../change_detection_benchmark.ts | 107 +- .../src/compiler/compiler_benchmark.ts | 38 +- .../src/compiler/selector_benchmark.ts | 4 +- modules/benchmarks/src/costs/index.ts | 49 +- modules/benchmarks/src/di/di_benchmark.ts | 7 +- .../src/largetable/largetable_benchmark.ts | 37 +- .../src/naive_infinite_scroll/common.ts | 5 +- .../src/naive_infinite_scroll/random_data.ts | 23 +- .../src/naive_infinite_scroll/scroll_area.ts | 10 +- .../src/naive_infinite_scroll/scroll_item.ts | 33 +- .../src/static_tree/tree_benchmark.ts | 47 +- modules/benchmarks/src/tree/tree_benchmark.ts | 47 +- .../e2e_test/naive_infinite_scroll_perf.ts | 3 +- .../src/compiler/compiler_benchmark.ts | 125 +- .../src/largetable/largetable_benchmark.ts | 121 +- .../src/static_tree/tree_benchmark.ts | 13 +- .../src/tree/react/index.ts | 18 +- .../src/tree/tree_benchmark.ts | 99 +- modules/benchpress/src/common_options.ts | 13 +- .../data/installed_script.ts | 18 +- .../src/firefox_extension/lib/main.ts | 11 +- .../src/firefox_extension/lib/test_helper.ts | 9 +- modules/benchpress/src/measure_values.ts | 4 +- modules/benchpress/src/metric/multi_metric.ts | 7 +- .../benchpress/src/metric/perflog_metric.ts | 57 +- .../src/reporter/console_reporter.ts | 23 +- .../src/reporter/json_file_reporter.ts | 7 +- .../benchpress/src/reporter/multi_reporter.ts | 5 +- modules/benchpress/src/runner.ts | 7 +- modules/benchpress/src/sample_description.ts | 40 +- modules/benchpress/src/sampler.ts | 40 +- modules/benchpress/src/statistic.ts | 4 +- .../validator/regression_slope_validator.ts | 12 +- .../src/validator/size_validator.ts | 7 +- .../benchpress/src/web_driver_extension.ts | 5 +- .../src/webdriver/chrome_driver_extension.ts | 94 +- .../src/webdriver/firefox_driver_extension.ts | 8 +- .../src/webdriver/ios_driver_extension.ts | 13 +- .../webdriver/selenium_webdriver_adapter.ts | 3 +- .../firefox_extension/parser_util_spec.ts | 76 +- .../firefox_extension/sample_benchmark.ts | 14 +- .../benchpress/test/firefox_extension/spec.ts | 5 +- .../test/metric/multi_metric_spec.ts | 53 +- .../test/metric/perflog_metric_spec.ts | 530 +-- .../test/reporter/console_reporter_spec.ts | 26 +- .../test/reporter/json_file_reporter_spec.ts | 78 +- .../test/reporter/multi_reporter_spec.ts | 39 +- modules/benchpress/test/runner_spec.ts | 76 +- modules/benchpress/test/sampler_spec.ts | 53 +- modules/benchpress/test/statistic_spec.ts | 11 +- .../regression_slope_validator_spec.ts | 31 +- .../test/validator/size_validator_spec.ts | 19 +- .../test/web_driver_extension_spec.ts | 32 +- .../webdriver/chrome_driver_extension_spec.ts | 169 +- .../webdriver/ios_driver_extension_spec.ts | 107 +- .../hash_routing/hash_location_spec.ts | 6 +- .../e2e_test/hello_world/hello_world_spec.ts | 10 +- modules/playground/e2e_test/http/http_spec.ts | 5 +- .../playground/e2e_test/jsonp/jsonp_spec.ts | 5 +- .../e2e_test/routing/routing_spec.ts | 6 +- .../e2e_test/sourcemap/sourcemap_spec.ts | 12 +- .../kitchen_sink/kitchen_sink_spec.ts | 20 +- .../message_broker/message_broker_spec.ts | 22 +- .../web_workers/router/router_spec.ts | 32 +- .../e2e_test/web_workers/todo/todo_spec.ts | 6 +- modules/playground/src/hash_routing/index.ts | 13 +- .../src/model_driven_forms/index.ts | 31 +- .../playground/src/order_management/index.ts | 37 +- .../playground/src/person_management/index.ts | 15 +- modules/playground/src/routing/data.ts | 3022 ++++++++--------- modules/playground/src/routing/inbox-app.ts | 27 +- modules/playground/src/routing/index.ts | 4 +- .../src/template_driven_forms/index.ts | 17 +- modules/playground/src/upgrade/index.ts | 6 +- .../src/web_workers/images/b64.d.ts | 2 +- .../web_workers/images/background_index.ts | 6 +- .../src/web_workers/images/bitmap.d.ts | 2 +- .../src/web_workers/images/index.ts | 11 +- .../src/web_workers/images/index_common.ts | 2 +- .../src/web_workers/images/services/bitmap.ts | 51 +- .../src/web_workers/images/single_thread.ts | 4 +- .../kitchen_sink/background_index.ts | 6 +- .../src/web_workers/kitchen_sink/index.ts | 11 +- .../message_broker/background_index.ts | 6 +- .../src/web_workers/message_broker/index.ts | 51 +- .../message_broker/index_common.ts | 12 +- .../web_workers/router/background_index.ts | 22 +- .../src/web_workers/router/index.ts | 20 +- .../src/web_workers/router/index_common.ts | 6 +- .../src/web_workers/todo/background_index.ts | 6 +- .../playground/src/web_workers/todo/index.ts | 11 +- .../src/web_workers/todo/index_common.ts | 2 +- npm-shrinkwrap.clean.json | 14 +- npm-shrinkwrap.json | 26 +- tools/broccoli/angular_builder.ts | 22 +- tools/broccoli/broccoli-check-imports.ts | 24 +- tools/broccoli/broccoli-dartfmt.ts | 33 +- tools/broccoli/broccoli-dest-copy.ts | 13 +- tools/broccoli/broccoli-flatten.spec.ts | 9 +- tools/broccoli/broccoli-flatten.ts | 5 +- tools/broccoli/broccoli-lodash.ts | 5 +- tools/broccoli/broccoli-merge-trees.spec.ts | 2 +- tools/broccoli/broccoli-merge-trees.ts | 4 +- tools/broccoli/broccoli-replace.ts | 55 +- tools/broccoli/broccoli-ts2dart.ts | 22 +- tools/broccoli/broccoli-typescript.ts | 40 +- tools/broccoli/broccoli-writer.d.ts | 2 +- tools/broccoli/broccoli.d.ts | 4 +- tools/broccoli/diffing-broccoli-plugin.ts | 29 +- tools/broccoli/html-replace/index.ts | 6 +- tools/broccoli/js-replace/index.ts | 2 +- tools/broccoli/multi_copy.ts | 33 +- tools/broccoli/tree-differ.spec.ts | 31 +- tools/broccoli/tree-differ.ts | 21 +- tools/broccoli/trees/browser_tree.ts | 114 +- tools/broccoli/trees/dart_tree.ts | 38 +- tools/broccoli/trees/node_tree.ts | 101 +- tools/metadata/src/collector.ts | 32 +- tools/metadata/src/evaluator.ts | 38 +- tools/metadata/src/schema.ts | 62 +- tools/metadata/test/collector.spec.ts | 152 +- tools/metadata/test/evaluator.spec.ts | 12 +- tools/metadata/test/typescript.mocks.ts | 40 +- tools/public_api_guard/public_api_spec.ts | 1119 ++++-- .../requireInternalWithUnderscoreRule.ts | 2 +- tools/tslint/requireParameterTypeRule.ts | 6 +- tools/tslint/requireReturnTypeRule.ts | 6 +- 527 files changed, 19247 insertions(+), 13970 deletions(-) diff --git a/gulpfile.js b/gulpfile.js index eaa8b2eec7..9863586bab 100644 --- a/gulpfile.js +++ b/gulpfile.js @@ -43,19 +43,21 @@ if (cliArgs.projects) { // --projects=angular2 => {angular2: true} var allProjects = 'angular1_router,angular2,benchmarks,benchmarks_external,benchpress,playground,payload_tests,bundle_deps'; -var cliArgsProjects = (cliArgs.projects || allProjects).split(',').reduce((map, projectName) => { - map[projectName] = true; - return map; -}, {}); +var cliArgsProjects = (cliArgs.projects || allProjects) + .split(',') + .reduce((map, projectName) => { + map[projectName] = true; + return map; + }, {}); var generateEs6 = !cliArgs.projects; function printModulesWarning() { if (!cliArgs.projects && !process.env.CI) { // if users didn't specify projects to build, tell them why and how they should console.warn( - 'Pro Tip: Did you know that you can speed up your build by specifying project name(s)?'); - console.warn(' It\'s like pressing the turbo button in the old days, but better!'); - console.warn(' Examples: --project=angular2 or --project=angular2'); + "Pro Tip: Did you know that you can speed up your build by specifying project name(s)?"); + console.warn(" It's like pressing the turbo button in the old days, but better!"); + console.warn(" Examples: --project=angular2 or --project=angular2"); } } @@ -103,19 +105,18 @@ function runJasmineTests(globs, done) { var fork = require('child_process').fork; var args = ['--'].concat(globs); - fork('./tools/cjs-jasmine', args, { - stdio: 'inherit' - }).on('close', function jasmineCloseHandler(exitCode) { - if (exitCode && treatTestErrorsAsFatal) { - var err = new Error('Jasmine tests failed'); - // Mark the error for gulp similar to how gulp-utils.PluginError does it. - // The stack is not useful in this context. - err.showStack = false; - done(err); - } else { - done(); - } - }); + fork('./tools/cjs-jasmine', args, {stdio: 'inherit'}) + .on('close', function jasmineCloseHandler(exitCode) { + if (exitCode && treatTestErrorsAsFatal) { + var err = new Error('Jasmine tests failed'); + // Mark the error for gulp similar to how gulp-utils.PluginError does it. + // The stack is not useful in this context. + err.showStack = false; + done(err); + } else { + done(); + } + }); } // Note: when DART_SDK is not found, all gulp tasks ending with `.dart` will be skipped. @@ -142,14 +143,18 @@ var CONFIG = { }; var ANGULAR2_BUNDLE_CONFIG = [ - 'angular2/common', 'angular2/core', 'angular2/compiler', 'angular2/instrumentation', - 'angular2/platform/browser', 'angular2/platform/common_dom' + 'angular2/common', + 'angular2/core', + 'angular2/compiler', + 'angular2/instrumentation', + 'angular2/platform/browser', + 'angular2/platform/common_dom' ]; var NG2_BUNDLE_CONTENT = ANGULAR2_BUNDLE_CONFIG.join(' + ') + ' - rxjs/*'; var HTTP_BUNDLE_CONTENT = 'angular2/http - rxjs/* - ' + ANGULAR2_BUNDLE_CONFIG.join(' - '); var ROUTER_BUNDLE_CONTENT = 'angular2/router + angular2/router/router_link_dsl - rxjs/* - ' + - ANGULAR2_BUNDLE_CONFIG.join(' - '); + ANGULAR2_BUNDLE_CONFIG.join(' - '); var TESTING_BUNDLE_CONTENT = 'angular2/testing + angular2/http/testing + angular2/router/testing + angular2/platform/testing/browser - rxjs/* - ' + ANGULAR2_BUNDLE_CONFIG.join(' - '); @@ -169,8 +174,8 @@ var PAYLOAD_TESTS_CONFIG = { bundleName: 'app-bundle-deps.min.js', cases: ['hello_world'], dist: function(caseName, packaging) { - return path.join( - __dirname, CONFIG.dest.js.prod.es5, 'payload_tests', caseName, 'ts/' + packaging); + return path.join(__dirname, CONFIG.dest.js.prod.es5, 'payload_tests', caseName, + 'ts/' + packaging); }, systemjs: {sizeLimits: {'uncompressed': 870 * 1024, 'gzip level=9': 165 * 1024}}, webpack: {sizeLimits: {'uncompressed': 550 * 1024, 'gzip level=9': 120 * 1024}} @@ -192,19 +197,18 @@ gulp.task('build/clean.docs_angular_io', (done) => fse.remove(CONFIG.dest.docs_a gulp.task('build/clean.bundles', (done) => fse.remove(CONFIG.dest.bundles.all, done)); -gulp.task( - 'build/clean.bundles.benchpress', (done) => fse.remove(CONFIG.dest.bundles.benchpress, done)); +gulp.task('build/clean.bundles.benchpress', + (done) => fse.remove(CONFIG.dest.bundles.benchpress, done)); // ------------ // transpile -gulp.task('build/tree.dart', ['build/clean.dart', 'build.tools'], function(done) { - runSequence('!build/tree.dart', sequenceComplete(done)); -}); +gulp.task('build/tree.dart', ['build/clean.dart', 'build.tools'], + function(done) { runSequence('!build/tree.dart', sequenceComplete(done)); }); -gulp.task( - '!build/tree.dart', function() { return angularBuilder.rebuildDartTree(cliArgsProjects); }); +gulp.task('!build/tree.dart', + function() { return angularBuilder.rebuildDartTree(cliArgsProjects); }); // ------------ @@ -214,15 +218,13 @@ gulp.task( gulp.task('pubget.dart', pubget.dir(gulp, gulpPlugins, {dir: '.', command: DART_SDK.PUB})); // Run `pub get` only on the angular2 dir of CONFIG.dest.dart -gulp.task( - '!build/pubget.angular2.dart', - pubget.dir( - gulp, gulpPlugins, {dir: path.join(CONFIG.dest.dart, 'angular2'), command: DART_SDK.PUB})); +gulp.task('!build/pubget.angular2.dart', + pubget.dir(gulp, gulpPlugins, + {dir: path.join(CONFIG.dest.dart, 'angular2'), command: DART_SDK.PUB})); // Run `pub get` over CONFIG.dest.dart -gulp.task( - 'build/pubspec.dart', - pubget.subDir(gulp, gulpPlugins, {dir: CONFIG.dest.dart, command: DART_SDK.PUB})); +gulp.task('build/pubspec.dart', + pubget.subDir(gulp, gulpPlugins, {dir: CONFIG.dest.dart, command: DART_SDK.PUB})); // This is a hacky way to work around dart's pub that creates `packages` symlink in every directory @@ -243,15 +245,14 @@ gulp.task('!build/remove-pub-symlinks', function(done) { return; } - exec( - 'find dist/dart/angular2/test/ -name packages | xargs rm -r', - function(error, stdout, stderr) { - if (error) { - done(stderr); - return; - } - done(); - }); + exec('find dist/dart/angular2/test/ -name packages | xargs rm -r', + function(error, stdout, stderr) { + if (error) { + done(stderr); + return; + } + done(); + }); }); // ------------ @@ -268,17 +269,16 @@ gulp.task('build/analyze.dart', () => { gulp.task('build/analyze.ddc.dart', () => { var dartanalyzer = require('./tools/build/dartanalyzer'); - return dartanalyzer( - gulp, gulpPlugins, {dest: CONFIG.dest.dart, command: DART_SDK.ANALYZER, use_ddc: true}); + return dartanalyzer(gulp, gulpPlugins, + {dest: CONFIG.dest.dart, command: DART_SDK.ANALYZER, use_ddc: true}); }); gulp.task('build/check.apidocs.dart', () => { var dartapidocs = require('./tools/build/dartapidocs'); - return dartapidocs( - gulp, gulpPlugins, - {dest: CONFIG.dest.dart, output: os.tmpdir(), command: DART_SDK.DARTDOCGEN}); + return dartapidocs(gulp, gulpPlugins, + {dest: CONFIG.dest.dart, output: os.tmpdir(), command: DART_SDK.DARTDOCGEN}); }); @@ -288,9 +288,8 @@ gulp.task('build/check.apidocs.dart', () => { gulp.task( 'build/pubbuild.dart', - pubbuild.subdirs( - gulp, gulpPlugins, - {src: CONFIG.dest.dart, dest: CONFIG.dest.js.dart2js, command: DART_SDK.PUB})); + pubbuild.subdirs(gulp, gulpPlugins, + {src: CONFIG.dest.dart, dest: CONFIG.dest.js.dart2js, command: DART_SDK.PUB})); // ------------ // formatting @@ -305,14 +304,14 @@ function doCheckFormat() { gulp.task('check-format', function() { return doCheckFormat().on('warning', function(e) { - console.log('NOTE: this will be promoted to an ERROR in the continuous build'); + console.log("NOTE: this will be promoted to an ERROR in the continuous build"); }); }); gulp.task('enforce-format', function() { return doCheckFormat().on('warning', function(e) { - console.log('ERROR: You forgot to run clang-format on your change.'); - console.log('See https://github.com/angular/angular/blob/master/DEVELOPER.md#clang-format'); + console.log("ERROR: You forgot to run clang-format on your change."); + console.log("See https://github.com/angular/angular/blob/master/DEVELOPER.md#clang-format"); process.exit(1); }); }); @@ -322,14 +321,14 @@ gulp.task('lint', ['build.tools'], function() { // Built-in rules are at // https://github.com/palantir/tslint#supported-rules var tslintConfig = { - 'rules': { - 'requireInternalWithUnderscore': true, - 'requireParameterType': true, - 'requireReturnType': true, - 'semicolon': true, + "rules": { + "requireInternalWithUnderscore": true, + "requireParameterType": true, + "requireReturnType": true, + "semicolon": true, // TODO: find a way to just screen for reserved names - 'variable-name': false + "variable-name": false } }; return gulp.src(['modules/angular2/src/**/*.ts', '!modules/angular2/src/testing/**']) @@ -349,7 +348,7 @@ gulp.task('build/checkCircularDependencies', function(done) { var dependencyObject = madge([CONFIG.dest.js.dev.es5], { format: 'cjs', extensions: ['.js'], - onParseFile: function(data) { data.src = data.src.replace(/\/\* circular \*\//g, '//'); } + onParseFile: function(data) { data.src = data.src.replace(/\/\* circular \*\//g, "//"); } }); var circularDependencies = dependencyObject.circular().getArray(); if (circularDependencies.length > 0) { @@ -420,29 +419,26 @@ gulp.task('!proxyServeDart', proxyServeDart); gulp.task('serve.dart', function(done) { runSequence( [ - '!proxyServeDart', 'serve/playground.dart', 'serve/benchmarks.dart', + '!proxyServeDart', + 'serve/playground.dart', + 'serve/benchmarks.dart', 'serve/benchmarks_external.dart' ], done); }); -gulp.task( - 'serve/playground.dart', - pubserve( - gulp, gulpPlugins, - {command: DART_SDK.PUB, path: CONFIG.dest.dart + '/playground', port: 8004})); +gulp.task('serve/playground.dart', + pubserve(gulp, gulpPlugins, + {command: DART_SDK.PUB, path: CONFIG.dest.dart + '/playground', port: 8004})); -gulp.task( - 'serve/benchmarks.dart', - pubserve( - gulp, gulpPlugins, - {command: DART_SDK.PUB, path: CONFIG.dest.dart + '/benchmarks', port: 8006})); +gulp.task('serve/benchmarks.dart', + pubserve(gulp, gulpPlugins, + {command: DART_SDK.PUB, path: CONFIG.dest.dart + '/benchmarks', port: 8006})); gulp.task( 'serve/benchmarks_external.dart', - pubserve( - gulp, gulpPlugins, - {command: DART_SDK.PUB, path: CONFIG.dest.dart + '/benchmarks_external', port: 8008})); + pubserve(gulp, gulpPlugins, + {command: DART_SDK.PUB, path: CONFIG.dest.dart + '/benchmarks_external', port: 8008})); gulp.task('serve.e2e.dart', ['build.js.cjs'], function(neverDone) { var watch = require('./tools/build/watch'); @@ -470,14 +466,13 @@ function runKarma(configFile, done) { } gulp.task('test.js', function(done) { - runSequence( - 'test.unit.tools/ci', 'test.transpiler.unittest', 'test.unit.js/ci', 'test.unit.cjs/ci', - 'test.typings', 'check-public-api', sequenceComplete(done)); + runSequence('test.unit.tools/ci', 'test.transpiler.unittest', 'test.unit.js/ci', + 'test.unit.cjs/ci', 'test.typings', 'check-public-api', sequenceComplete(done)); }); gulp.task('test.dart', function(done) { - runSequence( - 'versions.dart', 'test.transpiler.unittest', 'test.unit.dart/ci', sequenceComplete(done)); + runSequence('versions.dart', 'test.transpiler.unittest', 'test.unit.dart/ci', + sequenceComplete(done)); }); gulp.task('versions.dart', function() { dartSdk.logVersion(DART_SDK); }); @@ -500,26 +495,24 @@ function getBrowsersFromCLI(provider, isDart) { var input = inputList[i]; var karmaChromeLauncher = require('karma-chrome-launcher'); if (browserProvidersConf.customLaunchers.hasOwnProperty(input) || - karmaChromeLauncher.hasOwnProperty('launcher:' + input)) { + karmaChromeLauncher.hasOwnProperty("launcher:" + input)) { // In case of non-sauce browsers, or browsers defined in karma-chrome-launcher (Chrome, // ChromeCanary and Dartium): // overrides everything, ignoring other options outputList = [input]; isProvider = false; break; - } else if ( - provider && - browserProvidersConf.customLaunchers.hasOwnProperty(provider + '_' + input.toUpperCase())) { + } else if (provider && + browserProvidersConf.customLaunchers.hasOwnProperty(provider + "_" + + input.toUpperCase())) { isProvider = true; - outputList.push(provider + '_' + input.toUpperCase()); - } else if ( - provider && provider == 'SL' && - browserProvidersConf.sauceAliases.hasOwnProperty(input.toUpperCase())) { + outputList.push(provider + "_" + input.toUpperCase()); + } else if (provider && provider == 'SL' && + browserProvidersConf.sauceAliases.hasOwnProperty(input.toUpperCase())) { outputList = outputList.concat(browserProvidersConf.sauceAliases[input.toUpperCase()]); isProvider = true; - } else if ( - provider && provider == 'BS' && - browserProvidersConf.browserstackAliases.hasOwnProperty(input.toUpperCase())) { + } else if (provider && provider == 'BS' && + browserProvidersConf.browserstackAliases.hasOwnProperty(input.toUpperCase())) { outputList = outputList.concat(browserProvidersConf.browserstackAliases[input.toUpperCase()]); isProvider = true; } else { @@ -573,20 +566,19 @@ gulp.task('test.unit.js.browserstack', ['build.js.dev'], function(done) { function launchKarmaWithExternalBrowsers(reporters, browsers, done) { var karma = require('karma'); - new karma - .Server( - { - configFile: __dirname + '/karma-js.conf.js', - singleRun: true, - browserNoActivityTimeout: 240000, - captureTimeout: 120000, - reporters: reporters, - browsers: browsers - }, - function(err) { - done(); - process.exit(err ? 1 : 0); - }) + new karma.Server( + { + configFile: __dirname + '/karma-js.conf.js', + singleRun: true, + browserNoActivityTimeout: 240000, + captureTimeout: 120000, + reporters: reporters, + browsers: browsers + }, + function(err) { + done(); + process.exit(err ? 1 : 0); + }) .start(); } @@ -630,14 +622,13 @@ gulp.task('!test.unit.router/karma-server', function() { gulp.task('!test.unit.router/karma-run', function(done) { var karma = require('karma'); - karma.runner.run( - {configFile: __dirname + '/modules/angular1_router/karma-router.conf.js'}, - function(exitCode) { - // ignore exitCode, we don't want to fail the build in the interactive (non-ci) - // mode - // karma will print all test failures - done(); - }); + karma.runner.run({configFile: __dirname + '/modules/angular1_router/karma-router.conf.js'}, + function(exitCode) { + // ignore exitCode, we don't want to fail the build in the interactive (non-ci) + // mode + // karma will print all test failures + done(); + }); }); gulp.task('buildRouter.dev', function() { @@ -648,21 +639,21 @@ gulp.task('buildRouter.dev', function() { gulp.task('test.unit.dart', function(done) { printModulesWarning(); - runSequence( - 'build/tree.dart', 'build/pure-packages.dart', '!build/pubget.angular2.dart', - '!build/change_detect.dart', '!build/remove-pub-symlinks', function(error) { - var watch = require('./tools/build/watch'); + runSequence('build/tree.dart', 'build/pure-packages.dart', '!build/pubget.angular2.dart', + '!build/change_detect.dart', '!build/remove-pub-symlinks', function(error) { + var watch = require('./tools/build/watch'); - // if initial build failed (likely due to build or formatting step) then exit - // otherwise karma server doesn't start and we can't continue running properly - if (error) { - done(error); - return; - } - // treatTestErrorsAsFatal = false; + // if initial build failed (likely due to build or formatting step) then exit + // otherwise karma server doesn't start and we can't continue running properly + if (error) { + done(error); + return; + } + // treatTestErrorsAsFatal = false; - watch(['modules/angular2/**'], ['!build/tree.dart', '!test.unit.dart/run/angular2']); - }); + watch(['modules/angular2/**'], + ['!build/tree.dart', '!test.unit.dart/run/angular2']); + }); }); // Dart Payload Size Test @@ -671,26 +662,22 @@ gulp.task('test.unit.dart', function(done) { // Measure in bytes. var _DART_PAYLOAD_SIZE_LIMITS = {'uncompressed': 320 * 1024, 'gzip level=9': 90 * 1024}; gulp.task('test.payload.dart/ci', function(done) { - runSequence( - 'build/packages.dart', '!pubget.payload.dart', '!pubbuild.payload.dart', - '!checkAndReport.payload.dart', done); + runSequence('build/packages.dart', '!pubget.payload.dart', '!pubbuild.payload.dart', + '!checkAndReport.payload.dart', done); }); -gulp.task( - '!pubget.payload.dart', - pubget.dir( - gulp, gulpPlugins, {dir: 'modules_dart/payload/hello_world', command: DART_SDK.PUB})); +gulp.task('!pubget.payload.dart', + pubget.dir(gulp, gulpPlugins, + {dir: 'modules_dart/payload/hello_world', command: DART_SDK.PUB})); -gulp.task( - '!pubbuild.payload.dart', - pubbuild.single( - gulp, gulpPlugins, {command: DART_SDK.PUB, src: 'modules_dart/payload/hello_world'})); +gulp.task('!pubbuild.payload.dart', + pubbuild.single(gulp, gulpPlugins, + {command: DART_SDK.PUB, src: 'modules_dart/payload/hello_world'})); gulp.task('!checkAndReport.payload.dart', function() { var reportSize = require('./tools/analytics/reportsize'); - return reportSize( - 'modules_dart/payload/hello_world/build/web/*.dart.js', - {failConditions: _DART_PAYLOAD_SIZE_LIMITS, prefix: 'hello_world'}); + return reportSize('modules_dart/payload/hello_world/build/web/*.dart.js', + {failConditions: _DART_PAYLOAD_SIZE_LIMITS, prefix: 'hello_world'}); }); // JS payload size tracking @@ -714,7 +701,7 @@ gulp.task('!build.payload.js.webpack', function() { return webpack({ // bundle app + framework entry: CASE_PATH + '/index.js', - output: {path: CASE_PATH, filename: 'app-bundle.js'}, + output: {path: CASE_PATH, filename: "app-bundle.js"}, resolve: { extensions: ['', '.js'], packageAlias: '', // option added to ignore "broken" package.json in our dist folder @@ -726,7 +713,8 @@ gulp.task('!build.payload.js.webpack', function() { gulp.src([ 'node_modules/zone.js/dist/zone.js', 'node_modules/zone.js/dist/long-stack-trace-zone.js', - 'node_modules/reflect-metadata/Reflect.js', CASE_PATH + '/app-bundle.js' + 'node_modules/reflect-metadata/Reflect.js', + CASE_PATH + '/app-bundle.js' ]) .pipe(gulpPlugins.concat(PAYLOAD_TESTS_CONFIG.ts.bundleName)) .pipe(gulpPlugins.uglify()) @@ -756,8 +744,10 @@ gulp.task('!build.payload.js.systemjs', function() { gulp.src([ 'node_modules/systemjs/dist/system.src.js', 'dist/js/prod/es5/bundle/angular2-polyfills.js', - 'dist/js/prod/es5/bundle/angular2.js', 'dist/js/prod/es5//rxjs/bundles/Rx.js', - CASE_PATH + '/index.register.js', 'tools/build/systemjs/payload_tests_import.js' + 'dist/js/prod/es5/bundle/angular2.js', + 'dist/js/prod/es5//rxjs/bundles/Rx.js', + CASE_PATH + '/index.register.js', + 'tools/build/systemjs/payload_tests_import.js' ]) .pipe(gulpPlugins.concat(PAYLOAD_TESTS_CONFIG.ts.bundleName)) .pipe(gulpPlugins.uglify()) @@ -773,13 +763,12 @@ gulp.task('!checkAndReport.payload.js', function() { var reportSize = require('./tools/analytics/reportsize'); function caseSizeStream(caseName, packaging) { - return reportSize( - PAYLOAD_TESTS_CONFIG.ts.dist(caseName, packaging) + '/' + - PAYLOAD_TESTS_CONFIG.ts.bundleName, - { - failConditions: PAYLOAD_TESTS_CONFIG.ts[packaging].sizeLimits, - prefix: caseName + '_' + packaging - }); + return reportSize(PAYLOAD_TESTS_CONFIG.ts.dist(caseName, packaging) + '/' + + PAYLOAD_TESTS_CONFIG.ts.bundleName, + { + failConditions: PAYLOAD_TESTS_CONFIG.ts[packaging].sizeLimits, + prefix: caseName + '_' + packaging + }) } return PAYLOAD_TESTS_CONFIG.ts.cases.reduce(function(sizeReportingStreams, caseName) { @@ -789,35 +778,33 @@ gulp.task('!checkAndReport.payload.js', function() { }); gulp.task('watch.dart.dev', function(done) { - runSequence( - 'build/tree.dart', 'build/pure-packages.dart', '!build/pubget.angular2.dart', - '!build/change_detect.dart', '!build/remove-pub-symlinks', function(error) { - var watch = require('./tools/build/watch'); + runSequence('build/tree.dart', 'build/pure-packages.dart', '!build/pubget.angular2.dart', + '!build/change_detect.dart', '!build/remove-pub-symlinks', function(error) { + var watch = require('./tools/build/watch'); - // if initial build failed (likely due to build or formatting step) then exit - // otherwise karma server doesn't start and we can't continue running properly - if (error) { - done(error); - return; - } + // if initial build failed (likely due to build or formatting step) then exit + // otherwise karma server doesn't start and we can't continue running properly + if (error) { + done(error); + return; + } - watch(['modules/angular2/**'], {ignoreInitial: true}, ['!build/tree.dart']); - }); + watch(['modules/angular2/**'], {ignoreInitial: true}, ['!build/tree.dart']); + }); }); gulp.task('test.unit.router/ci', function(done) { var karma = require('karma'); var browserConf = getBrowsersFromCLI(); - new karma - .Server( - { - configFile: __dirname + '/modules/angular1_router/karma-router.conf.js', - singleRun: true, - reporters: ['dots'], - browsers: browserConf.browsersToRun - }, - done) + new karma.Server( + { + configFile: __dirname + '/modules/angular1_router/karma-router.conf.js', + singleRun: true, + reporters: ['dots'], + browsers: browserConf.browsersToRun + }, + done) .start(); }); @@ -825,15 +812,14 @@ gulp.task('test.unit.js/ci', function(done) { var karma = require('karma'); var browserConf = getBrowsersFromCLI(); - new karma - .Server( - { - configFile: __dirname + '/karma-js.conf.js', - singleRun: true, - reporters: ['dots'], - browsers: browserConf.browsersToRun - }, - function(err) { done(); }) + new karma.Server( + { + configFile: __dirname + '/karma-js.conf.js', + singleRun: true, + reporters: ['dots'], + browsers: browserConf.browsersToRun + }, + function(err) { done(); }) .start(); }); @@ -854,10 +840,9 @@ gulp.task('test.unit.js.browserstack/ci', function(done) { }); gulp.task('test.unit.dart/ci', function(done) { - runSequence( - 'test.dart.dartium_symlink', '!test.unit.dart/run/angular2', - '!test.unit.dart/run/angular2_testing', '!test.unit.dart/run/benchpress', - sequenceComplete(done)); + runSequence('test.dart.dartium_symlink', '!test.unit.dart/run/angular2', + '!test.unit.dart/run/angular2_testing', '!test.unit.dart/run/benchpress', + sequenceComplete(done)); }); // At the moment, dart test requires dartium to be an executable on the path. @@ -910,9 +895,8 @@ gulp.task('test.unit.cjs/ci', function(done) { runJasmineTests(['dist/js/cjs/{angular2,benchpress}/test/**/*_spec.js'], done); }); -gulp.task('check-public-api', function(done) { - runJasmineTests(['dist/tools/public_api_guard/**/*_spec.js'], done); -}); +gulp.task('check-public-api', + function(done) { runJasmineTests(['dist/tools/public_api_guard/**/*_spec.js'], done); }); gulp.task('test.unit.cjs', ['build/clean.js', 'build.tools'], function(neverDone) { var watch = require('./tools/build/watch'); @@ -933,21 +917,19 @@ gulp.task('test.unit.dartvm', function(neverDone) { // Watch for changes made in the TS and Dart code under "modules" and // run ts2dart and test change detector generator prior to rerunning the // tests. - watch( - 'modules/angular2/**', {ignoreInitial: true}, - ['!build/tree.dart', '!build/change_detect.dart', '!test.unit.dartvm/run']); + watch('modules/angular2/**', {ignoreInitial: true}, + ['!build/tree.dart', '!build/change_detect.dart', '!test.unit.dartvm/run']); // Watch for changes made in Dart code under "modules_dart", then copy it // to dist and run test change detector generator prior to retunning the // tests. - watch( - 'modules_dart/**', {ignoreInitial: true}, - ['build/pure-packages.dart', '!build/change_detect.dart', '!test.unit.dartvm/run']); + watch('modules_dart/**', {ignoreInitial: true}, + ['build/pure-packages.dart', '!build/change_detect.dart', '!test.unit.dartvm/run']); }); }); -gulp.task( - '!test.unit.dartvm/run', runServerDartTests(gulp, gulpPlugins, {dir: 'dist/dart/angular2'})); +gulp.task('!test.unit.dartvm/run', + runServerDartTests(gulp, gulpPlugins, {dir: 'dist/dart/angular2'})); gulp.task('test.unit.tools/ci', function(done) { @@ -971,9 +953,8 @@ gulp.task('test.server.dart', runServerDartTests(gulp, gulpPlugins, {dest: 'dist // ----------------- // test builders -gulp.task('test.transpiler.unittest', function(done) { - runJasmineTests(['tools/transpiler/unittest/**/*.js'], done); -}); +gulp.task('test.transpiler.unittest', + function(done) { runJasmineTests(['tools/transpiler/unittest/**/*.js'], done); }); // ----------------- // Pre-test checks @@ -1008,14 +989,13 @@ gulp.task('!pre.test.typings.layoutNodeModule', ['build.js.cjs'], function() { }); gulp.task('!pre.test.typings.copyDeps', function() { - return gulp - .src( - [ - 'modules/angular2/typings/angular-protractor/*.ts', - 'modules/angular2/typings/jasmine/*.ts', - 'modules/angular2/typings/selenium-webdriver/*.ts', - ], - {base: 'modules/angular2/typings'}) + return gulp.src( + [ + 'modules/angular2/typings/angular-protractor/*.ts', + 'modules/angular2/typings/jasmine/*.ts', + 'modules/angular2/typings/selenium-webdriver/*.ts', + ], + {base: 'modules/angular2/typings'}) .pipe(gulp.dest(tmpdir)); }); @@ -1023,24 +1003,25 @@ gulp.task('!pre.test.typings.copyTypingsSpec', function() { return gulp.src(['modules/angular2/examples/**/*.ts']).pipe(gulp.dest(tmpdir)); }); -gulp.task( - 'test.typings', - [ - '!pre.test.typings.layoutNodeModule', '!pre.test.typings.copyTypingsSpec', - '!pre.test.typings.copyDeps' - ], - function() { - var tsc = require('gulp-typescript'); +gulp.task('test.typings', + [ + '!pre.test.typings.layoutNodeModule', + '!pre.test.typings.copyTypingsSpec', + '!pre.test.typings.copyDeps' + ], + function() { + var tsc = require('gulp-typescript'); - return gulp.src([tmpdir + '/**/*.ts', '!' + tmpdir + '/node_modules/**/*']).pipe(tsc({ - target: 'ES6', - module: 'commonjs', - experimentalDecorators: true, - noImplicitAny: true, - moduleResolution: 'node', - typescript: require('typescript') - })); - }); + return gulp.src([tmpdir + '/**/*.ts', '!' + tmpdir + '/node_modules/**/*']) + .pipe(tsc({ + target: 'ES6', + module: 'commonjs', + experimentalDecorators: true, + noImplicitAny: true, + moduleResolution: 'node', + typescript: require('typescript') + })); + }); // ----------------- // orchestrated targets @@ -1051,22 +1032,20 @@ gulp.task( // // This task is expected to be run after build/tree.dart gulp.task('build/pure-packages.dart', function(done) { - runSequence( - 'build/pure-packages.dart/standalone', 'build/pure-packages.dart/license', - 'build/pure-packages.dart/angular2', sequenceComplete(done)); + runSequence('build/pure-packages.dart/standalone', 'build/pure-packages.dart/license', + 'build/pure-packages.dart/angular2', sequenceComplete(done)); }); gulp.task('build/pure-packages.dart/standalone', function() { - return gulp - .src([ - 'modules_dart/**/*', - '!modules_dart/**/*.proto', - '!modules_dart/**/packages{,/**}', - '!modules_dart/**/.packages', - '!modules_dart/payload{,/**}', - '!modules_dart/transform{,/**}', - ]) + return gulp.src([ + 'modules_dart/**/*', + '!modules_dart/**/*.proto', + '!modules_dart/**/packages{,/**}', + '!modules_dart/**/.packages', + '!modules_dart/payload{,/**}', + '!modules_dart/transform{,/**}', + ]) .pipe(gulp.dest(CONFIG.dest.dart)); }); @@ -1076,36 +1055,32 @@ gulp.task('build/pure-packages.dart/license', function() { gulp.task('build/pure-packages.dart/angular2', function() { - return gulp - .src([ - 'modules_dart/transform/**/*', - '!modules_dart/transform/**/*.proto', - '!modules_dart/transform/pubspec.yaml', - '!modules_dart/transform/**/packages{,/**}', - ]) + return gulp.src([ + 'modules_dart/transform/**/*', + '!modules_dart/transform/**/*.proto', + '!modules_dart/transform/pubspec.yaml', + '!modules_dart/transform/**/packages{,/**}', + ]) .pipe(gulp.dest(path.join(CONFIG.dest.dart, 'angular2'))); }); // Builds all Dart packages, but does not compile them gulp.task('build/packages.dart', function(done) { - runSequence( - 'lint_protos.dart', 'build/tree.dart', 'build/pure-packages.dart', - // Run after 'build/tree.dart' because broccoli clears the dist/dart folder - '!build/pubget.angular2.dart', '!build/change_detect.dart', sequenceComplete(done)); + runSequence('lint_protos.dart', 'build/tree.dart', 'build/pure-packages.dart', + // Run after 'build/tree.dart' because broccoli clears the dist/dart folder + '!build/pubget.angular2.dart', '!build/change_detect.dart', sequenceComplete(done)); }); // Builds and compiles all Dart packages gulp.task('build.dart', function(done) { - runSequence( - 'build/packages.dart', 'build/pubspec.dart', 'build/analyze.dart', 'build/check.apidocs.dart', - sequenceComplete(done)); + runSequence('build/packages.dart', 'build/pubspec.dart', 'build/analyze.dart', + 'build/check.apidocs.dart', sequenceComplete(done)); }); // public task to build tools -gulp.task('build.tools', ['build/clean.tools'], function(done) { - runSequence('!build.tools', sequenceComplete(done)); -}); +gulp.task('build.tools', ['build/clean.tools'], + function(done) { runSequence('!build.tools', sequenceComplete(done)); }); // private task to build tools @@ -1113,14 +1088,16 @@ gulp.task('!build.tools', function() { var sourcemaps = require('gulp-sourcemaps'); var tsc = require('gulp-typescript'); - var stream = gulp.src(['tools/**/*.ts']).pipe(sourcemaps.init()).pipe(tsc({ - target: 'ES5', - module: 'commonjs', - declaration: true, - // Don't use the version of typescript that gulp-typescript depends on - // see https://github.com/ivogabe/gulp-typescript#typescript-version - typescript: require('typescript') - })); + var stream = gulp.src(['tools/**/*.ts']) + .pipe(sourcemaps.init()) + .pipe(tsc({ + target: 'ES5', + module: 'commonjs', + declaration: true, + // Don't use the version of typescript that gulp-typescript depends on + // see https://github.com/ivogabe/gulp-typescript#typescript-version + typescript: require('typescript') + })); stream = merge2([stream.js.pipe(gulp.dest('dist/tools')), stream.dts.pipe(gulp.dest('dist/tools'))]) .on('error', @@ -1140,9 +1117,8 @@ gulp.task('!build.tools', function() { return stream; }); -gulp.task('broccoli.js.dev', ['build.tools'], function(done) { - runSequence('!broccoli.js.dev', sequenceComplete(done)); -}); +gulp.task('broccoli.js.dev', ['build.tools'], + function(done) { runSequence('!broccoli.js.dev', sequenceComplete(done)); }); gulp.task('!broccoli.js.dev', () => angularBuilder.rebuildBrowserDevTree({ generateEs6: generateEs6, @@ -1158,21 +1134,18 @@ gulp.task('!broccoli.js.prod', () => angularBuilder.rebuildBrowserProdTree({ useBundles: cliArgs.useBundles })); -gulp.task('build.js.dev', ['build/clean.js'], function(done) { - runSequence('broccoli.js.dev', sequenceComplete(done)); -}); +gulp.task('build.js.dev', ['build/clean.js'], + function(done) { runSequence('broccoli.js.dev', sequenceComplete(done)); }); -gulp.task('build.js.prod', ['build.tools'], function(done) { - runSequence('!broccoli.js.prod', sequenceComplete(done)); -}); +gulp.task('build.js.prod', ['build.tools'], + function(done) { runSequence('!broccoli.js.prod', sequenceComplete(done)); }); /** * public task */ -gulp.task('build.js.cjs', ['build.tools'], function(done) { - runSequence('!build.js.cjs', sequenceComplete(done)); -}); +gulp.task('build.js.cjs', ['build.tools'], + function(done) { runSequence('!build.js.cjs', sequenceComplete(done)); }); var firstBuildJsCjs = true; @@ -1181,13 +1154,12 @@ var firstBuildJsCjs = true; * private task */ gulp.task('!build.js.cjs', function() { - return angularBuilder - .rebuildNodeTree({ - generateEs6: generateEs6, - projects: cliArgsProjects, - noTypeChecks: cliArgs.noTypeChecks, - useBundles: cliArgs.useBundles - }) + return angularBuilder.rebuildNodeTree({ + generateEs6: generateEs6, + projects: cliArgsProjects, + noTypeChecks: cliArgs.noTypeChecks, + useBundles: cliArgs.useBundles + }) .then(function() { if (firstBuildJsCjs) { firstBuildJsCjs = false; @@ -1200,7 +1172,7 @@ gulp.task('!build.js.cjs', function() { var bundleConfig = { - paths: {'*': 'dist/js/prod/es5/*.js'}, + paths: {"*": "dist/js/prod/es5/*.js"}, // Files that end up empty after transpilation confuse system-builder // and need to be explitily listed here. // TODO: upgrade system builder and find a way to declare all input as cjs. @@ -1220,10 +1192,10 @@ gulp.task('!bundle.js.prod', ['build.js.prod'], function() { .then(function() { return Promise.all([ bundler.bundle(bundleConfig, HTTP_BUNDLE_CONTENT, './dist/build/http.js', bundlerConfig), - bundler.bundle( - bundleConfig, ROUTER_BUNDLE_CONTENT, './dist/build/router.js', bundlerConfig), - bundler.bundle( - bundleConfig, UPGRADE_BUNDLE_CONTENT, './dist/build/upgrade.js', bundlerConfig) + bundler.bundle(bundleConfig, ROUTER_BUNDLE_CONTENT, './dist/build/router.js', + bundlerConfig), + bundler.bundle(bundleConfig, UPGRADE_BUNDLE_CONTENT, './dist/build/upgrade.js', + bundlerConfig) ]); }); }); @@ -1234,16 +1206,16 @@ gulp.task('!bundle.js.min', ['build.js.prod'], function() { var bundlerConfig = {sourceMaps: true, minify: true, mangle: false, uglify: {compress: {keep_fnames: true}}}; - return bundler - .bundle(bundleConfig, NG2_BUNDLE_CONTENT, './dist/build/angular2.min.js', bundlerConfig) + return bundler.bundle(bundleConfig, NG2_BUNDLE_CONTENT, './dist/build/angular2.min.js', + bundlerConfig) .then(function() { return Promise.all([ - bundler.bundle( - bundleConfig, HTTP_BUNDLE_CONTENT, './dist/build/http.min.js', bundlerConfig), - bundler.bundle( - bundleConfig, ROUTER_BUNDLE_CONTENT, './dist/build/router.min.js', bundlerConfig), - bundler.bundle( - bundleConfig, UPGRADE_BUNDLE_CONTENT, './dist/build/upgrade.min.js', bundlerConfig) + bundler.bundle(bundleConfig, HTTP_BUNDLE_CONTENT, './dist/build/http.min.js', + bundlerConfig), + bundler.bundle(bundleConfig, ROUTER_BUNDLE_CONTENT, './dist/build/router.min.js', + bundlerConfig), + bundler.bundle(bundleConfig, UPGRADE_BUNDLE_CONTENT, './dist/build/upgrade.min.js', + bundlerConfig) ]); }); }); @@ -1254,37 +1226,34 @@ gulp.task('!bundle.js.dev', ['build.js.dev'], function() { var bundlerConfig = {sourceMaps: true}; var devBundleConfig = merge(true, bundleConfig); - devBundleConfig.paths = merge(true, devBundleConfig.paths, {'*': 'dist/js/dev/es5/*.js'}); + devBundleConfig.paths = merge(true, devBundleConfig.paths, {"*": "dist/js/dev/es5/*.js"}); - return bundler - .bundle(devBundleConfig, NG2_BUNDLE_CONTENT, './dist/build/angular2.dev.js', bundlerConfig) + return bundler.bundle(devBundleConfig, NG2_BUNDLE_CONTENT, './dist/build/angular2.dev.js', + bundlerConfig) .then(function() { return Promise.all([ - bundler.bundle( - devBundleConfig, HTTP_BUNDLE_CONTENT, './dist/build/http.dev.js', bundlerConfig), - bundler.bundle( - devBundleConfig, ROUTER_BUNDLE_CONTENT, './dist/build/router.dev.js', bundlerConfig), - bundler.bundle( - devBundleConfig, UPGRADE_BUNDLE_CONTENT, './dist/build/upgrade.dev.js', bundlerConfig) + bundler.bundle(devBundleConfig, HTTP_BUNDLE_CONTENT, './dist/build/http.dev.js', + bundlerConfig), + bundler.bundle(devBundleConfig, ROUTER_BUNDLE_CONTENT, './dist/build/router.dev.js', + bundlerConfig), + bundler.bundle(devBundleConfig, UPGRADE_BUNDLE_CONTENT, './dist/build/upgrade.dev.js', + bundlerConfig) ]); }); }); // WebWorker build -gulp.task('!bundle.web_worker.js.dev', ['build.js.dev'], function() { +gulp.task("!bundle.web_worker.js.dev", ["build.js.dev"], function() { var bundler = require('./tools/build/bundle'); var devBundleConfig = merge(true, bundleConfig); - devBundleConfig.paths = merge(true, devBundleConfig.paths, {'*': 'dist/js/dev/es5/*.js'}); + devBundleConfig.paths = merge(true, devBundleConfig.paths, {"*": "dist/js/dev/es5/*.js"}); - return bundler - .bundle( - devBundleConfig, 'angular2/web_worker/ui', './dist/build/web_worker/ui.dev.js', - {sourceMaps: true}) + return bundler.bundle(devBundleConfig, 'angular2/web_worker/ui', + './dist/build/web_worker/ui.dev.js', {sourceMaps: true}) .then(function() { - return bundler.bundle( - devBundleConfig, 'angular2/web_worker/worker', './dist/build/web_worker/worker.dev.js', - {sourceMaps: true}); + return bundler.bundle(devBundleConfig, 'angular2/web_worker/worker', + './dist/build/web_worker/worker.dev.js', {sourceMaps: true}); }); }); @@ -1292,11 +1261,10 @@ gulp.task('!bundle.testing', ['build.js.dev'], function() { var bundler = require('./tools/build/bundle'); var devBundleConfig = merge(true, bundleConfig); - devBundleConfig.paths = merge(true, devBundleConfig.paths, {'*': 'dist/js/dev/es5/*.js'}); + devBundleConfig.paths = merge(true, devBundleConfig.paths, {"*": "dist/js/dev/es5/*.js"}); - return bundler.bundle( - devBundleConfig, TESTING_BUNDLE_CONTENT, './dist/js/bundle/testing.dev.js', - {sourceMaps: true}); + return bundler.bundle(devBundleConfig, TESTING_BUNDLE_CONTENT, './dist/js/bundle/testing.dev.js', + {sourceMaps: true}); }); gulp.task('!bundles.js.docs', ['clean'], function() { @@ -1362,13 +1330,12 @@ gulp.task('!bundles.js.umd', ['build.js.dev'], function() { } return q.all([ - webpack(webPackConf( - [__dirname + '/tools/build/webpack/angular2-all.umd.js'], 'angular2-all', 'dev')), - webpack(webPackConf( - [__dirname + '/tools/build/webpack/angular2-all.umd.js'], 'angular2-all', 'prod')), - webpack(webPackConf( - [__dirname + '/tools/build/webpack/angular2-all-testing.umd.js'], 'angular2-all-testing', - 'dev')) + webpack(webPackConf([__dirname + '/tools/build/webpack/angular2-all.umd.js'], 'angular2-all', + 'dev')), + webpack(webPackConf([__dirname + '/tools/build/webpack/angular2-all.umd.js'], 'angular2-all', + 'prod')), + webpack(webPackConf([__dirname + '/tools/build/webpack/angular2-all-testing.umd.js'], + 'angular2-all-testing', 'dev')) ]); }); @@ -1386,11 +1353,10 @@ gulp.task('bundles.js.umd.min', ['!bundles.js.umd', '!bundle.ng.polyfills'], fun gulp.task('!bundle.js.prod.deps', ['!bundle.js.prod'], function() { var bundler = require('./tools/build/bundle'); - return merge2( - bundler.modify(['dist/build/angular2.js'], 'angular2.js'), - bundler.modify(['dist/build/http.js'], 'http.js'), - bundler.modify(['dist/build/router.js'], 'router.js'), - bundler.modify(['dist/build/upgrade.js'], 'upgrade.js')) + return merge2(bundler.modify(['dist/build/angular2.js'], 'angular2.js'), + bundler.modify(['dist/build/http.js'], 'http.js'), + bundler.modify(['dist/build/router.js'], 'router.js'), + bundler.modify(['dist/build/upgrade.js'], 'upgrade.js')) .pipe(gulp.dest('dist/js/bundle')); }); @@ -1398,21 +1364,20 @@ gulp.task('!bundle.js.min.deps', ['!bundle.js.min'], function() { var bundler = require('./tools/build/bundle'); var uglify = require('gulp-uglify'); - return merge2( - bundler.modify(['dist/build/angular2.min.js'], 'angular2.min.js'), - bundler.modify(['dist/build/http.min.js'], 'http.min.js'), - bundler.modify(['dist/build/router.min.js'], 'router.min.js'), - bundler.modify(['dist/build/upgrade.min.js'], 'upgrade.min.js')) + return merge2(bundler.modify(['dist/build/angular2.min.js'], 'angular2.min.js'), + bundler.modify(['dist/build/http.min.js'], 'http.min.js'), + bundler.modify(['dist/build/router.min.js'], 'router.min.js'), + bundler.modify(['dist/build/upgrade.min.js'], 'upgrade.min.js')) .pipe(uglify()) .pipe(gulp.dest('dist/js/bundle')); }); -gulp.task('!bundle.ng.polyfills', ['clean'], function() { - return addDevDependencies('angular2-polyfills.js'); -}); +gulp.task('!bundle.ng.polyfills', ['clean'], + function() { return addDevDependencies('angular2-polyfills.js'); }); var JS_DEV_DEPS = [ - licenseWrap('node_modules/zone.js/LICENSE', true), 'node_modules/zone.js/dist/zone.js', + licenseWrap('node_modules/zone.js/LICENSE', true), + 'node_modules/zone.js/dist/zone.js', 'node_modules/zone.js/dist/long-stack-trace-zone.js', licenseWrap('node_modules/reflect-metadata/LICENSE', true), 'node_modules/reflect-metadata/Reflect.js' @@ -1430,26 +1395,23 @@ function addDevDependencies(outputFile) { gulp.task('!bundle.js.dev.deps', ['!bundle.js.dev'], function() { var bundler = require('./tools/build/bundle'); - return merge2( - bundler.modify(['dist/build/angular2.dev.js'], 'angular2.dev.js'), - bundler.modify(['dist/build/http.dev.js'], 'http.dev.js'), - bundler.modify(['dist/build/router.dev.js'], 'router.dev.js'), - bundler.modify(['dist/build/upgrade.dev.js'], 'upgrade.dev.js')) + return merge2(bundler.modify(['dist/build/angular2.dev.js'], 'angular2.dev.js'), + bundler.modify(['dist/build/http.dev.js'], 'http.dev.js'), + bundler.modify(['dist/build/router.dev.js'], 'router.dev.js'), + bundler.modify(['dist/build/upgrade.dev.js'], 'upgrade.dev.js')) .pipe(gulp.dest('dist/js/bundle')); }); gulp.task('!bundle.web_worker.js.dev.deps', ['!bundle.web_worker.js.dev'], function() { var bundler = require('./tools/build/bundle'); - return merge2( - bundler.modify(['dist/build/web_worker/ui.dev.js'], 'web_worker/ui.dev.js'), - bundler.modify(['dist/build/web_worker/worker.dev.js'], 'web_worker/worker.dev.js')) + return merge2(bundler.modify(['dist/build/web_worker/ui.dev.js'], "web_worker/ui.dev.js"), + bundler.modify(['dist/build/web_worker/worker.dev.js'], "web_worker/worker.dev.js")) .pipe(gulp.dest('dist/js/bundle')); }); gulp.task('!bundle.copy', function() { - return merge2( - gulp.src('dist/js/bundle/**').pipe(gulp.dest('dist/js/prod/es5/bundle')), - gulp.src('dist/js/bundle/**').pipe(gulp.dest('dist/js/dev/es5/bundle'))); + return merge2(gulp.src('dist/js/bundle/**').pipe(gulp.dest('dist/js/prod/es5/bundle')), + gulp.src('dist/js/bundle/**').pipe(gulp.dest('dist/js/dev/es5/bundle'))); }); gulp.task('!bundles.js.checksize', function(done) { @@ -1457,21 +1419,27 @@ gulp.task('!bundles.js.checksize', function(done) { return reportSize('dist/js/bundle/**/*.js', {printToConsole: ['gzip level=2']}); }); -gulp.task( - 'bundles.js', - [ - '!bundle.js.prod.deps', '!bundle.js.dev.deps', '!bundle.js.min.deps', - '!bundle.web_worker.js.dev.deps', 'bundles.js.umd.min', '!bundle.testing', - '!bundle.ng.polyfills', '!bundles.js.docs' - ], - function(done) { runSequence('!bundle.copy', '!bundles.js.checksize', done); }); +gulp.task('bundles.js', + [ + '!bundle.js.prod.deps', + '!bundle.js.dev.deps', + '!bundle.js.min.deps', + '!bundle.web_worker.js.dev.deps', + 'bundles.js.umd.min', + '!bundle.testing', + '!bundle.ng.polyfills', + '!bundles.js.docs' + ], + function(done) { runSequence('!bundle.copy', '!bundles.js.checksize', done); }); -gulp.task( - 'build.js', - ['build.js.dev', 'build.js.prod', 'build.js.cjs', 'bundles.js', 'benchpress.bundle']); +gulp.task('build.js', + ['build.js.dev', 'build.js.prod', 'build.js.cjs', 'bundles.js', 'benchpress.bundle']); gulp.task('clean', [ - 'build/clean.tools', 'build/clean.js', 'build/clean.dart', 'build/clean.docs', + 'build/clean.tools', + 'build/clean.js', + 'build/clean.dart', + 'build/clean.docs', 'build/clean.bundles' ]); @@ -1498,8 +1466,8 @@ gulp.task('gen_protos.dart', function(done) { // change detection codegen gulp.task('build.change_detect.dart', function(done) { - return runSequence( - 'build/packages.dart', '!build/pubget.angular2.dart', '!build/change_detect.dart', done); + return runSequence('build/packages.dart', '!build/pubget.angular2.dart', + '!build/change_detect.dart', done); }); gulp.task('!build/change_detect.dart', function(done) { @@ -1514,9 +1482,8 @@ gulp.task('!build/change_detect.dart', function(done) { var genMain = path.join(srcDir, 'gen_change_detectors.dart'); var proc = spawn(DART_SDK.VM, [genMain], {stdio: ['ignore', 'pipe', 'inherit']}); proc.on('error', function(code) { - done(new Error( - 'Failed while generating change detector classes. Please run manually: ' + DART_SDK.VM + - ' ' + dartArgs.join(' '))); + done(new Error('Failed while generating change detector classes. Please run manually: ' + + DART_SDK.VM + ' ' + dartArgs.join(' '))); }); proc.on('close', function() { dartStream.close(); @@ -1532,10 +1499,9 @@ gulp.task('cleanup.builder', function() { return angularBuilder.cleanup(); }); gulp.task('benchpress.bundle', ['build/clean.bundles.benchpress', 'build.js.cjs'], function(cb) { var bundler = require('./tools/build/bundle'); - bundler.benchpressBundle( - BENCHPRESS_BUNDLE_CONFIG.entries, BENCHPRESS_BUNDLE_CONFIG.packageJson, - BENCHPRESS_BUNDLE_CONFIG.includes, BENCHPRESS_BUNDLE_CONFIG.excludes, - BENCHPRESS_BUNDLE_CONFIG.ignore, BENCHPRESS_BUNDLE_CONFIG.dest, cb); + bundler.benchpressBundle(BENCHPRESS_BUNDLE_CONFIG.entries, BENCHPRESS_BUNDLE_CONFIG.packageJson, + BENCHPRESS_BUNDLE_CONFIG.includes, BENCHPRESS_BUNDLE_CONFIG.excludes, + BENCHPRESS_BUNDLE_CONFIG.ignore, BENCHPRESS_BUNDLE_CONFIG.dest, cb); }); @@ -1571,7 +1537,7 @@ gulp.on('task_start', (e) => { analytics.buildSuccess('gulp ', process.uptime() * 1000); } - analytics.buildStart('gulp ' + e.task); + analytics.buildStart('gulp ' + e.task) }); -gulp.on('task_stop', (e) => { analytics.buildSuccess('gulp ' + e.task, e.duration * 1000); }); -gulp.on('task_err', (e) => { analytics.buildError('gulp ' + e.task, e.duration * 1000); }); +gulp.on('task_stop', (e) => {analytics.buildSuccess('gulp ' + e.task, e.duration * 1000)}); +gulp.on('task_err', (e) => {analytics.buildError('gulp ' + e.task, e.duration * 1000)}); diff --git a/modules/angular1_router/src/ng_outlet.ts b/modules/angular1_router/src/ng_outlet.ts index 94059318ce..f348020287 100644 --- a/modules/angular1_router/src/ng_outlet.ts +++ b/modules/angular1_router/src/ng_outlet.ts @@ -78,7 +78,7 @@ function ngOutletDirective($animate, $q: ng.IQService, $rootRouter) { result = this.currentController.$routerCanReuse(nextInstruction, this.currentInstruction); } else { result = nextInstruction === this.currentInstruction || - angular.equals(nextInstruction.params, this.currentInstruction.params); + angular.equals(nextInstruction.params, this.currentInstruction.params); } return $q.when(result); } @@ -110,7 +110,7 @@ function ngOutletDirective($animate, $q: ng.IQService, $rootRouter) { } this.controller.$$template = '<' + dashCase(componentName) + ' $router="::$$router">'; + dashCase(componentName) + '>'; this.controller.$$router = this.router.childRouter(instruction.componentType); this.controller.$$outlet = this; @@ -165,8 +165,8 @@ function routerTriggerDirective($q) { var currentComponent = outlet.currentController = element.controller(ngOutletCtrl.$$componentName); if (currentComponent.$routerOnActivate) { - promise = $q.when(currentComponent.$routerOnActivate( - outlet.currentInstruction, outlet.previousInstruction)); + promise = $q.when(currentComponent.$routerOnActivate(outlet.currentInstruction, + outlet.previousInstruction)); } promise.then(outlet.deferredActivation.resolve, outlet.deferredActivation.reject); } @@ -213,15 +213,14 @@ function ngLinkDirective($rootRouter, $parse) { function getLink(params) { navigationInstruction = router.generate(params); - scope.$watch( - function() { return router.isRouteActive(navigationInstruction); }, - function(active) { - if (active) { - element.addClass('ng-link-active'); - } else { - element.removeClass('ng-link-active'); - } - }); + scope.$watch(function() { return router.isRouteActive(navigationInstruction); }, + function(active) { + if (active) { + element.addClass('ng-link-active'); + } else { + element.removeClass('ng-link-active'); + } + }); const navigationHref = navigationInstruction.toLinkUrl(); return $rootRouter._location.prepareExternalUrl(navigationHref); @@ -233,8 +232,8 @@ function ngLinkDirective($rootRouter, $parse) { let params = routeParamsGetter(); element.attr('href', getLink(params)); } else { - scope.$watch( - () => routeParamsGetter(scope), params => element.attr('href', getLink(params)), true); + scope.$watch(() => routeParamsGetter(scope), params => element.attr('href', getLink(params)), + true); } element.on('click', event => { diff --git a/modules/angular2/core.ts b/modules/angular2/core.ts index e2e8a41be6..f7d786ae62 100644 --- a/modules/angular2/core.ts +++ b/modules/angular2/core.ts @@ -10,7 +10,13 @@ export * from './src/core/di'; export * from './src/facade/facade'; export {enableProdMode} from 'angular2/src/facade/lang'; export {platform, createNgZone, PlatformRef, ApplicationRef} from './src/core/application_ref'; -export {APP_ID, APP_COMPONENT, APP_INITIALIZER, PACKAGE_ROOT_URL, PLATFORM_INITIALIZER} from './src/core/application_tokens'; +export { + APP_ID, + APP_COMPONENT, + APP_INITIALIZER, + PACKAGE_ROOT_URL, + PLATFORM_INITIALIZER +} from './src/core/application_tokens'; export * from './src/core/zone'; export * from './src/core/render'; export * from './src/core/linker'; diff --git a/modules/angular2/examples/core/di/ts/forward_ref/forward_ref.ts b/modules/angular2/examples/core/di/ts/forward_ref/forward_ref.ts index 3e7e8dd048..a9b524b80f 100644 --- a/modules/angular2/examples/core/di/ts/forward_ref/forward_ref.ts +++ b/modules/angular2/examples/core/di/ts/forward_ref/forward_ref.ts @@ -20,7 +20,7 @@ expect(door.lock instanceof Lock).toBe(true); // #enddocregion // #docregion resolve_forward_ref -var ref = forwardRef(() => 'refValue'); -expect(resolveForwardRef(ref)).toEqual('refValue'); -expect(resolveForwardRef('regularValue')).toEqual('regularValue'); +var ref = forwardRef(() => "refValue"); +expect(resolveForwardRef(ref)).toEqual("refValue"); +expect(resolveForwardRef("regularValue")).toEqual("regularValue"); // #enddocregion \ No newline at end of file diff --git a/modules/angular2/examples/core/pipes/ts/async_pipe/async_pipe_example.ts b/modules/angular2/examples/core/pipes/ts/async_pipe/async_pipe_example.ts index 04acb2d2d7..861e644817 100644 --- a/modules/angular2/examples/core/pipes/ts/async_pipe/async_pipe_example.ts +++ b/modules/angular2/examples/core/pipes/ts/async_pipe/async_pipe_example.ts @@ -27,7 +27,7 @@ export class AsyncPipeExample { if (this.arrived) { this.reset(); } else { - this.resolve('hi there!'); + this.resolve("hi there!"); this.arrived = true; } } @@ -35,7 +35,7 @@ export class AsyncPipeExample { // #enddocregion // #docregion AsyncPipeObservable -@Component({selector: 'task-cmp', template: 'Time: {{ time | async }}'}) +@Component({selector: "task-cmp", template: "Time: {{ time | async }}"}) class Task { time = new Observable((observer: Subscriber) => { setInterval(() => observer.next(new Date().getTime()), 500); diff --git a/modules/angular2/examples/router/ts/can_activate/can_activate_example.ts b/modules/angular2/examples/router/ts/can_activate/can_activate_example.ts index eb34b7fc4e..bfa02bf67a 100644 --- a/modules/angular2/examples/router/ts/can_activate/can_activate_example.ts +++ b/modules/angular2/examples/router/ts/can_activate/can_activate_example.ts @@ -1,6 +1,12 @@ import {provide, Component} from 'angular2/core'; import {bootstrap} from 'angular2/platform/browser'; -import {CanActivate, RouteConfig, ComponentInstruction, APP_BASE_HREF, ROUTER_DIRECTIVES} from 'angular2/router'; +import { + CanActivate, + RouteConfig, + ComponentInstruction, + APP_BASE_HREF, + ROUTER_DIRECTIVES +} from 'angular2/router'; function checkIfWeHavePermission(instruction: ComponentInstruction) { return instruction.params['id'] == '1'; diff --git a/modules/angular2/examples/router/ts/can_deactivate/can_deactivate_example.ts b/modules/angular2/examples/router/ts/can_deactivate/can_deactivate_example.ts index b5afae99ef..e330aff1fe 100644 --- a/modules/angular2/examples/router/ts/can_deactivate/can_deactivate_example.ts +++ b/modules/angular2/examples/router/ts/can_deactivate/can_deactivate_example.ts @@ -1,6 +1,13 @@ import {provide, Component} from 'angular2/core'; import {bootstrap} from 'angular2/platform/browser'; -import {CanDeactivate, RouteConfig, RouteParams, ComponentInstruction, ROUTER_DIRECTIVES, APP_BASE_HREF} from 'angular2/router'; +import { + CanDeactivate, + RouteConfig, + RouteParams, + ComponentInstruction, + ROUTER_DIRECTIVES, + APP_BASE_HREF +} from 'angular2/router'; // #docregion routerCanDeactivate @Component({ diff --git a/modules/angular2/examples/router/ts/on_activate/on_activate_example.ts b/modules/angular2/examples/router/ts/on_activate/on_activate_example.ts index bfbc192094..47c24bcd09 100644 --- a/modules/angular2/examples/router/ts/on_activate/on_activate_example.ts +++ b/modules/angular2/examples/router/ts/on_activate/on_activate_example.ts @@ -1,6 +1,12 @@ import {Component, provide} from 'angular2/core'; import {bootstrap} from 'angular2/platform/browser'; -import {OnActivate, ComponentInstruction, RouteConfig, ROUTER_DIRECTIVES, APP_BASE_HREF} from 'angular2/router'; +import { + OnActivate, + ComponentInstruction, + RouteConfig, + ROUTER_DIRECTIVES, + APP_BASE_HREF +} from 'angular2/router'; // #docregion routerOnActivate @Component({template: `Child`}) diff --git a/modules/angular2/examples/router/ts/on_deactivate/on_deactivate_example.ts b/modules/angular2/examples/router/ts/on_deactivate/on_deactivate_example.ts index 790001cdf9..a4b4c15072 100644 --- a/modules/angular2/examples/router/ts/on_deactivate/on_deactivate_example.ts +++ b/modules/angular2/examples/router/ts/on_deactivate/on_deactivate_example.ts @@ -1,6 +1,12 @@ import {Component, Injectable, provide} from 'angular2/core'; import {bootstrap} from 'angular2/platform/browser'; -import {OnDeactivate, ComponentInstruction, RouteConfig, ROUTER_DIRECTIVES, APP_BASE_HREF} from 'angular2/router'; +import { + OnDeactivate, + ComponentInstruction, + RouteConfig, + ROUTER_DIRECTIVES, + APP_BASE_HREF +} from 'angular2/router'; @Injectable() @@ -51,6 +57,7 @@ class AppCmp { export function main() { return bootstrap(AppCmp, [ - provide(APP_BASE_HREF, {useValue: '/angular2/examples/router/ts/on_deactivate'}), LogService + provide(APP_BASE_HREF, {useValue: '/angular2/examples/router/ts/on_deactivate'}), + LogService ]); } diff --git a/modules/angular2/examples/router/ts/reuse/reuse_example.ts b/modules/angular2/examples/router/ts/reuse/reuse_example.ts index 2b7adfc6c4..7a2b182611 100644 --- a/modules/angular2/examples/router/ts/reuse/reuse_example.ts +++ b/modules/angular2/examples/router/ts/reuse/reuse_example.ts @@ -1,6 +1,15 @@ import {Component, provide} from 'angular2/core'; import {bootstrap} from 'angular2/platform/browser'; -import {CanActivate, RouteConfig, ComponentInstruction, ROUTER_DIRECTIVES, APP_BASE_HREF, CanReuse, RouteParams, OnReuse} from 'angular2/router'; +import { + CanActivate, + RouteConfig, + ComponentInstruction, + ROUTER_DIRECTIVES, + APP_BASE_HREF, + CanReuse, + RouteParams, + OnReuse +} from 'angular2/router'; // #docregion reuseCmp @@ -44,6 +53,6 @@ class AppCmp { export function main() { - return bootstrap( - AppCmp, [provide(APP_BASE_HREF, {useValue: '/angular2/examples/router/ts/reuse'})]); + return bootstrap(AppCmp, + [provide(APP_BASE_HREF, {useValue: '/angular2/examples/router/ts/reuse'})]); } diff --git a/modules/angular2/examples/testing/ts/testing.ts b/modules/angular2/examples/testing/ts/testing.ts index 6b5dffcc2a..a8a9980354 100644 --- a/modules/angular2/examples/testing/ts/testing.ts +++ b/modules/angular2/examples/testing/ts/testing.ts @@ -1,4 +1,15 @@ -import {describe, fdescribe, xdescribe, it, fit, xit, beforeEach, afterEach, beforeEachProviders, inject} from 'angular2/testing'; +import { + describe, + fdescribe, + xdescribe, + it, + fit, + xit, + beforeEach, + afterEach, + beforeEachProviders, + inject +} from 'angular2/testing'; import {provide} from 'angular2/core'; var db: any; @@ -19,9 +30,8 @@ fdescribe('some component', () => { // This test will run. }); }); -describe('another component', () => { - it('also has a test', () => { throw 'This test will not run.'; }); -}); +describe('another component', + () => { it('also has a test', () => { throw 'This test will not run.'; }); }); // #enddocregion // #docregion xdescribe @@ -63,10 +73,9 @@ describe('some component', () => { // #docregion beforeEachProviders describe('some component', () => { beforeEachProviders(() => [provide(MyService, {useClass: MyMockService})]); - it('uses MyService', inject( - [MyService], (service: MyMockService) => { - // service is an instance of MyMockService. - })); + it('uses MyService', inject([MyService], (service: MyMockService) => { + // service is an instance of MyMockService. + })); }); // #enddocregion diff --git a/modules/angular2/http.ts b/modules/angular2/http.ts index 6b7e0d1c3b..9b003f2fca 100644 --- a/modules/angular2/http.ts +++ b/modules/angular2/http.ts @@ -16,7 +16,12 @@ import {BaseResponseOptions, ResponseOptions} from './src/http/base_response_opt export {Request} from './src/http/static_request'; export {Response} from './src/http/static_response'; -export {RequestOptionsArgs, ResponseOptionsArgs, Connection, ConnectionBackend} from './src/http/interfaces'; +export { + RequestOptionsArgs, + ResponseOptionsArgs, + Connection, + ConnectionBackend +} from './src/http/interfaces'; export {BrowserXhr} from './src/http/backends/browser_xhr'; export {BaseRequestOptions, RequestOptions} from './src/http/base_request_options'; @@ -150,13 +155,16 @@ export {URLSearchParams} from './src/http/url_search_params'; export const HTTP_PROVIDERS: any[] = [ // TODO(pascal): use factory type annotations once supported in DI // issue: https://github.com/angular/angular/issues/3183 - provide(Http, { - useFactory: (xhrBackend: XHRBackend, requestOptions: RequestOptions) => - new Http(xhrBackend, requestOptions), - deps: [XHRBackend, RequestOptions] - }), - BrowserXhr, provide(RequestOptions, {useClass: BaseRequestOptions}), - provide(ResponseOptions, {useClass: BaseResponseOptions}), XHRBackend + provide(Http, + { + useFactory: (xhrBackend: XHRBackend, requestOptions: RequestOptions) => + new Http(xhrBackend, requestOptions), + deps: [XHRBackend, RequestOptions] + }), + BrowserXhr, + provide(RequestOptions, {useClass: BaseRequestOptions}), + provide(ResponseOptions, {useClass: BaseResponseOptions}), + XHRBackend ]; /** @@ -276,12 +284,14 @@ export const HTTP_BINDINGS = HTTP_PROVIDERS; export const JSONP_PROVIDERS: any[] = [ // TODO(pascal): use factory type annotations once supported in DI // issue: https://github.com/angular/angular/issues/3183 - provide(Jsonp, { - useFactory: (jsonpBackend: JSONPBackend, requestOptions: RequestOptions) => - new Jsonp(jsonpBackend, requestOptions), - deps: [JSONPBackend, RequestOptions] - }), - BrowserJsonp, provide(RequestOptions, {useClass: BaseRequestOptions}), + provide(Jsonp, + { + useFactory: (jsonpBackend: JSONPBackend, requestOptions: RequestOptions) => + new Jsonp(jsonpBackend, requestOptions), + deps: [JSONPBackend, RequestOptions] + }), + BrowserJsonp, + provide(RequestOptions, {useClass: BaseRequestOptions}), provide(ResponseOptions, {useClass: BaseResponseOptions}), provide(JSONPBackend, {useClass: JSONPBackend_}) ]; diff --git a/modules/angular2/instrumentation.ts b/modules/angular2/instrumentation.ts index 1d64e85073..67049babaf 100644 --- a/modules/angular2/instrumentation.ts +++ b/modules/angular2/instrumentation.ts @@ -1 +1,7 @@ -export {wtfCreateScope, wtfLeave, wtfStartTimeRange, wtfEndTimeRange, WtfScopeFn} from './src/core/profile/profile'; +export { + wtfCreateScope, + wtfLeave, + wtfStartTimeRange, + wtfEndTimeRange, + WtfScopeFn +} from './src/core/profile/profile'; diff --git a/modules/angular2/platform/browser.ts b/modules/angular2/platform/browser.ts index ef905838f2..ee4f4498fe 100644 --- a/modules/angular2/platform/browser.ts +++ b/modules/angular2/platform/browser.ts @@ -1,12 +1,27 @@ export {AngularEntrypoint} from 'angular2/src/core/angular_entrypoint'; -export {BROWSER_PROVIDERS, CACHED_TEMPLATE_PROVIDER, ELEMENT_PROBE_PROVIDERS, ELEMENT_PROBE_PROVIDERS_PROD_MODE, inspectNativeElement, BrowserDomAdapter, By, Title, DOCUMENT, enableDebugTools, disableDebugTools} from 'angular2/src/platform/browser_common'; +export { + BROWSER_PROVIDERS, + CACHED_TEMPLATE_PROVIDER, + ELEMENT_PROBE_PROVIDERS, + ELEMENT_PROBE_PROVIDERS_PROD_MODE, + inspectNativeElement, + BrowserDomAdapter, + By, + Title, + DOCUMENT, + enableDebugTools, + disableDebugTools +} from 'angular2/src/platform/browser_common'; import {Type, isPresent, CONST_EXPR} from 'angular2/src/facade/lang'; -import {BROWSER_PROVIDERS, BROWSER_APP_COMMON_PROVIDERS} from 'angular2/src/platform/browser_common'; +import { + BROWSER_PROVIDERS, + BROWSER_APP_COMMON_PROVIDERS +} from 'angular2/src/platform/browser_common'; import {COMPILER_PROVIDERS} from 'angular2/compiler'; import {ComponentRef, platform, reflector} from 'angular2/core'; import {ReflectionCapabilities} from 'angular2/src/core/reflection/reflection_capabilities'; -import {XHRImpl} from 'angular2/src/platform/browser/xhr_impl'; +import {XHRImpl} from "angular2/src/platform/browser/xhr_impl"; import {XHR} from 'angular2/compiler'; import {Provider} from 'angular2/src/core/di'; diff --git a/modules/angular2/platform/browser_static.ts b/modules/angular2/platform/browser_static.ts index eab25aa624..928a31639d 100644 --- a/modules/angular2/platform/browser_static.ts +++ b/modules/angular2/platform/browser_static.ts @@ -1,8 +1,21 @@ export {AngularEntrypoint} from 'angular2/src/core/angular_entrypoint'; -export {BROWSER_PROVIDERS, ELEMENT_PROBE_PROVIDERS, ELEMENT_PROBE_PROVIDERS_PROD_MODE, inspectNativeElement, BrowserDomAdapter, By, Title, enableDebugTools, disableDebugTools} from 'angular2/src/platform/browser_common'; +export { + BROWSER_PROVIDERS, + ELEMENT_PROBE_PROVIDERS, + ELEMENT_PROBE_PROVIDERS_PROD_MODE, + inspectNativeElement, + BrowserDomAdapter, + By, + Title, + enableDebugTools, + disableDebugTools +} from 'angular2/src/platform/browser_common'; import {Type, isPresent} from 'angular2/src/facade/lang'; -import {BROWSER_PROVIDERS, BROWSER_APP_COMMON_PROVIDERS} from 'angular2/src/platform/browser_common'; +import { + BROWSER_PROVIDERS, + BROWSER_APP_COMMON_PROVIDERS +} from 'angular2/src/platform/browser_common'; import {ComponentRef, platform} from 'angular2/core'; /** @@ -16,9 +29,9 @@ export const BROWSER_APP_PROVIDERS: Array = /** * See {@link bootstrap} for more information. */ -export function bootstrapStatic( - appComponentType: Type, customProviders?: Array, - initReflector?: Function): Promise { +export function bootstrapStatic(appComponentType: Type, + customProviders?: Array, + initReflector?: Function): Promise { if (isPresent(initReflector)) { initReflector(); } diff --git a/modules/angular2/platform/common_dom.ts b/modules/angular2/platform/common_dom.ts index 2b4c8a7153..50d3b5ba04 100644 --- a/modules/angular2/platform/common_dom.ts +++ b/modules/angular2/platform/common_dom.ts @@ -6,6 +6,10 @@ export {DomRenderer} from 'angular2/src/platform/dom/dom_renderer'; export {DOCUMENT} from 'angular2/src/platform/dom/dom_tokens'; export {SharedStylesHost, DomSharedStylesHost} from 'angular2/src/platform/dom/shared_styles_host'; export {DomEventsPlugin} from 'angular2/src/platform/dom/events/dom_events'; -export {EVENT_MANAGER_PLUGINS, EventManager, EventManagerPlugin} from 'angular2/src/platform/dom/events/event_manager'; +export { + EVENT_MANAGER_PLUGINS, + EventManager, + EventManagerPlugin +} from 'angular2/src/platform/dom/events/event_manager'; export * from 'angular2/src/platform/dom/debug/by'; export * from 'angular2/src/platform/dom/debug/ng_probe'; diff --git a/modules/angular2/platform/testing/browser.ts b/modules/angular2/platform/testing/browser.ts index 4defef4d1d..d344afb44c 100644 --- a/modules/angular2/platform/testing/browser.ts +++ b/modules/angular2/platform/testing/browser.ts @@ -1,4 +1,7 @@ -import {TEST_BROWSER_STATIC_PLATFORM_PROVIDERS, ADDITIONAL_TEST_BROWSER_PROVIDERS} from 'angular2/platform/testing/browser_static'; +import { + TEST_BROWSER_STATIC_PLATFORM_PROVIDERS, + ADDITIONAL_TEST_BROWSER_PROVIDERS +} from 'angular2/platform/testing/browser_static'; import {BROWSER_APP_PROVIDERS} from 'angular2/platform/browser'; import {CONST_EXPR} from 'angular2/src/facade/lang'; diff --git a/modules/angular2/platform/testing/browser_static.ts b/modules/angular2/platform/testing/browser_static.ts index 06dac1bef5..d1555c719b 100644 --- a/modules/angular2/platform/testing/browser_static.ts +++ b/modules/angular2/platform/testing/browser_static.ts @@ -1,4 +1,12 @@ -import {APP_ID, DirectiveResolver, NgZone, Provider, ViewResolver, PLATFORM_COMMON_PROVIDERS, PLATFORM_INITIALIZER} from 'angular2/core'; +import { + APP_ID, + DirectiveResolver, + NgZone, + Provider, + ViewResolver, + PLATFORM_COMMON_PROVIDERS, + PLATFORM_INITIALIZER +} from 'angular2/core'; import {BROWSER_APP_COMMON_PROVIDERS} from 'angular2/src/platform/browser_common'; import {BrowserDomAdapter} from 'angular2/src/platform/browser/browser_adapter'; @@ -10,7 +18,7 @@ import {MockLocationStrategy} from 'angular2/src/mock/mock_location_strategy'; import {LocationStrategy} from 'angular2/src/router/location/location_strategy'; import {MockNgZone} from 'angular2/src/mock/ng_zone_mock'; -import {XHRImpl} from 'angular2/src/platform/browser/xhr_impl'; +import {XHRImpl} from "angular2/src/platform/browser/xhr_impl"; import {XHR} from 'angular2/compiler'; import {TestComponentBuilder} from 'angular2/src/testing/test_component_builder'; @@ -55,6 +63,7 @@ export const ADDITIONAL_TEST_BROWSER_PROVIDERS: Array = CONST_EXPR([ - BROWSER_APP_COMMON_PROVIDERS, new Provider(XHR, {useClass: XHRImpl}), + BROWSER_APP_COMMON_PROVIDERS, + new Provider(XHR, {useClass: XHRImpl}), ADDITIONAL_TEST_BROWSER_PROVIDERS ]); diff --git a/modules/angular2/platform/testing/server.ts b/modules/angular2/platform/testing/server.ts index 97f7f8f26f..a6bdb3c3b1 100644 --- a/modules/angular2/platform/testing/server.ts +++ b/modules/angular2/platform/testing/server.ts @@ -1,4 +1,14 @@ -import {APP_ID, DirectiveResolver, NgZone, Provider, ViewResolver, PLATFORM_COMMON_PROVIDERS, PLATFORM_INITIALIZER, APPLICATION_COMMON_PROVIDERS, Renderer} from 'angular2/core'; +import { + APP_ID, + DirectiveResolver, + NgZone, + Provider, + ViewResolver, + PLATFORM_COMMON_PROVIDERS, + PLATFORM_INITIALIZER, + APPLICATION_COMMON_PROVIDERS, + Renderer +} from 'angular2/core'; import {Parse5DomAdapter} from 'angular2/src/platform/server/parse5_adapter'; import {AnimationBuilder} from 'angular2/src/animate/animation_builder'; @@ -20,7 +30,11 @@ import {RootRenderer} from 'angular2/src/core/render/api'; import {DomRootRenderer, DomRootRenderer_} from 'angular2/src/platform/dom/dom_renderer'; import {DomSharedStylesHost} from 'angular2/src/platform/dom/shared_styles_host'; -import {EventManager, EVENT_MANAGER_PLUGINS, ELEMENT_PROBE_PROVIDERS} from 'angular2/platform/common_dom'; +import { + EventManager, + EVENT_MANAGER_PLUGINS, + ELEMENT_PROBE_PROVIDERS +} from 'angular2/platform/common_dom'; import {DomEventsPlugin} from 'angular2/src/platform/dom/events/dom_events'; import {CONST_EXPR} from 'angular2/src/facade/lang'; diff --git a/modules/angular2/platform/worker_app.ts b/modules/angular2/platform/worker_app.ts index 0d17735036..d3b255c430 100644 --- a/modules/angular2/platform/worker_app.ts +++ b/modules/angular2/platform/worker_app.ts @@ -1,7 +1,19 @@ -export {WORKER_APP_PLATFORM, WORKER_APP_APPLICATION_COMMON} from 'angular2/src/platform/worker_app_common'; +export { + WORKER_APP_PLATFORM, + WORKER_APP_APPLICATION_COMMON +} from 'angular2/src/platform/worker_app_common'; export {WORKER_APP_APPLICATION} from 'angular2/src/platform/worker_app'; -export {ClientMessageBroker, ClientMessageBrokerFactory, FnArg, UiArguments} from 'angular2/src/web_workers/shared/client_message_broker'; -export {ReceivedMessage, ServiceMessageBroker, ServiceMessageBrokerFactory} from 'angular2/src/web_workers/shared/service_message_broker'; +export { + ClientMessageBroker, + ClientMessageBrokerFactory, + FnArg, + UiArguments +} from 'angular2/src/web_workers/shared/client_message_broker'; +export { + ReceivedMessage, + ServiceMessageBroker, + ServiceMessageBrokerFactory +} from 'angular2/src/web_workers/shared/service_message_broker'; export {PRIMITIVE} from 'angular2/src/web_workers/shared/serializer'; export * from 'angular2/src/web_workers/shared/message_bus'; export {AngularEntrypoint} from 'angular2/src/core/angular_entrypoint'; diff --git a/modules/angular2/platform/worker_render.ts b/modules/angular2/platform/worker_render.ts index 41281325ee..b6b7f3ffa5 100644 --- a/modules/angular2/platform/worker_render.ts +++ b/modules/angular2/platform/worker_render.ts @@ -1,7 +1,21 @@ -export {WORKER_SCRIPT, WORKER_RENDER_PLATFORM, initializeGenericWorkerRenderer, WORKER_RENDER_APPLICATION_COMMON} from 'angular2/src/platform/worker_render_common'; +export { + WORKER_SCRIPT, + WORKER_RENDER_PLATFORM, + initializeGenericWorkerRenderer, + WORKER_RENDER_APPLICATION_COMMON +} from 'angular2/src/platform/worker_render_common'; export {WORKER_RENDER_APPLICATION, WebWorkerInstance} from 'angular2/src/platform/worker_render'; -export {ClientMessageBroker, ClientMessageBrokerFactory, FnArg, UiArguments} from '../src/web_workers/shared/client_message_broker'; -export {ReceivedMessage, ServiceMessageBroker, ServiceMessageBrokerFactory} from '../src/web_workers/shared/service_message_broker'; +export { + ClientMessageBroker, + ClientMessageBrokerFactory, + FnArg, + UiArguments +} from '../src/web_workers/shared/client_message_broker'; +export { + ReceivedMessage, + ServiceMessageBroker, + ServiceMessageBrokerFactory +} from '../src/web_workers/shared/service_message_broker'; export {PRIMITIVE} from '../src/web_workers/shared/serializer'; export * from '../src/web_workers/shared/message_bus'; import {WORKER_RENDER_APPLICATION} from 'angular2/src/platform/worker_render'; diff --git a/modules/angular2/src/animate/animation.ts b/modules/angular2/src/animate/animation.ts index ae5f75bd97..49e14a120a 100644 --- a/modules/angular2/src/animate/animation.ts +++ b/modules/angular2/src/animate/animation.ts @@ -1,4 +1,10 @@ -import {DateWrapper, StringWrapper, RegExpWrapper, NumberWrapper, isPresent} from 'angular2/src/facade/lang'; +import { + DateWrapper, + StringWrapper, + RegExpWrapper, + NumberWrapper, + isPresent +} from 'angular2/src/facade/lang'; import {Math} from 'angular2/src/facade/math'; import {camelCaseToDashCase} from 'angular2/src/platform/dom/util'; import {StringMapWrapper} from 'angular2/src/facade/collection'; @@ -41,9 +47,8 @@ export class Animation { * @param data * @param browserDetails */ - constructor( - public element: HTMLElement, public data: CssAnimationOptions, - public browserDetails: BrowserDetails) { + constructor(public element: HTMLElement, public data: CssAnimationOptions, + public browserDetails: BrowserDetails) { this.startTime = DateWrapper.toMillis(DateWrapper.now()); this._stringPrefix = DOM.getAnimationPrefix(); this.setup(); @@ -75,16 +80,15 @@ export class Animation { this.removeClasses(this.data.classesToRemove); if (this.data.toStyles != null) this.applyStyles(this.data.toStyles); var computedStyles = DOM.getComputedStyle(this.element); - this.computedDelay = Math.max( - this.parseDurationString( - computedStyles.getPropertyValue(this._stringPrefix + 'transition-delay')), - this.parseDurationString( - this.element.style.getPropertyValue(this._stringPrefix + 'transition-delay'))); - this.computedDuration = Math.max( - this.parseDurationString( - computedStyles.getPropertyValue(this._stringPrefix + 'transition-duration')), - this.parseDurationString( - this.element.style.getPropertyValue(this._stringPrefix + 'transition-duration'))); + this.computedDelay = + Math.max(this.parseDurationString( + computedStyles.getPropertyValue(this._stringPrefix + 'transition-delay')), + this.parseDurationString( + this.element.style.getPropertyValue(this._stringPrefix + 'transition-delay'))); + this.computedDuration = Math.max(this.parseDurationString(computedStyles.getPropertyValue( + this._stringPrefix + 'transition-duration')), + this.parseDurationString(this.element.style.getPropertyValue( + this._stringPrefix + 'transition-duration'))); this.addEvents(); } diff --git a/modules/angular2/src/common/directives/core_directives.ts b/modules/angular2/src/common/directives/core_directives.ts index 39b83e914b..64772e101a 100644 --- a/modules/angular2/src/common/directives/core_directives.ts +++ b/modules/angular2/src/common/directives/core_directives.ts @@ -47,5 +47,13 @@ import {NgPlural, NgPluralCase} from './ng_plural'; * ``` */ export const CORE_DIRECTIVES: Type[] = CONST_EXPR([ - NgClass, NgFor, NgIf, NgStyle, NgSwitch, NgSwitchWhen, NgSwitchDefault, NgPlural, NgPluralCase + NgClass, + NgFor, + NgIf, + NgStyle, + NgSwitch, + NgSwitchWhen, + NgSwitchDefault, + NgPlural, + NgPluralCase ]); diff --git a/modules/angular2/src/common/directives/ng_class.ts b/modules/angular2/src/common/directives/ng_class.ts index 2ce3d0fe16..0b997a8a88 100644 --- a/modules/angular2/src/common/directives/ng_class.ts +++ b/modules/angular2/src/common/directives/ng_class.ts @@ -1,5 +1,17 @@ import {isPresent, isString, isArray} from 'angular2/src/facade/lang'; -import {DoCheck, OnDestroy, Directive, ElementRef, IterableDiffers, KeyValueDiffers, Renderer, IterableDiffer, KeyValueDiffer, CollectionChangeRecord, KeyValueChangeRecord} from 'angular2/core'; +import { + DoCheck, + OnDestroy, + Directive, + ElementRef, + IterableDiffers, + KeyValueDiffers, + Renderer, + IterableDiffer, + KeyValueDiffer, + CollectionChangeRecord, + KeyValueChangeRecord +} from 'angular2/core'; import {StringMapWrapper, isListLikeIterable} from 'angular2/src/facade/collection'; /** @@ -66,11 +78,10 @@ export class NgClass implements DoCheck, OnDestroy { private _iterableDiffer: IterableDiffer; private _keyValueDiffer: KeyValueDiffer; private _initialClasses: string[] = []; - private _rawClass: string[]|Set; + private _rawClass: string[] | Set; - constructor( - private _iterableDiffers: IterableDiffers, private _keyValueDiffers: KeyValueDiffers, - private _ngEl: ElementRef, private _renderer: Renderer) {} + constructor(private _iterableDiffers: IterableDiffers, private _keyValueDiffers: KeyValueDiffers, + private _ngEl: ElementRef, private _renderer: Renderer) {} set initialClasses(v: string) { this._applyInitialClasses(true); @@ -79,14 +90,14 @@ export class NgClass implements DoCheck, OnDestroy { this._applyClasses(this._rawClass, false); } - set rawClass(v: string|string[]|Set|{[key: string]: any}) { + set rawClass(v: string | string[] | Set| {[key: string]: any}) { this._cleanupClasses(this._rawClass); if (isString(v)) { v = (v).split(' '); } - this._rawClass = >v; + this._rawClass = >v; this._iterableDiffer = null; this._keyValueDiffer = null; if (isPresent(v)) { @@ -115,7 +126,7 @@ export class NgClass implements DoCheck, OnDestroy { ngOnDestroy(): void { this._cleanupClasses(this._rawClass); } - private _cleanupClasses(rawClassVal: string[]|Set|{[key: string]: any}): void { + private _cleanupClasses(rawClassVal: string[] | Set| {[key: string]: any}): void { this._applyClasses(rawClassVal, true); this._applyInitialClasses(false); } @@ -143,18 +154,18 @@ export class NgClass implements DoCheck, OnDestroy { this._initialClasses.forEach(className => this._toggleClass(className, !isCleanup)); } - private _applyClasses( - rawClassVal: string[]|Set|{[key: string]: any}, isCleanup: boolean) { + private _applyClasses(rawClassVal: string[] | Set| {[key: string]: any}, + isCleanup: boolean) { if (isPresent(rawClassVal)) { if (isArray(rawClassVal)) { (rawClassVal).forEach(className => this._toggleClass(className, !isCleanup)); } else if (rawClassVal instanceof Set) { (>rawClassVal).forEach(className => this._toggleClass(className, !isCleanup)); } else { - StringMapWrapper.forEach( - <{[k: string]: any}>rawClassVal, (expVal: any, className: string) => { - if (isPresent(expVal)) this._toggleClass(className, !isCleanup); - }); + StringMapWrapper.forEach(<{[k: string]: any}>rawClassVal, + (expVal: any, className: string) => { + if (isPresent(expVal)) this._toggleClass(className, !isCleanup); + }); } } } diff --git a/modules/angular2/src/common/directives/ng_for.ts b/modules/angular2/src/common/directives/ng_for.ts index 7c64c581cc..07267ee632 100644 --- a/modules/angular2/src/common/directives/ng_for.ts +++ b/modules/angular2/src/common/directives/ng_for.ts @@ -1,7 +1,20 @@ -import {DoCheck, Directive, ChangeDetectorRef, IterableDiffer, IterableDiffers, ViewContainerRef, TemplateRef, EmbeddedViewRef, TrackByFn} from 'angular2/core'; +import { + DoCheck, + Directive, + ChangeDetectorRef, + IterableDiffer, + IterableDiffers, + ViewContainerRef, + TemplateRef, + EmbeddedViewRef, + TrackByFn +} from 'angular2/core'; import {isPresent, isBlank, stringify, getTypeNameForDebugging} from 'angular2/src/facade/lang'; -import {DefaultIterableDiffer, CollectionChangeRecord} from '../../core/change_detection/differs/default_iterable_differ'; -import {BaseException} from '../../facade/exceptions'; +import { + DefaultIterableDiffer, + CollectionChangeRecord +} from "../../core/change_detection/differs/default_iterable_differ"; +import {BaseException} from "../../facade/exceptions"; /** * The `NgFor` directive instantiates a template once per item from an iterable. The context for @@ -62,9 +75,8 @@ export class NgFor implements DoCheck { _ngForTrackBy: TrackByFn; private _differ: IterableDiffer; - constructor( - private _viewContainer: ViewContainerRef, private _templateRef: TemplateRef, - private _iterableDiffers: IterableDiffers, private _cdr: ChangeDetectorRef) {} + constructor(private _viewContainer: ViewContainerRef, private _templateRef: TemplateRef, + private _iterableDiffers: IterableDiffers, private _cdr: ChangeDetectorRef) {} set ngForOf(value: any) { this._ngForOf = value; @@ -97,19 +109,16 @@ export class NgFor implements DoCheck { // TODO(rado): check if change detection can produce a change record that is // easier to consume than current. var recordViewTuples: RecordViewTuple[] = []; - changes.forEachRemovedItem( - (removedRecord: CollectionChangeRecord) => - recordViewTuples.push(new RecordViewTuple(removedRecord, null))); + changes.forEachRemovedItem((removedRecord: CollectionChangeRecord) => + recordViewTuples.push(new RecordViewTuple(removedRecord, null))); - changes.forEachMovedItem( - (movedRecord: CollectionChangeRecord) => - recordViewTuples.push(new RecordViewTuple(movedRecord, null))); + changes.forEachMovedItem((movedRecord: CollectionChangeRecord) => + recordViewTuples.push(new RecordViewTuple(movedRecord, null))); var insertTuples = this._bulkRemove(recordViewTuples); - changes.forEachAddedItem( - (addedRecord: CollectionChangeRecord) => - insertTuples.push(new RecordViewTuple(addedRecord, null))); + changes.forEachAddedItem((addedRecord: CollectionChangeRecord) => + insertTuples.push(new RecordViewTuple(addedRecord, null))); this._bulkInsert(insertTuples); @@ -137,9 +146,8 @@ export class NgFor implements DoCheck { } private _bulkRemove(tuples: RecordViewTuple[]): RecordViewTuple[] { - tuples.sort( - (a: RecordViewTuple, b: RecordViewTuple) => - a.record.previousIndex - b.record.previousIndex); + tuples.sort((a: RecordViewTuple, b: RecordViewTuple) => + a.record.previousIndex - b.record.previousIndex); var movedTuples: RecordViewTuple[] = []; for (var i = tuples.length - 1; i >= 0; i--) { var tuple = tuples[i]; diff --git a/modules/angular2/src/common/directives/ng_plural.ts b/modules/angular2/src/common/directives/ng_plural.ts index 28ac39adae..e5e892c862 100644 --- a/modules/angular2/src/common/directives/ng_plural.ts +++ b/modules/angular2/src/common/directives/ng_plural.ts @@ -1,4 +1,13 @@ -import {Directive, ViewContainerRef, TemplateRef, ContentChildren, QueryList, Attribute, AfterContentInit, Input} from 'angular2/core'; +import { + Directive, + ViewContainerRef, + TemplateRef, + ContentChildren, + QueryList, + Attribute, + AfterContentInit, + Input +} from 'angular2/core'; import {isPresent, NumberWrapper} from 'angular2/src/facade/lang'; import {Map} from 'angular2/src/facade/collection'; import {SwitchView} from './ng_switch'; @@ -67,9 +76,8 @@ export abstract class NgLocalization { abstract getPluralCategory(value: any): s export class NgPluralCase { /** @internal */ _view: SwitchView; - constructor( - @Attribute('ngPluralCase') public value: string, template: TemplateRef, - viewContainer: ViewContainerRef) { + constructor(@Attribute('ngPluralCase') public value: string, template: TemplateRef, + viewContainer: ViewContainerRef) { this._view = new SwitchView(viewContainer, template); } } @@ -127,7 +135,7 @@ export class NgPlural implements AfterContentInit { } /** @internal */ - _isValueView(pluralCase: NgPluralCase): boolean { return pluralCase.value[0] === '='; } + _isValueView(pluralCase: NgPluralCase): boolean { return pluralCase.value[0] === "="; } /** @internal */ _formatValue(pluralCase: NgPluralCase): any { diff --git a/modules/angular2/src/common/directives/ng_style.ts b/modules/angular2/src/common/directives/ng_style.ts index ed9bcc5b04..3b5824277f 100644 --- a/modules/angular2/src/common/directives/ng_style.ts +++ b/modules/angular2/src/common/directives/ng_style.ts @@ -1,6 +1,13 @@ -import {DoCheck, KeyValueDiffer, KeyValueDiffers, ElementRef, Directive, Renderer} from 'angular2/core'; +import { + DoCheck, + KeyValueDiffer, + KeyValueDiffers, + ElementRef, + Directive, + Renderer +} from 'angular2/core'; import {isPresent, isBlank, print} from 'angular2/src/facade/lang'; -import {KeyValueChangeRecord} from '../../core/change_detection/differs/default_keyvalue_differ'; +import {KeyValueChangeRecord} from "../../core/change_detection/differs/default_keyvalue_differ"; /** * The `NgStyle` directive changes styles based on a result of expression evaluation. @@ -60,8 +67,8 @@ export class NgStyle implements DoCheck { /** @internal */ _differ: KeyValueDiffer; - constructor( - private _differs: KeyValueDiffers, private _ngEl: ElementRef, private _renderer: Renderer) {} + constructor(private _differs: KeyValueDiffers, private _ngEl: ElementRef, + private _renderer: Renderer) {} set rawStyle(v: {[key: string]: string}) { this._rawStyle = v; diff --git a/modules/angular2/src/common/directives/ng_switch.ts b/modules/angular2/src/common/directives/ng_switch.ts index 4ef5b9c769..62afe01b60 100644 --- a/modules/angular2/src/common/directives/ng_switch.ts +++ b/modules/angular2/src/common/directives/ng_switch.ts @@ -175,8 +175,8 @@ export class NgSwitchWhen { _view: SwitchView; private _switch: NgSwitch; - constructor( - viewContainer: ViewContainerRef, templateRef: TemplateRef, @Host() ngSwitch: NgSwitch) { + constructor(viewContainer: ViewContainerRef, templateRef: TemplateRef, + @Host() ngSwitch: NgSwitch) { this._switch = ngSwitch; this._view = new SwitchView(viewContainer, templateRef); } @@ -195,8 +195,8 @@ export class NgSwitchWhen { */ @Directive({selector: '[ngSwitchDefault]'}) export class NgSwitchDefault { - constructor( - viewContainer: ViewContainerRef, templateRef: TemplateRef, @Host() sswitch: NgSwitch) { + constructor(viewContainer: ViewContainerRef, templateRef: TemplateRef, + @Host() sswitch: NgSwitch) { sswitch._registerView(_WHEN_DEFAULT, new SwitchView(viewContainer, templateRef)); } } diff --git a/modules/angular2/src/common/forms.ts b/modules/angular2/src/common/forms.ts index 6a870f8164..f25b8067c2 100644 --- a/modules/angular2/src/common/forms.ts +++ b/modules/angular2/src/common/forms.ts @@ -27,10 +27,19 @@ export {ControlValueAccessor, NG_VALUE_ACCESSOR} from './forms/directives/contro export {DefaultValueAccessor} from './forms/directives/default_value_accessor'; export {NgControlStatus} from './forms/directives/ng_control_status'; export {CheckboxControlValueAccessor} from './forms/directives/checkbox_value_accessor'; -export {NgSelectOption, SelectControlValueAccessor} from './forms/directives/select_control_value_accessor'; +export { + NgSelectOption, + SelectControlValueAccessor +} from './forms/directives/select_control_value_accessor'; export {FORM_DIRECTIVES, RadioButtonState} from './forms/directives'; export {NG_VALIDATORS, NG_ASYNC_VALIDATORS, Validators} from './forms/validators'; -export {RequiredValidator, MinLengthValidator, MaxLengthValidator, PatternValidator, Validator} from './forms/directives/validators'; +export { + RequiredValidator, + MinLengthValidator, + MaxLengthValidator, + PatternValidator, + Validator +} from './forms/directives/validators'; export {FormBuilder} from './forms/form_builder'; import {FormBuilder} from './forms/form_builder'; import {RadioControlRegistry} from './forms/directives/radio_control_value_accessor'; diff --git a/modules/angular2/src/common/forms/directives.ts b/modules/angular2/src/common/forms/directives.ts index b1df6837b4..5becfaa109 100644 --- a/modules/angular2/src/common/forms/directives.ts +++ b/modules/angular2/src/common/forms/directives.ts @@ -10,8 +10,16 @@ import {CheckboxControlValueAccessor} from './directives/checkbox_value_accessor import {NumberValueAccessor} from './directives/number_value_accessor'; import {RadioControlValueAccessor} from './directives/radio_control_value_accessor'; import {NgControlStatus} from './directives/ng_control_status'; -import {SelectControlValueAccessor, NgSelectOption} from './directives/select_control_value_accessor'; -import {RequiredValidator, MinLengthValidator, MaxLengthValidator, PatternValidator} from './directives/validators'; +import { + SelectControlValueAccessor, + NgSelectOption +} from './directives/select_control_value_accessor'; +import { + RequiredValidator, + MinLengthValidator, + MaxLengthValidator, + PatternValidator +} from './directives/validators'; export {NgControlName} from './directives/ng_control_name'; export {NgFormControl} from './directives/ng_form_control'; @@ -21,11 +29,22 @@ export {NgFormModel} from './directives/ng_form_model'; export {NgForm} from './directives/ng_form'; export {DefaultValueAccessor} from './directives/default_value_accessor'; export {CheckboxControlValueAccessor} from './directives/checkbox_value_accessor'; -export {RadioControlValueAccessor, RadioButtonState} from './directives/radio_control_value_accessor'; +export { + RadioControlValueAccessor, + RadioButtonState +} from './directives/radio_control_value_accessor'; export {NumberValueAccessor} from './directives/number_value_accessor'; export {NgControlStatus} from './directives/ng_control_status'; -export {SelectControlValueAccessor, NgSelectOption} from './directives/select_control_value_accessor'; -export {RequiredValidator, MinLengthValidator, MaxLengthValidator, PatternValidator} from './directives/validators'; +export { + SelectControlValueAccessor, + NgSelectOption +} from './directives/select_control_value_accessor'; +export { + RequiredValidator, + MinLengthValidator, + MaxLengthValidator, + PatternValidator +} from './directives/validators'; export {NgControl} from './directives/ng_control'; export {ControlValueAccessor} from './directives/control_value_accessor'; @@ -46,12 +65,24 @@ export {ControlValueAccessor} from './directives/control_value_accessor'; * ``` */ export const FORM_DIRECTIVES: Type[] = CONST_EXPR([ - NgControlName, NgControlGroup, + NgControlName, + NgControlGroup, - NgFormControl, NgModel, NgFormModel, NgForm, + NgFormControl, + NgModel, + NgFormModel, + NgForm, - NgSelectOption, DefaultValueAccessor, NumberValueAccessor, CheckboxControlValueAccessor, - SelectControlValueAccessor, RadioControlValueAccessor, NgControlStatus, + NgSelectOption, + DefaultValueAccessor, + NumberValueAccessor, + CheckboxControlValueAccessor, + SelectControlValueAccessor, + RadioControlValueAccessor, + NgControlStatus, - RequiredValidator, MinLengthValidator, MaxLengthValidator, PatternValidator + RequiredValidator, + MinLengthValidator, + MaxLengthValidator, + PatternValidator ]); diff --git a/modules/angular2/src/common/forms/directives/control_value_accessor.ts b/modules/angular2/src/common/forms/directives/control_value_accessor.ts index 66784979e9..90820f7d70 100644 --- a/modules/angular2/src/common/forms/directives/control_value_accessor.ts +++ b/modules/angular2/src/common/forms/directives/control_value_accessor.ts @@ -31,4 +31,4 @@ export interface ControlValueAccessor { * * See {@link DefaultValueAccessor} for how to implement one. */ -export const NG_VALUE_ACCESSOR: OpaqueToken = CONST_EXPR(new OpaqueToken('NgValueAccessor')); \ No newline at end of file +export const NG_VALUE_ACCESSOR: OpaqueToken = CONST_EXPR(new OpaqueToken("NgValueAccessor")); \ No newline at end of file diff --git a/modules/angular2/src/common/forms/directives/ng_control_group.ts b/modules/angular2/src/common/forms/directives/ng_control_group.ts index a3b643f63f..f66b6eceb2 100644 --- a/modules/angular2/src/common/forms/directives/ng_control_group.ts +++ b/modules/angular2/src/common/forms/directives/ng_control_group.ts @@ -1,4 +1,15 @@ -import {OnInit, OnDestroy, Directive, Optional, Inject, Host, SkipSelf, forwardRef, Provider, Self} from 'angular2/core'; +import { + OnInit, + OnDestroy, + Directive, + Optional, + Inject, + Host, + SkipSelf, + forwardRef, + Provider, + Self +} from 'angular2/core'; import {CONST_EXPR} from 'angular2/src/facade/lang'; import {ControlContainer} from './control_container'; @@ -67,10 +78,9 @@ export class NgControlGroup extends ControlContainer implements OnInit, /** @internal */ _parent: ControlContainer; - constructor( - @Host() @SkipSelf() parent: ControlContainer, - @Optional() @Self() @Inject(NG_VALIDATORS) private _validators: any[], - @Optional() @Self() @Inject(NG_ASYNC_VALIDATORS) private _asyncValidators: any[]) { + constructor(@Host() @SkipSelf() parent: ControlContainer, + @Optional() @Self() @Inject(NG_VALIDATORS) private _validators: any[], + @Optional() @Self() @Inject(NG_ASYNC_VALIDATORS) private _asyncValidators: any[]) { super(); this._parent = parent; } diff --git a/modules/angular2/src/common/forms/directives/ng_control_name.ts b/modules/angular2/src/common/forms/directives/ng_control_name.ts index 3c0bfb9813..57493193fb 100644 --- a/modules/angular2/src/common/forms/directives/ng_control_name.ts +++ b/modules/angular2/src/common/forms/directives/ng_control_name.ts @@ -1,12 +1,31 @@ import {CONST_EXPR} from 'angular2/src/facade/lang'; import {EventEmitter, ObservableWrapper} from 'angular2/src/facade/async'; -import {OnChanges, OnDestroy, SimpleChange, Query, Directive, forwardRef, Host, SkipSelf, Provider, Inject, Optional, Self} from 'angular2/core'; +import { + OnChanges, + OnDestroy, + SimpleChange, + Query, + Directive, + forwardRef, + Host, + SkipSelf, + Provider, + Inject, + Optional, + Self +} from 'angular2/core'; import {ControlContainer} from './control_container'; import {NgControl} from './ng_control'; import {ControlValueAccessor, NG_VALUE_ACCESSOR} from './control_value_accessor'; -import {controlPath, composeValidators, composeAsyncValidators, isPropertyUpdated, selectValueAccessor} from './shared'; +import { + controlPath, + composeValidators, + composeAsyncValidators, + isPropertyUpdated, + selectValueAccessor +} from './shared'; import {Control} from '../model'; import {NG_VALIDATORS, NG_ASYNC_VALIDATORS} from '../validators'; import {ValidatorFn, AsyncValidatorFn} from './validators'; @@ -92,37 +111,35 @@ export class NgControlName extends NgControl implements OnChanges, /* Array */ any[], @Optional() @Self() @Inject(NG_VALUE_ACCESSOR) valueAccessors: ControlValueAccessor[]) { - super(); - this.valueAccessor = selectValueAccessor(this, valueAccessors); - } + super(); + this.valueAccessor = selectValueAccessor(this, valueAccessors); + } - ngOnChanges(changes: {[key: string]: SimpleChange}) { - if (!this._added) { - this.formDirective.addControl(this); - this._added = true; - } - if (isPropertyUpdated(changes, this.viewModel)) { - this.viewModel = this.model; - this.formDirective.updateModel(this, this.model); - } - } + ngOnChanges(changes: {[key: string]: SimpleChange}) { + if (!this._added) { + this.formDirective.addControl(this); + this._added = true; + } + if (isPropertyUpdated(changes, this.viewModel)) { + this.viewModel = this.model; + this.formDirective.updateModel(this, this.model); + } + } - ngOnDestroy(): void { this.formDirective.removeControl(this); } + ngOnDestroy(): void { this.formDirective.removeControl(this); } - viewToModelUpdate(newValue: any): void { - this.viewModel = newValue; - ObservableWrapper.callEmit(this.update, newValue); - } + viewToModelUpdate(newValue: any): void { + this.viewModel = newValue; + ObservableWrapper.callEmit(this.update, newValue); + } - get path(): string[] { return controlPath(this.name, this._parent); } + get path(): string[] { return controlPath(this.name, this._parent); } - get formDirective(): any { return this._parent.formDirective; } + get formDirective(): any { return this._parent.formDirective; } - get validator(): ValidatorFn { return composeValidators(this._validators); } + get validator(): ValidatorFn { return composeValidators(this._validators); } - get asyncValidator(): AsyncValidatorFn { - return composeAsyncValidators(this._asyncValidators); - } + get asyncValidator(): AsyncValidatorFn { return composeAsyncValidators(this._asyncValidators); } - get control(): Control { return this.formDirective.getControl(this); } + get control(): Control { return this.formDirective.getControl(this); } } diff --git a/modules/angular2/src/common/forms/directives/ng_form.ts b/modules/angular2/src/common/forms/directives/ng_form.ts index e8524d1925..639bbf4a58 100644 --- a/modules/angular2/src/common/forms/directives/ng_form.ts +++ b/modules/angular2/src/common/forms/directives/ng_form.ts @@ -1,4 +1,9 @@ -import {PromiseWrapper, ObservableWrapper, EventEmitter, PromiseCompleter} from 'angular2/src/facade/async'; +import { + PromiseWrapper, + ObservableWrapper, + EventEmitter, + PromiseCompleter +} from 'angular2/src/facade/async'; import {StringMapWrapper, ListWrapper} from 'angular2/src/facade/collection'; import {isPresent, isBlank, CONST_EXPR} from 'angular2/src/facade/lang'; import {Directive, forwardRef, Provider, Optional, Inject, Self} from 'angular2/core'; @@ -85,12 +90,11 @@ export class NgForm extends ControlContainer implements Form { form: ControlGroup; ngSubmit = new EventEmitter(); - constructor( - @Optional() @Self() @Inject(NG_VALIDATORS) validators: any[], - @Optional() @Self() @Inject(NG_ASYNC_VALIDATORS) asyncValidators: any[]) { + constructor(@Optional() @Self() @Inject(NG_VALIDATORS) validators: any[], + @Optional() @Self() @Inject(NG_ASYNC_VALIDATORS) asyncValidators: any[]) { super(); - this.form = new ControlGroup( - {}, null, composeValidators(validators), composeAsyncValidators(asyncValidators)); + this.form = new ControlGroup({}, null, composeValidators(validators), + composeAsyncValidators(asyncValidators)); } get formDirective(): Form { return this; } diff --git a/modules/angular2/src/common/forms/directives/ng_form_control.ts b/modules/angular2/src/common/forms/directives/ng_form_control.ts index b445e32e26..b69d0d9fb5 100644 --- a/modules/angular2/src/common/forms/directives/ng_form_control.ts +++ b/modules/angular2/src/common/forms/directives/ng_form_control.ts @@ -1,12 +1,28 @@ import {CONST_EXPR} from 'angular2/src/facade/lang'; import {StringMapWrapper} from 'angular2/src/facade/collection'; import {EventEmitter, ObservableWrapper} from 'angular2/src/facade/async'; -import {OnChanges, SimpleChange, Query, Directive, forwardRef, Provider, Inject, Optional, Self} from 'angular2/core'; +import { + OnChanges, + SimpleChange, + Query, + Directive, + forwardRef, + Provider, + Inject, + Optional, + Self +} from 'angular2/core'; import {NgControl} from './ng_control'; import {Control} from '../model'; import {Validators, NG_VALIDATORS, NG_ASYNC_VALIDATORS} from '../validators'; import {ControlValueAccessor, NG_VALUE_ACCESSOR} from './control_value_accessor'; -import {setUpControl, composeValidators, composeAsyncValidators, isPropertyUpdated, selectValueAccessor} from './shared'; +import { + setUpControl, + composeValidators, + composeAsyncValidators, + isPropertyUpdated, + selectValueAccessor +} from './shared'; import {ValidatorFn, AsyncValidatorFn} from './validators'; const formControlBinding = @@ -78,37 +94,35 @@ export class NgFormControl extends NgControl implements OnChanges { /* Array */ any[], @Optional() @Self() @Inject(NG_VALUE_ACCESSOR) valueAccessors: ControlValueAccessor[]) { - super(); - this.valueAccessor = selectValueAccessor(this, valueAccessors); - } + super(); + this.valueAccessor = selectValueAccessor(this, valueAccessors); + } - ngOnChanges(changes: {[key: string]: SimpleChange}): void { - if (this._isControlChanged(changes)) { - setUpControl(this.form, this); - this.form.updateValueAndValidity({emitEvent: false}); - } - if (isPropertyUpdated(changes, this.viewModel)) { - this.form.updateValue(this.model); - this.viewModel = this.model; - } - } + ngOnChanges(changes: {[key: string]: SimpleChange}): void { + if (this._isControlChanged(changes)) { + setUpControl(this.form, this); + this.form.updateValueAndValidity({emitEvent: false}); + } + if (isPropertyUpdated(changes, this.viewModel)) { + this.form.updateValue(this.model); + this.viewModel = this.model; + } + } - get path(): string[] { return []; } + get path(): string[] { return []; } - get validator(): ValidatorFn { return composeValidators(this._validators); } + get validator(): ValidatorFn { return composeValidators(this._validators); } - get asyncValidator(): AsyncValidatorFn { - return composeAsyncValidators(this._asyncValidators); - } + get asyncValidator(): AsyncValidatorFn { return composeAsyncValidators(this._asyncValidators); } - get control(): Control { return this.form; } + get control(): Control { return this.form; } - viewToModelUpdate(newValue: any): void { - this.viewModel = newValue; - ObservableWrapper.callEmit(this.update, newValue); - } + viewToModelUpdate(newValue: any): void { + this.viewModel = newValue; + ObservableWrapper.callEmit(this.update, newValue); + } - private _isControlChanged(changes: {[key: string]: any}): boolean { - return StringMapWrapper.contains(changes, 'form'); - } + private _isControlChanged(changes: {[key: string]: any}): boolean { + return StringMapWrapper.contains(changes, "form"); + } } diff --git a/modules/angular2/src/common/forms/directives/ng_form_model.ts b/modules/angular2/src/common/forms/directives/ng_form_model.ts index fecf0aa252..26ae1dff6c 100644 --- a/modules/angular2/src/common/forms/directives/ng_form_model.ts +++ b/modules/angular2/src/common/forms/directives/ng_form_model.ts @@ -1,7 +1,16 @@ import {CONST_EXPR} from 'angular2/src/facade/lang'; import {ListWrapper, StringMapWrapper} from 'angular2/src/facade/collection'; import {ObservableWrapper, EventEmitter} from 'angular2/src/facade/async'; -import {SimpleChange, OnChanges, Directive, forwardRef, Provider, Inject, Optional, Self} from 'angular2/core'; +import { + SimpleChange, + OnChanges, + Directive, + forwardRef, + Provider, + Inject, + Optional, + Self +} from 'angular2/core'; import {NgControl} from './ng_control'; import {NgControlGroup} from './ng_control_group'; import {ControlContainer} from './control_container'; @@ -99,14 +108,13 @@ export class NgFormModel extends ControlContainer implements Form, directives: NgControl[] = []; ngSubmit = new EventEmitter(); - constructor( - @Optional() @Self() @Inject(NG_VALIDATORS) private _validators: any[], - @Optional() @Self() @Inject(NG_ASYNC_VALIDATORS) private _asyncValidators: any[]) { + constructor(@Optional() @Self() @Inject(NG_VALIDATORS) private _validators: any[], + @Optional() @Self() @Inject(NG_ASYNC_VALIDATORS) private _asyncValidators: any[]) { super(); } ngOnChanges(changes: {[key: string]: SimpleChange}): void { - if (StringMapWrapper.contains(changes, 'form')) { + if (StringMapWrapper.contains(changes, "form")) { var sync = composeValidators(this._validators); this.form.validator = Validators.compose([this.form.validator, sync]); diff --git a/modules/angular2/src/common/forms/directives/ng_model.ts b/modules/angular2/src/common/forms/directives/ng_model.ts index 0188c18c7d..4bcbb960df 100644 --- a/modules/angular2/src/common/forms/directives/ng_model.ts +++ b/modules/angular2/src/common/forms/directives/ng_model.ts @@ -1,11 +1,26 @@ import {CONST_EXPR} from 'angular2/src/facade/lang'; import {EventEmitter, ObservableWrapper} from 'angular2/src/facade/async'; -import {OnChanges, SimpleChange, Directive, forwardRef, Provider, Inject, Optional, Self} from 'angular2/core'; +import { + OnChanges, + SimpleChange, + Directive, + forwardRef, + Provider, + Inject, + Optional, + Self +} from 'angular2/core'; import {ControlValueAccessor, NG_VALUE_ACCESSOR} from './control_value_accessor'; import {NgControl} from './ng_control'; import {Control} from '../model'; import {NG_VALIDATORS, NG_ASYNC_VALIDATORS} from '../validators'; -import {setUpControl, isPropertyUpdated, selectValueAccessor, composeValidators, composeAsyncValidators} from './shared'; +import { + setUpControl, + isPropertyUpdated, + selectValueAccessor, + composeValidators, + composeAsyncValidators +} from './shared'; import {ValidatorFn, AsyncValidatorFn} from './validators'; const formControlBinding = @@ -52,35 +67,33 @@ export class NgModel extends NgControl implements OnChanges { @Optional() @Self() @Inject(NG_ASYNC_VALIDATORS) private _asyncValidators: any[], @Optional() @Self() @Inject(NG_VALUE_ACCESSOR) valueAccessors: ControlValueAccessor[]) { - super(); - this.valueAccessor = selectValueAccessor(this, valueAccessors); - } + super(); + this.valueAccessor = selectValueAccessor(this, valueAccessors); + } - ngOnChanges(changes: {[key: string]: SimpleChange}) { - if (!this._added) { - setUpControl(this._control, this); - this._control.updateValueAndValidity({emitEvent: false}); - this._added = true; - } + ngOnChanges(changes: {[key: string]: SimpleChange}) { + if (!this._added) { + setUpControl(this._control, this); + this._control.updateValueAndValidity({emitEvent: false}); + this._added = true; + } - if (isPropertyUpdated(changes, this.viewModel)) { - this._control.updateValue(this.model); - this.viewModel = this.model; - } - } + if (isPropertyUpdated(changes, this.viewModel)) { + this._control.updateValue(this.model); + this.viewModel = this.model; + } + } - get control(): Control { return this._control; } + get control(): Control { return this._control; } - get path(): string[] { return []; } + get path(): string[] { return []; } - get validator(): ValidatorFn { return composeValidators(this._validators); } + get validator(): ValidatorFn { return composeValidators(this._validators); } - get asyncValidator(): AsyncValidatorFn { - return composeAsyncValidators(this._asyncValidators); - } + get asyncValidator(): AsyncValidatorFn { return composeAsyncValidators(this._asyncValidators); } - viewToModelUpdate(newValue: any): void { - this.viewModel = newValue; - ObservableWrapper.callEmit(this.update, newValue); - } + viewToModelUpdate(newValue: any): void { + this.viewModel = newValue; + ObservableWrapper.callEmit(this.update, newValue); + } } diff --git a/modules/angular2/src/common/forms/directives/normalize_validator.ts b/modules/angular2/src/common/forms/directives/normalize_validator.ts index c956c8d4ae..85e2ebdfbb 100644 --- a/modules/angular2/src/common/forms/directives/normalize_validator.ts +++ b/modules/angular2/src/common/forms/directives/normalize_validator.ts @@ -1,4 +1,4 @@ -import {AbstractControl} from '../model'; +import {AbstractControl} from "../model"; import {Validator, ValidatorFn, AsyncValidatorFn} from './validators'; export function normalizeValidator(validator: ValidatorFn | Validator): ValidatorFn { diff --git a/modules/angular2/src/common/forms/directives/radio_control_value_accessor.ts b/modules/angular2/src/common/forms/directives/radio_control_value_accessor.ts index 9add896a7b..ee9475643e 100644 --- a/modules/angular2/src/common/forms/directives/radio_control_value_accessor.ts +++ b/modules/angular2/src/common/forms/directives/radio_control_value_accessor.ts @@ -1,5 +1,21 @@ -import {Directive, ElementRef, Renderer, Self, forwardRef, Provider, Attribute, Input, OnInit, OnDestroy, Injector, Injectable} from 'angular2/core'; -import {NG_VALUE_ACCESSOR, ControlValueAccessor} from 'angular2/src/common/forms/directives/control_value_accessor'; +import { + Directive, + ElementRef, + Renderer, + Self, + forwardRef, + Provider, + Attribute, + Input, + OnInit, + OnDestroy, + Injector, + Injectable +} from 'angular2/core'; +import { + NG_VALUE_ACCESSOR, + ControlValueAccessor +} from 'angular2/src/common/forms/directives/control_value_accessor'; import {NgControl} from 'angular2/src/common/forms/directives/ng_control'; import {CONST_EXPR, looseIdentical, isPresent} from 'angular2/src/facade/lang'; import {ListWrapper} from 'angular2/src/facade/collection'; @@ -82,9 +98,8 @@ export class RadioControlValueAccessor implements ControlValueAccessor, onChange = () => {}; onTouched = () => {}; - constructor( - private _renderer: Renderer, private _elementRef: ElementRef, - private _registry: RadioControlRegistry, private _injector: Injector) {} + constructor(private _renderer: Renderer, private _elementRef: ElementRef, + private _registry: RadioControlRegistry, private _injector: Injector) {} ngOnInit(): void { this._control = this._injector.get(NgControl); diff --git a/modules/angular2/src/common/forms/directives/select_control_value_accessor.ts b/modules/angular2/src/common/forms/directives/select_control_value_accessor.ts index 622b25320a..afc5c85797 100644 --- a/modules/angular2/src/common/forms/directives/select_control_value_accessor.ts +++ b/modules/angular2/src/common/forms/directives/select_control_value_accessor.ts @@ -1,6 +1,23 @@ -import {Directive, Renderer, forwardRef, Provider, ElementRef, Input, Host, OnDestroy, Optional} from 'angular2/core'; +import { + Directive, + Renderer, + forwardRef, + Provider, + ElementRef, + Input, + Host, + OnDestroy, + Optional +} from 'angular2/core'; import {NG_VALUE_ACCESSOR, ControlValueAccessor} from './control_value_accessor'; -import {CONST_EXPR, StringWrapper, isPrimitive, isPresent, isBlank, looseIdentical} from 'angular2/src/facade/lang'; +import { + CONST_EXPR, + StringWrapper, + isPrimitive, + isPresent, + isBlank, + looseIdentical +} from 'angular2/src/facade/lang'; import {MapWrapper} from 'angular2/src/facade/collection'; @@ -9,12 +26,12 @@ const SELECT_VALUE_ACCESSOR = CONST_EXPR(new Provider( function _buildValueString(id: string, value: any): string { if (isBlank(id)) return `${value}`; - if (!isPrimitive(value)) value = 'Object'; + if (!isPrimitive(value)) value = "Object"; return StringWrapper.slice(`${id}: ${value}`, 0, 50); } function _extractId(valueString: string): string { - return valueString.split(':')[0]; + return valueString.split(":")[0]; } /** @@ -81,9 +98,8 @@ export class SelectControlValueAccessor implements ControlValueAccessor { export class NgSelectOption implements OnDestroy { id: string; - constructor( - private _element: ElementRef, private _renderer: Renderer, - @Optional() @Host() private _select: SelectControlValueAccessor) { + constructor(private _element: ElementRef, private _renderer: Renderer, + @Optional() @Host() private _select: SelectControlValueAccessor) { if (isPresent(this._select)) this.id = this._select._registerOption(); } diff --git a/modules/angular2/src/common/forms/directives/shared.ts b/modules/angular2/src/common/forms/directives/shared.ts index 2d34500186..d4b776dd4c 100644 --- a/modules/angular2/src/common/forms/directives/shared.ts +++ b/modules/angular2/src/common/forms/directives/shared.ts @@ -25,8 +25,8 @@ export function controlPath(name: string, parent: ControlContainer): string[] { } export function setUpControl(control: Control, dir: NgControl): void { - if (isBlank(control)) _throwError(dir, 'Cannot find control'); - if (isBlank(dir.valueAccessor)) _throwError(dir, 'No value accessor for'); + if (isBlank(control)) _throwError(dir, "Cannot find control"); + if (isBlank(dir.valueAccessor)) _throwError(dir, "No value accessor for"); control.validator = Validators.compose([control.validator, dir.validator]); control.asyncValidator = Validators.composeAsync([control.asyncValidator, dir.asyncValidator]); @@ -47,13 +47,13 @@ export function setUpControl(control: Control, dir: NgControl): void { } export function setUpControlGroup(control: ControlGroup, dir: NgControlGroup) { - if (isBlank(control)) _throwError(dir, 'Cannot find control'); + if (isBlank(control)) _throwError(dir, "Cannot find control"); control.validator = Validators.compose([control.validator, dir.validator]); control.asyncValidator = Validators.composeAsync([control.asyncValidator, dir.asyncValidator]); } function _throwError(dir: AbstractControlDirective, message: string): void { - var path = dir.path.join(' -> '); + var path = dir.path.join(" -> "); throw new BaseException(`${message} '${path}'`); } @@ -61,23 +61,23 @@ export function composeValidators(validators: /* Array */ an return isPresent(validators) ? Validators.compose(validators.map(normalizeValidator)) : null; } -export function composeAsyncValidators(validators: /* Array */ any[]): - AsyncValidatorFn { +export function composeAsyncValidators( + validators: /* Array */ any[]): AsyncValidatorFn { return isPresent(validators) ? Validators.composeAsync(validators.map(normalizeAsyncValidator)) : null; } export function isPropertyUpdated(changes: {[key: string]: any}, viewModel: any): boolean { - if (!StringMapWrapper.contains(changes, 'model')) return false; - var change = changes['model']; + if (!StringMapWrapper.contains(changes, "model")) return false; + var change = changes["model"]; if (change.isFirstChange()) return true; return !looseIdentical(viewModel, change.currentValue); } // TODO: vsavkin remove it once https://github.com/angular/angular/issues/3011 is implemented -export function selectValueAccessor( - dir: NgControl, valueAccessors: ControlValueAccessor[]): ControlValueAccessor { +export function selectValueAccessor(dir: NgControl, + valueAccessors: ControlValueAccessor[]): ControlValueAccessor { if (isBlank(valueAccessors)) return null; var defaultAccessor: ControlValueAccessor; @@ -87,17 +87,17 @@ export function selectValueAccessor( if (hasConstructor(v, DefaultValueAccessor)) { defaultAccessor = v; - } else if ( - hasConstructor(v, CheckboxControlValueAccessor) || hasConstructor(v, NumberValueAccessor) || - hasConstructor(v, SelectControlValueAccessor) || - hasConstructor(v, RadioControlValueAccessor)) { + } else if (hasConstructor(v, CheckboxControlValueAccessor) || + hasConstructor(v, NumberValueAccessor) || + hasConstructor(v, SelectControlValueAccessor) || + hasConstructor(v, RadioControlValueAccessor)) { if (isPresent(builtinAccessor)) - _throwError(dir, 'More than one built-in value accessor matches'); + _throwError(dir, "More than one built-in value accessor matches"); builtinAccessor = v; } else { if (isPresent(customAccessor)) - _throwError(dir, 'More than one custom value accessor matches'); + _throwError(dir, "More than one custom value accessor matches"); customAccessor = v; } }); @@ -106,6 +106,6 @@ export function selectValueAccessor( if (isPresent(builtinAccessor)) return builtinAccessor; if (isPresent(defaultAccessor)) return defaultAccessor; - _throwError(dir, 'No valid value accessor for'); + _throwError(dir, "No valid value accessor for"); return null; } diff --git a/modules/angular2/src/common/forms/directives/validators.ts b/modules/angular2/src/common/forms/directives/validators.ts index 537512b6c9..27bdf3a87f 100644 --- a/modules/angular2/src/common/forms/directives/validators.ts +++ b/modules/angular2/src/common/forms/directives/validators.ts @@ -3,7 +3,7 @@ import {CONST_EXPR} from 'angular2/src/facade/lang'; import {Validators, NG_VALIDATORS} from '../validators'; import {AbstractControl} from '../model'; import * as modelModule from '../model'; -import {NumberWrapper} from 'angular2/src/facade/lang'; +import {NumberWrapper} from "angular2/src/facade/lang"; @@ -74,7 +74,7 @@ const MIN_LENGTH_VALIDATOR = CONST_EXPR( export class MinLengthValidator implements Validator { private _validator: ValidatorFn; - constructor(@Attribute('minlength') minLength: string) { + constructor(@Attribute("minlength") minLength: string) { this._validator = Validators.minLength(NumberWrapper.parseInt(minLength, 10)); } @@ -102,7 +102,7 @@ const MAX_LENGTH_VALIDATOR = CONST_EXPR( export class MaxLengthValidator implements Validator { private _validator: ValidatorFn; - constructor(@Attribute('maxlength') maxLength: string) { + constructor(@Attribute("maxlength") maxLength: string) { this._validator = Validators.maxLength(NumberWrapper.parseInt(maxLength, 10)); } @@ -131,7 +131,7 @@ const PATTERN_VALIDATOR = CONST_EXPR( export class PatternValidator implements Validator { private _validator: ValidatorFn; - constructor(@Attribute('pattern') pattern: string) { + constructor(@Attribute("pattern") pattern: string) { this._validator = Validators.pattern(pattern); } diff --git a/modules/angular2/src/common/forms/form_builder.ts b/modules/angular2/src/common/forms/form_builder.ts index 467b9e3ea4..960192eaa6 100644 --- a/modules/angular2/src/common/forms/form_builder.ts +++ b/modules/angular2/src/common/forms/form_builder.ts @@ -54,21 +54,21 @@ export class FormBuilder { * * See the {@link ControlGroup} constructor for more details. */ - group(controlsConfig: {[key: string]: any}, extra: {[key: string]: any} = null): - modelModule.ControlGroup { + group(controlsConfig: {[key: string]: any}, + extra: {[key: string]: any} = null): modelModule.ControlGroup { var controls = this._reduceControls(controlsConfig); var optionals = <{[key: string]: boolean}>( - isPresent(extra) ? StringMapWrapper.get(extra, 'optionals') : null); - var validator: ValidatorFn = isPresent(extra) ? StringMapWrapper.get(extra, 'validator') : null; + isPresent(extra) ? StringMapWrapper.get(extra, "optionals") : null); + var validator: ValidatorFn = isPresent(extra) ? StringMapWrapper.get(extra, "validator") : null; var asyncValidator: AsyncValidatorFn = - isPresent(extra) ? StringMapWrapper.get(extra, 'asyncValidator') : null; + isPresent(extra) ? StringMapWrapper.get(extra, "asyncValidator") : null; return new modelModule.ControlGroup(controls, optionals, validator, asyncValidator); } /** * Construct a new {@link Control} with the given `value`,`validator`, and `asyncValidator`. */ - control(value: Object, validator: ValidatorFn = null, asyncValidator: AsyncValidatorFn = null): - modelModule.Control { + control(value: Object, validator: ValidatorFn = null, + asyncValidator: AsyncValidatorFn = null): modelModule.Control { return new modelModule.Control(value, validator, asyncValidator); } @@ -76,16 +76,15 @@ export class FormBuilder { * Construct an array of {@link Control}s from the given `controlsConfig` array of * configuration, with the given optional `validator` and `asyncValidator`. */ - array( - controlsConfig: any[], validator: ValidatorFn = null, - asyncValidator: AsyncValidatorFn = null): modelModule.ControlArray { + array(controlsConfig: any[], validator: ValidatorFn = null, + asyncValidator: AsyncValidatorFn = null): modelModule.ControlArray { var controls = controlsConfig.map(c => this._createControl(c)); return new modelModule.ControlArray(controls, validator, asyncValidator); } /** @internal */ - _reduceControls(controlsConfig: {[k: string]: any}): - {[key: string]: modelModule.AbstractControl} { + _reduceControls(controlsConfig: {[k: string]: + any}): {[key: string]: modelModule.AbstractControl} { var controls: {[key: string]: modelModule.AbstractControl} = {}; StringMapWrapper.forEach(controlsConfig, (controlConfig: any, controlName: string) => { controls[controlName] = this._createControl(controlConfig); diff --git a/modules/angular2/src/common/forms/model.ts b/modules/angular2/src/common/forms/model.ts index b50fe8717a..5e032223ee 100644 --- a/modules/angular2/src/common/forms/model.ts +++ b/modules/angular2/src/common/forms/model.ts @@ -7,41 +7,42 @@ import {ValidatorFn, AsyncValidatorFn} from './directives/validators'; /** * Indicates that a Control is valid, i.e. that no errors exist in the input value. */ -export const VALID = 'VALID'; +export const VALID = "VALID"; /** * Indicates that a Control is invalid, i.e. that an error exists in the input value. */ -export const INVALID = 'INVALID'; +export const INVALID = "INVALID"; /** * Indicates that a Control is pending, i.e. that async validation is occurring and * errors are not yet available for the input value. */ -export const PENDING = 'PENDING'; +export const PENDING = "PENDING"; export function isControl(control: Object): boolean { return control instanceof AbstractControl; } -function _find(control: AbstractControl, path: Array| string) { +function _find(control: AbstractControl, path: Array| string) { if (isBlank(path)) return null; if (!(path instanceof Array)) { - path = (path).split('/'); + path = (path).split("/"); } if (path instanceof Array && ListWrapper.isEmpty(path)) return null; - return (>path).reduce((v, name) => { - if (v instanceof ControlGroup) { - return isPresent(v.controls[name]) ? v.controls[name] : null; - } else if (v instanceof ControlArray) { - var index = name; - return isPresent(v.at(index)) ? v.at(index) : null; - } else { - return null; - } - }, control); + return (>path) + .reduce((v, name) => { + if (v instanceof ControlGroup) { + return isPresent(v.controls[name]) ? v.controls[name] : null; + } else if (v instanceof ControlArray) { + var index = name; + return isPresent(v.at(index)) ? v.at(index) : null; + } else { + return null; + } + }, control); } function toObservable(r: any): Observable { @@ -61,7 +62,7 @@ export abstract class AbstractControl { private _errors: {[key: string]: any}; private _pristine: boolean = true; private _touched: boolean = false; - private _parent: ControlGroup|ControlArray; + private _parent: ControlGroup | ControlArray; private _asyncValidationSubscription: any; constructor(public validator: ValidatorFn, public asyncValidator: AsyncValidatorFn) {} @@ -111,10 +112,10 @@ export abstract class AbstractControl { } } - setParent(parent: ControlGroup|ControlArray): void { this._parent = parent; } + setParent(parent: ControlGroup | ControlArray): void { this._parent = parent; } - updateValueAndValidity({onlySelf, emitEvent}: {onlySelf?: boolean, emitEvent?: boolean} = {}): - void { + updateValueAndValidity( + {onlySelf, emitEvent}: {onlySelf?: boolean, emitEvent?: boolean} = {}): void { onlySelf = normalizeBool(onlySelf); emitEvent = isPresent(emitEvent) ? emitEvent : true; @@ -195,7 +196,7 @@ export abstract class AbstractControl { } } - find(path: Array|string): AbstractControl { return _find(this, path); } + find(path: Array| string): AbstractControl { return _find(this, path); } getError(errorCode: string, path: string[] = null): any { var control = isPresent(path) && !ListWrapper.isEmpty(path) ? this.find(path) : this; @@ -270,8 +271,8 @@ export class Control extends AbstractControl { /** @internal */ _onChange: Function; - constructor( - value: any = null, validator: ValidatorFn = null, asyncValidator: AsyncValidatorFn = null) { + constructor(value: any = null, validator: ValidatorFn = null, + asyncValidator: AsyncValidatorFn = null) { super(validator, asyncValidator); this._value = value; this.updateValueAndValidity({onlySelf: true, emitEvent: false}); @@ -334,9 +335,9 @@ export class Control extends AbstractControl { export class ControlGroup extends AbstractControl { private _optionals: {[key: string]: boolean}; - constructor( - public controls: {[key: string]: AbstractControl}, optionals: {[key: string]: boolean} = null, - validator: ValidatorFn = null, asyncValidator: AsyncValidatorFn = null) { + constructor(public controls: {[key: string]: AbstractControl}, + optionals: {[key: string]: boolean} = null, validator: ValidatorFn = null, + asyncValidator: AsyncValidatorFn = null) { super(validator, asyncValidator); this._optionals = isPresent(optionals) ? optionals : {}; this._initObservables(); @@ -449,9 +450,8 @@ export class ControlGroup extends AbstractControl { * ### Example ([live demo](http://plnkr.co/edit/23DESOpbNnBpBHZt1BR4?p=preview)) */ export class ControlArray extends AbstractControl { - constructor( - public controls: AbstractControl[], validator: ValidatorFn = null, - asyncValidator: AsyncValidatorFn = null) { + constructor(public controls: AbstractControl[], validator: ValidatorFn = null, + asyncValidator: AsyncValidatorFn = null) { super(validator, asyncValidator); this._initObservables(); this._setParentForControls(); diff --git a/modules/angular2/src/common/forms/validators.ts b/modules/angular2/src/common/forms/validators.ts index f1066c50f7..7663b7263e 100644 --- a/modules/angular2/src/common/forms/validators.ts +++ b/modules/angular2/src/common/forms/validators.ts @@ -16,7 +16,7 @@ import {ValidatorFn, AsyncValidatorFn} from './directives/validators'; * * {@example core/forms/ts/ng_validators/ng_validators.ts region='ng_validators'} */ -export const NG_VALIDATORS: OpaqueToken = CONST_EXPR(new OpaqueToken('NgValidators')); +export const NG_VALIDATORS: OpaqueToken = CONST_EXPR(new OpaqueToken("NgValidators")); /** * Providers for asynchronous validators to be used for {@link Control}s @@ -26,7 +26,7 @@ export const NG_VALIDATORS: OpaqueToken = CONST_EXPR(new OpaqueToken('NgValidato * * See {@link NG_VALIDATORS} for more details. */ -export const NG_ASYNC_VALIDATORS: OpaqueToken = CONST_EXPR(new OpaqueToken('NgAsyncValidators')); +export const NG_ASYNC_VALIDATORS: OpaqueToken = CONST_EXPR(new OpaqueToken("NgAsyncValidators")); /** * Provides a set of validators used by form controls. @@ -45,9 +45,9 @@ export class Validators { * Validator that requires controls to have a non-empty value. */ static required(control: modelModule.AbstractControl): {[key: string]: boolean} { - return isBlank(control.value) || (isString(control.value) && control.value == '') ? - {'required': true} : - null; + return isBlank(control.value) || (isString(control.value) && control.value == "") ? + {"required": true} : + null; } /** @@ -58,8 +58,8 @@ export class Validators { if (isPresent(Validators.required(control))) return null; var v: string = control.value; return v.length < minLength ? - {'minlength': {'requiredLength': minLength, 'actualLength': v.length}} : - null; + {"minlength": {"requiredLength": minLength, "actualLength": v.length}} : + null; }; } @@ -71,8 +71,8 @@ export class Validators { if (isPresent(Validators.required(control))) return null; var v: string = control.value; return v.length > maxLength ? - {'maxlength': {'requiredLength': maxLength, 'actualLength': v.length}} : - null; + {"maxlength": {"requiredLength": maxLength, "actualLength": v.length}} : + null; }; } @@ -85,7 +85,7 @@ export class Validators { let regex = new RegExp(`^${pattern}$`); let v: string = control.value; return regex.test(v) ? null : - {'pattern': {'requiredPattern': `^${pattern}$`, 'actualValue': v}}; + {"pattern": {"requiredPattern": `^${pattern}$`, "actualValue": v}}; }; } @@ -124,13 +124,13 @@ function _convertToPromise(obj: any): any { return PromiseWrapper.isPromise(obj) ? obj : ObservableWrapper.toPromise(obj); } -function _executeValidators( - control: modelModule.AbstractControl, validators: ValidatorFn[]): any[] { +function _executeValidators(control: modelModule.AbstractControl, + validators: ValidatorFn[]): any[] { return validators.map(v => v(control)); } -function _executeAsyncValidators( - control: modelModule.AbstractControl, validators: AsyncValidatorFn[]): any[] { +function _executeAsyncValidators(control: modelModule.AbstractControl, + validators: AsyncValidatorFn[]): any[] { return validators.map(v => v(control)); } diff --git a/modules/angular2/src/common/pipes/async_pipe.ts b/modules/angular2/src/common/pipes/async_pipe.ts index 78f3efdeed..9131cfb147 100644 --- a/modules/angular2/src/common/pipes/async_pipe.ts +++ b/modules/angular2/src/common/pipes/async_pipe.ts @@ -1,6 +1,13 @@ import {isBlank, isPresent, isPromise, CONST} from 'angular2/src/facade/lang'; import {ObservableWrapper, Observable, EventEmitter} from 'angular2/src/facade/async'; -import {Pipe, Injectable, ChangeDetectorRef, OnDestroy, PipeTransform, WrappedValue} from 'angular2/core'; +import { + Pipe, + Injectable, + ChangeDetectorRef, + OnDestroy, + PipeTransform, + WrappedValue +} from 'angular2/core'; import {InvalidPipeArgumentException} from './invalid_pipe_argument_exception'; @@ -57,7 +64,7 @@ export class AsyncPipe implements PipeTransform, OnDestroy { /** @internal */ _subscription: Object = null; /** @internal */ - _obj: Observable|Promise|EventEmitter = null; + _obj: Observable| Promise| EventEmitter = null; private _strategy: any = null; /** @internal */ public _ref: ChangeDetectorRef; @@ -69,7 +76,7 @@ export class AsyncPipe implements PipeTransform, OnDestroy { } } - transform(obj: Observable|Promise|EventEmitter, args?: any[]): any { + transform(obj: Observable| Promise| EventEmitter, args?: any[]): any { if (isBlank(this._obj)) { if (isPresent(obj)) { this._subscribe(obj); @@ -92,7 +99,7 @@ export class AsyncPipe implements PipeTransform, OnDestroy { } /** @internal */ - _subscribe(obj: Observable|Promise|EventEmitter): void { + _subscribe(obj: Observable| Promise| EventEmitter): void { this._obj = obj; this._strategy = this._selectStrategy(obj); this._subscription = this._strategy.createSubscription( @@ -100,7 +107,7 @@ export class AsyncPipe implements PipeTransform, OnDestroy { } /** @internal */ - _selectStrategy(obj: Observable|Promise|EventEmitter): any { + _selectStrategy(obj: Observable| Promise| EventEmitter): any { if (isPromise(obj)) { return _promiseStrategy; } else if (ObservableWrapper.isObservable(obj)) { diff --git a/modules/angular2/src/common/pipes/common_pipes.ts b/modules/angular2/src/common/pipes/common_pipes.ts index d16e86ca71..cc92c09f20 100644 --- a/modules/angular2/src/common/pipes/common_pipes.ts +++ b/modules/angular2/src/common/pipes/common_pipes.ts @@ -23,6 +23,16 @@ import {CONST_EXPR} from 'angular2/src/facade/lang'; * property of the `@Component` decorator. */ export const COMMON_PIPES = CONST_EXPR([ - AsyncPipe, UpperCasePipe, LowerCasePipe, JsonPipe, SlicePipe, DecimalPipe, PercentPipe, - CurrencyPipe, DatePipe, ReplacePipe, I18nPluralPipe, I18nSelectPipe + AsyncPipe, + UpperCasePipe, + LowerCasePipe, + JsonPipe, + SlicePipe, + DecimalPipe, + PercentPipe, + CurrencyPipe, + DatePipe, + ReplacePipe, + I18nPluralPipe, + I18nSelectPipe ]); diff --git a/modules/angular2/src/common/pipes/date_pipe.ts b/modules/angular2/src/common/pipes/date_pipe.ts index 8813892774..27f38308a6 100644 --- a/modules/angular2/src/common/pipes/date_pipe.ts +++ b/modules/angular2/src/common/pipes/date_pipe.ts @@ -1,4 +1,13 @@ -import {isDate, isNumber, isPresent, Date, DateWrapper, CONST, isBlank, FunctionWrapper} from 'angular2/src/facade/lang'; +import { + isDate, + isNumber, + isPresent, + Date, + DateWrapper, + CONST, + isBlank, + FunctionWrapper +} from 'angular2/src/facade/lang'; import {DateFormatter} from 'angular2/src/facade/intl'; import {PipeTransform, WrappedValue, Pipe, Injectable} from 'angular2/core'; import {StringMapWrapper, ListWrapper} from 'angular2/src/facade/collection'; diff --git a/modules/angular2/src/common/pipes/i18n_plural_pipe.ts b/modules/angular2/src/common/pipes/i18n_plural_pipe.ts index 229f48bbf2..0501441e3a 100644 --- a/modules/angular2/src/common/pipes/i18n_plural_pipe.ts +++ b/modules/angular2/src/common/pipes/i18n_plural_pipe.ts @@ -1,4 +1,10 @@ -import {CONST, isStringMap, StringWrapper, isPresent, RegExpWrapper} from 'angular2/src/facade/lang'; +import { + CONST, + isStringMap, + StringWrapper, + isPresent, + RegExpWrapper +} from 'angular2/src/facade/lang'; import {Injectable, PipeTransform, Pipe} from 'angular2/core'; import {InvalidPipeArgumentException} from './invalid_pipe_argument_exception'; diff --git a/modules/angular2/src/common/pipes/number_pipe.ts b/modules/angular2/src/common/pipes/number_pipe.ts index 9ab437b142..d26bd53128 100644 --- a/modules/angular2/src/common/pipes/number_pipe.ts +++ b/modules/angular2/src/common/pipes/number_pipe.ts @@ -1,4 +1,13 @@ -import {isNumber, isPresent, isBlank, StringWrapper, NumberWrapper, RegExpWrapper, CONST, FunctionWrapper} from 'angular2/src/facade/lang'; +import { + isNumber, + isPresent, + isBlank, + StringWrapper, + NumberWrapper, + RegExpWrapper, + CONST, + FunctionWrapper +} from 'angular2/src/facade/lang'; import {BaseException, WrappedException} from 'angular2/src/facade/exceptions'; import {NumberFormatter, NumberFormatStyle} from 'angular2/src/facade/intl'; import {Injectable, PipeTransform, WrappedValue, Pipe} from 'angular2/core'; @@ -16,9 +25,8 @@ var _re = RegExpWrapper.create('^(\\d+)?\\.((\\d+)(\\-(\\d+))?)?$'); @Injectable() export class NumberPipe { /** @internal */ - static _format( - value: number, style: NumberFormatStyle, digits: string, currency: string = null, - currencyAsSymbol: boolean = false): string { + static _format(value: number, style: NumberFormatStyle, digits: string, currency: string = null, + currencyAsSymbol: boolean = false): string { if (isBlank(value)) return null; if (!isNumber(value)) { throw new InvalidPipeArgumentException(NumberPipe, value); @@ -139,7 +147,7 @@ export class CurrencyPipe extends NumberPipe implements PipeTransform { var currencyCode: string = isPresent(args) && args.length > 0 ? args[0] : 'USD'; var symbolDisplay: boolean = isPresent(args) && args.length > 1 ? args[1] : false; var digits: string = isPresent(args) && args.length > 2 ? args[2] : null; - return NumberPipe._format( - value, NumberFormatStyle.Currency, digits, currencyCode, symbolDisplay); + return NumberPipe._format(value, NumberFormatStyle.Currency, digits, currencyCode, + symbolDisplay); } } diff --git a/modules/angular2/src/common/pipes/replace_pipe.ts b/modules/angular2/src/common/pipes/replace_pipe.ts index 6e19ba0276..de3c0e9f73 100644 --- a/modules/angular2/src/common/pipes/replace_pipe.ts +++ b/modules/angular2/src/common/pipes/replace_pipe.ts @@ -1,4 +1,11 @@ -import {isBlank, isString, isNumber, isFunction, RegExpWrapper, StringWrapper} from 'angular2/src/facade/lang'; +import { + isBlank, + isString, + isNumber, + isFunction, + RegExpWrapper, + StringWrapper +} from 'angular2/src/facade/lang'; import {BaseException} from 'angular2/src/facade/exceptions'; import {Injectable, PipeTransform, Pipe} from 'angular2/core'; import {InvalidPipeArgumentException} from './invalid_pipe_argument_exception'; diff --git a/modules/angular2/src/compiler/change_definition_factory.ts b/modules/angular2/src/compiler/change_definition_factory.ts index f7ad44e53c..51b8f61263 100644 --- a/modules/angular2/src/compiler/change_definition_factory.ts +++ b/modules/angular2/src/compiler/change_definition_factory.ts @@ -2,10 +2,34 @@ import {ListWrapper, StringMapWrapper} from 'angular2/src/facade/collection'; import {isPresent, isBlank} from 'angular2/src/facade/lang'; import {reflector} from 'angular2/src/core/reflection/reflection'; -import {DirectiveIndex, BindingRecord, DirectiveRecord, ChangeDetectionStrategy, ChangeDetectorDefinition, ChangeDetectorGenConfig, ASTWithSource} from 'angular2/src/core/change_detection/change_detection'; +import { + DirectiveIndex, + BindingRecord, + DirectiveRecord, + ChangeDetectionStrategy, + ChangeDetectorDefinition, + ChangeDetectorGenConfig, + ASTWithSource +} from 'angular2/src/core/change_detection/change_detection'; import {CompileDirectiveMetadata, CompileTypeMetadata} from './directive_metadata'; -import {TemplateAst, ElementAst, BoundTextAst, PropertyBindingType, DirectiveAst, TemplateAstVisitor, templateVisitAll, NgContentAst, EmbeddedTemplateAst, VariableAst, BoundElementPropertyAst, BoundEventAst, BoundDirectivePropertyAst, AttrAst, TextAst} from './template_ast'; +import { + TemplateAst, + ElementAst, + BoundTextAst, + PropertyBindingType, + DirectiveAst, + TemplateAstVisitor, + templateVisitAll, + NgContentAst, + EmbeddedTemplateAst, + VariableAst, + BoundElementPropertyAst, + BoundEventAst, + BoundDirectivePropertyAst, + AttrAst, + TextAst +} from './template_ast'; import {LifecycleHooks} from 'angular2/src/core/linker/interfaces'; export function createChangeDetectorDefinitions( @@ -26,9 +50,8 @@ class ProtoViewVisitor implements TemplateAstVisitor { eventRecords: BindingRecord[] = []; directiveRecords: DirectiveRecord[] = []; - constructor( - public parent: ProtoViewVisitor, public allVisitors: ProtoViewVisitor[], - public strategy: ChangeDetectionStrategy) { + constructor(public parent: ProtoViewVisitor, public allVisitors: ProtoViewVisitor[], + public strategy: ChangeDetectionStrategy) { this.viewIndex = allVisitors.length; allVisitors.push(this); } @@ -73,9 +96,10 @@ class ProtoViewVisitor implements TemplateAstVisitor { } visitEvent(ast: BoundEventAst, directiveRecord: DirectiveRecord): any { - var bindingRecord = isPresent(directiveRecord) ? - BindingRecord.createForHostEvent(ast.handler, ast.fullName, directiveRecord) : - BindingRecord.createForEvent(ast.handler, ast.fullName, this.boundElementCount - 1); + var bindingRecord = + isPresent(directiveRecord) ? + BindingRecord.createForHostEvent(ast.handler, ast.fullName, directiveRecord) : + BindingRecord.createForEvent(ast.handler, ast.fullName, this.boundElementCount - 1); this.eventRecords.push(bindingRecord); return null; } @@ -85,21 +109,25 @@ class ProtoViewVisitor implements TemplateAstVisitor { var dirIndex = isPresent(directiveRecord) ? directiveRecord.directiveIndex : null; var bindingRecord; if (ast.type === PropertyBindingType.Property) { - bindingRecord = isPresent(dirIndex) ? - BindingRecord.createForHostProperty(dirIndex, ast.value, ast.name) : - BindingRecord.createForElementProperty(ast.value, boundElementIndex, ast.name); + bindingRecord = + isPresent(dirIndex) ? + BindingRecord.createForHostProperty(dirIndex, ast.value, ast.name) : + BindingRecord.createForElementProperty(ast.value, boundElementIndex, ast.name); } else if (ast.type === PropertyBindingType.Attribute) { - bindingRecord = isPresent(dirIndex) ? - BindingRecord.createForHostAttribute(dirIndex, ast.value, ast.name) : - BindingRecord.createForElementAttribute(ast.value, boundElementIndex, ast.name); + bindingRecord = + isPresent(dirIndex) ? + BindingRecord.createForHostAttribute(dirIndex, ast.value, ast.name) : + BindingRecord.createForElementAttribute(ast.value, boundElementIndex, ast.name); } else if (ast.type === PropertyBindingType.Class) { - bindingRecord = isPresent(dirIndex) ? - BindingRecord.createForHostClass(dirIndex, ast.value, ast.name) : - BindingRecord.createForElementClass(ast.value, boundElementIndex, ast.name); + bindingRecord = + isPresent(dirIndex) ? + BindingRecord.createForHostClass(dirIndex, ast.value, ast.name) : + BindingRecord.createForElementClass(ast.value, boundElementIndex, ast.name); } else if (ast.type === PropertyBindingType.Style) { - bindingRecord = isPresent(dirIndex) ? - BindingRecord.createForHostStyle(dirIndex, ast.value, ast.name, ast.unit) : - BindingRecord.createForElementStyle(ast.value, boundElementIndex, ast.name, ast.unit); + bindingRecord = + isPresent(dirIndex) ? + BindingRecord.createForHostStyle(dirIndex, ast.value, ast.name, ast.unit) : + BindingRecord.createForElementStyle(ast.value, boundElementIndex, ast.name, ast.unit); } this.bindingRecords.push(bindingRecord); return null; @@ -167,9 +195,8 @@ class ProtoViewVisitor implements TemplateAstVisitor { } -function createChangeDefinitions( - pvVisitors: ProtoViewVisitor[], componentType: CompileTypeMetadata, - genConfig: ChangeDetectorGenConfig): ChangeDetectorDefinition[] { +function createChangeDefinitions(pvVisitors: ProtoViewVisitor[], componentType: CompileTypeMetadata, + genConfig: ChangeDetectorGenConfig): ChangeDetectorDefinition[] { var pvVariableNames = _collectNestedProtoViewsVariableNames(pvVisitors); return pvVisitors.map(pvVisitor => { var id = `${componentType.name}_${pvVisitor.viewIndex}`; diff --git a/modules/angular2/src/compiler/change_detector_compiler.ts b/modules/angular2/src/compiler/change_detector_compiler.ts index dd3a099014..db3b727b4a 100644 --- a/modules/angular2/src/compiler/change_detector_compiler.ts +++ b/modules/angular2/src/compiler/change_detector_compiler.ts @@ -1,6 +1,8 @@ import {CompileTypeMetadata} from './directive_metadata'; import {SourceExpressions, moduleRef} from './source_module'; -import {ChangeDetectorJITGenerator} from 'angular2/src/core/change_detection/change_detection_jit_generator'; +import { + ChangeDetectorJITGenerator +} from 'angular2/src/core/change_detection/change_detection_jit_generator'; import {AbstractChangeDetector} from 'angular2/src/core/change_detection/abstract_change_detector'; import {ChangeDetectionUtil} from 'angular2/src/core/change_detection/change_detection_util'; import {ChangeDetectorState} from 'angular2/src/core/change_detection/constants'; @@ -8,16 +10,21 @@ import {ChangeDetectorState} from 'angular2/src/core/change_detection/constants' import {createChangeDetectorDefinitions} from './change_definition_factory'; import {IS_DART, isJsObject, CONST_EXPR} from 'angular2/src/facade/lang'; -import {ChangeDetectorGenConfig, ChangeDetectorDefinition, DynamicProtoChangeDetector, ChangeDetectionStrategy} from 'angular2/src/core/change_detection/change_detection'; +import { + ChangeDetectorGenConfig, + ChangeDetectorDefinition, + DynamicProtoChangeDetector, + ChangeDetectionStrategy +} from 'angular2/src/core/change_detection/change_detection'; import {TemplateAst} from './template_ast'; import {Codegen} from 'angular2/src/transform/template_compiler/change_detector_codegen'; import {MODULE_SUFFIX} from './util'; import {Injectable} from 'angular2/src/core/di'; -const ABSTRACT_CHANGE_DETECTOR = 'AbstractChangeDetector'; -const UTIL = 'ChangeDetectionUtil'; -const CHANGE_DETECTOR_STATE = 'ChangeDetectorState'; +const ABSTRACT_CHANGE_DETECTOR = "AbstractChangeDetector"; +const UTIL = "ChangeDetectionUtil"; +const CHANGE_DETECTOR_STATE = "ChangeDetectorState"; export const CHANGE_DETECTION_JIT_IMPORTS = CONST_EXPR({ 'AbstractChangeDetector': AbstractChangeDetector, @@ -38,13 +45,12 @@ var CONSTANTS_MODULE = export class ChangeDetectionCompiler { constructor(private _genConfig: ChangeDetectorGenConfig) {} - compileComponentRuntime( - componentType: CompileTypeMetadata, strategy: ChangeDetectionStrategy, - parsedTemplate: TemplateAst[]): Function[] { + compileComponentRuntime(componentType: CompileTypeMetadata, strategy: ChangeDetectionStrategy, + parsedTemplate: TemplateAst[]): Function[] { var changeDetectorDefinitions = createChangeDetectorDefinitions(componentType, strategy, this._genConfig, parsedTemplate); - return changeDetectorDefinitions.map( - definition => this._createChangeDetectorFactory(definition)); + return changeDetectorDefinitions.map(definition => + this._createChangeDetectorFactory(definition)); } private _createChangeDetectorFactory(definition: ChangeDetectorDefinition): Function { @@ -52,9 +58,8 @@ export class ChangeDetectionCompiler { return () => proto.instantiate(); } - compileComponentCodeGen( - componentType: CompileTypeMetadata, strategy: ChangeDetectionStrategy, - parsedTemplate: TemplateAst[]): SourceExpressions { + compileComponentCodeGen(componentType: CompileTypeMetadata, strategy: ChangeDetectionStrategy, + parsedTemplate: TemplateAst[]): SourceExpressions { var changeDetectorDefinitions = createChangeDetectorDefinitions(componentType, strategy, this._genConfig, parsedTemplate); var factories = []; @@ -69,8 +74,8 @@ export class ChangeDetectionCompiler { codegen = new Codegen(PREGEN_PROTO_CHANGE_DETECTOR_MODULE); var className = `_${definition.id}`; var typeRef = (index === 0 && componentType.isHost) ? - 'dynamic' : - `${moduleRef(componentType.moduleUrl)}${componentType.name}`; + 'dynamic' : + `${moduleRef(componentType.moduleUrl)}${componentType.name}`; codegen.generate(typeRef, className, definition); factories.push(`${className}.newChangeDetector`); sourcePart = codegen.toString(); diff --git a/modules/angular2/src/compiler/compiler.ts b/modules/angular2/src/compiler/compiler.ts index cdfe4c826a..23426ce6c1 100644 --- a/modules/angular2/src/compiler/compiler.ts +++ b/modules/angular2/src/compiler/compiler.ts @@ -1,6 +1,10 @@ -import {RuntimeCompiler_} from './runtime_compiler'; +import {RuntimeCompiler_} from "./runtime_compiler"; export {TemplateCompiler} from './template_compiler'; -export {CompileDirectiveMetadata, CompileTypeMetadata, CompileTemplateMetadata} from './directive_metadata'; +export { + CompileDirectiveMetadata, + CompileTypeMetadata, + CompileTemplateMetadata +} from './directive_metadata'; export {SourceModule, SourceWithImports} from './source_module'; export {PLATFORM_DIRECTIVES, PLATFORM_PIPES} from 'angular2/src/core/platform_directives_and_pipes'; export * from 'angular2/src/compiler/template_ast'; @@ -32,12 +36,23 @@ function _createChangeDetectorGenConfig() { * A set of providers that provide `RuntimeCompiler` and its dependencies to use for * template compilation. */ -export const COMPILER_PROVIDERS: Array = CONST_EXPR([ - Lexer, Parser, HtmlParser, TemplateParser, TemplateNormalizer, RuntimeMetadataResolver, - DEFAULT_PACKAGE_URL_PROVIDER, StyleCompiler, ProtoViewCompiler, ViewCompiler, +export const COMPILER_PROVIDERS: Array = CONST_EXPR([ + Lexer, + Parser, + HtmlParser, + TemplateParser, + TemplateNormalizer, + RuntimeMetadataResolver, + DEFAULT_PACKAGE_URL_PROVIDER, + StyleCompiler, + ProtoViewCompiler, + ViewCompiler, ChangeDetectionCompiler, new Provider(ChangeDetectorGenConfig, {useFactory: _createChangeDetectorGenConfig, deps: []}), - TemplateCompiler, new Provider(RuntimeCompiler, {useClass: RuntimeCompiler_}), - new Provider(Compiler, {useExisting: RuntimeCompiler}), DomElementSchemaRegistry, - new Provider(ElementSchemaRegistry, {useExisting: DomElementSchemaRegistry}), UrlResolver + TemplateCompiler, + new Provider(RuntimeCompiler, {useClass: RuntimeCompiler_}), + new Provider(Compiler, {useExisting: RuntimeCompiler}), + DomElementSchemaRegistry, + new Provider(ElementSchemaRegistry, {useExisting: DomElementSchemaRegistry}), + UrlResolver ]); diff --git a/modules/angular2/src/compiler/css/lexer.ts b/modules/angular2/src/compiler/css/lexer.ts index e0cde08be0..1f79ea870e 100644 --- a/modules/angular2/src/compiler/css/lexer.ts +++ b/modules/angular2/src/compiler/css/lexer.ts @@ -1,9 +1,65 @@ -import {NumberWrapper, StringWrapper, isPresent, resolveEnumToken} from 'angular2/src/facade/lang'; +import {NumberWrapper, StringWrapper, isPresent, resolveEnumToken} from "angular2/src/facade/lang"; import {BaseException} from 'angular2/src/facade/exceptions'; -import {isWhitespace, $EOF, $HASH, $TILDA, $CARET, $PERCENT, $$, $_, $COLON, $SQ, $DQ, $EQ, $SLASH, $BACKSLASH, $PERIOD, $STAR, $PLUS, $LPAREN, $RPAREN, $LBRACE, $RBRACE, $LBRACKET, $RBRACKET, $PIPE, $COMMA, $SEMICOLON, $MINUS, $BANG, $QUESTION, $AT, $AMPERSAND, $GT, $a, $A, $z, $Z, $0, $9, $FF, $CR, $LF, $VTAB} from 'angular2/src/compiler/chars'; +import { + isWhitespace, + $EOF, + $HASH, + $TILDA, + $CARET, + $PERCENT, + $$, + $_, + $COLON, + $SQ, + $DQ, + $EQ, + $SLASH, + $BACKSLASH, + $PERIOD, + $STAR, + $PLUS, + $LPAREN, + $RPAREN, + $LBRACE, + $RBRACE, + $LBRACKET, + $RBRACKET, + $PIPE, + $COMMA, + $SEMICOLON, + $MINUS, + $BANG, + $QUESTION, + $AT, + $AMPERSAND, + $GT, + $a, + $A, + $z, + $Z, + $0, + $9, + $FF, + $CR, + $LF, + $VTAB +} from "angular2/src/compiler/chars"; -export {$EOF, $AT, $RBRACE, $LBRACE, $LBRACKET, $RBRACKET, $LPAREN, $RPAREN, $COMMA, $COLON, $SEMICOLON, isWhitespace} from 'angular2/src/compiler/chars'; +export { + $EOF, + $AT, + $RBRACE, + $LBRACE, + $LBRACKET, + $RBRACKET, + $LPAREN, + $RPAREN, + $COMMA, + $COLON, + $SEMICOLON, + isWhitespace +} from "angular2/src/compiler/chars"; export enum CssTokenType { EOF, @@ -38,37 +94,35 @@ export class LexedCssResult { constructor(public error: CssScannerError, public token: CssToken) {} } -export function generateErrorMessage( - input: string, message: string, errorValue: string, index: number, row: number, - column: number): string { +export function generateErrorMessage(input: string, message: string, errorValue: string, + index: number, row: number, column: number): string { return `${message} at column ${row}:${column} in expression [` + - findProblemCode(input, errorValue, index, column) + ']'; + findProblemCode(input, errorValue, index, column) + ']'; } -export function findProblemCode( - input: string, errorValue: string, index: number, column: number): string { +export function findProblemCode(input: string, errorValue: string, index: number, + column: number): string { var endOfProblemLine = index; var current = charCode(input, index); while (current > 0 && !isNewline(current)) { current = charCode(input, ++endOfProblemLine); } var choppedString = input.substring(0, endOfProblemLine); - var pointerPadding = ''; + var pointerPadding = ""; for (var i = 0; i < column; i++) { - pointerPadding += ' '; + pointerPadding += " "; } - var pointerString = ''; + var pointerString = ""; for (var i = 0; i < errorValue.length; i++) { - pointerString += '^'; + pointerString += "^"; } - return choppedString + '\n' + pointerPadding + pointerString + '\n'; + return choppedString + "\n" + pointerPadding + pointerString + "\n"; } export class CssToken { numValue: number; - constructor( - public index: number, public column: number, public line: number, public type: CssTokenType, - public strValue: string) { + constructor(public index: number, public column: number, public line: number, + public type: CssTokenType, public strValue: string) { this.numValue = charCode(strValue, 0); } } @@ -194,7 +248,7 @@ export class CssScanner { var next = output.token; if (!isPresent(next)) { - next = new CssToken(0, 0, 0, CssTokenType.EOF, 'end of file'); + next = new CssToken(0, 0, 0, CssTokenType.EOF, "end of file"); } var isMatchingType; @@ -211,17 +265,16 @@ export class CssScanner { var error = null; if (!isMatchingType || (isPresent(value) && value != next.strValue)) { - var errorMessage = resolveEnumToken(CssTokenType, next.type) + ' does not match expected ' + - resolveEnumToken(CssTokenType, type) + ' value'; + var errorMessage = resolveEnumToken(CssTokenType, next.type) + " does not match expected " + + resolveEnumToken(CssTokenType, type) + " value"; if (isPresent(value)) { errorMessage += ' ("' + next.strValue + '" should match "' + value + '")'; } error = new CssScannerError( - next, generateErrorMessage( - this.input, errorMessage, next.strValue, previousIndex, previousLine, - previousColumn)); + next, generateErrorMessage(this.input, errorMessage, next.strValue, previousIndex, + previousLine, previousColumn)); } return new LexedCssResult(error, next); @@ -301,8 +354,8 @@ export class CssScanner { } scanComment(): CssToken { - if (this.assertCondition( - isCommentStart(this.peek, this.peekPeek), 'Expected comment start value')) { + if (this.assertCondition(isCommentStart(this.peek, this.peekPeek), + "Expected comment start value")) { return null; } @@ -339,8 +392,8 @@ export class CssScanner { } scanString(): CssToken { - if (this.assertCondition( - isStringStart(this.peek, this.peekPeek), 'Unexpected non-string starting value')) { + if (this.assertCondition(isStringStart(this.peek, this.peekPeek), + "Unexpected non-string starting value")) { return null; } @@ -359,7 +412,7 @@ export class CssScanner { this.advance(); } - if (this.assertCondition(this.peek == target, 'Unterminated quote')) { + if (this.assertCondition(this.peek == target, "Unterminated quote")) { return null; } this.advance(); @@ -389,8 +442,8 @@ export class CssScanner { } scanIdentifier(): CssToken { - if (this.assertCondition( - isIdentifierStart(this.peek, this.peekPeek), 'Expected identifier starting value')) { + if (this.assertCondition(isIdentifierStart(this.peek, this.peekPeek), + 'Expected identifier starting value')) { return null; } @@ -416,9 +469,8 @@ export class CssScanner { scanCharacter(): CssToken { var start = this.index; var startingColumn = this.column; - if (this.assertCondition( - isValidCssCharacter(this.peek, this._currentMode), - charStr(this.peek) + ' is not a valid CSS character')) { + if (this.assertCondition(isValidCssCharacter(this.peek, this._currentMode), + charStr(this.peek) + ' is not a valid CSS character')) { return null; } @@ -505,12 +557,12 @@ function isIdentifierStart(code: number, next: number): boolean { } return ($a <= target && target <= $z) || ($A <= target && target <= $Z) || target == $BACKSLASH || - target == $MINUS || target == $_; + target == $MINUS || target == $_; } function isIdentifierPart(target: number): boolean { return ($a <= target && target <= $z) || ($A <= target && target <= $Z) || target == $BACKSLASH || - target == $MINUS || target == $_ || isDigit(target); + target == $MINUS || target == $_ || isDigit(target); } function isValidPseudoSelectorCharacter(code: number): boolean { diff --git a/modules/angular2/src/compiler/css/parser.ts b/modules/angular2/src/compiler/css/parser.ts index 7a28f8c1eb..00267ccca6 100644 --- a/modules/angular2/src/compiler/css/parser.ts +++ b/modules/angular2/src/compiler/css/parser.ts @@ -1,10 +1,40 @@ -import {ParseSourceSpan, ParseSourceFile, ParseLocation, ParseError} from 'angular2/src/compiler/parse_util'; +import { + ParseSourceSpan, + ParseSourceFile, + ParseLocation, + ParseError +} from "angular2/src/compiler/parse_util"; -import {bitWiseOr, bitWiseAnd, NumberWrapper, StringWrapper, isPresent} from 'angular2/src/facade/lang'; +import { + bitWiseOr, + bitWiseAnd, + NumberWrapper, + StringWrapper, + isPresent +} from "angular2/src/facade/lang"; -import {CssLexerMode, CssToken, CssTokenType, CssScanner, CssScannerError, generateErrorMessage, $AT, $EOF, $RBRACE, $LBRACE, $LBRACKET, $RBRACKET, $LPAREN, $RPAREN, $COMMA, $COLON, $SEMICOLON, isNewline} from 'angular2/src/compiler/css/lexer'; +import { + CssLexerMode, + CssToken, + CssTokenType, + CssScanner, + CssScannerError, + generateErrorMessage, + $AT, + $EOF, + $RBRACE, + $LBRACE, + $LBRACKET, + $RBRACKET, + $LPAREN, + $RPAREN, + $COMMA, + $COLON, + $SEMICOLON, + isNewline +} from "angular2/src/compiler/css/lexer"; -export {CssToken} from 'angular2/src/compiler/css/lexer'; +export {CssToken} from "angular2/src/compiler/css/lexer"; export enum BlockType { Import, @@ -30,7 +60,7 @@ const SEMICOLON_DELIM = 32; const NEWLINE_DELIM = 64; const RPAREN_DELIM = 128; -function mergeTokens(tokens: CssToken[], separator: string = ''): CssToken { +function mergeTokens(tokens: CssToken[], separator: string = ""): CssToken { var mainToken = tokens[0]; var str = mainToken.strValue; for (var i = 1; i < tokens.length; i++) { @@ -175,9 +205,8 @@ export class CssParser { var token = this._scan(); - this._assertCondition( - token.type == CssTokenType.AtKeyword, - `The CSS Rule ${token.strValue} is not a valid [@] rule.`, token); + this._assertCondition(token.type == CssTokenType.AtKeyword, + `The CSS Rule ${token.strValue} is not a valid [@] rule.`, token); var block, type = this._resolveBlockType(token); switch (type) { @@ -216,12 +245,11 @@ export class CssParser { default: var listOfTokens = []; this._scanner.setMode(CssLexerMode.ALL); - this._error( - generateErrorMessage( - this._scanner.input, - `The CSS "at" rule "${token.strValue}" is not allowed to used here`, token.strValue, - token.index, token.line, token.column), - token); + this._error(generateErrorMessage( + this._scanner.input, + `The CSS "at" rule "${token.strValue}" is not allowed to used here`, + token.strValue, token.index, token.line, token.column), + token); this._collectUntilDelim(bitWiseOr([delimiters, LBRACE_DELIM, SEMICOLON_DELIM])) .forEach((token) => { listOfTokens.push(token); }); @@ -375,7 +403,7 @@ export class CssParser { // contains an inner selector that needs to be parsed // in isolation if (this._scanner.getMode() == CssLexerMode.PSEUDO_SELECTOR && isPresent(previousToken) && - previousToken.numValue == $COLON && token.strValue == 'not' && + previousToken.numValue == $COLON && token.strValue == "not" && this._scanner.peek == $LPAREN) { selectorCssTokens.push(token); selectorCssTokens.push(this._consume(CssTokenType.Character, '(')); @@ -425,7 +453,7 @@ export class CssParser { this._scanner.setMode(CssLexerMode.STYLE_VALUE); - var strValue = ''; + var strValue = ""; var tokens = []; var previous: CssToken; while (!characterContainsDelimiter(this._scanner.peek, delimiters)) { @@ -465,9 +493,9 @@ export class CssParser { this._consume(CssTokenType.Character, ';'); } else if (code != $RBRACE) { this._error( - generateErrorMessage( - this._scanner.input, `The CSS key/value definition did not end with a semicolon`, - previous.strValue, previous.index, previous.line, previous.column), + generateErrorMessage(this._scanner.input, + `The CSS key/value definition did not end with a semicolon`, + previous.strValue, previous.index, previous.line, previous.column), previous); } @@ -564,7 +592,7 @@ export class CssParser { remainingTokens.forEach((token) => { propStr.push(token.strValue); }); } - prop = new CssToken(prop.index, prop.column, prop.line, prop.type, propStr.join(' ')); + prop = new CssToken(prop.index, prop.column, prop.line, prop.type, propStr.join(" ")); } // this means we've reached the end of the definition and/or block @@ -580,11 +608,10 @@ export class CssParser { if (parseValue) { value = this._parseValue(delimiters); } else { - this._error( - generateErrorMessage( - this._scanner.input, `The CSS property was not paired with a style value`, - prop.strValue, prop.index, prop.line, prop.column), - prop); + this._error(generateErrorMessage(this._scanner.input, + `The CSS property was not paired with a style value`, + prop.strValue, prop.index, prop.line, prop.column), + prop); } return new CssDefinitionAST(prop, value); @@ -602,8 +629,8 @@ export class CssParser { /** @internal */ _error(message: string, problemToken: CssToken) { var length = problemToken.strValue.length; - var error = CssParseError.create( - this._file, 0, problemToken.line, problemToken.column, length, message); + var error = CssParseError.create(this._file, 0, problemToken.line, problemToken.column, length, + message); this._errors.push(error); } } @@ -630,7 +657,7 @@ export class CssKeyframeRuleAST extends CssBlockRuleAST { export class CssKeyframeDefinitionAST extends CssBlockRuleAST { public steps; constructor(_steps: CssToken[], block: CssBlockAST) { - super(BlockType.Keyframes, block, mergeTokens(_steps, ',')); + super(BlockType.Keyframes, block, mergeTokens(_steps, ",")); this.steps = _steps; } visit(visitor: CssASTVisitor, context?: any) { @@ -642,11 +669,10 @@ export class CssBlockDefinitionRuleAST extends CssBlockRuleAST { public strValue: string; constructor(type: BlockType, public query: CssToken[], block: CssBlockAST) { super(type, block); - this.strValue = query.map(token => token.strValue).join(''); + this.strValue = query.map(token => token.strValue).join(""); var firstCssToken: CssToken = query[0]; - this.name = new CssToken( - firstCssToken.index, firstCssToken.column, firstCssToken.line, CssTokenType.Identifier, - this.strValue); + this.name = new CssToken(firstCssToken.index, firstCssToken.column, firstCssToken.line, + CssTokenType.Identifier, this.strValue); } visit(visitor: CssASTVisitor, context?: any) { visitor.visitCssBlock(this.block, context); } } @@ -666,7 +692,7 @@ export class CssSelectorRuleAST extends CssBlockRuleAST { constructor(public selectors: CssSelectorAST[], block: CssBlockAST) { super(BlockType.Selector, block); - this.strValue = selectors.map(selector => selector.strValue).join(','); + this.strValue = selectors.map(selector => selector.strValue).join(","); } visit(visitor: CssASTVisitor, context?: any) { visitor.visitCssSelectorRule(this, context); } @@ -681,7 +707,7 @@ export class CssSelectorAST extends CssAST { public strValue; constructor(public tokens: CssToken[], public isComplex: boolean = false) { super(); - this.strValue = tokens.map(token => token.strValue).join(''); + this.strValue = tokens.map(token => token.strValue).join(""); } visit(visitor: CssASTVisitor, context?: any) { visitor.visitCssSelector(this, context); } } @@ -697,13 +723,12 @@ export class CssStyleSheetAST extends CssAST { } export class CssParseError extends ParseError { - static create( - file: ParseSourceFile, offset: number, line: number, col: number, length: number, - errMsg: string): CssParseError { + static create(file: ParseSourceFile, offset: number, line: number, col: number, length: number, + errMsg: string): CssParseError { var start = new ParseLocation(file, offset, line, col); var end = new ParseLocation(file, offset, line, col + length); var span = new ParseSourceSpan(start, end); - return new CssParseError(span, 'CSS Parse Error: ' + errMsg); + return new CssParseError(span, "CSS Parse Error: " + errMsg); } constructor(span: ParseSourceSpan, message: string) { super(span, message); } diff --git a/modules/angular2/src/compiler/directive_metadata.ts b/modules/angular2/src/compiler/directive_metadata.ts index c1a4f253a0..1240fe12da 100644 --- a/modules/angular2/src/compiler/directive_metadata.ts +++ b/modules/angular2/src/compiler/directive_metadata.ts @@ -1,7 +1,23 @@ -import {isPresent, isBlank, isNumber, isBoolean, normalizeBool, normalizeBlank, serializeEnum, Type, isString, RegExpWrapper, StringWrapper, isArray} from 'angular2/src/facade/lang'; +import { + isPresent, + isBlank, + isNumber, + isBoolean, + normalizeBool, + normalizeBlank, + serializeEnum, + Type, + isString, + RegExpWrapper, + StringWrapper, + isArray +} from 'angular2/src/facade/lang'; import {unimplemented} from 'angular2/src/facade/exceptions'; import {StringMapWrapper} from 'angular2/src/facade/collection'; -import {ChangeDetectionStrategy, CHANGE_DETECTION_STRATEGY_VALUES} from 'angular2/src/core/change_detection/change_detection'; +import { + ChangeDetectionStrategy, + CHANGE_DETECTION_STRATEGY_VALUES +} from 'angular2/src/core/change_detection/change_detection'; import {ViewEncapsulation, VIEW_ENCAPSULATION_VALUES} from 'angular2/src/core/metadata/view'; import {CssSelector} from 'angular2/src/compiler/selector'; import {splitAtColon} from './util'; @@ -89,7 +105,7 @@ export class CompileDiDependencyMetadata { isOptional: boolean; query: CompileQueryMetadata; viewQuery: CompileQueryMetadata; - token: CompileIdentifierMetadata|string; + token: CompileIdentifierMetadata | string; constructor({isAttribute, isSelf, isHost, isSkipSelf, isOptional, query, viewQuery, token}: { isAttribute?: boolean, @@ -99,7 +115,7 @@ export class CompileDiDependencyMetadata { isOptional?: boolean, query?: CompileQueryMetadata, viewQuery?: CompileQueryMetadata, - token?: CompileIdentifierMetadata|string + token?: CompileIdentifierMetadata | string } = {}) { this.isAttribute = normalizeBool(isAttribute); this.isSelf = normalizeBool(isSelf); @@ -140,10 +156,10 @@ export class CompileDiDependencyMetadata { } export class CompileProviderMetadata { - token: CompileIdentifierMetadata|string; + token: CompileIdentifierMetadata | string; useClass: CompileTypeMetadata; useValue: any; - useExisting: CompileIdentifierMetadata|string; + useExisting: CompileIdentifierMetadata | string; useFactory: CompileFactoryMetadata; deps: CompileDiDependencyMetadata[]; multi: boolean; @@ -152,7 +168,7 @@ export class CompileProviderMetadata { token?: CompileIdentifierMetadata | string, useClass?: CompileTypeMetadata, useValue?: any, - useExisting?: CompileIdentifierMetadata|string, + useExisting?: CompileIdentifierMetadata | string, useFactory?: CompileFactoryMetadata, deps?: CompileDiDependencyMetadata[], multi?: boolean @@ -307,13 +323,13 @@ export class CompileTypeMetadata implements CompileIdentifierMetadata, CompileMe } export class CompileQueryMetadata { - selectors: Array; + selectors: Array; descendants: boolean; first: boolean; propertyName: string; constructor({selectors, descendants, first, propertyName}: { - selectors?: Array, + selectors?: Array, descendants?: boolean, first?: boolean, propertyName?: string @@ -373,8 +389,8 @@ export class CompileTemplateMetadata { static fromJson(data: {[key: string]: any}): CompileTemplateMetadata { return new CompileTemplateMetadata({ encapsulation: isPresent(data['encapsulation']) ? - VIEW_ENCAPSULATION_VALUES[data['encapsulation']] : - data['encapsulation'], + VIEW_ENCAPSULATION_VALUES[data['encapsulation']] : + data['encapsulation'], template: data['template'], templateUrl: data['templateUrl'], styles: data['styles'], @@ -385,8 +401,8 @@ export class CompileTemplateMetadata { toJson(): {[key: string]: any} { return { - 'encapsulation': isPresent(this.encapsulation) ? serializeEnum(this.encapsulation) : - this.encapsulation, + 'encapsulation': + isPresent(this.encapsulation) ? serializeEnum(this.encapsulation) : this.encapsulation, 'template': this.template, 'templateUrl': this.templateUrl, 'styles': this.styles, @@ -400,27 +416,27 @@ export class CompileTemplateMetadata { * Metadata regarding compilation of a directive. */ export class CompileDirectiveMetadata implements CompileMetadataWithType { - static create( - {type, isComponent, dynamicLoadable, selector, exportAs, changeDetection, inputs, outputs, - host, lifecycleHooks, providers, viewProviders, queries, viewQueries, template}: { - type?: CompileTypeMetadata, - isComponent?: boolean, - dynamicLoadable?: boolean, - selector?: string, - exportAs?: string, - changeDetection?: ChangeDetectionStrategy, - inputs?: string[], - outputs?: string[], - host?: {[key: string]: string}, - lifecycleHooks?: LifecycleHooks[], - providers?: - Array, - viewProviders?: - Array, - queries?: CompileQueryMetadata[], - viewQueries?: CompileQueryMetadata[], - template?: CompileTemplateMetadata - } = {}): CompileDirectiveMetadata { + static create({type, isComponent, dynamicLoadable, selector, exportAs, changeDetection, inputs, + outputs, host, lifecycleHooks, providers, viewProviders, queries, viewQueries, + template}: { + type?: CompileTypeMetadata, + isComponent?: boolean, + dynamicLoadable?: boolean, + selector?: string, + exportAs?: string, + changeDetection?: ChangeDetectionStrategy, + inputs?: string[], + outputs?: string[], + host?: {[key: string]: string}, + lifecycleHooks?: LifecycleHooks[], + providers?: + Array, + viewProviders?: + Array, + queries?: CompileQueryMetadata[], + viewQueries?: CompileQueryMetadata[], + template?: CompileTemplateMetadata + } = {}): CompileDirectiveMetadata { var hostListeners: {[key: string]: string} = {}; var hostProperties: {[key: string]: string} = {}; var hostAttributes: {[key: string]: string} = {}; @@ -487,35 +503,34 @@ export class CompileDirectiveMetadata implements CompileMetadataWithType { hostProperties: {[key: string]: string}; hostAttributes: {[key: string]: string}; lifecycleHooks: LifecycleHooks[]; - providers: Array; - viewProviders: Array; + providers: Array; + viewProviders: Array; queries: CompileQueryMetadata[]; viewQueries: CompileQueryMetadata[]; template: CompileTemplateMetadata; - constructor( - {type, isComponent, dynamicLoadable, selector, exportAs, changeDetection, inputs, outputs, - hostListeners, hostProperties, hostAttributes, lifecycleHooks, providers, viewProviders, - queries, viewQueries, template}: { - type?: CompileTypeMetadata, - isComponent?: boolean, - dynamicLoadable?: boolean, - selector?: string, - exportAs?: string, - changeDetection?: ChangeDetectionStrategy, - inputs?: {[key: string]: string}, - outputs?: {[key: string]: string}, - hostListeners?: {[key: string]: string}, - hostProperties?: {[key: string]: string}, - hostAttributes?: {[key: string]: string}, - lifecycleHooks?: LifecycleHooks[], - providers?: - Array, - viewProviders?: - Array, - queries?: CompileQueryMetadata[], - viewQueries?: CompileQueryMetadata[], - template?: CompileTemplateMetadata - } = {}) { + constructor({type, isComponent, dynamicLoadable, selector, exportAs, changeDetection, inputs, + outputs, hostListeners, hostProperties, hostAttributes, lifecycleHooks, providers, + viewProviders, queries, viewQueries, template}: { + type?: CompileTypeMetadata, + isComponent?: boolean, + dynamicLoadable?: boolean, + selector?: string, + exportAs?: string, + changeDetection?: ChangeDetectionStrategy, + inputs?: {[key: string]: string}, + outputs?: {[key: string]: string}, + hostListeners?: {[key: string]: string}, + hostProperties?: {[key: string]: string}, + hostAttributes?: {[key: string]: string}, + lifecycleHooks?: LifecycleHooks[], + providers?: + Array, + viewProviders?: + Array, + queries?: CompileQueryMetadata[], + viewQueries?: CompileQueryMetadata[], + template?: CompileTemplateMetadata + } = {}) { this.type = type; this.isComponent = isComponent; this.dynamicLoadable = dynamicLoadable; @@ -545,8 +560,8 @@ export class CompileDirectiveMetadata implements CompileMetadataWithType { exportAs: data['exportAs'], type: isPresent(data['type']) ? CompileTypeMetadata.fromJson(data['type']) : data['type'], changeDetection: isPresent(data['changeDetection']) ? - CHANGE_DETECTION_STRATEGY_VALUES[data['changeDetection']] : - data['changeDetection'], + CHANGE_DETECTION_STRATEGY_VALUES[data['changeDetection']] : + data['changeDetection'], inputs: data['inputs'], outputs: data['outputs'], hostListeners: data['hostListeners'], @@ -591,8 +606,8 @@ export class CompileDirectiveMetadata implements CompileMetadataWithType { /** * Construct {@link CompileDirectiveMetadata} from {@link ComponentTypeMetadata} and a selector. */ -export function createHostComponentMeta( - componentType: CompileTypeMetadata, componentSelector: string): CompileDirectiveMetadata { +export function createHostComponentMeta(componentType: CompileTypeMetadata, + componentSelector: string): CompileDirectiveMetadata { var template = CssSelector.parse(componentSelector)[0].getMatchingElementTemplate(); return CompileDirectiveMetadata.create({ type: new CompileTypeMetadata({ @@ -623,9 +638,8 @@ export class CompilePipeMetadata implements CompileMetadataWithType { type: CompileTypeMetadata; name: string; pure: boolean; - constructor({type, name, pure}: {type?: CompileTypeMetadata, - name?: string, - pure?: boolean} = {}) { + constructor({type, name, + pure}: {type?: CompileTypeMetadata, name?: string, pure?: boolean} = {}) { this.type = type; this.name = name; this.pure = normalizeBool(pure); @@ -663,7 +677,7 @@ function arrayFromJson(obj: any[], fn: (a: {[key: string]: any}) => any): any { return isBlank(obj) ? null : obj.map(o => objFromJson(o, fn)); } -function arrayToJson(obj: any[]): string|{[key: string]: any} { +function arrayToJson(obj: any[]): string | {[key: string]: any} { return isBlank(obj) ? null : obj.map(objToJson); } @@ -673,7 +687,7 @@ function objFromJson(obj: any, fn: (a: {[key: string]: any}) => any): any { return fn(obj); } -function objToJson(obj: any): string|{[key: string]: any} { +function objToJson(obj: any): string | {[key: string]: any} { if (isArray(obj)) return arrayToJson(obj); if (isString(obj) || isBlank(obj) || isBoolean(obj) || isNumber(obj)) return obj; return obj.toJson(); diff --git a/modules/angular2/src/compiler/html_ast.ts b/modules/angular2/src/compiler/html_ast.ts index 5aa1d2d957..d1f18b47df 100644 --- a/modules/angular2/src/compiler/html_ast.ts +++ b/modules/angular2/src/compiler/html_ast.ts @@ -18,10 +18,9 @@ export class HtmlAttrAst implements HtmlAst { } export class HtmlElementAst implements HtmlAst { - constructor( - public name: string, public attrs: HtmlAttrAst[], public children: HtmlAst[], - public sourceSpan: ParseSourceSpan, public startSourceSpan: ParseSourceSpan, - public endSourceSpan: ParseSourceSpan) {} + constructor(public name: string, public attrs: HtmlAttrAst[], public children: HtmlAst[], + public sourceSpan: ParseSourceSpan, public startSourceSpan: ParseSourceSpan, + public endSourceSpan: ParseSourceSpan) {} visit(visitor: HtmlAstVisitor, context: any): any { return visitor.visitElement(this, context); } } diff --git a/modules/angular2/src/compiler/html_lexer.ts b/modules/angular2/src/compiler/html_lexer.ts index d2fec58215..d3a90d74aa 100644 --- a/modules/angular2/src/compiler/html_lexer.ts +++ b/modules/angular2/src/compiler/html_lexer.ts @@ -1,4 +1,11 @@ -import {StringWrapper, NumberWrapper, isPresent, isBlank, CONST_EXPR, serializeEnum} from 'angular2/src/facade/lang'; +import { + StringWrapper, + NumberWrapper, + isPresent, + isBlank, + CONST_EXPR, + serializeEnum +} from 'angular2/src/facade/lang'; import {ListWrapper} from 'angular2/src/facade/collection'; import {ParseLocation, ParseError, ParseSourceFile, ParseSourceSpan} from './parse_util'; import {getHtmlTagDefinition, HtmlTagContentType, NAMED_ENTITIES} from './html_tags'; @@ -22,8 +29,8 @@ export enum HtmlTokenType { } export class HtmlToken { - constructor( - public type: HtmlTokenType, public parts: string[], public sourceSpan: ParseSourceSpan) {} + constructor(public type: HtmlTokenType, public parts: string[], + public sourceSpan: ParseSourceSpan) {} } export class HtmlTokenError extends ParseError { @@ -184,8 +191,8 @@ class _HtmlTokenizer { if (isBlank(end)) { end = this._getLocation(); } - var token = new HtmlToken( - this.currentTokenType, parts, new ParseSourceSpan(this.currentTokenStart, end)); + var token = new HtmlToken(this.currentTokenType, parts, + new ParseSourceSpan(this.currentTokenStart, end)); this.tokens.push(token); this.currentTokenStart = null; this.currentTokenType = null; @@ -232,8 +239,8 @@ class _HtmlTokenizer { private _requireCharCode(charCode: number) { var location = this._getLocation(); if (!this._attemptCharCode(charCode)) { - throw this._createError( - unexpectedCharacterErrorMsg(this.peek), this._getSpan(location, location)); + throw this._createError(unexpectedCharacterErrorMsg(this.peek), + this._getSpan(location, location)); } } @@ -328,12 +335,12 @@ class _HtmlTokenizer { } } - private _consumeRawText( - decodeEntities: boolean, firstCharOfEnd: number, attemptEndRest: Function): HtmlToken { + private _consumeRawText(decodeEntities: boolean, firstCharOfEnd: number, + attemptEndRest: Function): HtmlToken { var tagCloseStart; var textStart = this._getLocation(); - this._beginToken( - decodeEntities ? HtmlTokenType.ESCAPABLE_RAW_TEXT : HtmlTokenType.RAW_TEXT, textStart); + this._beginToken(decodeEntities ? HtmlTokenType.ESCAPABLE_RAW_TEXT : HtmlTokenType.RAW_TEXT, + textStart); var parts = []; while (true) { tagCloseStart = this._getLocation(); @@ -536,7 +543,7 @@ function isWhitespace(code: number): boolean { function isNameEnd(code: number): boolean { return isWhitespace(code) || code === $GT || code === $SLASH || code === $SQ || code === $DQ || - code === $EQ; + code === $EQ; } function isPrefixEnd(code: number): boolean { diff --git a/modules/angular2/src/compiler/html_parser.ts b/modules/angular2/src/compiler/html_parser.ts index d6f1d5d92e..40385eb105 100644 --- a/modules/angular2/src/compiler/html_parser.ts +++ b/modules/angular2/src/compiler/html_parser.ts @@ -1,4 +1,13 @@ -import {isPresent, isBlank, StringWrapper, stringify, assertionsEnabled, StringJoiner, serializeEnum, CONST_EXPR} from 'angular2/src/facade/lang'; +import { + isPresent, + isBlank, + StringWrapper, + stringify, + assertionsEnabled, + StringJoiner, + serializeEnum, + CONST_EXPR +} from 'angular2/src/facade/lang'; import {ListWrapper} from 'angular2/src/facade/collection'; @@ -26,9 +35,8 @@ export class HtmlParser { parse(sourceContent: string, sourceUrl: string): HtmlParseTreeResult { var tokensAndErrors = tokenizeHtml(sourceContent, sourceUrl); var treeAndErrors = new TreeBuilder(tokensAndErrors.tokens).build(); - return new HtmlParseTreeResult( - treeAndErrors.rootNodes, - (tokensAndErrors.errors).concat(treeAndErrors.errors)); + return new HtmlParseTreeResult(treeAndErrors.rootNodes, (tokensAndErrors.errors) + .concat(treeAndErrors.errors)); } } @@ -55,9 +63,9 @@ class TreeBuilder { } else if (this.peek.type === HtmlTokenType.COMMENT_START) { this._closeVoidElement(); this._consumeComment(this._advance()); - } else if ( - this.peek.type === HtmlTokenType.TEXT || this.peek.type === HtmlTokenType.RAW_TEXT || - this.peek.type === HtmlTokenType.ESCAPABLE_RAW_TEXT) { + } else if (this.peek.type === HtmlTokenType.TEXT || + this.peek.type === HtmlTokenType.RAW_TEXT || + this.peek.type === HtmlTokenType.ESCAPABLE_RAW_TEXT) { this._closeVoidElement(); this._consumeText(this._advance()); } else { @@ -166,8 +174,8 @@ class TreeBuilder { var tagDef = getHtmlTagDefinition(el.name); var parentEl = this._getParentElement(); if (tagDef.requireExtraParent(isPresent(parentEl) ? parentEl.name : null)) { - var newParent = new HtmlElementAst( - tagDef.parentToAdd, [], [el], el.sourceSpan, el.startSourceSpan, el.endSourceSpan); + var newParent = new HtmlElementAst(tagDef.parentToAdd, [], [el], el.sourceSpan, + el.startSourceSpan, el.endSourceSpan); this._addToParent(newParent); this.elementStack.push(newParent); this.elementStack.push(el); @@ -184,12 +192,12 @@ class TreeBuilder { this._getParentElement().endSourceSpan = endTagToken.sourceSpan; if (getHtmlTagDefinition(fullName).isVoid) { - this.errors.push(HtmlTreeError.create( - fullName, endTagToken.sourceSpan, - `Void elements do not have end tags "${endTagToken.parts[1]}"`)); + this.errors.push( + HtmlTreeError.create(fullName, endTagToken.sourceSpan, + `Void elements do not have end tags "${endTagToken.parts[1]}"`)); } else if (!this._popElement(fullName)) { - this.errors.push(HtmlTreeError.create( - fullName, endTagToken.sourceSpan, `Unexpected closing tag "${endTagToken.parts[1]}"`)); + this.errors.push(HtmlTreeError.create(fullName, endTagToken.sourceSpan, + `Unexpected closing tag "${endTagToken.parts[1]}"`)); } } @@ -234,8 +242,8 @@ class TreeBuilder { } } -function getElementFullName( - prefix: string, localName: string, parentElement: HtmlElementAst): string { +function getElementFullName(prefix: string, localName: string, + parentElement: HtmlElementAst): string { if (isBlank(prefix)) { prefix = getHtmlTagDefinition(localName).implicitNamespacePrefix; if (isBlank(prefix) && isPresent(parentElement)) { diff --git a/modules/angular2/src/compiler/html_tags.ts b/modules/angular2/src/compiler/html_tags.ts index 2c06bb6b23..14924f93a4 100644 --- a/modules/angular2/src/compiler/html_tags.ts +++ b/modules/angular2/src/compiler/html_tags.ts @@ -1,4 +1,10 @@ -import {isPresent, isBlank, normalizeBool, RegExpWrapper, CONST_EXPR} from 'angular2/src/facade/lang'; +import { + isPresent, + isBlank, + normalizeBool, + RegExpWrapper, + CONST_EXPR +} from 'angular2/src/facade/lang'; // see http://www.w3.org/TR/html51/syntax.html#named-character-references // see https://html.spec.whatwg.org/multipage/entities.json @@ -275,17 +281,16 @@ export class HtmlTagDefinition { public isVoid: boolean; public ignoreFirstLf: boolean; - constructor( - {closedByChildren, requiredParents, implicitNamespacePrefix, contentType, closedByParent, - isVoid, ignoreFirstLf}: { - closedByChildren?: string[], - closedByParent?: boolean, - requiredParents?: string[], - implicitNamespacePrefix?: string, - contentType?: HtmlTagContentType, - isVoid?: boolean, - ignoreFirstLf?: boolean - } = {}) { + constructor({closedByChildren, requiredParents, implicitNamespacePrefix, contentType, + closedByParent, isVoid, ignoreFirstLf}: { + closedByChildren?: string[], + closedByParent?: boolean, + requiredParents?: string[], + implicitNamespacePrefix?: string, + contentType?: HtmlTagContentType, + isVoid?: boolean, + ignoreFirstLf?: boolean + } = {}) { if (isPresent(closedByChildren) && closedByChildren.length > 0) { closedByChildren.forEach(tagName => this.closedByChildren[tagName] = true); } @@ -337,9 +342,32 @@ var TAG_DEFINITIONS: {[key: string]: HtmlTagDefinition} = { 'wbr': new HtmlTagDefinition({isVoid: true}), 'p': new HtmlTagDefinition({ closedByChildren: [ - 'address', 'article', 'aside', 'blockquote', 'div', 'dl', 'fieldset', 'footer', 'form', - 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'header', 'hgroup', 'hr', - 'main', 'nav', 'ol', 'p', 'pre', 'section', 'table', 'ul' + 'address', + 'article', + 'aside', + 'blockquote', + 'div', + 'dl', + 'fieldset', + 'footer', + 'form', + 'h1', + 'h2', + 'h3', + 'h4', + 'h5', + 'h6', + 'header', + 'hgroup', + 'hr', + 'main', + 'nav', + 'ol', + 'p', + 'pre', + 'section', + 'table', + 'ul' ], closedByParent: true }), diff --git a/modules/angular2/src/compiler/legacy_template.ts b/modules/angular2/src/compiler/legacy_template.ts index 294265e2c4..6adbf78a4a 100644 --- a/modules/angular2/src/compiler/legacy_template.ts +++ b/modules/angular2/src/compiler/legacy_template.ts @@ -1,8 +1,21 @@ import {Injectable, Provider, provide} from 'angular2/src/core/di'; -import {StringWrapper, RegExpWrapper, CONST_EXPR, isBlank, isPresent} from 'angular2/src/facade/lang'; +import { + StringWrapper, + RegExpWrapper, + CONST_EXPR, + isBlank, + isPresent +} from 'angular2/src/facade/lang'; -import {HtmlAstVisitor, HtmlAttrAst, HtmlElementAst, HtmlTextAst, HtmlCommentAst, HtmlAst} from './html_ast'; +import { + HtmlAstVisitor, + HtmlAttrAst, + HtmlElementAst, + HtmlTextAst, + HtmlCommentAst, + HtmlAst +} from './html_ast'; import {HtmlParser, HtmlParseTreeResult} from './html_parser'; import {dashCaseToCamelCase, camelCaseToDashCase} from './util'; @@ -37,8 +50,8 @@ export class LegacyHtmlAstTransformer implements HtmlAstVisitor { this.visitingTemplateEl = ast.name.toLowerCase() == 'template'; let attrs = ast.attrs.map(attr => attr.visit(this, null)); let children = ast.children.map(child => child.visit(this, null)); - return new HtmlElementAst( - ast.name, attrs, children, ast.sourceSpan, ast.startSourceSpan, ast.endSourceSpan); + return new HtmlElementAst(ast.name, attrs, children, ast.sourceSpan, ast.startSourceSpan, + ast.endSourceSpan); } visitAttr(originalAst: HtmlAttrAst, context: any): HtmlAttrAst { @@ -90,8 +103,8 @@ export class LegacyHtmlAstTransformer implements HtmlAstVisitor { } return attrName == ast.name && attrValue == ast.value ? - ast : - new HtmlAttrAst(attrName, attrValue, ast.sourceSpan); + ast : + new HtmlAttrAst(attrName, attrValue, ast.sourceSpan); } private _rewriteTemplateAttribute(ast: HtmlAttrAst): HtmlAttrAst { @@ -102,8 +115,8 @@ export class LegacyHtmlAstTransformer implements HtmlAstVisitor { name = 'template'; // rewrite the directive selector - value = StringWrapper.replaceAllMapped( - value, TEMPLATE_SELECTOR_REGEXP, (m) => { return dashCaseToCamelCase(m[1]); }); + value = StringWrapper.replaceAllMapped(value, TEMPLATE_SELECTOR_REGEXP, + (m) => { return dashCaseToCamelCase(m[1]); }); // rewrite the var declarations value = StringWrapper.replaceAllMapped(value, VARIABLE_TPL_BINDING_REGEXP, m => { @@ -129,8 +142,8 @@ export class LegacyHtmlAstTransformer implements HtmlAstVisitor { } else if (isPresent(m[2])) { attrName = `[(${dashCaseToCamelCase(m[2])})]`; } else if (isPresent(m[3])) { - let prop = StringWrapper.replaceAllMapped( - m[3], SPECIAL_PREFIXES_REGEXP, (m) => { return m[1].toLowerCase() + '.'; }); + let prop = StringWrapper.replaceAllMapped(m[3], SPECIAL_PREFIXES_REGEXP, + (m) => { return m[1].toLowerCase() + '.'; }); if (prop.startsWith('class.') || prop.startsWith('attr.') || prop.startsWith('style.')) { attrName = `[${prop}]`; @@ -144,8 +157,8 @@ export class LegacyHtmlAstTransformer implements HtmlAstVisitor { } return attrName == ast.name && attrValue == ast.value ? - ast : - new HtmlAttrAst(attrName, attrValue, ast.sourceSpan); + ast : + new HtmlAttrAst(attrName, attrValue, ast.sourceSpan); } private _rewriteStar(ast: HtmlAttrAst): HtmlAttrAst { @@ -161,8 +174,8 @@ export class LegacyHtmlAstTransformer implements HtmlAstVisitor { } return attrName == ast.name && attrValue == ast.value ? - ast : - new HtmlAttrAst(attrName, attrValue, ast.sourceSpan); + ast : + new HtmlAttrAst(attrName, attrValue, ast.sourceSpan); } private _rewriteInterpolation(ast: HtmlAttrAst): HtmlAttrAst { @@ -205,7 +218,7 @@ export class LegacyHtmlParser extends HtmlParser { let rootNodes = htmlParseTreeResult.rootNodes.map(node => node.visit(transformer, null)); return transformer.rewrittenAst.length > 0 ? - new HtmlParseTreeResult(rootNodes, htmlParseTreeResult.errors) : - htmlParseTreeResult; + new HtmlParseTreeResult(rootNodes, htmlParseTreeResult.errors) : + htmlParseTreeResult; } } diff --git a/modules/angular2/src/compiler/parse_util.ts b/modules/angular2/src/compiler/parse_util.ts index 063ca6a930..a1070f2e68 100644 --- a/modules/angular2/src/compiler/parse_util.ts +++ b/modules/angular2/src/compiler/parse_util.ts @@ -1,7 +1,6 @@ export class ParseLocation { - constructor( - public file: ParseSourceFile, public offset: number, public line: number, - public col: number) {} + constructor(public file: ParseSourceFile, public offset: number, public line: number, + public col: number) {} toString(): string { return `${this.file.url}@${this.line}:${this.col}`; } } @@ -34,7 +33,7 @@ export abstract class ParseError { while (ctxLen < 100 && ctxStart > 0) { ctxStart--; ctxLen++; - if (source[ctxStart] == '\n') { + if (source[ctxStart] == "\n") { if (++ctxLines == 3) { break; } @@ -46,7 +45,7 @@ export abstract class ParseError { while (ctxLen < 100 && ctxEnd < source.length - 1) { ctxEnd++; ctxLen++; - if (source[ctxEnd] == '\n') { + if (source[ctxEnd] == "\n") { if (++ctxLines == 3) { break; } @@ -54,7 +53,7 @@ export abstract class ParseError { } let context = source.substring(ctxStart, this.span.start.offset) + '[ERROR ->]' + - source.substring(this.span.start.offset, ctxEnd + 1); + source.substring(this.span.start.offset, ctxEnd + 1); return `${this.msg} ("${context}"): ${this.span.start}`; } diff --git a/modules/angular2/src/compiler/proto_view_compiler.ts b/modules/angular2/src/compiler/proto_view_compiler.ts index d3be41cf33..68f489505c 100644 --- a/modules/angular2/src/compiler/proto_view_compiler.ts +++ b/modules/angular2/src/compiler/proto_view_compiler.ts @@ -1,13 +1,54 @@ -import {isPresent, isBlank, Type, isString, StringWrapper, IS_DART, CONST_EXPR} from 'angular2/src/facade/lang'; -import {SetWrapper, StringMapWrapper, ListWrapper, MapWrapper} from 'angular2/src/facade/collection'; -import {TemplateAst, TemplateAstVisitor, NgContentAst, EmbeddedTemplateAst, ElementAst, VariableAst, BoundEventAst, BoundElementPropertyAst, AttrAst, BoundTextAst, TextAst, DirectiveAst, BoundDirectivePropertyAst, templateVisitAll} from './template_ast'; -import {CompileTypeMetadata, CompileDirectiveMetadata, CompilePipeMetadata} from './directive_metadata'; +import { + isPresent, + isBlank, + Type, + isString, + StringWrapper, + IS_DART, + CONST_EXPR +} from 'angular2/src/facade/lang'; +import { + SetWrapper, + StringMapWrapper, + ListWrapper, + MapWrapper +} from 'angular2/src/facade/collection'; +import { + TemplateAst, + TemplateAstVisitor, + NgContentAst, + EmbeddedTemplateAst, + ElementAst, + VariableAst, + BoundEventAst, + BoundElementPropertyAst, + AttrAst, + BoundTextAst, + TextAst, + DirectiveAst, + BoundDirectivePropertyAst, + templateVisitAll +} from './template_ast'; +import { + CompileTypeMetadata, + CompileDirectiveMetadata, + CompilePipeMetadata +} from './directive_metadata'; import {SourceExpressions, SourceExpression, moduleRef} from './source_module'; import {AppProtoView, AppView} from 'angular2/src/core/linker/view'; import {ViewType} from 'angular2/src/core/linker/view_type'; import {AppProtoElement, AppElement} from 'angular2/src/core/linker/element'; import {ResolvedMetadataCache} from 'angular2/src/core/linker/resolved_metadata_cache'; -import {escapeSingleQuoteString, codeGenConstConstructorCall, codeGenValueFn, codeGenFnHeader, MODULE_SUFFIX, codeGenStringMap, Expression, Statement} from './util'; +import { + escapeSingleQuoteString, + codeGenConstConstructorCall, + codeGenValueFn, + codeGenFnHeader, + MODULE_SUFFIX, + codeGenStringMap, + Expression, + Statement +} from './util'; import {Injectable} from 'angular2/src/core/di'; export const PROTO_VIEW_JIT_IMPORTS = CONST_EXPR( @@ -33,20 +74,19 @@ const STYLE_ATTR = 'style'; export class ProtoViewCompiler { constructor() {} - compileProtoViewRuntime( - metadataCache: ResolvedMetadataCache, component: CompileDirectiveMetadata, - template: TemplateAst[], - pipes: CompilePipeMetadata[]): CompileProtoViews { + compileProtoViewRuntime(metadataCache: ResolvedMetadataCache, component: CompileDirectiveMetadata, + template: TemplateAst[], pipes: CompilePipeMetadata[]): + CompileProtoViews { var protoViewFactory = new RuntimeProtoViewFactory(metadataCache, component, pipes); var allProtoViews = []; protoViewFactory.createCompileProtoView(template, [], [], allProtoViews); return new CompileProtoViews([], allProtoViews); } - compileProtoViewCodeGen( - resolvedMetadataCacheExpr: Expression, component: CompileDirectiveMetadata, - template: TemplateAst[], - pipes: CompilePipeMetadata[]): CompileProtoViews { + compileProtoViewCodeGen(resolvedMetadataCacheExpr: Expression, + component: CompileDirectiveMetadata, template: TemplateAst[], + pipes: CompilePipeMetadata[]): + CompileProtoViews { var protoViewFactory = new CodeGenProtoViewFactory(resolvedMetadataCacheExpr, component, pipes); var allProtoViews = []; var allStatements = []; @@ -57,29 +97,26 @@ export class ProtoViewCompiler { } export class CompileProtoViews { - constructor( - public declarations: STATEMENT[], - public protoViews: CompileProtoView[]) {} + constructor(public declarations: STATEMENT[], + public protoViews: CompileProtoView[]) {} } export class CompileProtoView { - constructor( - public embeddedTemplateIndex: number, - public protoElements: CompileProtoElement[], public protoView: APP_PROTO_VIEW) { - } + constructor(public embeddedTemplateIndex: number, + public protoElements: CompileProtoElement[], + public protoView: APP_PROTO_VIEW) {} } export class CompileProtoElement { - constructor( - public boundElementIndex, public attrNameAndValues: string[][], - public variableNameAndValues: string[][], public renderEvents: BoundEventAst[], - public directives: CompileDirectiveMetadata[], public embeddedTemplateIndex: number, - public appProtoEl: APP_PROTO_EL) {} + constructor(public boundElementIndex, public attrNameAndValues: string[][], + public variableNameAndValues: string[][], public renderEvents: BoundEventAst[], + public directives: CompileDirectiveMetadata[], public embeddedTemplateIndex: number, + public appProtoEl: APP_PROTO_EL) {} } -function visitAndReturnContext( - visitor: TemplateAstVisitor, asts: TemplateAst[], context: any): any { +function visitAndReturnContext(visitor: TemplateAstVisitor, asts: TemplateAst[], + context: any): any { templateVisitAll(visitor, asts, context); return context; } @@ -87,17 +124,18 @@ function visitAndReturnContext( abstract class ProtoViewFactory { constructor(public component: CompileDirectiveMetadata) {} - abstract createAppProtoView( - embeddedTemplateIndex: number, viewType: ViewType, templateVariableBindings: string[][], - targetStatements: STATEMENT[]): APP_PROTO_VIEW; + abstract createAppProtoView(embeddedTemplateIndex: number, viewType: ViewType, + templateVariableBindings: string[][], + targetStatements: STATEMENT[]): APP_PROTO_VIEW; - abstract createAppProtoElement( - boundElementIndex: number, attrNameAndValues: string[][], variableNameAndValues: string[][], - directives: CompileDirectiveMetadata[], targetStatements: STATEMENT[]): APP_PROTO_EL; + abstract createAppProtoElement(boundElementIndex: number, attrNameAndValues: string[][], + variableNameAndValues: string[][], + directives: CompileDirectiveMetadata[], + targetStatements: STATEMENT[]): APP_PROTO_EL; - createCompileProtoView( - template: TemplateAst[], templateVariableBindings: string[][], targetStatements: STATEMENT[], - targetProtoViews: CompileProtoView[]): + createCompileProtoView(template: TemplateAst[], templateVariableBindings: string[][], + targetStatements: STATEMENT[], + targetProtoViews: CompileProtoView[]): CompileProtoView { var embeddedTemplateIndex = targetProtoViews.length; // Note: targetProtoViews needs to be in depth first order. @@ -107,8 +145,8 @@ abstract class ProtoViewFactory { this, targetStatements, targetProtoViews); templateVisitAll(builder, template); var viewType = getViewType(this.component, embeddedTemplateIndex); - var appProtoView = this.createAppProtoView( - embeddedTemplateIndex, viewType, templateVariableBindings, targetStatements); + var appProtoView = this.createAppProtoView(embeddedTemplateIndex, viewType, + templateVariableBindings, targetStatements); var cpv = new CompileProtoView( embeddedTemplateIndex, builder.protoElements, appProtoView); targetProtoViews[embeddedTemplateIndex] = cpv; @@ -119,9 +157,8 @@ abstract class ProtoViewFactory { class CodeGenProtoViewFactory extends ProtoViewFactory { private _nextVarId: number = 0; - constructor( - public resolvedMetadataCacheExpr: Expression, component: CompileDirectiveMetadata, - public pipes: CompilePipeMetadata[]) { + constructor(public resolvedMetadataCacheExpr: Expression, component: CompileDirectiveMetadata, + public pipes: CompilePipeMetadata[]) { super(component); } @@ -129,23 +166,23 @@ class CodeGenProtoViewFactory extends ProtoViewFactory pipeMeta.type)) : - null; + codeGenTypesArray(this.pipes.map(pipeMeta => pipeMeta.type)) : + null; var statement = `var ${protoViewVarName} = ${APP_VIEW_MODULE_REF}AppProtoView.create(${this.resolvedMetadataCacheExpr.expression}, ${viewTypeExpr}, ${pipesExpr}, ${codeGenStringMap(templateVariableBindings)});`; targetStatements.push(new Statement(statement)); return new Expression(protoViewVarName); } - createAppProtoElement( - boundElementIndex: number, attrNameAndValues: string[][], variableNameAndValues: string[][], - directives: CompileDirectiveMetadata[], targetStatements: Statement[]): Expression { + createAppProtoElement(boundElementIndex: number, attrNameAndValues: string[][], + variableNameAndValues: string[][], directives: CompileDirectiveMetadata[], + targetStatements: Statement[]): Expression { var varName = `appProtoEl${this._nextVarId++}_${this.component.type.name}`; var value = `${APP_EL_MODULE_REF}AppProtoElement.create( ${this.resolvedMetadataCacheExpr.expression}, @@ -161,29 +198,26 @@ class CodeGenProtoViewFactory extends ProtoViewFactory { - constructor( - public metadataCache: ResolvedMetadataCache, component: CompileDirectiveMetadata, - public pipes: CompilePipeMetadata[]) { + constructor(public metadataCache: ResolvedMetadataCache, component: CompileDirectiveMetadata, + public pipes: CompilePipeMetadata[]) { super(component); } - createAppProtoView( - embeddedTemplateIndex: number, viewType: ViewType, templateVariableBindings: string[][], - targetStatements: any[]): AppProtoView { + createAppProtoView(embeddedTemplateIndex: number, viewType: ViewType, + templateVariableBindings: string[][], targetStatements: any[]): AppProtoView { var pipes = embeddedTemplateIndex === 0 ? this.pipes.map(pipeMeta => pipeMeta.type.runtime) : []; var templateVars = keyValueArrayToStringMap(templateVariableBindings); return AppProtoView.create(this.metadataCache, viewType, pipes, templateVars); } - createAppProtoElement( - boundElementIndex: number, attrNameAndValues: string[][], variableNameAndValues: string[][], - directives: CompileDirectiveMetadata[], targetStatements: any[]): AppProtoElement { + createAppProtoElement(boundElementIndex: number, attrNameAndValues: string[][], + variableNameAndValues: string[][], directives: CompileDirectiveMetadata[], + targetStatements: any[]): AppProtoElement { var attrs = keyValueArrayToStringMap(attrNameAndValues); - return AppProtoElement.create( - this.metadataCache, boundElementIndex, attrs, - directives.map(dirMeta => dirMeta.type.runtime), - keyValueArrayToStringMap(variableNameAndValues)); + return AppProtoElement.create(this.metadataCache, boundElementIndex, attrs, + directives.map(dirMeta => dirMeta.type.runtime), + keyValueArrayToStringMap(variableNameAndValues)); } } @@ -192,13 +226,12 @@ class ProtoViewBuilderVisitor implement protoElements: CompileProtoElement[] = []; boundElementCount: number = 0; - constructor( - public factory: ProtoViewFactory, - public allStatements: STATEMENT[], - public allProtoViews: CompileProtoView[]) {} + constructor(public factory: ProtoViewFactory, + public allStatements: STATEMENT[], + public allProtoViews: CompileProtoView[]) {} - private _readAttrNameAndValues(directives: CompileDirectiveMetadata[], attrAsts: TemplateAst[]): - string[][] { + private _readAttrNameAndValues(directives: CompileDirectiveMetadata[], + attrAsts: TemplateAst[]): string[][] { var attrs = visitAndReturnContext(this, attrAsts, {}); directives.forEach(directiveMeta => { StringMapWrapper.forEach(directiveMeta.hostAttributes, (value: string, name: string) => { @@ -229,17 +262,15 @@ class ProtoViewBuilderVisitor implement var renderEvents: Map = visitAndReturnContext(this, ast.outputs, new Map()); ListWrapper.forEachWithIndex(ast.directives, (directiveAst: DirectiveAst, index: number) => { - directiveAst.visit( - this, new DirectiveContext( - index, boundElementIndex, renderEvents, variableNameAndValues, directives)); + directiveAst.visit(this, new DirectiveContext(index, boundElementIndex, renderEvents, + variableNameAndValues, directives)); }); var renderEventArray = []; renderEvents.forEach((eventAst, _) => renderEventArray.push(eventAst)); var attrNameAndValues = this._readAttrNameAndValues(directives, ast.attrs); - this._addProtoElement( - ast.isBound(), boundElementIndex, attrNameAndValues, variableNameAndValues, - renderEventArray, directives, null); + this._addProtoElement(ast.isBound(), boundElementIndex, attrNameAndValues, + variableNameAndValues, renderEventArray, directives, null); templateVisitAll(this, ast.children); return null; } @@ -249,8 +280,8 @@ class ProtoViewBuilderVisitor implement var directives: CompileDirectiveMetadata[] = []; ListWrapper.forEachWithIndex(ast.directives, (directiveAst: DirectiveAst, index: number) => { directiveAst.visit( - this, new DirectiveContext( - index, boundElementIndex, new Map(), [], directives)); + this, new DirectiveContext(index, boundElementIndex, new Map(), [], + directives)); }); var attrNameAndValues = this._readAttrNameAndValues(directives, ast.attrs); @@ -258,21 +289,19 @@ class ProtoViewBuilderVisitor implement varAst => [varAst.value.length > 0 ? varAst.value : IMPLICIT_TEMPLATE_VAR, varAst.name]); var nestedProtoView = this.factory.createCompileProtoView( ast.children, templateVariableBindings, this.allStatements, this.allProtoViews); - this._addProtoElement( - true, boundElementIndex, attrNameAndValues, [], [], directives, - nestedProtoView.embeddedTemplateIndex); + this._addProtoElement(true, boundElementIndex, attrNameAndValues, [], [], directives, + nestedProtoView.embeddedTemplateIndex); return null; } - private _addProtoElement( - isBound: boolean, boundElementIndex, attrNameAndValues: string[][], - variableNameAndValues: string[][], renderEvents: BoundEventAst[], - directives: CompileDirectiveMetadata[], embeddedTemplateIndex: number) { + private _addProtoElement(isBound: boolean, boundElementIndex, attrNameAndValues: string[][], + variableNameAndValues: string[][], renderEvents: BoundEventAst[], + directives: CompileDirectiveMetadata[], embeddedTemplateIndex: number) { var appProtoEl = null; if (isBound) { - appProtoEl = this.factory.createAppProtoElement( - boundElementIndex, attrNameAndValues, variableNameAndValues, directives, - this.allStatements); + appProtoEl = + this.factory.createAppProtoElement(boundElementIndex, attrNameAndValues, + variableNameAndValues, directives, this.allStatements); } var compileProtoEl = new CompileProtoElement( boundElementIndex, attrNameAndValues, variableNameAndValues, renderEvents, directives, @@ -288,9 +317,8 @@ class ProtoViewBuilderVisitor implement visitDirective(ast: DirectiveAst, ctx: DirectiveContext): any { ctx.targetDirectives.push(ast.directive); templateVisitAll(this, ast.hostEvents, ctx.hostEventTargetAndNames); - ast.exportAsVars.forEach(varAst => { - ctx.targetVariableNameAndValues.push([varAst.name, ctx.index]); - }); + ast.exportAsVars.forEach( + varAst => { ctx.targetVariableNameAndValues.push([varAst.name, ctx.index]); }); return null; } visitEvent(ast: BoundEventAst, eventTargetAndNames: Map): any { @@ -303,14 +331,12 @@ class ProtoViewBuilderVisitor implement function mapToKeyValueArray(data: {[key: string]: string}): string[][] { var entryArray: string[][] = []; - StringMapWrapper.forEach(data, (value: string, name: string) => { - entryArray.push([name, value]); - }); + StringMapWrapper.forEach(data, + (value: string, name: string) => { entryArray.push([name, value]); }); // We need to sort to get a defined output order // for tests and for caching generated artifacts... - ListWrapper.sort( - entryArray, - (entry1: string[], entry2: string[]) => StringWrapper.compare(entry1[0], entry2[0])); + ListWrapper.sort(entryArray, (entry1: string[], entry2: string[]) => + StringWrapper.compare(entry1[0], entry2[0])); var keyValueArray: string[][] = []; entryArray.forEach((entry) => { keyValueArray.push([entry[0], entry[1]]); }); return keyValueArray; @@ -325,11 +351,10 @@ function mergeAttributeValue(attrName: string, attrValue1: string, attrValue2: s } class DirectiveContext { - constructor( - public index: number, public boundElementIndex: number, - public hostEventTargetAndNames: Map, - public targetVariableNameAndValues: any[][], - public targetDirectives: CompileDirectiveMetadata[]) {} + constructor(public index: number, public boundElementIndex: number, + public hostEventTargetAndNames: Map, + public targetVariableNameAndValues: any[][], + public targetDirectives: CompileDirectiveMetadata[]) {} } function keyValueArrayToStringMap(keyValueArray: any[][]): {[key: string]: any} { diff --git a/modules/angular2/src/compiler/runtime_metadata.ts b/modules/angular2/src/compiler/runtime_metadata.ts index 4bc6a2a984..6a48faac7a 100644 --- a/modules/angular2/src/compiler/runtime_metadata.ts +++ b/modules/angular2/src/compiler/runtime_metadata.ts @@ -1,5 +1,12 @@ import {resolveForwardRef} from 'angular2/src/core/di'; -import {Type, isBlank, isPresent, isArray, stringify, RegExpWrapper} from 'angular2/src/facade/lang'; +import { + Type, + isBlank, + isPresent, + isArray, + stringify, + RegExpWrapper +} from 'angular2/src/facade/lang'; import {BaseException} from 'angular2/src/facade/exceptions'; import * as cpl from './directive_metadata'; import * as md from 'angular2/src/core/metadata/directives'; @@ -23,11 +30,10 @@ export class RuntimeMetadataResolver { private _anonymousTypes = new Map(); private _anonymousTypeIndex = 0; - constructor( - private _directiveResolver: DirectiveResolver, private _pipeResolver: PipeResolver, - private _viewResolver: ViewResolver, - @Optional() @Inject(PLATFORM_DIRECTIVES) private _platformDirectives: Type[], - @Optional() @Inject(PLATFORM_PIPES) private _platformPipes: Type[]) {} + constructor(private _directiveResolver: DirectiveResolver, private _pipeResolver: PipeResolver, + private _viewResolver: ViewResolver, + @Optional() @Inject(PLATFORM_DIRECTIVES) private _platformDirectives: Type[], + @Optional() @Inject(PLATFORM_PIPES) private _platformPipes: Type[]) {} /** * Wrap the stringify method to avoid naming things `function (arg1...) {` @@ -151,7 +157,7 @@ function flattenPipes(view: ViewMetadata, platformPipes: any[]): Type[] { return pipes; } -function flattenArray(tree: any[], out: Array): void { +function flattenArray(tree: any[], out: Array): void { for (var i = 0; i < tree.length; i++) { var item = resolveForwardRef(tree[i]); if (isArray(item)) { diff --git a/modules/angular2/src/compiler/schema/dom_element_schema_registry.ts b/modules/angular2/src/compiler/schema/dom_element_schema_registry.ts index 600e9a258c..84a9230fe3 100644 --- a/modules/angular2/src/compiler/schema/dom_element_schema_registry.ts +++ b/modules/angular2/src/compiler/schema/dom_element_schema_registry.ts @@ -18,8 +18,8 @@ export class DomElementSchemaRegistry extends ElementSchemaRegistry { if (isBlank(element)) { var nsAndName = splitNsName(tagName); element = isPresent(nsAndName[0]) ? - DOM.createElementNS(NAMESPACE_URIS[nsAndName[0]], nsAndName[1]) : - DOM.createElement(nsAndName[1]); + DOM.createElementNS(NAMESPACE_URIS[nsAndName[0]], nsAndName[1]) : + DOM.createElement(nsAndName[1]); this._protoElements.set(tagName, element); } return element; diff --git a/modules/angular2/src/compiler/selector.ts b/modules/angular2/src/compiler/selector.ts index 3c3adb32a6..deed232f37 100644 --- a/modules/angular2/src/compiler/selector.ts +++ b/modules/angular2/src/compiler/selector.ts @@ -1,5 +1,11 @@ import {Map, ListWrapper, MapWrapper} from 'angular2/src/facade/collection'; -import {isPresent, isBlank, RegExpWrapper, RegExpMatcherWrapper, StringWrapper} from 'angular2/src/facade/lang'; +import { + isPresent, + isBlank, + RegExpWrapper, + RegExpMatcherWrapper, + StringWrapper +} from 'angular2/src/facade/lang'; import {BaseException, WrappedException} from 'angular2/src/facade/exceptions'; const _EMPTY_ATTR_VALUE = ''; @@ -30,7 +36,7 @@ export class CssSelector { var _addResult = (res: CssSelector[], cssSel) => { if (cssSel.notSelectors.length > 0 && isBlank(cssSel.element) && ListWrapper.isEmpty(cssSel.classNames) && ListWrapper.isEmpty(cssSel.attrs)) { - cssSel.element = '*'; + cssSel.element = "*"; } res.push(cssSel); }; @@ -75,7 +81,7 @@ export class CssSelector { isElementSelector(): boolean { return isPresent(this.element) && ListWrapper.isEmpty(this.classNames) && - ListWrapper.isEmpty(this.attrs) && this.notSelectors.length === 0; + ListWrapper.isEmpty(this.attrs) && this.notSelectors.length === 0; } setElement(element: string = null) { this.element = element; } @@ -168,8 +174,8 @@ export class SelectorMatcher { * @param cssSelector A css selector * @param callbackCtxt An opaque object that will be given to the callback of the `match` function */ - private _addSelectable( - cssSelector: CssSelector, callbackCtxt: any, listContext: SelectorListContext) { + private _addSelectable(cssSelector: CssSelector, callbackCtxt: any, + listContext: SelectorListContext) { var matcher: SelectorMatcher = this; var element = cssSelector.element; var classNames = cssSelector.classNames; @@ -223,8 +229,8 @@ export class SelectorMatcher { } } - private _addTerminal( - map: Map, name: string, selectable: SelectorContext) { + private _addTerminal(map: Map, name: string, + selectable: SelectorContext) { var terminalList = map.get(name); if (isBlank(terminalList)) { terminalList = []; @@ -261,7 +267,7 @@ export class SelectorMatcher { result = this._matchTerminal(this._elementMap, element, cssSelector, matchedCallback) || result; result = this._matchPartial(this._elementPartialMap, element, cssSelector, matchedCallback) || - result; + result; if (isPresent(classNames)) { for (var index = 0; index < classNames.length; index++) { @@ -281,18 +287,18 @@ export class SelectorMatcher { var terminalValuesMap = this._attrValueMap.get(attrName); if (!StringWrapper.equals(attrValue, _EMPTY_ATTR_VALUE)) { - result = this._matchTerminal( - terminalValuesMap, _EMPTY_ATTR_VALUE, cssSelector, matchedCallback) || - result; + result = this._matchTerminal(terminalValuesMap, _EMPTY_ATTR_VALUE, cssSelector, + matchedCallback) || + result; } result = this._matchTerminal(terminalValuesMap, attrValue, cssSelector, matchedCallback) || - result; + result; var partialValuesMap = this._attrValuePartialMap.get(attrName); if (!StringWrapper.equals(attrValue, _EMPTY_ATTR_VALUE)) { - result = this._matchPartial( - partialValuesMap, _EMPTY_ATTR_VALUE, cssSelector, matchedCallback) || - result; + result = this._matchPartial(partialValuesMap, _EMPTY_ATTR_VALUE, cssSelector, + matchedCallback) || + result; } result = this._matchPartial(partialValuesMap, attrValue, cssSelector, matchedCallback) || result; @@ -302,15 +308,14 @@ export class SelectorMatcher { } /** @internal */ - _matchTerminal( - map: Map, name, cssSelector: CssSelector, - matchedCallback: (c: CssSelector, a: any) => void): boolean { + _matchTerminal(map: Map, name, cssSelector: CssSelector, + matchedCallback: (c: CssSelector, a: any) => void): boolean { if (isBlank(map) || isBlank(name)) { return false; } var selectables = map.get(name); - var starSelectables = map.get('*'); + var starSelectables = map.get("*"); if (isPresent(starSelectables)) { selectables = selectables.concat(starSelectables); } @@ -327,9 +332,8 @@ export class SelectorMatcher { } /** @internal */ - _matchPartial( - map: Map, name, cssSelector: CssSelector, - matchedCallback /*: (c: CssSelector, a: any) => void*/): boolean { + _matchPartial(map: Map, name, cssSelector: CssSelector, + matchedCallback /*: (c: CssSelector, a: any) => void*/): boolean { if (isBlank(map) || isBlank(name)) { return false; } @@ -355,9 +359,8 @@ export class SelectorListContext { export class SelectorContext { notSelectors: CssSelector[]; - constructor( - public selector: CssSelector, public cbContext: any, - public listContext: SelectorListContext) { + constructor(public selector: CssSelector, public cbContext: any, + public listContext: SelectorListContext) { this.notSelectors = selector.notSelectors; } diff --git a/modules/angular2/src/compiler/shadow_css.ts b/modules/angular2/src/compiler/shadow_css.ts index 2115132dcf..21775e2362 100644 --- a/modules/angular2/src/compiler/shadow_css.ts +++ b/modules/angular2/src/compiler/shadow_css.ts @@ -1,5 +1,12 @@ import {ListWrapper} from 'angular2/src/facade/collection'; -import {StringWrapper, RegExp, RegExpWrapper, RegExpMatcherWrapper, isPresent, isBlank} from 'angular2/src/facade/lang'; +import { + StringWrapper, + RegExp, + RegExpWrapper, + RegExpMatcherWrapper, + isPresent, + isBlank +} from 'angular2/src/facade/lang'; /** * This file is a port of shadowCSS from webcomponents.js to TypeScript. @@ -167,8 +174,8 @@ export class ShadowCss { **/ private _insertPolyfillDirectivesInCssText(cssText: string): string { // Difference with webcomponents.js: does not handle comments - return StringWrapper.replaceAllMapped( - cssText, _cssContentNextSelectorRe, function(m) { return m[1] + '{'; }); + return StringWrapper.replaceAllMapped(cssText, _cssContentNextSelectorRe, + function(m) { return m[1] + '{'; }); } /* @@ -272,8 +279,8 @@ export class ShadowCss { * scopeName.foo .bar { ... } */ private _convertColonHostContext(cssText: string): string { - return this._convertColonRule( - cssText, _cssColonHostContextRe, this._colonHostContextPartReplacer); + return this._convertColonRule(cssText, _cssColonHostContextRe, + this._colonHostContextPartReplacer); } private _convertColonRule(cssText: string, regExp: RegExp, partReplacer: Function): string { @@ -332,8 +339,8 @@ export class ShadowCss { }); } - private _scopeSelector( - selector: string, scopeSelector: string, hostSelector: string, strict: boolean): string { + private _scopeSelector(selector: string, scopeSelector: string, hostSelector: string, + strict: boolean): string { var r = [], parts = selector.split(','); for (var i = 0; i < parts.length; i++) { var p = parts[i].trim(); @@ -341,8 +348,8 @@ export class ShadowCss { var shallowPart = deepParts[0]; if (this._selectorNeedsScoping(shallowPart, scopeSelector)) { deepParts[0] = strict && !StringWrapper.contains(shallowPart, _polyfillHostNoCombinator) ? - this._applyStrictSelectorScope(shallowPart, scopeSelector) : - this._applySelectorScope(shallowPart, scopeSelector, hostSelector); + this._applyStrictSelectorScope(shallowPart, scopeSelector) : + this._applySelectorScope(shallowPart, scopeSelector, hostSelector); } // replace /deep/ with a space for child selectors r.push(deepParts.join(' ')); @@ -363,15 +370,15 @@ export class ShadowCss { return RegExpWrapper.create('^(' + scopeSelector + ')' + _selectorReSuffix, 'm'); } - private _applySelectorScope(selector: string, scopeSelector: string, hostSelector: string): - string { + private _applySelectorScope(selector: string, scopeSelector: string, + hostSelector: string): string { // Difference from webcomponentsjs: scopeSelector could not be an array return this._applySimpleSelectorScope(selector, scopeSelector, hostSelector); } // scope via name and [is=name] - private _applySimpleSelectorScope(selector: string, scopeSelector: string, hostSelector: string): - string { + private _applySimpleSelectorScope(selector: string, scopeSelector: string, + hostSelector: string): string { if (isPresent(RegExpWrapper.firstMatch(_polyfillHostRe, selector))) { var replaceBy = this.strictStyling ? `[${hostSelector}]` : scopeSelector; selector = StringWrapper.replace(selector, _polyfillHostNoCombinator, replaceBy); @@ -390,20 +397,19 @@ export class ShadowCss { for (var i = 0; i < splits.length; i++) { var sep = splits[i]; var parts = scoped.split(sep); - scoped = parts - .map(p => { - // remove :host since it should be unnecessary - var t = StringWrapper.replaceAll(p.trim(), _polyfillHostRe, ''); - if (t.length > 0 && !ListWrapper.contains(splits, t) && - !StringWrapper.contains(t, attrName)) { - var re = /([^:]*)(:*)(.*)/g; - var m = RegExpWrapper.firstMatch(re, t); - if (isPresent(m)) { - p = m[1] + attrName + m[2] + m[3]; - } - } - return p; - }) + scoped = parts.map(p => { + // remove :host since it should be unnecessary + var t = StringWrapper.replaceAll(p.trim(), _polyfillHostRe, ''); + if (t.length > 0 && !ListWrapper.contains(splits, t) && + !StringWrapper.contains(t, attrName)) { + var re = /([^:]*)(:*)(.*)/g; + var m = RegExpWrapper.firstMatch(re, t); + if (isPresent(m)) { + p = m[1] + attrName + m[2] + m[3]; + } + } + return p; + }) .join(sep); } return scoped; @@ -424,13 +430,14 @@ var _polyfillHost = '-shadowcsshost'; // note: :host-context pre-processed to -shadowcsshostcontext. var _polyfillHostContext = '-shadowcsscontext'; var _parenSuffix = ')(?:\\((' + - '(?:\\([^)(]*\\)|[^)(]*)+?' + - ')\\))?([^,{]*)'; + '(?:\\([^)(]*\\)|[^)(]*)+?' + + ')\\))?([^,{]*)'; var _cssColonHostRe = RegExpWrapper.create('(' + _polyfillHost + _parenSuffix, 'im'); var _cssColonHostContextRe = RegExpWrapper.create('(' + _polyfillHostContext + _parenSuffix, 'im'); var _polyfillHostNoCombinator = _polyfillHost + '-no-combinator'; var _shadowDOMSelectorsRe = [ - /::shadow/g, /::content/g, + /::shadow/g, + /::content/g, // Deprecated selectors // TODO(vicb): see https://github.com/angular/clang-format/issues/16 // clang-format off diff --git a/modules/angular2/src/compiler/static_reflector.ts b/modules/angular2/src/compiler/static_reflector.ts index cf11b1bcbc..925466e4ee 100644 --- a/modules/angular2/src/compiler/static_reflector.ts +++ b/modules/angular2/src/compiler/static_reflector.ts @@ -1,6 +1,30 @@ import {ListWrapper, StringMapWrapper} from 'angular2/src/facade/collection'; -import {isArray, isBlank, isNumber, isPresent, isPrimitive, isString, Type} from 'angular2/src/facade/lang'; -import {AttributeMetadata, DirectiveMetadata, ComponentMetadata, ContentChildrenMetadata, ContentChildMetadata, InputMetadata, HostBindingMetadata, HostListenerMetadata, OutputMetadata, PipeMetadata, ViewMetadata, ViewChildMetadata, ViewChildrenMetadata, ViewQueryMetadata, QueryMetadata,} from 'angular2/src/core/metadata'; +import { + isArray, + isBlank, + isNumber, + isPresent, + isPrimitive, + isString, + Type +} from 'angular2/src/facade/lang'; +import { + AttributeMetadata, + DirectiveMetadata, + ComponentMetadata, + ContentChildrenMetadata, + ContentChildMetadata, + InputMetadata, + HostBindingMetadata, + HostListenerMetadata, + OutputMetadata, + PipeMetadata, + ViewMetadata, + ViewChildMetadata, + ViewChildrenMetadata, + ViewQueryMetadata, + QueryMetadata, +} from 'angular2/src/core/metadata'; /** * The host of the static resolver is expected to be able to provide module metadata in the form of @@ -100,62 +124,60 @@ export class StaticReflector { private initializeConversionMap(): any { let core_metadata = 'angular2/src/core/metadata'; let conversionMap = this.conversionMap; - conversionMap.set( - this.getStaticType(core_metadata, 'Directive'), (moduleContext, expression) => { - let p0 = this.getDecoratorParameter(moduleContext, expression, 0); - if (!isPresent(p0)) { - p0 = {}; - } - return new DirectiveMetadata({ - selector: p0['selector'], - inputs: p0['inputs'], - outputs: p0['outputs'], - events: p0['events'], - host: p0['host'], - bindings: p0['bindings'], - providers: p0['providers'], - exportAs: p0['exportAs'], - queries: p0['queries'], - }); - }); - conversionMap.set( - this.getStaticType(core_metadata, 'Component'), (moduleContext, expression) => { - let p0 = this.getDecoratorParameter(moduleContext, expression, 0); - if (!isPresent(p0)) { - p0 = {}; - } - return new ComponentMetadata({ - selector: p0['selector'], - inputs: p0['inputs'], - outputs: p0['outputs'], - properties: p0['properties'], - events: p0['events'], - host: p0['host'], - exportAs: p0['exportAs'], - moduleId: p0['moduleId'], - bindings: p0['bindings'], - providers: p0['providers'], - viewBindings: p0['viewBindings'], - viewProviders: p0['viewProviders'], - changeDetection: p0['changeDetection'], - queries: p0['queries'], - templateUrl: p0['templateUrl'], - template: p0['template'], - styleUrls: p0['styleUrls'], - styles: p0['styles'], - directives: p0['directives'], - pipes: p0['pipes'], - encapsulation: p0['encapsulation'] - }); - }); - conversionMap.set( - this.getStaticType(core_metadata, 'Input'), - (moduleContext, expression) => - new InputMetadata(this.getDecoratorParameter(moduleContext, expression, 0))); - conversionMap.set( - this.getStaticType(core_metadata, 'Output'), - (moduleContext, expression) => - new OutputMetadata(this.getDecoratorParameter(moduleContext, expression, 0))); + conversionMap.set(this.getStaticType(core_metadata, 'Directive'), + (moduleContext, expression) => { + let p0 = this.getDecoratorParameter(moduleContext, expression, 0); + if (!isPresent(p0)) { + p0 = {}; + } + return new DirectiveMetadata({ + selector: p0['selector'], + inputs: p0['inputs'], + outputs: p0['outputs'], + events: p0['events'], + host: p0['host'], + bindings: p0['bindings'], + providers: p0['providers'], + exportAs: p0['exportAs'], + queries: p0['queries'], + }); + }); + conversionMap.set(this.getStaticType(core_metadata, 'Component'), + (moduleContext, expression) => { + let p0 = this.getDecoratorParameter(moduleContext, expression, 0); + if (!isPresent(p0)) { + p0 = {}; + } + return new ComponentMetadata({ + selector: p0['selector'], + inputs: p0['inputs'], + outputs: p0['outputs'], + properties: p0['properties'], + events: p0['events'], + host: p0['host'], + exportAs: p0['exportAs'], + moduleId: p0['moduleId'], + bindings: p0['bindings'], + providers: p0['providers'], + viewBindings: p0['viewBindings'], + viewProviders: p0['viewProviders'], + changeDetection: p0['changeDetection'], + queries: p0['queries'], + templateUrl: p0['templateUrl'], + template: p0['template'], + styleUrls: p0['styleUrls'], + styles: p0['styles'], + directives: p0['directives'], + pipes: p0['pipes'], + encapsulation: p0['encapsulation'] + }); + }); + conversionMap.set(this.getStaticType(core_metadata, 'Input'), + (moduleContext, expression) => new InputMetadata( + this.getDecoratorParameter(moduleContext, expression, 0))); + conversionMap.set(this.getStaticType(core_metadata, 'Output'), + (moduleContext, expression) => new OutputMetadata( + this.getDecoratorParameter(moduleContext, expression, 0))); conversionMap.set(this.getStaticType(core_metadata, 'View'), (moduleContext, expression) => { let p0 = this.getDecoratorParameter(moduleContext, expression, 0); if (!isPresent(p0)) { @@ -170,10 +192,9 @@ export class StaticReflector { styles: p0['styles'], }); }); - conversionMap.set( - this.getStaticType(core_metadata, 'Attribute'), - (moduleContext, expression) => - new AttributeMetadata(this.getDecoratorParameter(moduleContext, expression, 0))); + conversionMap.set(this.getStaticType(core_metadata, 'Attribute'), + (moduleContext, expression) => new AttributeMetadata( + this.getDecoratorParameter(moduleContext, expression, 0))); conversionMap.set(this.getStaticType(core_metadata, 'Query'), (moduleContext, expression) => { let p0 = this.getDecoratorParameter(moduleContext, expression, 0); let p1 = this.getDecoratorParameter(moduleContext, expression, 1); @@ -182,34 +203,30 @@ export class StaticReflector { } return new QueryMetadata(p0, {descendants: p1.descendants, first: p1.first}); }); - conversionMap.set( - this.getStaticType(core_metadata, 'ContentChildren'), - (moduleContext, expression) => - new ContentChildrenMetadata(this.getDecoratorParameter(moduleContext, expression, 0))); - conversionMap.set( - this.getStaticType(core_metadata, 'ContentChild'), - (moduleContext, expression) => - new ContentChildMetadata(this.getDecoratorParameter(moduleContext, expression, 0))); - conversionMap.set( - this.getStaticType(core_metadata, 'ViewChildren'), - (moduleContext, expression) => - new ViewChildrenMetadata(this.getDecoratorParameter(moduleContext, expression, 0))); - conversionMap.set( - this.getStaticType(core_metadata, 'ViewChild'), - (moduleContext, expression) => - new ViewChildMetadata(this.getDecoratorParameter(moduleContext, expression, 0))); - conversionMap.set( - this.getStaticType(core_metadata, 'ViewQuery'), (moduleContext, expression) => { - let p0 = this.getDecoratorParameter(moduleContext, expression, 0); - let p1 = this.getDecoratorParameter(moduleContext, expression, 1); - if (!isPresent(p1)) { - p1 = {}; - } - return new ViewQueryMetadata(p0, { - descendants: p1['descendants'], - first: p1['first'], - }); - }); + conversionMap.set(this.getStaticType(core_metadata, 'ContentChildren'), + (moduleContext, expression) => new ContentChildrenMetadata( + this.getDecoratorParameter(moduleContext, expression, 0))); + conversionMap.set(this.getStaticType(core_metadata, 'ContentChild'), + (moduleContext, expression) => new ContentChildMetadata( + this.getDecoratorParameter(moduleContext, expression, 0))); + conversionMap.set(this.getStaticType(core_metadata, 'ViewChildren'), + (moduleContext, expression) => new ViewChildrenMetadata( + this.getDecoratorParameter(moduleContext, expression, 0))); + conversionMap.set(this.getStaticType(core_metadata, 'ViewChild'), + (moduleContext, expression) => new ViewChildMetadata( + this.getDecoratorParameter(moduleContext, expression, 0))); + conversionMap.set(this.getStaticType(core_metadata, 'ViewQuery'), + (moduleContext, expression) => { + let p0 = this.getDecoratorParameter(moduleContext, expression, 0); + let p1 = this.getDecoratorParameter(moduleContext, expression, 1); + if (!isPresent(p1)) { + p1 = {}; + } + return new ViewQueryMetadata(p0, { + descendants: p1['descendants'], + first: p1['first'], + }); + }); conversionMap.set(this.getStaticType(core_metadata, 'Pipe'), (moduleContext, expression) => { let p0 = this.getDecoratorParameter(moduleContext, expression, 0); if (!isPresent(p0)) { @@ -220,15 +237,13 @@ export class StaticReflector { pure: p0['pure'], }); }); - conversionMap.set( - this.getStaticType(core_metadata, 'HostBinding'), - (moduleContext, expression) => - new HostBindingMetadata(this.getDecoratorParameter(moduleContext, expression, 0))); - conversionMap.set( - this.getStaticType(core_metadata, 'HostListener'), - (moduleContext, expression) => new HostListenerMetadata( - this.getDecoratorParameter(moduleContext, expression, 0), - this.getDecoratorParameter(moduleContext, expression, 1))); + conversionMap.set(this.getStaticType(core_metadata, 'HostBinding'), + (moduleContext, expression) => new HostBindingMetadata( + this.getDecoratorParameter(moduleContext, expression, 0))); + conversionMap.set(this.getStaticType(core_metadata, 'HostListener'), + (moduleContext, expression) => new HostListenerMetadata( + this.getDecoratorParameter(moduleContext, expression, 0), + this.getDecoratorParameter(moduleContext, expression, 1))); return null; } @@ -249,8 +264,8 @@ export class StaticReflector { return null; } - private getDecoratorParameter( - moduleContext: string, expression: {[key: string]: any}, index: number): any { + private getDecoratorParameter(moduleContext: string, expression: {[key: string]: any}, + index: number): any { if (isMetadataSymbolicCallExpression(expression) && isPresent(expression['arguments']) && (expression['arguments']).length <= index + 1) { return this.simplify(moduleContext, (expression['arguments'])[index]); @@ -258,14 +273,14 @@ export class StaticReflector { return null; } - private getPropertyMetadata(moduleContext: string, value: {[key: string]: any}): - {[key: string]: any} { + private getPropertyMetadata(moduleContext: string, + value: {[key: string]: any}): {[key: string]: any} { if (isPresent(value)) { let result = {}; StringMapWrapper.forEach(value, (value, name) => { let data = this.getMemberData(moduleContext, value); if (isPresent(data)) { - let propertyData = data.filter(d => d['kind'] == 'property') + let propertyData = data.filter(d => d['kind'] == "property") .map(d => d['directives']) .reduce((p, c) => (p).concat(c), []); if (propertyData.length != 0) { @@ -286,11 +301,12 @@ export class StaticReflector { for (let item of member) { result.push({ kind: item['__symbolic'], - directives: isPresent(item['decorators']) ? - (item['decorators']) - .map(decorator => this.convertKnownDecorator(moduleContext, decorator)) - .filter(d => isPresent(d)) : - null + directives: + isPresent(item['decorators']) ? + (item['decorators']) + .map(decorator => this.convertKnownDecorator(moduleContext, decorator)) + .filter(d => isPresent(d)) : + null }); } } @@ -307,7 +323,7 @@ export class StaticReflector { } if (isArray(expression)) { let result = []; - for (let item of (expression)) { + for (let item of(expression)) { result.push(simplify(item)); } return result; @@ -315,7 +331,7 @@ export class StaticReflector { if (isPresent(expression)) { if (isPresent(expression['__symbolic'])) { switch (expression['__symbolic']) { - case 'binop': + case "binop": let left = simplify(expression['left']); let right = simplify(expression['right']); switch (expression['operator']) { @@ -361,7 +377,7 @@ export class StaticReflector { return left % right; } return null; - case 'pre': + case "pre": let operand = simplify(expression['operand']); switch (expression['operator']) { case '+': @@ -374,17 +390,17 @@ export class StaticReflector { return ~operand; } return null; - case 'index': + case "index": let indexTarget = simplify(expression['expression']); let index = simplify(expression['index']); if (isPresent(indexTarget) && isPrimitive(index)) return indexTarget[index]; return null; - case 'select': + case "select": let selectTarget = simplify(expression['expression']); let member = simplify(expression['member']); if (isPresent(selectTarget) && isPrimitive(member)) return selectTarget[member]; return null; - case 'reference': + case "reference": let referenceModuleName = _this.normalizeModuleName(moduleContext, expression['module']); let referenceModule = _this.getModuleMetadata(referenceModuleName); @@ -394,7 +410,7 @@ export class StaticReflector { return _this.getStaticType(referenceModuleName, expression['name']); } return _this.simplify(referenceModuleName, referenceValue); - case 'call': + case "call": return null; } return null; @@ -414,7 +430,7 @@ export class StaticReflector { if (!isPresent(moduleMetadata)) { moduleMetadata = this.host.getMetadataFor(module); if (!isPresent(moduleMetadata)) { - moduleMetadata = {__symbolic: 'module', module: module, metadata: {}}; + moduleMetadata = {__symbolic: "module", module: module, metadata: {}}; } this.metadataCache.set(module, moduleMetadata); } @@ -425,7 +441,7 @@ export class StaticReflector { let moduleMetadata = this.getModuleMetadata(type.moduleId); let result = moduleMetadata['metadata'][type.name]; if (!isPresent(result)) { - result = {__symbolic: 'class'}; + result = {__symbolic: "class"}; } return result; } @@ -444,7 +460,7 @@ function isMetadataSymbolicCallExpression(expression: any): boolean { function isMetadataSymbolicReferenceExpression(expression: any): boolean { return !isPrimitive(expression) && !isArray(expression) && - expression['__symbolic'] == 'reference'; + expression['__symbolic'] == 'reference'; } function isClassMetadata(expression: any): boolean { diff --git a/modules/angular2/src/compiler/style_compiler.ts b/modules/angular2/src/compiler/style_compiler.ts index 376bbdd36a..565e33c0c6 100644 --- a/modules/angular2/src/compiler/style_compiler.ts +++ b/modules/angular2/src/compiler/style_compiler.ts @@ -7,7 +7,12 @@ import {PromiseWrapper} from 'angular2/src/facade/async'; import {ShadowCss} from 'angular2/src/compiler/shadow_css'; import {UrlResolver} from 'angular2/src/compiler/url_resolver'; import {extractStyleUrls} from './style_url_resolver'; -import {escapeSingleQuoteString, codeGenExportVariable, codeGenToString, MODULE_SUFFIX} from './util'; +import { + escapeSingleQuoteString, + codeGenExportVariable, + codeGenToString, + MODULE_SUFFIX +} from './util'; import {Injectable} from 'angular2/src/core/di'; const COMPONENT_VARIABLE = '%COMP%'; @@ -21,11 +26,11 @@ export class StyleCompiler { constructor(private _xhr: XHR, private _urlResolver: UrlResolver) {} - compileComponentRuntime(template: CompileTemplateMetadata): Promise> { + compileComponentRuntime(template: CompileTemplateMetadata): Promise> { var styles = template.styles; var styleAbsUrls = template.styleUrls; - return this._loadStyles( - styles, styleAbsUrls, template.encapsulation === ViewEncapsulation.Emulated); + return this._loadStyles(styles, styleAbsUrls, + template.encapsulation === ViewEncapsulation.Emulated); } compileComponentCodeGen(template: CompileTemplateMetadata): SourceExpression { @@ -39,31 +44,30 @@ export class StyleCompiler { this._styleModule( stylesheetUrl, false, this._styleCodeGen([styleWithImports.style], styleWithImports.styleUrls, false)), - this._styleModule( - stylesheetUrl, true, - this._styleCodeGen([styleWithImports.style], styleWithImports.styleUrls, true)) + this._styleModule(stylesheetUrl, true, this._styleCodeGen([styleWithImports.style], + styleWithImports.styleUrls, true)) ]; } clearCache() { this._styleCache.clear(); } - private _loadStyles(plainStyles: string[], absUrls: string[], encapsulate: boolean): - Promise> { + private _loadStyles(plainStyles: string[], absUrls: string[], + encapsulate: boolean): Promise> { var promises: Promise[] = absUrls.map((absUrl: string): Promise => { var cacheKey = `${absUrl}${encapsulate ? '.shim' : ''}`; var result: Promise = this._styleCache.get(cacheKey); if (isBlank(result)) { result = this._xhr.get(absUrl).then((style) => { var styleWithImports = extractStyleUrls(this._urlResolver, absUrl, style); - return this._loadStyles( - [styleWithImports.style], styleWithImports.styleUrls, encapsulate); + return this._loadStyles([styleWithImports.style], styleWithImports.styleUrls, + encapsulate); }); this._styleCache.set(cacheKey, result); } return result; }); return PromiseWrapper.all(promises).then((nestedStyles: string[][]) => { - var result: Array = + var result: Array = plainStyles.map(plainStyle => this._shimIfNeeded(plainStyle, encapsulate)); nestedStyles.forEach(styles => result.push(styles)); return result; @@ -83,8 +87,8 @@ export class StyleCompiler { return new SourceExpression([], expressionSource); } - private _styleModule(stylesheetUrl: string, shim: boolean, expression: SourceExpression): - SourceModule { + private _styleModule(stylesheetUrl: string, shim: boolean, + expression: SourceExpression): SourceModule { var moduleSource = ` ${expression.declarations.join('\n')} ${codeGenExportVariable('STYLES')}${expression.expression}; diff --git a/modules/angular2/src/compiler/style_url_resolver.ts b/modules/angular2/src/compiler/style_url_resolver.ts index 2603456a48..bdd229e254 100644 --- a/modules/angular2/src/compiler/style_url_resolver.ts +++ b/modules/angular2/src/compiler/style_url_resolver.ts @@ -18,8 +18,8 @@ export function isStyleUrlResolvable(url: string): boolean { * Rewrites stylesheets by resolving and removing the @import urls that * are either relative or don't have a `package:` scheme */ -export function extractStyleUrls( - resolver: UrlResolver, baseUrl: string, cssText: string): StyleWithImports { +export function extractStyleUrls(resolver: UrlResolver, baseUrl: string, + cssText: string): StyleWithImports { var foundUrls = []; var modifiedCssText = StringWrapper.replaceAllMapped(cssText, _cssImportRe, (m) => { var url = isPresent(m[1]) ? m[1] : m[2]; diff --git a/modules/angular2/src/compiler/template_ast.ts b/modules/angular2/src/compiler/template_ast.ts index 53f876d65c..1b79d32be5 100644 --- a/modules/angular2/src/compiler/template_ast.ts +++ b/modules/angular2/src/compiler/template_ast.ts @@ -22,8 +22,8 @@ export interface TemplateAst { * A segment of text within the template. */ export class TextAst implements TemplateAst { - constructor( - public value: string, public ngContentIndex: number, public sourceSpan: ParseSourceSpan) {} + constructor(public value: string, public ngContentIndex: number, + public sourceSpan: ParseSourceSpan) {} visit(visitor: TemplateAstVisitor, context: any): any { return visitor.visitText(this, context); } } @@ -31,8 +31,8 @@ export class TextAst implements TemplateAst { * A bound expression within the text of a template. */ export class BoundTextAst implements TemplateAst { - constructor( - public value: AST, public ngContentIndex: number, public sourceSpan: ParseSourceSpan) {} + constructor(public value: AST, public ngContentIndex: number, + public sourceSpan: ParseSourceSpan) {} visit(visitor: TemplateAstVisitor, context: any): any { return visitor.visitBoundText(this, context); } @@ -50,9 +50,8 @@ export class AttrAst implements TemplateAst { * A binding for an element property (e.g. `[property]="expression"`). */ export class BoundElementPropertyAst implements TemplateAst { - constructor( - public name: string, public type: PropertyBindingType, public value: AST, public unit: string, - public sourceSpan: ParseSourceSpan) {} + constructor(public name: string, public type: PropertyBindingType, public value: AST, + public unit: string, public sourceSpan: ParseSourceSpan) {} visit(visitor: TemplateAstVisitor, context: any): any { return visitor.visitElementProperty(this, context); } @@ -62,9 +61,8 @@ export class BoundElementPropertyAst implements TemplateAst { * A binding for an element event (e.g. `(event)="handler()"`). */ export class BoundEventAst implements TemplateAst { - constructor( - public name: string, public target: string, public handler: AST, - public sourceSpan: ParseSourceSpan) {} + constructor(public name: string, public target: string, public handler: AST, + public sourceSpan: ParseSourceSpan) {} visit(visitor: TemplateAstVisitor, context: any): any { return visitor.visitEvent(this, context); } @@ -91,11 +89,11 @@ export class VariableAst implements TemplateAst { * An element declaration in a template. */ export class ElementAst implements TemplateAst { - constructor( - public name: string, public attrs: AttrAst[], public inputs: BoundElementPropertyAst[], - public outputs: BoundEventAst[], public exportAsVars: VariableAst[], - public directives: DirectiveAst[], public children: TemplateAst[], - public ngContentIndex: number, public sourceSpan: ParseSourceSpan) {} + constructor(public name: string, public attrs: AttrAst[], + public inputs: BoundElementPropertyAst[], public outputs: BoundEventAst[], + public exportAsVars: VariableAst[], public directives: DirectiveAst[], + public children: TemplateAst[], public ngContentIndex: number, + public sourceSpan: ParseSourceSpan) {} visit(visitor: TemplateAstVisitor, context: any): any { return visitor.visitElement(this, context); } @@ -104,9 +102,8 @@ export class ElementAst implements TemplateAst { * Whether the element has any active bindings (inputs, outputs, vars, or directives). */ isBound(): boolean { - return ( - this.inputs.length > 0 || this.outputs.length > 0 || this.exportAsVars.length > 0 || - this.directives.length > 0); + return (this.inputs.length > 0 || this.outputs.length > 0 || this.exportAsVars.length > 0 || + this.directives.length > 0); } /** @@ -114,8 +111,8 @@ export class ElementAst implements TemplateAst { */ getComponent(): CompileDirectiveMetadata { return this.directives.length > 0 && this.directives[0].directive.isComponent ? - this.directives[0].directive : - null; + this.directives[0].directive : + null; } } @@ -123,10 +120,9 @@ export class ElementAst implements TemplateAst { * A `