From fa517e01e7308b65d3f18a03ff4f028f9c388611 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Farkas=20J=C3=B3zsef?= Date: Tue, 11 Oct 2016 17:44:03 +0200 Subject: [PATCH] Version on 11th October 2016 --- app.js | 149 - assets/compiled_sprite.svg | 2 +- css/app.css | 195 - css/macro.css | 76 - css/style.css | 127 - images/icons/kbd__mouse--scroll-right.svg | 126 + index.html | 2 - keymapLegacy.html | 79 - macro.html | 104 - macro.js | 70 - macroLegacy.html | 97 - popup.html | 299 - popup__iframe.html | 294 - script.js | 974 - uhk.js | 45512 +++++++++++--------- uhk.js.map | 2 +- vendor/handlebars/handlebars.min.js | 29 - vendor/jquery/jquery.min.js | 8 +- vendor/jquery/jquery.min.map | 2 +- vendor/sortablejs/Sortable.min.js | 2 - 20 files changed, 24430 insertions(+), 23719 deletions(-) delete mode 100644 app.js delete mode 100644 css/app.css delete mode 100644 css/macro.css delete mode 100644 css/style.css create mode 100644 images/icons/kbd__mouse--scroll-right.svg delete mode 100644 keymapLegacy.html delete mode 100644 macro.html delete mode 100644 macro.js delete mode 100644 macroLegacy.html delete mode 100644 popup.html delete mode 100644 popup__iframe.html delete mode 100644 script.js delete mode 100644 vendor/handlebars/handlebars.min.js delete mode 100644 vendor/sortablejs/Sortable.min.js diff --git a/app.js b/app.js deleted file mode 100644 index f1737e9b..00000000 --- a/app.js +++ /dev/null @@ -1,149 +0,0 @@ -$(function() { - _init('.keymap--edit'); - - $('.notification').on('click', '.notification__dismiss', function(e) { - $('.notification').hide(); - }).on('click', '.notification__action--undo', function(e) { - $('.notification').hide(); - $('.sidebar__level-2--item:hidden').show().click(); - });; - - $(function () { - $('[data-toggle="tooltip"]').tooltip() - }); - - // ======================= - // Menu-item functionality LEGACY TODO remove - // ======================= - $('.pane-title__name, .pane-title__abbrev').on('mouseover', function() { - $(this).addClass('active'); - }).on('mouseout', function() { - if (!$(this).is(':focus')) { - $(this).removeClass('active'); - } - }).on('focusout', function() { - $(this).removeClass('active'); - }); - - $('.keymap__is-default').on('click', function() { - $(this).toggleClass('fa-star-o'); - }); - - // ======================== - // Keymap related settings. - // ======================== - $('button.uhk__layer-switcher').on('click', function(e) { - var button = $(this), - layerOrder = ['base', 'mod', 'fn', 'mouse'], - currentButton = $('button.uhk__layer-switcher.current'), - slideLayer = button.data('layer'), - slideNumber = layerOrder.indexOf(slideLayer), - currentSlideLayer = currentButton.data('layer'), - currentSlideNumber = layerOrder.indexOf(currentSlideLayer), - slide = $('.uhk__layer-wrapper--' + slideLayer), - currentSlide = $('.uhk__layer-wrapper.current'), - slideWidth = currentSlide.width() + 'px'; - - if (slideNumber < currentSlideNumber) { - // From left to right - currentSlide.css('left', 0); - slide.css('left', '-' + slideWidth); - - currentSlide.animate({left: slideWidth}, function() { - $(this).removeClass('current'); - }); - slide.animate({left: 0}, function() { - $(this).addClass('current'); - }); - - currentButton.removeClass('current btn-primary').addClass('btn-default'); - button.addClass('current btn-primary').removeClass('btn-default').blur(); - } else if (slideNumber != currentSlideNumber) { - // From right to left - currentSlide.css({left: 0}); - slide.css({left: slideWidth}); - - currentSlide.animate({left: '-' + slideWidth}, function() { - $(this).removeClass('current'); - }); - slide.animate({left: 0}, function() { - $(this).addClass('current'); - }); - - currentButton.removeClass('current btn-primary').addClass('btn-default'); - button.addClass('current btn-primary').addClass('btn-default').blur(); - } - }); - - $('.keymap__remove').on('click', function(e) { - // Mimic the removal of a keymap with undo option. - $('.sidebar__level-2--item:hidden').remove(); - $('.sidebar__level-2--item.active').hide(); - - // Show the factory keymap after removal of a keymap. - $('.sidebar__level-2--item:first').click(); - $('.notification').show(); - }); - - // Based on: http://stackoverflow.com/a/24933495 - $('img.uhk').each(function(){ - var $img = $(this); - var imgID = $img.attr('id'); - var imgClass = $img.attr('class'); - var imgURL = $img.attr('src'); - var imgSelector = '.' + imgClass.replace(' ', '.') - - $.get(imgURL, function(data) { - // Get the SVG tag, ignore the rest - var $svg = $(data).find('svg'); - - // Add replaced image's ID to the new SVG - if(typeof imgID !== 'undefined') { - $svg = $svg.attr('id', imgID); - } - // Add replaced image's classes to the new SVG - if(typeof imgClass !== 'undefined') { - $svg = $svg.attr('class', imgClass+' replaced-svg'); - } - - // Remove any invalid XML tags as per http://validator.w3.org - $svg = $svg.removeAttr('xmlns:a'); - - // Check if the viewport is set, else we gonna set it if we can. - if(!$svg.attr('viewBox') && $svg.attr('height') && $svg.attr('width')) { - $svg.attr('viewBox', '0 0 ' + $svg.attr('height') + ' ' + $svg.attr('width')) - } - - // Replace image with new SVG - $img.replaceWith($svg); - $('.keyboard-slider').height($svg.height()); - - // Quick fix as jQuery 2.1.4 addClass() method is not working on SVG elements. - var finalClasses = $svg.attr('class'); - - $('#left-parts rect, #right-parts rect', imgSelector).on('click', function() { - var _popup = $('.key-editor__popup'), - rectB7 = $('rect#b7', $svg); - if (_popup.is(':hidden')) { - $svg.attr('class', finalClasses + ' faded'); - _popup.show(); - rectB7.attr('class', 'active'); - } else { - $svg.attr('class', finalClasses); - _popup.hide(); - rectB7.attr('class', ''); - } - }); - - }, 'xml'); - }); -}); - -function _init(view) { - switch (view) { - case '.keymap--edit': - var h = $('.uhk--base-layer').height(); - $('.keyboard-slider').height(h + 'px'); - break; - } -} diff --git a/assets/compiled_sprite.svg b/assets/compiled_sprite.svg index 90a59839..625da678 100644 --- a/assets/compiled_sprite.svg +++ b/assets/compiled_sprite.svg @@ -1 +1 @@ - \ No newline at end of file + \ No newline at end of file diff --git a/css/app.css b/css/app.css deleted file mode 100644 index 0d273ea9..00000000 --- a/css/app.css +++ /dev/null @@ -1,195 +0,0 @@ -.main-content { - margin-left: 250px; } - -.sidebar-menu { - background-color: #f5f5f5; - border-right: 1px solid #ccc; - position: fixed; - overflow-y: auto; - width: 250px; - height: 100%; } - -ul { - padding: 0; - margin: 0; } - ul li { - list-style: none; - padding: 0; } - -.sidebar__level-1 { - padding: 0.5rem 1rem; - font-size: 2rem; - line-height: 3rem; } - .sidebar__level-1--item { - margin-top: 0; } - .sidebar__level-1--item:nth-child(1) { - margin: 0; } - .sidebar__level-1 .fa-chevron-up, - .sidebar__level-1 .fa-chevron-down { - margin-right: 1rem; - font-size: 1.5rem; - position: relative; - top: 0.5rem; - display: none; } - .sidebar__level-1:hover .fa-chevron-up, - .sidebar__level-1:hover .fa-chevron-down { - display: inline-block; } - -.sidebar__level-1, .sidebar__level-2 { - padding-left: 15px; } - -.sidebar__level-2 { - margin-left: 15px; } - .sidebar__level-2--item { - padding: 0 20px 0 0; } - .sidebar__level-2--item.active { - background-color: #555; - color: #fff; } - .sidebar__level-2--item.active .fa-star { - color: #fff; } - .sidebar__level-2--item.active:hover { - background-color: #555; } - .sidebar__level-2--item .fa.pull-right { - position: relative; - top: 2px; } - .sidebar__level-2--item .fa-star { - color: #666; } - -.sidebar__level-1:hover, .sidebar__level-2--item:hover { - cursor: pointer; - background-color: rgba(0, 0, 0, 0.05); } - -.menu--bottom { - position: absolute; - bottom: 0; - left: 0; - width: 100%; } - .menu--bottom .sidebar__level-1 { - background-color: transparent; - padding: 1rem; } - -.pane-title { - margin-bottom: 1em; } - .pane-title__name[contenteditable=true], .pane-title__abbrev[contenteditable=true] { - border: none; - border-bottom: 2px dotted #999; - padding: 0 0.5rem; - margin: 0 0.25rem; } - .pane-title__name[contenteditable=true].active, .pane-title__abbrev[contenteditable=true].active { - box-shadow: 0 0 0 1px #ccc, 0 0 5px 0 #ccc; - border-color: transparent; } - -.keymap__is-default.fa-star { - color: #333; } - -.keymap__is-default.fa-star-o { - color: #333; } - -.keymap__is-default:hover { - color: #555; - cursor: pointer; } - -.keymap__remove { - font-size: 0.75em; - top: 0.3em; } - .keymap__remove:hover { - cursor: pointer; - color: #900; } - -.notification { - padding: 1rem 1.5rem; - box-shadow: 0 0 0 1px #000; - border-radius: 0.5rem; - position: absolute; - top: 2rem; - right: 2rem; - z-index: 2000; - background-color: #333; - color: #eee; } - .notification__action { - margin-left: 1rem; - margin-right: 1rem; - color: #5bc0de; - text-transform: uppercase; - font-weight: bold; } - .notification__action:focus, .notification__action:active, .notification__action:hover { - text-decoration: none; - color: #5bc0de; } - .notification__dismiss { - position: relative; - bottom: 1px; - color: #ccc; } - .notification__dismiss:hover { - cursor: pointer; - color: #fff; } - -.uhk__layer-switcher--wrapper { - position: relative; } - .uhk__layer-switcher--wrapper:before { - content: attr(data-title); - display: inline-block; - position: absolute; - bottom: -0.3em; - right: 100%; - font-size: 2.4rem; - padding-right: 0.25em; - margin: 0; } - -.keyboard-slider { - position: relative; - overflow: hidden; - width: 100%; - height: auto; } - .keyboard-slider .uhk__layer-wrapper { - width: 100%; - height: auto; - text-align: center; - position: absolute; - left: 100%; } - .keyboard-slider .uhk__layer-wrapper.current { - left: 0; } - .keyboard-slider .uhk__layer-wrapper .uhk { - max-width: 100%; - width: 98%; } - -.key-editor__popup { - border: none; - width: 0; - height: 0; - position: absolute; - top: 215px; - left: 50%; - margin-left: -310px; } - -svg.uhk rect.active { - fill: #337ab7; } - -/* GitHub ribbon */ -.github-fork-ribbon { - background-color: #a00; - overflow: hidden; - white-space: nowrap; - position: fixed; - right: -50px; - bottom: 40px; - z-index: 2000; - /* stylelint-disable indentation */ - -webkit-transform: rotate(-45deg); - -moz-transform: rotate(-45deg); - -ms-transform: rotate(-45deg); - -o-transform: rotate(-45deg); - transform: rotate(-45deg); - -webkit-box-shadow: 0 0 10px #888; - -moz-box-shadow: 0 0 10px #888; - box-shadow: 0 0 10px #888; - /* stylelint-enable indentation */ } - .github-fork-ribbon a { - border: 1px solid #faa; - color: #fff; - display: block; - font: bold 81.25% 'Helvetica Neue', Helvetica, Arial, sans-serif; - margin: 1px 0; - padding: 10px 50px; - text-align: center; - text-decoration: none; - text-shadow: 0 0 5px #444; } diff --git a/css/macro.css b/css/macro.css deleted file mode 100644 index f35d89d6..00000000 --- a/css/macro.css +++ /dev/null @@ -1,76 +0,0 @@ -.main-wrapper { - width: 500px; } - -h1 { - margin-bottom: 3rem; } - -.action--item { - padding-left: 8px; } - -.action--item.active, -.action--item.active:hover { - background-color: white; - font-weight: bold; - color: black; - border-color: black; - z-index: 10; } - -.macro-settings { - border: 1px solid black; - border-top-color: #999; - z-index: 100; } - -.macro-settings .helper { - position: absolute; - display: block; - height: 13px; - background: #fff; - width: 100%; - left: 0; - top: -14px; } - -.action--item.active.callout, -.macro-settings.callout { - box-shadow: 0 0 20px 0 rgba(0, 0, 0, 0.5); } - -.list-group-item .move-handle:hover { - cursor: move; } - -.action--edit { - float: right; } - -.action--edit:hover { - color: #337ab7; - cursor: pointer; } - -.action--trash { - float: right; - margin-right: 1rem; } - -.action--trash:hover { - color: #d9534f; - cursor: pointer; } - -.action--edit__form { - background-color: whtie; - margin-left: -0.5rem; - margin-right: -15px; - margin-top: 15px; - padding-top: 15px; - border-top: 1px solid #ddd; } - -.flex-button-wrapper { - display: flex; - flex-direction: row-reverse; } - -.flex-button { - align-self: flex-end; } - -.add-new__action-item:hover { - cursor: pointer; } - -.add-new__action-item--link, -.add-new__action-item--link:active, -.add-new__action-item--link:hover { - text-decoration: none; - color: #337ab7; } diff --git a/css/style.css b/css/style.css deleted file mode 100644 index e71f5f3e..00000000 --- a/css/style.css +++ /dev/null @@ -1,127 +0,0 @@ -.popover { - padding: 0; } - .popover.bottom > .arrow { - border-bottom-color: #000; } - .popover.bottom > .arrow:after { - border-bottom-color: #f7f7f7; } - -.popover-content { - padding: 10px 24px; } - -.popover-title.menu-tabs { - padding: 0.5rem 0.5rem 0; - display: block; } - .popover-title.menu-tabs .nav-tabs { - position: relative; - top: 1px; } - -.popover-title.menu-button-group { - display: none; } - -.popover-actions { - padding: 8px 14px; - margin: 0; - font-size: 14px; - background-color: #f7f7f7; - border-top: 1px solid #ebebeb; - border-radius: 0 0 5px 5px; - text-align: right; } - -.select2-container { - z-index: 100; } - -.nav-tabs > li > a { - cursor: pointer; } - -.scancode--searchterm { - color: lightgray; - float: right; } - -.layout-abbreviation { - font-weight: bold; - color: #fff; - background: #333; - padding: 4px 8px; - font-family: monospace; - margin-right: 0.5em; } - -.layout-preview img { - max-width: 100%; - margin-top: 10px; } - -.key-editor--none__description p { - padding: 2rem 0; - margin: 0; - text-align: center; } - -.select2-item { - position: relative; - font-size: 1.5rem; } - .select2-item.keymap-name--wrapper { - padding-left: 50px; } - .select2-item .layout-segment-code { - height: 2rem; - position: absolute; - left: 0; - top: 50%; - margin-top: -1rem; } - -.preview-wrapper img { - max-width: 100%; } - -.global-key-setup.disabled { - opacity: 0; } - .global-key-setup.disabled .setting-label { - color: #999; } - -.setting-label.disabled { - color: #999; } - -.global-key-setup--wrapper { - position: relative; } - .global-key-setup--wrapper .disabled-state--text { - position: absolute; - top: 50%; - margin-top: -4rem; } - -.mouse.popover-content { - padding: 10px; - display: flex; - align-items: center; } - -.mouse__action--type .nav { - border-right: 1px solid #ccc; } - .mouse__action--type .nav li a { - border-top-right-radius: 0; - border-bottom-right-radius: 0; } - .mouse__action--type .nav li a.selected { - font-style: italic; } - .mouse__action--type .nav li.active a.selected { - font-style: normal; } - .mouse__action--type .nav li.active a:after { - content: ''; - display: block; - position: absolute; - width: 0; - height: 0; - top: 0; - right: -4rem; - border-color: transparent transparent transparent #337ab7; - border-style: solid; - border-width: 2rem; } - -.mouse__action--config .btn-placeholder { - visibility: hidden; } - -.help-text--mouse-speed { - margin-bottom: 2rem; - font-size: 0.9em; - color: #666; } - .help-text--mouse-speed p { - margin: 0; } - -.select2-results { - text-align: center; } - -.select2-container--default .select2-selection--single .select2-selection__rendered { - line-height: 26px; } diff --git a/images/icons/kbd__mouse--scroll-right.svg b/images/icons/kbd__mouse--scroll-right.svg new file mode 100644 index 00000000..5a019e8d --- /dev/null +++ b/images/icons/kbd__mouse--scroll-right.svg @@ -0,0 +1,126 @@ + + + + + + + + + + image/svg+xml + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/index.html b/index.html index af98caa0..e1ca0cca 100644 --- a/index.html +++ b/index.html @@ -26,9 +26,7 @@ j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src= - - diff --git a/keymapLegacy.html b/keymapLegacy.html deleted file mode 100644 index f54ef5a9..00000000 --- a/keymapLegacy.html +++ /dev/null @@ -1,79 +0,0 @@ - - - - - Ultimate Hacking Keyboard Configurator - - - - - - - - - - - - - -
-
-

- - QWERTY keymap (QTY) - - -

-
-
-
-
-
- - - - - - -
-
-
-
- -
-
- -
-
- -
-
- -
-
- -
-
-
- - - - - - - diff --git a/macro.html b/macro.html deleted file mode 100644 index 38a90b4a..00000000 --- a/macro.html +++ /dev/null @@ -1,104 +0,0 @@ - - - - - - - - - Ultimate Hacking Keyboard - Agent mockups - - - - - - - - -

Ultimate Hacking Keyboard — Agent mockups

- - -
-
-
-
-
- - Move pointer by 100px leftward - - -
- -
- - Press letter A - - -
-
- - Press Alt+Tab - - -
-
- - Delay of 235ms - - -
-
- - Press button 1 - - -
-
- - Scroll by 150px downward - - -
- -
-
-

Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.

-
-
- - -
-
-
-
-
-
-
- - - - - - - - - diff --git a/macro.js b/macro.js deleted file mode 100644 index 75caae00..00000000 --- a/macro.js +++ /dev/null @@ -1,70 +0,0 @@ -$(function() { - var macroSettingsHtml = $('.macro-settings'); - var toggleSpeed = 'fast'; - var notActiveOpacity = '0.75'; - - var newMacroHtml = $('.new-macro-settings'); - - // List with handle - Sortable.create(document.getElementById('listWithHandle'), { - handle: '.move-handle', - filter: '.no-reorder', - draggable: '.list-group-item', - animation: 150 - }); - - - $('.action--edit').on('click', function(e) { - var $this = $(this); - var action = $this.parent('.list-group-item'); - $('.action--item.active').removeClass('callout'); - macroSettingsHtml.removeClass('callout'); - if (macroSettingsHtml.is(':visible') && !action.hasClass('active')) { - macroSettingsHtml.slideToggle(toggleSpeed, function() { - $('.action--item:not(.active)').css('opacity', '1'); - $('.action--item.active').removeClass('active'); - action.toggleClass('active'); - $('.action--item:not(.active)').css('opacity', notActiveOpacity); - - $(this).detach().insertAfter(action).slideToggle(toggleSpeed, function () { - action.addClass('callout'); - macroSettingsHtml.addClass('callout'); - }); - }); - } - else { - if (!macroSettingsHtml.is(':visible')) { - action.addClass('active'); - } - macroSettingsHtml.detach().insertAfter(action).slideToggle(toggleSpeed, function() { - if (macroSettingsHtml.is(':visible')) { - $('.action--item:not(.active)').css('opacity', notActiveOpacity); - action.addClass('callout'); - macroSettingsHtml.addClass('callout'); - } - else { - $('.action--item:not(.active)').css('opacity', '1'); - action.removeClass('active'); - } - }); - } - }); - - $('.flex-button', '.macro-settings').on('click', function() { - $('.action--item.active .action--edit').click(); - }); - - $('.flex-button', '.new-macro-settings').on('click', function() { - newMacroHtml.slideToggle(toggleSpeed, function() { - newMacroHtml.hide().detach(); - }); - }); - - $('.add-new__action-item').on('click', function() { - newMacroHtml.insertAfter($(this)); - newMacroHtml.slideToggle(toggleSpeed); - }); - - // Detach and remove this item only after all event listhere has been registered on it. - newMacroHtml.hide().detach(); -}); diff --git a/macroLegacy.html b/macroLegacy.html deleted file mode 100644 index ed66a537..00000000 --- a/macroLegacy.html +++ /dev/null @@ -1,97 +0,0 @@ - - - - - Ultimate Hacking Keyboard Configurator - - - - - - - - -
-
-

- - Macro1 -

-
-
-
-
- - Move pointer by 100px leftward - - -
- -
- - Press letter A - - -
-
- - Press Alt+Tab - - -
-
- - Delay of 235ms - - -
-
- - Press button 1 - - -
-
- - Scroll by 150px downward - - -
- -
-
-

Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut - labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo - dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor - sit amet.

-
-
- - -
-
-
-
-
-
- - - - - - - \ No newline at end of file diff --git a/popup.html b/popup.html deleted file mode 100644 index 293c36e4..00000000 --- a/popup.html +++ /dev/null @@ -1,299 +0,0 @@ - - - - - - - - - Ultimate Hacking Keyboard - Agent mockups - - - - - - - - -

Ultimate Hacking Keyboard – Agent mockups

- - - -
-
-
-
-
-
-
-
-
-
-
-
-
-
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/popup__iframe.html b/popup__iframe.html deleted file mode 100644 index 69e221ee..00000000 --- a/popup__iframe.html +++ /dev/null @@ -1,294 +0,0 @@ - - - - - - - - - Ultimate Hacking Keyboard - Agent mockups - - - - -
-
-
-
-
-
-
-
-
-
-
-
-
-
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/script.js b/script.js deleted file mode 100644 index 3b248be3..00000000 --- a/script.js +++ /dev/null @@ -1,974 +0,0 @@ -$(function() { - // General configuration for popover contents. - var contentContext = { - keypress: { - layers: [ - { - name: 'None', - class: 'layer-key layer-key--disabled', - primary: 'btn-primary' - }, - { - name: 'Mod', - class: 'layer-key layer-key--mod', - primary: '' - }, - { - name: 'Fn', - class: 'layer-key layer-key--fn', - primary: '' - }, - { - name: 'Mouse', - class: 'layer-key layer-key--mouse', - primary: '' - } - ], - modifiers: { - left: [ - { - name: 'LShift', - primary: 'btn-primary' - }, - { - name: 'LCtrl', - primary: '' - }, - { - name: 'LSuper', - primary: '' - }, - { - name: 'LAlt', - primary: 'btn-primary' - } - ], - right: [ - { - name: 'RShift', - primary: '' - }, - { - name: 'RCtrl', - primary: '' - }, - { - name: 'RSuper', - primary: '' - }, - { - name: 'RAlt', - primary: '' - } - ] - }, - scancode: [ - { - groupName: 'Alphabet', - groupValues: [ - { - scancode: '4', - searchTerm: '', - label: 'A' - }, - { - scancode: '5', - searchTerm: '', - label: 'B' - }, - { - scancode: '6', - searchTerm: '', - label: 'C' - }, - { - scancode: '7', - searchTerm: '', - label: 'D' - }, - { - scancode: '8', - searchTerm: '', - label: 'E' - }, - { - scancode: '9', - searchTerm: '', - label: 'F' - }, - { - scancode: '10', - searchTerm: '', - label: 'G' - }, - { - scancode: '11', - searchTerm: '', - label: 'H' - }, - { - scancode: '12', - searchTerm: '', - label: 'I' - }, - { - scancode: '13', - searchTerm: '', - label: 'J' - }, - { - scancode: '14', - searchTerm: '', - label: 'K' - }, - { - scancode: '15', - searchTerm: '', - label: 'L' - }, - { - scancode: '16', - searchTerm: '', - label: 'M' - }, - { - scancode: '17', - searchTerm: '', - label: 'N' - }, - { - scancode: '18', - searchTerm: '', - label: 'O' - }, - { - scancode: '19', - searchTerm: '', - label: 'P' - }, - { - scancode: '20', - searchTerm: '', - label: 'Q' - }, - { - scancode: '21', - searchTerm: '', - label: 'R' - }, - { - scancode: '22', - searchTerm: '', - label: 'S' - }, - { - scancode: '23', - searchTerm: '', - label: 'T' - }, - { - scancode: '24', - searchTerm: '', - label: 'U' - }, - { - scancode: '25', - searchTerm: '', - label: 'V' - }, - { - scancode: '26', - searchTerm: '', - label: 'W' - }, - { - scancode: '27', - searchTerm: '', - label: 'X' - }, - { - scancode: '28', - searchTerm: '', - label: 'Y' - }, - { - scancode: '29', - searchTerm: '', - label: 'Z' - } - ] - }, - { - groupName: 'Number Row', - groupValues: [ - { - scancode: '30', - searchTerm: '', - label: '1 !' - }, - { - scancode: '31', - searchTerm: '', - label: '2 @' - }, - { - scancode: '32', - searchTerm: '', - label: '3 #' - }, - { - scancode: '33', - searchTerm: '', - label: '4 $' - }, - { - scancode: '34', - searchTerm: '', - label: '5 %' - }, - { - scancode: '35', - searchTerm: '', - label: '6 ^' - }, - { - scancode: '36', - searchTerm: '', - label: '7 &' - }, - { - scancode: '37', - searchTerm: '', - label: '8 *' - }, - { - scancode: '38', - searchTerm: '', - label: '9 (' - }, - { - scancode: '39', - searchTerm: '', - label: '0 )' - } - ] - }, - { - groupName: 'Whitespace', - groupValues: [ - { - scancode: '40', - searchTerm: 'Enter', - label: 'Return' - }, - { - scancode: '41', - searchTerm: '', - label: 'Escape' - }, - { - scancode: '42', - searchTerm: '', - label: 'Backspace' - }, - { - scancode: '43', - searchTerm: '', - label: 'Tab' - }, - { - scancode: '44', - searchTerm: '', - label: 'Spacebar' - } - ] - }, - { - groupName: 'Punctuation', - groupValues: [ - { - scancode: '45', - searchTerm: '', - label: '- _' - }, - { - scancode: '46', - searchTerm: '', - label: '= +' - }, - { - scancode: '47', - searchTerm: '', - label: '[ {' - }, - { - scancode: '48', - searchTerm: '', - label: '] }' - }, - { - scancode: '49', - searchTerm: '', - label: '\ |' - }, - { - scancode: '51', - searchTerm: '', - label: '; :' - }, - { - scancode: '52', - searchTerm: '', - label: '\' "' - }, - { - scancode: '53', - searchTerm: '', - label: '` ~' - }, - { - scancode: '54', - searchTerm: '', - label: ', <' - }, - { - scancode: '55', - searchTerm: '', - label: '. >' - }, - { - scancode: '56', - searchTerm: '', - label: '/ ?' - } - ] - }, - { - groupName: 'Function keys', - groupValues: [ - { - scancode: '58', - searchTerm: '', - label: 'F1' - }, - { - scancode: '59', - searchTerm: '', - label: 'F2' - }, - { - scancode: '60', - searchTerm: '', - label: 'F3' - }, - { - scancode: '61', - searchTerm: '', - label: 'F4' - }, - { - scancode: '62', - searchTerm: '', - label: 'F5' - }, - { - scancode: '63', - searchTerm: '', - label: 'F6' - }, - { - scancode: '64', - searchTerm: '', - label: 'F7' - }, - { - scancode: '65', - searchTerm: '', - label: 'F8' - }, - { - scancode: '66', - searchTerm: '', - label: 'F9' - }, - { - scancode: '67', - searchTerm: '', - label: 'F10' - }, - { - scancode: '68', - searchTerm: '', - label: 'F11' - }, - { - scancode: '69', - searchTerm: '', - label: 'F12' - } - ] - }, - { - groupName: 'Navigation', - groupValues: [ - { - scancode: '73', - searchTerm: '', - label: 'Insert' - }, - { - scancode: '74', - searchTerm: '', - label: 'Home' - }, - { - scancode: '75', - searchTerm: 'PgUp pageup', - label: 'Page Up' - }, - { - scancode: '76', - searchTerm: 'Delete Forward', - label: 'Delete' - }, - { - scancode: '77', - searchTerm: '', - label: 'End' - }, - { - scancode: '78', - searchTerm: 'PgDn pagedown', - label: 'Page Down' - }, - { - scancode: '79', - searchTerm: 'ArrowRight', - label: 'Right Arrow' - }, - { - scancode: '80', - searchTerm: 'ArrowLeft', - label: 'Left Arrow' - }, - { - scancode: '81', - searchTerm: 'ArrowDown', - label: 'Down Arrow' - }, - { - scancode: '82', - searchTerm: 'ArrowUp', - label: 'Up Arrow' - } - ] - }, - { - groupName: 'Number Pad', - groupValues: [ - { - scancode: '83', - searchTerm: '', - label: 'NumLock' - }, - { - scancode: '84', - searchTerm: 'slash', - label: '/' - }, - { - scancode: '85', - searchTerm: 'asterisk', - label: '*' - }, - { - scancode: '86', - searchTerm: 'minus', - label: '-' - }, - { - scancode: '87', - searchTerm: 'plus', - label: '+' - }, - { - scancode: '88', - searchTerm: '', - label: 'Enter' - }, - { - scancode: '89', - searchTerm: 'one', - label: '1' - }, - { - scancode: '90', - searchTerm: 'two', - label: '2' - }, - { - scancode: '91', - searchTerm: 'three', - label: '3' - }, - { - scancode: '92', - searchTerm: 'four', - label: '4' - }, - { - scancode: '93', - searchTerm: 'five', - label: '5' - }, - { - scancode: '94', - searchTerm: 'six', - label: '6' - }, - { - scancode: '95', - searchTerm: 'seven', - label: '7' - }, - { - scancode: '96', - searchTerm: 'eight', - label: '8' - }, - { - scancode: '97', - searchTerm: 'nine', - label: '9' - }, - { - scancode: '98', - searchTerm: 'zero', - label: '0' - }, - { - scancode: '99', - searchTerm: 'Period', - label: ',' - }, - { - scancode: '176', - searchTerm: 'Double zero', - label: '00' - }, - { - scancode: '177', - searchTerm: 'Triple zero', - label: '000' - } - ] - }, - { - groupName: 'Misc', - groupValues: [ - { - scancode: '70', - searchTerm: '', - label: 'Print Screen' - }, - { - scancode: '57', - searchTerm: '', - label: 'Caps Lock' - }, - { - scancode: '71', - searchTerm: '', - label: 'Scroll Lock' - }, - { - scancode: '72', - searchTerm: '', - label: 'Pause' - } - ] - }, - { - groupName: 'Media Keys', - groupValues: [ - { - scancode: '127', - searchTerm: '', - label: 'Mute' - }, - { - scancode: '128', - searchTerm: '', - label: 'Volume Up' - }, - { - scancode: '129', - searchTerm: '', - label: 'Volume Down' - }, - { - scancode: '', - searchTerm: '', - label: 'Next Track' - }, - { - scancode: '', - searchTerm: '', - label: 'Previous Track' - }, - { - scancode: '', - searchTerm: '', - label: 'Stop' - }, - { - scancode: '', - searchTerm: '', - label: 'Play/Pause' - }, - { - scancode: '', - searchTerm: '', - label: 'Eject' // Adding this as can be part of shortcuts on Mac. - } - ] - } - ], - secondaryRole: [ - { - groupName: '', - groupValues: [ - { - value: 'None', - label: 'None', - } - ] - }, - { - groupName: 'Modifiers', - groupValues: [ - { - value: 'LShift', - label: 'LShift' - }, - { - value: 'LCtrl', - label: 'LCtrl' - }, - { - value: 'LSuper', - label: 'LSuper' - }, - { - value: 'LAlt', - label: 'LAlt' - }, - { - value: 'RShift', - label: 'RShift' - }, - { - value: 'RCtrl', - label: 'RCtrl' - }, - { - value: 'RSuper', - label: 'RSuper' - }, - { - value: 'RAlt', - label: 'RAlt' - } - ] - }, - { - groupName: 'Layer Switcher', - groupValues: [ - { - value: 'Mod', - label: 'Mod' - }, - { - value: 'Mouse', - label: 'Mouse' - }, - { - value: 'Fn', - label: 'Fn' - } - ] - } - ] - }, - macro: { - macros: [ - { - value: 'Select macro', - name: 'Select macro' - }, - { - value: 'Latex custom equation', - name: 'Latex custom equation' - }, - { - value: 'Process shops xml', - name: 'Process shops xml' - }, - ] - }, - switchKeymap: { - layouts: [ - { - value: 'Select keymap', - name: 'Select keymap', - dataImage: 'base-layer--blank.svg', - abbrev: '', - dataAbbrevImage: '' - }, - { - value: 'Factory keymap', - name: 'Factory keymap', - dataImage: 'base-layer.svg', - abbrev: 'QWE', - dataAbbrevImage: 'segments_qwe.svg' - }, - { - value: 'Dvorak', - name: 'Dvorak', - dataImage: 'base-layer--dvorak.svg', - abbrev: 'DVR', - dataAbbrevImage: 'segments_dvr.svg' - } - ] - } - }; - - // Handlebars template for Popover top. - var keyEditorTopSource = $('#key-editor-top__source').html(); - var keyEditorTopTemplate = Handlebars.compile(keyEditorTopSource); - var keyEditorTopContext = { - buttons: [ - { - type: 'primary', - icon: 'fa-keyboard-o', - title: 'Keypress', - content: 'keypress' - }, - { - type: 'default', - icon: 'fa-clone', // The icon for the tab will be a layer icon in svg. But for the mockup it was easier to just use something similar from fontawesome. - title: 'Layer', - content: 'layer' - }, - { - type: 'default', - icon: 'fa-mouse-pointer', - title: 'Mouse', - content: 'mouse' - }, - { - type: 'default', - icon: 'fa-play', - title: 'Macro', - content: 'macro' - }, - { - type: 'default', - icon: 'fa-keyboard-o', - title: 'Keymap', - content: 'switchKeymap' - }, - { - type: 'default', - icon: 'fa-ban', - title: 'None', - content: 'none' - } - ] - }; - $('#key-editor-top__target').html(keyEditorTopTemplate(keyEditorTopContext)); - - // Handlebars template for Popover bottom. - var keyEditorBottomSource = $('#key-editor-bottom__source').html(); - var keyEditorBottomTemplate = Handlebars.compile(keyEditorBottomSource); - var keyEditorBottomContext = {}; - $('#key-editor-bottom__target').html(keyEditorBottomTemplate(keyEditorBottomContext)); - - // Handlebars template for Popover content to be displayed by default. - var keyEditorContentSource = $('#key-editor-content__source--keypress').html(); - var keyEditorContentTemplate = Handlebars.compile(keyEditorContentSource); - $('#key-editor-content__target').html(keyEditorContentTemplate(contentContext.keypress)); - - - // ================================ - // General library initializations. - // ================================ - - // Init select2. - $('select').select2({ - templateResult: formatState - }); - - // Init tooltips. - $('[data-toggle="tooltip"]').tooltip() - - // Init popover-title tabs. - $('li:first', '.popover-title.menu-tabs').addClass('active'); - - - // =============== - // Event handlers. - // =============== - - $('.popover-menu').on('click', 'button', function() { - $('.btn-primary', '.popover-menu').removeClass('btn-primary').addClass('btn-default'); - $(this).addClass('btn-primary').blur(); - var tplName = $(this).data('content'); - var contentSource = $('#key-editor-content__source--' + tplName).html(); - var contentTemplate = Handlebars.compile(contentSource); - $('#key-editor-content__target').html(contentTemplate(contentContext[tplName])); - initSelect2items(); - }); - - $('.popover-menu').on('click', 'a.menu-tabs--item', function() { - $('.popover-menu.nav-tabs li.active').removeClass('active'); - $(this).parent('li').addClass('active'); - var tplName = $(this).data('content'); - var contentSource = $('#key-editor-content__source--' + tplName).html(); - var contentTemplate = Handlebars.compile(contentSource); - $('#key-editor-content__target').html(contentTemplate(contentContext[tplName])); - var noSearch = false; - switch (tplName) { - case 'layer': - noSearch = true; - - case 'keypress': - _keypress_event_handlers(); - - case 'mouse': - _mouse_event_handlers(); - - default: - initSelect2items(noSearch); - } - }); - - - var _keypress_event_handlers = function() { - $('.modifiers').on('click', 'button', function() { - $(this).toggleClass('btn-primary').blur(); - }); - - $('.btn--capture-keystroke').on('click', function(e) { - $('.btn--capture-keystroke').toggle(); - _toggleScancodeForm(); - }); - - $('.layer-action--buttons').on('click', '.layer-key', function(e) { - $this = $(this); - $('.layer-key.btn-primary', '.layer-action--buttons').removeClass('btn-primary'); - $this.addClass('btn-primary').blur(); - if ($this.hasClass('layer-key--disabled')) { - // Enable all form controls in .global-key-setup - $('button, select', '.global-key-setup').prop('disabled', false); - $('.global-key-setup').removeClass('disabled'); - $('.disabled-state--text').hide(); - } - else { - // Disable all form controls in .global-key-setup - $('button, select', '.global-key-setup').prop('disabled', true); - $('.global-key-setup').addClass('disabled'); - $('.disabled-state--text').show(); - } - }); - }; - _keypress_event_handlers(); - - var _mouse_event_handlers = function() { - $('.mouse__action--type').on('click', 'a', function(e) { - var _this = $(this), - _mouse_config_name = _this.data('config'); - $('.mouse__config').hide(); - $('.mouse__config--' + _mouse_config_name).show(); - $('.mouse__action--type li').removeClass('active'); - _this.parents('li').addClass('active'); - }); - - $('.mouse__action--config').on('click', '.btn', function(e) { - var _buttons = $('.mouse__action--config .btn'), - _mouseActionTypes = $('.mouse__action--type a'), - _currentMouseAction = $('.mouse__action--type li.active a'), - _this = $(this); - - _buttons.removeClass('btn-primary'); - _this.addClass('btn-primary'); - _mouseActionTypes.removeClass('selected'); - _currentMouseAction.addClass('selected'); - }); - } -}); - - -// ========================== -// Select2 related functions. -// ========================== - -function initSelect2items(noSearch) { - var noSearch = typeof noSearch !== 'undefined' ? noSearch : false, - noSearchValue = 0; - if (noSearch) { - var noSearchValue = Infinity; - } - $('select').select2({ - templateResult: formatState, - minimumResultsForSearch: noSearchValue - }); - - $('select').on('select2:select', function(e) { - var selected = $(e.params.data.element); - var image = selected.data('image'); - console.log(e, selected, image); - $('img', '.layout-preview').attr('src', 'images/' + image); - }); - - $('.layer-toggle').on('select2:select', function(e) { - $('.layer-help').toggle(); - }); - - $('.layout-switcher').on('select2:open', function(e) { - $('.layout-preview').css('opacity', '0.1'); - }).on('select2:close', function(e) { - $('.layout-preview').css('opacity', '1'); - }); -} - -function formatState(state) { - if (!state.id) { return state.text; } - var searchTerm = $(state.element).data('searchterm'); - var dataAbbrev = $(state.element).data('abbrev'); - var dataAbbrevImage = $(state.element).data('abbrev-image'); - var $state = $('' + state.text + '') - if (searchTerm != '' && typeof searchTerm != 'undefined') { - $(' (' + searchTerm + ')').appendTo($state); - } - if (dataAbbrevImage != '' && typeof dataAbbrevImage != 'undefined') { - $('') - .attr('src', 'images/' + dataAbbrevImage) - .attr('class', 'layout-segment-code') - .prependTo($state); - $state.addClass('keymap-name--wrapper'); - } - return $state; -} - - -// =============== -// Misc functions. -// =============== - -function _toggleScancodeForm() { - var disabledState = $('.btn--capture-keystroke__stop').is(':visible'); - $('button', '.modifiers__left, .modifiers__right').prop('disabled', disabledState); - $('select.scancode').prop('disabled', disabledState); - $('b', '.scancode-options').toggleClass('disabled'); -} diff --git a/uhk.js b/uhk.js index 1c24b9d5..5e31007d 100644 --- a/uhk.js +++ b/uhk.js @@ -7614,1383 +7614,1335 @@ /* 308 */ /***/ function(module, exports, __webpack_require__) { - /* WEBPACK VAR INJECTION */(function(process) {/******/ (function(modules) { // webpackBootstrap - /******/ // The module cache - /******/ var installedModules = {}; + /* WEBPACK VAR INJECTION */(function(global, process) {/** + * @license + * Copyright Google Inc. All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.io/license + */ + (function (global, factory) { + true ? factory() : + typeof define === 'function' && define.amd ? define(factory) : + (factory()); + }(this, (function () { 'use strict'; - /******/ // The require function - /******/ function __webpack_require__(moduleId) { + var Zone$1 = (function (global) { + if (global.Zone) { + throw new Error('Zone already loaded.'); + } + var Zone = (function () { + function Zone(parent, zoneSpec) { + this._properties = null; + this._parent = parent; + this._name = zoneSpec ? zoneSpec.name || 'unnamed' : ''; + this._properties = zoneSpec && zoneSpec.properties || {}; + this._zoneDelegate = new ZoneDelegate(this, this._parent && this._parent._zoneDelegate, zoneSpec); + } + Zone.assertZonePatched = function () { + if (global.Promise !== ZoneAwarePromise) { + throw new Error("Zone.js has detected that ZoneAwarePromise `(window|global).Promise` " + + "has been overwritten.\n" + + "Most likely cause is that a Promise polyfill has been loaded " + + "after Zone.js (Polyfilling Promise api is not necessary when zone.js is loaded. " + + "If you must load one, do so before loading zone.js.)"); + } + }; + Object.defineProperty(Zone, "current", { + get: function () { return _currentZone; }, + enumerable: true, + configurable: true + }); + + Object.defineProperty(Zone, "currentTask", { + get: function () { return _currentTask; }, + enumerable: true, + configurable: true + }); + + Object.defineProperty(Zone.prototype, "parent", { + get: function () { return this._parent; }, + enumerable: true, + configurable: true + }); + + Object.defineProperty(Zone.prototype, "name", { + get: function () { return this._name; }, + enumerable: true, + configurable: true + }); + + Zone.prototype.get = function (key) { + var zone = this.getZoneWith(key); + if (zone) + return zone._properties[key]; + }; + Zone.prototype.getZoneWith = function (key) { + var current = this; + while (current) { + if (current._properties.hasOwnProperty(key)) { + return current; + } + current = current._parent; + } + return null; + }; + Zone.prototype.fork = function (zoneSpec) { + if (!zoneSpec) + throw new Error('ZoneSpec required!'); + return this._zoneDelegate.fork(this, zoneSpec); + }; + Zone.prototype.wrap = function (callback, source) { + if (typeof callback !== 'function') { + throw new Error('Expecting function got: ' + callback); + } + var _callback = this._zoneDelegate.intercept(this, callback, source); + var zone = this; + return function () { + return zone.runGuarded(_callback, this, arguments, source); + }; + }; + Zone.prototype.run = function (callback, applyThis, applyArgs, source) { + if (applyThis === void 0) { applyThis = null; } + if (applyArgs === void 0) { applyArgs = null; } + if (source === void 0) { source = null; } + var oldZone = _currentZone; + _currentZone = this; + try { + return this._zoneDelegate.invoke(this, callback, applyThis, applyArgs, source); + } + finally { + _currentZone = oldZone; + } + }; + Zone.prototype.runGuarded = function (callback, applyThis, applyArgs, source) { + if (applyThis === void 0) { applyThis = null; } + if (applyArgs === void 0) { applyArgs = null; } + if (source === void 0) { source = null; } + var oldZone = _currentZone; + _currentZone = this; + try { + try { + return this._zoneDelegate.invoke(this, callback, applyThis, applyArgs, source); + } + catch (error) { + if (this._zoneDelegate.handleError(this, error)) { + throw error; + } + } + } + finally { + _currentZone = oldZone; + } + }; + Zone.prototype.runTask = function (task, applyThis, applyArgs) { + task.runCount++; + if (task.zone != this) + throw new Error('A task can only be run in the zone which created it! (Creation: ' + + task.zone.name + '; Execution: ' + this.name + ')'); + var previousTask = _currentTask; + _currentTask = task; + var oldZone = _currentZone; + _currentZone = this; + try { + if (task.type == 'macroTask' && task.data && !task.data.isPeriodic) { + task.cancelFn = null; + } + try { + return this._zoneDelegate.invokeTask(this, task, applyThis, applyArgs); + } + catch (error) { + if (this._zoneDelegate.handleError(this, error)) { + throw error; + } + } + } + finally { + _currentZone = oldZone; + _currentTask = previousTask; + } + }; + Zone.prototype.scheduleMicroTask = function (source, callback, data, customSchedule) { + return this._zoneDelegate.scheduleTask(this, new ZoneTask('microTask', this, source, callback, data, customSchedule, null)); + }; + Zone.prototype.scheduleMacroTask = function (source, callback, data, customSchedule, customCancel) { + return this._zoneDelegate.scheduleTask(this, new ZoneTask('macroTask', this, source, callback, data, customSchedule, customCancel)); + }; + Zone.prototype.scheduleEventTask = function (source, callback, data, customSchedule, customCancel) { + return this._zoneDelegate.scheduleTask(this, new ZoneTask('eventTask', this, source, callback, data, customSchedule, customCancel)); + }; + Zone.prototype.cancelTask = function (task) { + var value = this._zoneDelegate.cancelTask(this, task); + task.runCount = -1; + task.cancelFn = null; + return value; + }; + Zone.__symbol__ = __symbol__; + return Zone; + }()); + + var ZoneDelegate = (function () { + function ZoneDelegate(zone, parentDelegate, zoneSpec) { + this._taskCounts = { microTask: 0, macroTask: 0, eventTask: 0 }; + this.zone = zone; + this._parentDelegate = parentDelegate; + this._forkZS = zoneSpec && (zoneSpec && zoneSpec.onFork ? zoneSpec : parentDelegate._forkZS); + this._forkDlgt = zoneSpec && (zoneSpec.onFork ? parentDelegate : parentDelegate._forkDlgt); + this._interceptZS = zoneSpec && (zoneSpec.onIntercept ? zoneSpec : parentDelegate._interceptZS); + this._interceptDlgt = zoneSpec && (zoneSpec.onIntercept ? parentDelegate : parentDelegate._interceptDlgt); + this._invokeZS = zoneSpec && (zoneSpec.onInvoke ? zoneSpec : parentDelegate._invokeZS); + this._invokeDlgt = zoneSpec && (zoneSpec.onInvoke ? parentDelegate : parentDelegate._invokeDlgt); + this._handleErrorZS = zoneSpec && (zoneSpec.onHandleError ? zoneSpec : parentDelegate._handleErrorZS); + this._handleErrorDlgt = zoneSpec && (zoneSpec.onHandleError ? parentDelegate : parentDelegate._handleErrorDlgt); + this._scheduleTaskZS = zoneSpec && (zoneSpec.onScheduleTask ? zoneSpec : parentDelegate._scheduleTaskZS); + this._scheduleTaskDlgt = zoneSpec && (zoneSpec.onScheduleTask ? parentDelegate : parentDelegate._scheduleTaskDlgt); + this._invokeTaskZS = zoneSpec && (zoneSpec.onInvokeTask ? zoneSpec : parentDelegate._invokeTaskZS); + this._invokeTaskDlgt = zoneSpec && (zoneSpec.onInvokeTask ? parentDelegate : parentDelegate._invokeTaskDlgt); + this._cancelTaskZS = zoneSpec && (zoneSpec.onCancelTask ? zoneSpec : parentDelegate._cancelTaskZS); + this._cancelTaskDlgt = zoneSpec && (zoneSpec.onCancelTask ? parentDelegate : parentDelegate._cancelTaskDlgt); + this._hasTaskZS = zoneSpec && (zoneSpec.onHasTask ? zoneSpec : parentDelegate._hasTaskZS); + this._hasTaskDlgt = zoneSpec && (zoneSpec.onHasTask ? parentDelegate : parentDelegate._hasTaskDlgt); + } + ZoneDelegate.prototype.fork = function (targetZone, zoneSpec) { + return this._forkZS + ? this._forkZS.onFork(this._forkDlgt, this.zone, targetZone, zoneSpec) + : new Zone(targetZone, zoneSpec); + }; + ZoneDelegate.prototype.intercept = function (targetZone, callback, source) { + return this._interceptZS + ? this._interceptZS.onIntercept(this._interceptDlgt, this.zone, targetZone, callback, source) + : callback; + }; + ZoneDelegate.prototype.invoke = function (targetZone, callback, applyThis, applyArgs, source) { + return this._invokeZS + ? this._invokeZS.onInvoke(this._invokeDlgt, this.zone, targetZone, callback, applyThis, applyArgs, source) + : callback.apply(applyThis, applyArgs); + }; + ZoneDelegate.prototype.handleError = function (targetZone, error) { + return this._handleErrorZS + ? this._handleErrorZS.onHandleError(this._handleErrorDlgt, this.zone, targetZone, error) + : true; + }; + ZoneDelegate.prototype.scheduleTask = function (targetZone, task) { + try { + if (this._scheduleTaskZS) { + return this._scheduleTaskZS.onScheduleTask(this._scheduleTaskDlgt, this.zone, targetZone, task); + } + else if (task.scheduleFn) { + task.scheduleFn(task); + } + else if (task.type == 'microTask') { + scheduleMicroTask(task); + } + else { + throw new Error('Task is missing scheduleFn.'); + } + return task; + } + finally { + if (targetZone == this.zone) { + this._updateTaskCount(task.type, 1); + } + } + }; + ZoneDelegate.prototype.invokeTask = function (targetZone, task, applyThis, applyArgs) { + try { + return this._invokeTaskZS + ? this._invokeTaskZS.onInvokeTask(this._invokeTaskDlgt, this.zone, targetZone, task, applyThis, applyArgs) + : task.callback.apply(applyThis, applyArgs); + } + finally { + if (targetZone == this.zone && (task.type != 'eventTask') && !(task.data && task.data.isPeriodic)) { + this._updateTaskCount(task.type, -1); + } + } + }; + ZoneDelegate.prototype.cancelTask = function (targetZone, task) { + var value; + if (this._cancelTaskZS) { + value = this._cancelTaskZS.onCancelTask(this._cancelTaskDlgt, this.zone, targetZone, task); + } + else if (!task.cancelFn) { + throw new Error('Task does not support cancellation, or is already canceled.'); + } + else { + value = task.cancelFn(task); + } + if (targetZone == this.zone) { + // this should not be in the finally block, because exceptions assume not canceled. + this._updateTaskCount(task.type, -1); + } + return value; + }; + ZoneDelegate.prototype.hasTask = function (targetZone, isEmpty) { + return this._hasTaskZS && this._hasTaskZS.onHasTask(this._hasTaskDlgt, this.zone, targetZone, isEmpty); + }; + ZoneDelegate.prototype._updateTaskCount = function (type, count) { + var counts = this._taskCounts; + var prev = counts[type]; + var next = counts[type] = prev + count; + if (next < 0) { + throw new Error('More tasks executed then were scheduled.'); + } + if (prev == 0 || next == 0) { + var isEmpty = { + microTask: counts.microTask > 0, + macroTask: counts.macroTask > 0, + eventTask: counts.eventTask > 0, + change: type + }; + try { + this.hasTask(this.zone, isEmpty); + } + finally { + if (this._parentDelegate) { + this._parentDelegate._updateTaskCount(type, count); + } + } + } + }; + return ZoneDelegate; + }()); + var ZoneTask = (function () { + function ZoneTask(type, zone, source, callback, options, scheduleFn, cancelFn) { + this.runCount = 0; + this.type = type; + this.zone = zone; + this.source = source; + this.data = options; + this.scheduleFn = scheduleFn; + this.cancelFn = cancelFn; + this.callback = callback; + var self = this; + this.invoke = function () { + _numberOfNestedTaskFrames++; + try { + return zone.runTask(self, this, arguments); + } + finally { + if (_numberOfNestedTaskFrames == 1) { + drainMicroTaskQueue(); + } + _numberOfNestedTaskFrames--; + } + }; + } + ZoneTask.prototype.toString = function () { + if (this.data && typeof this.data.handleId !== 'undefined') { + return this.data.handleId; + } + else { + return this.toString(); + } + }; + return ZoneTask; + }()); + function __symbol__(name) { return '__zone_symbol__' + name; } + + var symbolSetTimeout = __symbol__('setTimeout'); + var symbolPromise = __symbol__('Promise'); + var symbolThen = __symbol__('then'); + var _currentZone = new Zone(null, null); + var _currentTask = null; + var _microTaskQueue = []; + var _isDrainingMicrotaskQueue = false; + var _uncaughtPromiseErrors = []; + var _numberOfNestedTaskFrames = 0; + function scheduleQueueDrain() { + // if we are not running in any task, and there has not been anything scheduled + // we must bootstrap the initial task creation by manually scheduling the drain + if (_numberOfNestedTaskFrames == 0 && _microTaskQueue.length == 0) { + // We are not running in Task, so we need to kickstart the microtask queue. + if (global[symbolPromise]) { + global[symbolPromise].resolve(0)[symbolThen](drainMicroTaskQueue); + } + else { + global[symbolSetTimeout](drainMicroTaskQueue, 0); + } + } + } + function scheduleMicroTask(task) { + scheduleQueueDrain(); + _microTaskQueue.push(task); + } + function consoleError(e) { + var rejection = e && e.rejection; + if (rejection) { + console.error('Unhandled Promise rejection:', rejection instanceof Error ? rejection.message : rejection, '; Zone:', e.zone.name, '; Task:', e.task && e.task.source, '; Value:', rejection, rejection instanceof Error ? rejection.stack : undefined); + } + console.error(e); + } + function drainMicroTaskQueue() { + if (!_isDrainingMicrotaskQueue) { + _isDrainingMicrotaskQueue = true; + while (_microTaskQueue.length) { + var queue = _microTaskQueue; + _microTaskQueue = []; + for (var i = 0; i < queue.length; i++) { + var task = queue[i]; + try { + task.zone.runTask(task, null, null); + } + catch (e) { + consoleError(e); + } + } + } + while (_uncaughtPromiseErrors.length) { + var _loop_1 = function() { + var uncaughtPromiseError = _uncaughtPromiseErrors.shift(); + try { + uncaughtPromiseError.zone.runGuarded(function () { throw uncaughtPromiseError; }); + } + catch (e) { + consoleError(e); + } + }; + while (_uncaughtPromiseErrors.length) { + _loop_1(); + } + } + _isDrainingMicrotaskQueue = false; + } + } + function isThenable(value) { + return value && value.then; + } + function forwardResolution(value) { return value; } + function forwardRejection(rejection) { return ZoneAwarePromise.reject(rejection); } + var symbolState = __symbol__('state'); + var symbolValue = __symbol__('value'); + var source = 'Promise.then'; + var UNRESOLVED = null; + var RESOLVED = true; + var REJECTED = false; + var REJECTED_NO_CATCH = 0; + function makeResolver(promise, state) { + return function (v) { + resolvePromise(promise, state, v); + // Do not return value or you will break the Promise spec. + }; + } + function resolvePromise(promise, state, value) { + if (promise[symbolState] === UNRESOLVED) { + if (value instanceof ZoneAwarePromise && value[symbolState] !== UNRESOLVED) { + clearRejectedNoCatch(value); + resolvePromise(promise, value[symbolState], value[symbolValue]); + } + else if (isThenable(value)) { + value.then(makeResolver(promise, state), makeResolver(promise, false)); + } + else { + promise[symbolState] = state; + var queue = promise[symbolValue]; + promise[symbolValue] = value; + for (var i = 0; i < queue.length;) { + scheduleResolveOrReject(promise, queue[i++], queue[i++], queue[i++], queue[i++]); + } + if (queue.length == 0 && state == REJECTED) { + promise[symbolState] = REJECTED_NO_CATCH; + try { + throw new Error("Uncaught (in promise): " + value); + } + catch (e) { + var error_1 = e; + error_1.rejection = value; + error_1.promise = promise; + error_1.zone = Zone.current; + error_1.task = Zone.currentTask; + _uncaughtPromiseErrors.push(error_1); + scheduleQueueDrain(); + } + } + } + } + // Resolving an already resolved promise is a noop. + return promise; + } + function clearRejectedNoCatch(promise) { + if (promise[symbolState] === REJECTED_NO_CATCH) { + promise[symbolState] = REJECTED; + for (var i = 0; i < _uncaughtPromiseErrors.length; i++) { + if (promise === _uncaughtPromiseErrors[i].promise) { + _uncaughtPromiseErrors.splice(i, 1); + break; + } + } + } + } + function scheduleResolveOrReject(promise, zone, chainPromise, onFulfilled, onRejected) { + clearRejectedNoCatch(promise); + var delegate = promise[symbolState] ? onFulfilled || forwardResolution : onRejected || forwardRejection; + zone.scheduleMicroTask(source, function () { + try { + resolvePromise(chainPromise, true, zone.run(delegate, null, [promise[symbolValue]])); + } + catch (error) { + resolvePromise(chainPromise, false, error); + } + }); + } + var ZoneAwarePromise = (function () { + function ZoneAwarePromise(executor) { + var promise = this; + if (!(promise instanceof ZoneAwarePromise)) { + throw new Error('Must be an instanceof Promise.'); + } + promise[symbolState] = UNRESOLVED; + promise[symbolValue] = []; // queue; + try { + executor && executor(makeResolver(promise, RESOLVED), makeResolver(promise, REJECTED)); + } + catch (e) { + resolvePromise(promise, false, e); + } + } + ZoneAwarePromise.resolve = function (value) { + return resolvePromise(new this(null), RESOLVED, value); + }; + ZoneAwarePromise.reject = function (error) { + return resolvePromise(new this(null), REJECTED, error); + }; + ZoneAwarePromise.race = function (values) { + var resolve; + var reject; + var promise = new this(function (res, rej) { resolve = res; reject = rej; }); + function onResolve(value) { promise && (promise = null || resolve(value)); } + function onReject(error) { promise && (promise = null || reject(error)); } + for (var _i = 0, values_1 = values; _i < values_1.length; _i++) { + var value = values_1[_i]; + if (!isThenable(value)) { + value = this.resolve(value); + } + value.then(onResolve, onReject); + } + return promise; + }; + ZoneAwarePromise.all = function (values) { + var resolve; + var reject; + var promise = new this(function (res, rej) { resolve = res; reject = rej; }); + var count = 0; + var resolvedValues = []; + for (var _i = 0, values_2 = values; _i < values_2.length; _i++) { + var value = values_2[_i]; + if (!isThenable(value)) { + value = this.resolve(value); + } + value.then((function (index) { return function (value) { + resolvedValues[index] = value; + count--; + if (!count) { + resolve(resolvedValues); + } + }; })(count), reject); + count++; + } + if (!count) + resolve(resolvedValues); + return promise; + }; + ZoneAwarePromise.prototype.then = function (onFulfilled, onRejected) { + var chainPromise = new this.constructor(null); + var zone = Zone.current; + if (this[symbolState] == UNRESOLVED) { + this[symbolValue].push(zone, chainPromise, onFulfilled, onRejected); + } + else { + scheduleResolveOrReject(this, zone, chainPromise, onFulfilled, onRejected); + } + return chainPromise; + }; + ZoneAwarePromise.prototype.catch = function (onRejected) { + return this.then(null, onRejected); + }; + return ZoneAwarePromise; + }()); + // Protect against aggressive optimizers dropping seemingly unused properties. + // E.g. Closure Compiler in advanced mode. + ZoneAwarePromise['resolve'] = ZoneAwarePromise.resolve; + ZoneAwarePromise['reject'] = ZoneAwarePromise.reject; + ZoneAwarePromise['race'] = ZoneAwarePromise.race; + ZoneAwarePromise['all'] = ZoneAwarePromise.all; + var NativePromise = global[__symbol__('Promise')] = global.Promise; + global.Promise = ZoneAwarePromise; + function patchThen(NativePromise) { + var NativePromiseProtototype = NativePromise.prototype; + var NativePromiseThen = NativePromiseProtototype[__symbol__('then')] + = NativePromiseProtototype.then; + NativePromiseProtototype.then = function (onResolve, onReject) { + var nativePromise = this; + return new ZoneAwarePromise(function (resolve, reject) { + NativePromiseThen.call(nativePromise, resolve, reject); + }).then(onResolve, onReject); + }; + } + if (NativePromise) { + patchThen(NativePromise); + if (typeof global['fetch'] !== 'undefined') { + var fetchPromise = void 0; + try { + // In MS Edge this throws + fetchPromise = global['fetch'](); + } + catch (e) { + // In Chrome this throws instead. + fetchPromise = global['fetch']('about:blank'); + } + // ignore output to prevent error; + fetchPromise.then(function () { return null; }, function () { return null; }); + if (fetchPromise.constructor != NativePromise) { + patchThen(fetchPromise.constructor); + } + } + } + // This is not part of public API, but it is usefull for tests, so we expose it. + Promise[Zone.__symbol__('uncaughtPromiseErrors')] = _uncaughtPromiseErrors; + return global.Zone = Zone; + })(typeof window === 'object' && window || typeof self === 'object' && self || global); - /******/ // Check if module is in cache - /******/ if(installedModules[moduleId]) - /******/ return installedModules[moduleId].exports; + /** + * Suppress closure compiler errors about unknown 'process' variable + * @fileoverview + * @suppress {undefinedVars} + */ + var zoneSymbol = Zone['__symbol__']; + var _global$1 = typeof window === 'object' && window || typeof self === 'object' && self || global; + function bindArguments(args, source) { + for (var i = args.length - 1; i >= 0; i--) { + if (typeof args[i] === 'function') { + args[i] = Zone.current.wrap(args[i], source + '_' + i); + } + } + return args; + } - /******/ // Create a new module (and put it into the cache) - /******/ var module = installedModules[moduleId] = { - /******/ exports: {}, - /******/ id: moduleId, - /******/ loaded: false - /******/ }; + function patchPrototype(prototype, fnNames) { + var source = prototype.constructor['name']; + var _loop_1 = function(i) { + var name_1 = fnNames[i]; + var delegate = prototype[name_1]; + if (delegate) { + prototype[name_1] = (function (delegate) { + return function () { + return delegate.apply(this, bindArguments(arguments, source + '.' + name_1)); + }; + })(delegate); + } + }; + for (var i = 0; i < fnNames.length; i++) { + _loop_1(i); + } + } - /******/ // Execute the module function - /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); + var isWebWorker = (typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope); + var isNode = (typeof process !== 'undefined' && {}.toString.call(process) === '[object process]'); + var isBrowser = !isNode && !isWebWorker && !!(typeof window !== 'undefined' && window['HTMLElement']); + function patchProperty(obj, prop) { + var desc = Object.getOwnPropertyDescriptor(obj, prop) || { + enumerable: true, + configurable: true + }; + // A property descriptor cannot have getter/setter and be writable + // deleting the writable and value properties avoids this error: + // + // TypeError: property descriptors must not specify a value or be writable when a + // getter or setter has been specified + delete desc.writable; + delete desc.value; + // substr(2) cuz 'onclick' -> 'click', etc + var eventName = prop.substr(2); + var _prop = '_' + prop; + desc.set = function (fn) { + if (this[_prop]) { + this.removeEventListener(eventName, this[_prop]); + } + if (typeof fn === 'function') { + var wrapFn = function (event) { + var result; + result = fn.apply(this, arguments); + if (result != undefined && !result) + event.preventDefault(); + }; + this[_prop] = wrapFn; + this.addEventListener(eventName, wrapFn, false); + } + else { + this[_prop] = null; + } + }; + // The getter would return undefined for unassigned properties but the default value of an unassigned property is null + desc.get = function () { + return this[_prop] || null; + }; + Object.defineProperty(obj, prop, desc); + } - /******/ // Flag the module as loaded - /******/ module.loaded = true; + function patchOnProperties(obj, properties) { + var onProperties = []; + for (var prop in obj) { + if (prop.substr(0, 2) == 'on') { + onProperties.push(prop); + } + } + for (var j = 0; j < onProperties.length; j++) { + patchProperty(obj, onProperties[j]); + } + if (properties) { + for (var i = 0; i < properties.length; i++) { + patchProperty(obj, 'on' + properties[i]); + } + } + } - /******/ // Return the exports of the module - /******/ return module.exports; - /******/ } + var EVENT_TASKS = zoneSymbol('eventTasks'); + // For EventTarget + var ADD_EVENT_LISTENER = 'addEventListener'; + var REMOVE_EVENT_LISTENER = 'removeEventListener'; + function findExistingRegisteredTask(target, handler, name, capture, remove) { + var eventTasks = target[EVENT_TASKS]; + if (eventTasks) { + for (var i = 0; i < eventTasks.length; i++) { + var eventTask = eventTasks[i]; + var data = eventTask.data; + if (data.handler === handler + && data.useCapturing === capture + && data.eventName === name) { + if (remove) { + eventTasks.splice(i, 1); + } + return eventTask; + } + } + } + return null; + } + function attachRegisteredEvent(target, eventTask) { + var eventTasks = target[EVENT_TASKS]; + if (!eventTasks) { + eventTasks = target[EVENT_TASKS] = []; + } + eventTasks.push(eventTask); + } + function makeZoneAwareAddListener(addFnName, removeFnName, useCapturingParam, allowDuplicates) { + if (useCapturingParam === void 0) { useCapturingParam = true; } + if (allowDuplicates === void 0) { allowDuplicates = false; } + var addFnSymbol = zoneSymbol(addFnName); + var removeFnSymbol = zoneSymbol(removeFnName); + var defaultUseCapturing = useCapturingParam ? false : undefined; + function scheduleEventListener(eventTask) { + var meta = eventTask.data; + attachRegisteredEvent(meta.target, eventTask); + return meta.target[addFnSymbol](meta.eventName, eventTask.invoke, meta.useCapturing); + } + function cancelEventListener(eventTask) { + var meta = eventTask.data; + findExistingRegisteredTask(meta.target, eventTask.invoke, meta.eventName, meta.useCapturing, true); + meta.target[removeFnSymbol](meta.eventName, eventTask.invoke, meta.useCapturing); + } + return function zoneAwareAddListener(self, args) { + var eventName = args[0]; + var handler = args[1]; + var useCapturing = args[2] || defaultUseCapturing; + // - Inside a Web Worker, `this` is undefined, the context is `global` + // - When `addEventListener` is called on the global context in strict mode, `this` is undefined + // see https://github.com/angular/zone.js/issues/190 + var target = self || _global$1; + var delegate = null; + if (typeof handler == 'function') { + delegate = handler; + } + else if (handler && handler.handleEvent) { + delegate = function (event) { return handler.handleEvent(event); }; + } + var validZoneHandler = false; + try { + // In cross site contexts (such as WebDriver frameworks like Selenium), + // accessing the handler object here will cause an exception to be thrown which + // will fail tests prematurely. + validZoneHandler = handler && handler.toString() === "[object FunctionWrapper]"; + } + catch (e) { + // Returning nothing here is fine, because objects in a cross-site context are unusable + return; + } + // Ignore special listeners of IE11 & Edge dev tools, see https://github.com/angular/zone.js/issues/150 + if (!delegate || validZoneHandler) { + return target[addFnSymbol](eventName, handler, useCapturing); + } + if (!allowDuplicates) { + var eventTask = findExistingRegisteredTask(target, handler, eventName, useCapturing, false); + if (eventTask) { + // we already registered, so this will have noop. + return target[addFnSymbol](eventName, eventTask.invoke, useCapturing); + } + } + var zone = Zone.current; + var source = target.constructor['name'] + '.' + addFnName + ':' + eventName; + var data = { + target: target, + eventName: eventName, + name: eventName, + useCapturing: useCapturing, + handler: handler + }; + zone.scheduleEventTask(source, delegate, data, scheduleEventListener, cancelEventListener); + }; + } + function makeZoneAwareRemoveListener(fnName, useCapturingParam) { + if (useCapturingParam === void 0) { useCapturingParam = true; } + var symbol = zoneSymbol(fnName); + var defaultUseCapturing = useCapturingParam ? false : undefined; + return function zoneAwareRemoveListener(self, args) { + var eventName = args[0]; + var handler = args[1]; + var useCapturing = args[2] || defaultUseCapturing; + // - Inside a Web Worker, `this` is undefined, the context is `global` + // - When `addEventListener` is called on the global context in strict mode, `this` is undefined + // see https://github.com/angular/zone.js/issues/190 + var target = self || _global$1; + var eventTask = findExistingRegisteredTask(target, handler, eventName, useCapturing, true); + if (eventTask) { + eventTask.zone.cancelTask(eventTask); + } + else { + target[symbol](eventName, handler, useCapturing); + } + }; + } + var zoneAwareAddEventListener = makeZoneAwareAddListener(ADD_EVENT_LISTENER, REMOVE_EVENT_LISTENER); + var zoneAwareRemoveEventListener = makeZoneAwareRemoveListener(REMOVE_EVENT_LISTENER); + function patchEventTargetMethods(obj) { + if (obj && obj.addEventListener) { + patchMethod(obj, ADD_EVENT_LISTENER, function () { return zoneAwareAddEventListener; }); + patchMethod(obj, REMOVE_EVENT_LISTENER, function () { return zoneAwareRemoveEventListener; }); + return true; + } + else { + return false; + } + } + var originalInstanceKey = zoneSymbol('originalInstance'); + // wrap some native API on `window` + function patchClass(className) { + var OriginalClass = _global$1[className]; + if (!OriginalClass) + return; + _global$1[className] = function () { + var a = bindArguments(arguments, className); + switch (a.length) { + case 0: + this[originalInstanceKey] = new OriginalClass(); + break; + case 1: + this[originalInstanceKey] = new OriginalClass(a[0]); + break; + case 2: + this[originalInstanceKey] = new OriginalClass(a[0], a[1]); + break; + case 3: + this[originalInstanceKey] = new OriginalClass(a[0], a[1], a[2]); + break; + case 4: + this[originalInstanceKey] = new OriginalClass(a[0], a[1], a[2], a[3]); + break; + default: throw new Error('Arg list too long.'); + } + }; + var instance = new OriginalClass(function () { }); + var prop; + for (prop in instance) { + // https://bugs.webkit.org/show_bug.cgi?id=44721 + if (className === 'XMLHttpRequest' && prop === 'responseBlob') + continue; + (function (prop) { + if (typeof instance[prop] === 'function') { + _global$1[className].prototype[prop] = function () { + return this[originalInstanceKey][prop].apply(this[originalInstanceKey], arguments); + }; + } + else { + Object.defineProperty(_global$1[className].prototype, prop, { + set: function (fn) { + if (typeof fn === 'function') { + this[originalInstanceKey][prop] = Zone.current.wrap(fn, className + '.' + prop); + } + else { + this[originalInstanceKey][prop] = fn; + } + }, + get: function () { + return this[originalInstanceKey][prop]; + } + }); + } + }(prop)); + } + for (prop in OriginalClass) { + if (prop !== 'prototype' && OriginalClass.hasOwnProperty(prop)) { + _global$1[className][prop] = OriginalClass[prop]; + } + } + } - /******/ // expose the modules object (__webpack_modules__) - /******/ __webpack_require__.m = modules; + function createNamedFn(name, delegate) { + try { + return (Function('f', "return function " + name + "(){return f(this, arguments)}"))(delegate); + } + catch (e) { + // if we fail, we must be CSP, just return delegate. + return function () { + return delegate(this, arguments); + }; + } + } + function patchMethod(target, name, patchFn) { + var proto = target; + while (proto && !proto.hasOwnProperty(name)) { + proto = Object.getPrototypeOf(proto); + } + if (!proto && target[name]) { + // somehow we did not find it, but we can see it. This happens on IE for Window properties. + proto = target; + } + var delegateName = zoneSymbol(name); + var delegate; + if (proto && !(delegate = proto[delegateName])) { + delegate = proto[delegateName] = proto[name]; + proto[name] = createNamedFn(name, patchFn(delegate, delegateName, name)); + } + return delegate; + } - /******/ // expose the module cache - /******/ __webpack_require__.c = installedModules; + var WTF_ISSUE_555 = 'Anchor,Area,Audio,BR,Base,BaseFont,Body,Button,Canvas,Content,DList,Directory,Div,Embed,FieldSet,Font,Form,Frame,FrameSet,HR,Head,Heading,Html,IFrame,Image,Input,Keygen,LI,Label,Legend,Link,Map,Marquee,Media,Menu,Meta,Meter,Mod,OList,Object,OptGroup,Option,Output,Paragraph,Pre,Progress,Quote,Script,Select,Source,Span,Style,TableCaption,TableCell,TableCol,Table,TableRow,TableSection,TextArea,Title,Track,UList,Unknown,Video'; + var NO_EVENT_TARGET = 'ApplicationCache,EventSource,FileReader,InputMethodContext,MediaController,MessagePort,Node,Performance,SVGElementInstance,SharedWorker,TextTrack,TextTrackCue,TextTrackList,WebKitNamedFlow,Window,Worker,WorkerGlobalScope,XMLHttpRequest,XMLHttpRequestEventTarget,XMLHttpRequestUpload,IDBRequest,IDBOpenDBRequest,IDBDatabase,IDBTransaction,IDBCursor,DBIndex'.split(','); + var EVENT_TARGET = 'EventTarget'; + function eventTargetPatch(_global) { + var apis = []; + var isWtf = _global['wtf']; + if (isWtf) { + // Workaround for: https://github.com/google/tracing-framework/issues/555 + apis = WTF_ISSUE_555.split(',').map(function (v) { return 'HTML' + v + 'Element'; }).concat(NO_EVENT_TARGET); + } + else if (_global[EVENT_TARGET]) { + apis.push(EVENT_TARGET); + } + else { + // Note: EventTarget is not available in all browsers, + // if it's not available, we instead patch the APIs in the IDL that inherit from EventTarget + apis = NO_EVENT_TARGET; + } + for (var i = 0; i < apis.length; i++) { + var type = _global[apis[i]]; + patchEventTargetMethods(type && type.prototype); + } + } - /******/ // __webpack_public_path__ - /******/ __webpack_require__.p = ""; + /* + * This is necessary for Chrome and Chrome mobile, to enable + * things like redefining `createdCallback` on an element. + */ + var _defineProperty = Object[zoneSymbol('defineProperty')] = Object.defineProperty; + var _getOwnPropertyDescriptor = Object[zoneSymbol('getOwnPropertyDescriptor')] = Object.getOwnPropertyDescriptor; + var _create = Object.create; + var unconfigurablesKey = zoneSymbol('unconfigurables'); + function propertyPatch() { + Object.defineProperty = function (obj, prop, desc) { + if (isUnconfigurable(obj, prop)) { + throw new TypeError('Cannot assign to read only property \'' + prop + '\' of ' + obj); + } + var originalConfigurableFlag = desc.configurable; + if (prop !== 'prototype') { + desc = rewriteDescriptor(obj, prop, desc); + } + return _tryDefineProperty(obj, prop, desc, originalConfigurableFlag); + }; + Object.defineProperties = function (obj, props) { + Object.keys(props).forEach(function (prop) { + Object.defineProperty(obj, prop, props[prop]); + }); + return obj; + }; + Object.create = function (obj, proto) { + if (typeof proto === 'object' && !Object.isFrozen(proto)) { + Object.keys(proto).forEach(function (prop) { + proto[prop] = rewriteDescriptor(obj, prop, proto[prop]); + }); + } + return _create(obj, proto); + }; + Object.getOwnPropertyDescriptor = function (obj, prop) { + var desc = _getOwnPropertyDescriptor(obj, prop); + if (isUnconfigurable(obj, prop)) { + desc.configurable = false; + } + return desc; + }; + } - /******/ // Load entry module and return exports - /******/ return __webpack_require__(0); - /******/ }) - /************************************************************************/ - /******/ ([ - /* 0 */ - /***/ function(module, exports, __webpack_require__) { + function _redefineProperty(obj, prop, desc) { + var originalConfigurableFlag = desc.configurable; + desc = rewriteDescriptor(obj, prop, desc); + return _tryDefineProperty(obj, prop, desc, originalConfigurableFlag); + } - /* WEBPACK VAR INJECTION */(function(global) {"use strict"; - __webpack_require__(1); - var event_target_1 = __webpack_require__(2); - var define_property_1 = __webpack_require__(4); - var register_element_1 = __webpack_require__(5); - var property_descriptor_1 = __webpack_require__(6); - var timers_1 = __webpack_require__(8); - var utils_1 = __webpack_require__(3); - var set = 'set'; - var clear = 'clear'; - var blockingMethods = ['alert', 'prompt', 'confirm']; - var _global = typeof window == 'undefined' ? global : window; - timers_1.patchTimer(_global, set, clear, 'Timeout'); - timers_1.patchTimer(_global, set, clear, 'Interval'); - timers_1.patchTimer(_global, set, clear, 'Immediate'); - timers_1.patchTimer(_global, 'request', 'cancel', 'AnimationFrame'); - timers_1.patchTimer(_global, 'mozRequest', 'mozCancel', 'AnimationFrame'); - timers_1.patchTimer(_global, 'webkitRequest', 'webkitCancel', 'AnimationFrame'); - for (var i = 0; i < blockingMethods.length; i++) { - var name = blockingMethods[i]; - utils_1.patchMethod(_global, name, function (delegate, symbol, name) { - return function (s, args) { - return Zone.current.run(delegate, _global, args, name); - }; - }); - } - event_target_1.eventTargetPatch(_global); - property_descriptor_1.propertyDescriptorPatch(_global); - utils_1.patchClass('MutationObserver'); - utils_1.patchClass('WebKitMutationObserver'); - utils_1.patchClass('FileReader'); - define_property_1.propertyPatch(); - register_element_1.registerElementPatch(_global); - // Treat XMLHTTPRequest as a macrotask. - patchXHR(_global); - var XHR_TASK = utils_1.zoneSymbol('xhrTask'); - function patchXHR(window) { - function findPendingTask(target) { - var pendingTask = target[XHR_TASK]; - return pendingTask; - } - function scheduleTask(task) { - var data = task.data; - data.target.addEventListener('readystatechange', function () { - if (data.target.readyState === data.target.DONE) { - if (!data.aborted) { - task.invoke(); - } - } - }); - var storedTask = data.target[XHR_TASK]; - if (!storedTask) { - data.target[XHR_TASK] = task; - } - setNative.apply(data.target, data.args); - return task; - } - function placeholderCallback() { - } - function clearTask(task) { - var data = task.data; - // Note - ideally, we would call data.target.removeEventListener here, but it's too late - // to prevent it from firing. So instead, we store info for the event listener. - data.aborted = true; - return clearNative.apply(data.target, data.args); - } - var setNative = utils_1.patchMethod(window.XMLHttpRequest.prototype, 'send', function () { return function (self, args) { - var zone = Zone.current; - var options = { - target: self, - isPeriodic: false, - delay: null, - args: args, - aborted: false - }; - return zone.scheduleMacroTask('XMLHttpRequest.send', placeholderCallback, options, scheduleTask, clearTask); - }; }); - var clearNative = utils_1.patchMethod(window.XMLHttpRequest.prototype, 'abort', function (delegate) { return function (self, args) { - var task = findPendingTask(self); - if (task && typeof task.type == 'string') { - // If the XHR has already completed, do nothing. - if (task.cancelFn == null) { - return; - } - task.zone.cancelTask(task); - } - // Otherwise, we are trying to abort an XHR which has not yet been sent, so there is no task to cancel. Do nothing. - }; }); - } - /// GEO_LOCATION - if (_global['navigator'] && _global['navigator'].geolocation) { - utils_1.patchPrototype(_global['navigator'].geolocation, [ - 'getCurrentPosition', - 'watchPosition' - ]); - } + function isUnconfigurable(obj, prop) { + return obj && obj[unconfigurablesKey] && obj[unconfigurablesKey][prop]; + } + function rewriteDescriptor(obj, prop, desc) { + desc.configurable = true; + if (!desc.configurable) { + if (!obj[unconfigurablesKey]) { + _defineProperty(obj, unconfigurablesKey, { writable: true, value: {} }); + } + obj[unconfigurablesKey][prop] = true; + } + return desc; + } + function _tryDefineProperty(obj, prop, desc, originalConfigurableFlag) { + try { + return _defineProperty(obj, prop, desc); + } + catch (e) { + if (desc.configurable) { + // In case of errors, when the configurable flag was likely set by rewriteDescriptor(), let's retry with the original flag value + if (typeof originalConfigurableFlag == 'undefined') { + delete desc.configurable; + } + else { + desc.configurable = originalConfigurableFlag; + } + try { + return _defineProperty(obj, prop, desc); + } + catch (e) { + var descJson = null; + try { + descJson = JSON.stringify(desc); + } + catch (e) { + descJson = descJson.toString(); + } + console.log("Attempting to configure '" + prop + "' with descriptor '" + descJson + "' on object '" + obj + "' and got error, giving up: " + e); + } + } + else { + throw e; + } + } + } - /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()))) + function registerElementPatch(_global) { + if (!isBrowser || !('registerElement' in _global.document)) { + return; + } + var _registerElement = document.registerElement; + var callbacks = [ + 'createdCallback', + 'attachedCallback', + 'detachedCallback', + 'attributeChangedCallback' + ]; + document.registerElement = function (name, opts) { + if (opts && opts.prototype) { + callbacks.forEach(function (callback) { + var source = 'Document.registerElement::' + callback; + if (opts.prototype.hasOwnProperty(callback)) { + var descriptor = Object.getOwnPropertyDescriptor(opts.prototype, callback); + if (descriptor && descriptor.value) { + descriptor.value = Zone.current.wrap(descriptor.value, source); + _redefineProperty(opts.prototype, callback, descriptor); + } + else { + opts.prototype[callback] = Zone.current.wrap(opts.prototype[callback], source); + } + } + else if (opts.prototype[callback]) { + opts.prototype[callback] = Zone.current.wrap(opts.prototype[callback], source); + } + }); + } + return _registerElement.apply(document, [name, opts]); + }; + } - /***/ }, - /* 1 */ - /***/ function(module, exports) { + // we have to patch the instance since the proto is non-configurable + function apply(_global) { + var WS = _global.WebSocket; + // On Safari window.EventTarget doesn't exist so need to patch WS add/removeEventListener + // On older Chrome, no need since EventTarget was already patched + if (!_global.EventTarget) { + patchEventTargetMethods(WS.prototype); + } + _global.WebSocket = function (a, b) { + var socket = arguments.length > 1 ? new WS(a, b) : new WS(a); + var proxySocket; + // Safari 7.0 has non-configurable own 'onmessage' and friends properties on the socket instance + var onmessageDesc = Object.getOwnPropertyDescriptor(socket, 'onmessage'); + if (onmessageDesc && onmessageDesc.configurable === false) { + proxySocket = Object.create(socket); + ['addEventListener', 'removeEventListener', 'send', 'close'].forEach(function (propName) { + proxySocket[propName] = function () { + return socket[propName].apply(socket, arguments); + }; + }); + } + else { + // we can patch the real socket + proxySocket = socket; + } + patchOnProperties(proxySocket, ['close', 'error', 'message', 'open']); + return proxySocket; + }; + for (var prop in WS) { + _global.WebSocket[prop] = WS[prop]; + } + } - /* WEBPACK VAR INJECTION */(function(global) {; - ; - var Zone = (function (global) { - if (global.Zone) { - throw new Error('Zone already loaded.'); - } - var Zone = (function () { - function Zone(parent, zoneSpec) { - this._properties = null; - this._parent = parent; - this._name = zoneSpec ? zoneSpec.name || 'unnamed' : ''; - this._properties = zoneSpec && zoneSpec.properties || {}; - this._zoneDelegate = new ZoneDelegate(this, this._parent && this._parent._zoneDelegate, zoneSpec); - } - Object.defineProperty(Zone, "current", { - get: function () { return _currentZone; }, - enumerable: true, - configurable: true - }); - ; - Object.defineProperty(Zone, "currentTask", { - get: function () { return _currentTask; }, - enumerable: true, - configurable: true - }); - ; - Object.defineProperty(Zone.prototype, "parent", { - get: function () { return this._parent; }, - enumerable: true, - configurable: true - }); - ; - Object.defineProperty(Zone.prototype, "name", { - get: function () { return this._name; }, - enumerable: true, - configurable: true - }); - ; - Zone.prototype.get = function (key) { - var zone = this.getZoneWith(key); - if (zone) - return zone._properties[key]; - }; - Zone.prototype.getZoneWith = function (key) { - var current = this; - while (current) { - if (current._properties.hasOwnProperty(key)) { - return current; - } - current = current._parent; - } - return null; - }; - Zone.prototype.fork = function (zoneSpec) { - if (!zoneSpec) - throw new Error('ZoneSpec required!'); - return this._zoneDelegate.fork(this, zoneSpec); - }; - Zone.prototype.wrap = function (callback, source) { - if (typeof callback !== 'function') { - throw new Error('Expecting function got: ' + callback); - } - var _callback = this._zoneDelegate.intercept(this, callback, source); - var zone = this; - return function () { - return zone.runGuarded(_callback, this, arguments, source); - }; - }; - Zone.prototype.run = function (callback, applyThis, applyArgs, source) { - if (applyThis === void 0) { applyThis = null; } - if (applyArgs === void 0) { applyArgs = null; } - if (source === void 0) { source = null; } - var oldZone = _currentZone; - _currentZone = this; - try { - return this._zoneDelegate.invoke(this, callback, applyThis, applyArgs, source); - } - finally { - _currentZone = oldZone; - } - }; - Zone.prototype.runGuarded = function (callback, applyThis, applyArgs, source) { - if (applyThis === void 0) { applyThis = null; } - if (applyArgs === void 0) { applyArgs = null; } - if (source === void 0) { source = null; } - var oldZone = _currentZone; - _currentZone = this; - try { - try { - return this._zoneDelegate.invoke(this, callback, applyThis, applyArgs, source); - } - catch (error) { - if (this._zoneDelegate.handleError(this, error)) { - throw error; - } - } - } - finally { - _currentZone = oldZone; - } - }; - Zone.prototype.runTask = function (task, applyThis, applyArgs) { - task.runCount++; - if (task.zone != this) - throw new Error('A task can only be run in the zone which created it! (Creation: ' + - task.zone.name + '; Execution: ' + this.name + ')'); - var previousTask = _currentTask; - _currentTask = task; - var oldZone = _currentZone; - _currentZone = this; - try { - if (task.type == 'macroTask' && task.data && !task.data.isPeriodic) { - task.cancelFn = null; - } - try { - return this._zoneDelegate.invokeTask(this, task, applyThis, applyArgs); - } - catch (error) { - if (this._zoneDelegate.handleError(this, error)) { - throw error; - } - } - } - finally { - _currentZone = oldZone; - _currentTask = previousTask; - } - }; - Zone.prototype.scheduleMicroTask = function (source, callback, data, customSchedule) { - return this._zoneDelegate.scheduleTask(this, new ZoneTask('microTask', this, source, callback, data, customSchedule, null)); - }; - Zone.prototype.scheduleMacroTask = function (source, callback, data, customSchedule, customCancel) { - return this._zoneDelegate.scheduleTask(this, new ZoneTask('macroTask', this, source, callback, data, customSchedule, customCancel)); - }; - Zone.prototype.scheduleEventTask = function (source, callback, data, customSchedule, customCancel) { - return this._zoneDelegate.scheduleTask(this, new ZoneTask('eventTask', this, source, callback, data, customSchedule, customCancel)); - }; - Zone.prototype.cancelTask = function (task) { - var value = this._zoneDelegate.cancelTask(this, task); - task.runCount = -1; - task.cancelFn = null; - return value; - }; - Zone.__symbol__ = __symbol__; - return Zone; - }()); - ; - var ZoneDelegate = (function () { - function ZoneDelegate(zone, parentDelegate, zoneSpec) { - this._taskCounts = { microTask: 0, macroTask: 0, eventTask: 0 }; - this.zone = zone; - this._parentDelegate = parentDelegate; - this._forkZS = zoneSpec && (zoneSpec && zoneSpec.onFork ? zoneSpec : parentDelegate._forkZS); - this._forkDlgt = zoneSpec && (zoneSpec.onFork ? parentDelegate : parentDelegate._forkDlgt); - this._interceptZS = zoneSpec && (zoneSpec.onIntercept ? zoneSpec : parentDelegate._interceptZS); - this._interceptDlgt = zoneSpec && (zoneSpec.onIntercept ? parentDelegate : parentDelegate._interceptDlgt); - this._invokeZS = zoneSpec && (zoneSpec.onInvoke ? zoneSpec : parentDelegate._invokeZS); - this._invokeDlgt = zoneSpec && (zoneSpec.onInvoke ? parentDelegate : parentDelegate._invokeDlgt); - this._handleErrorZS = zoneSpec && (zoneSpec.onHandleError ? zoneSpec : parentDelegate._handleErrorZS); - this._handleErrorDlgt = zoneSpec && (zoneSpec.onHandleError ? parentDelegate : parentDelegate._handleErrorDlgt); - this._scheduleTaskZS = zoneSpec && (zoneSpec.onScheduleTask ? zoneSpec : parentDelegate._scheduleTaskZS); - this._scheduleTaskDlgt = zoneSpec && (zoneSpec.onScheduleTask ? parentDelegate : parentDelegate._scheduleTaskDlgt); - this._invokeTaskZS = zoneSpec && (zoneSpec.onInvokeTask ? zoneSpec : parentDelegate._invokeTaskZS); - this._invokeTaskDlgt = zoneSpec && (zoneSpec.onInvokeTask ? parentDelegate : parentDelegate._invokeTaskDlgt); - this._cancelTaskZS = zoneSpec && (zoneSpec.onCancelTask ? zoneSpec : parentDelegate._cancelTaskZS); - this._cancelTaskDlgt = zoneSpec && (zoneSpec.onCancelTask ? parentDelegate : parentDelegate._cancelTaskDlgt); - this._hasTaskZS = zoneSpec && (zoneSpec.onHasTask ? zoneSpec : parentDelegate._hasTaskZS); - this._hasTaskDlgt = zoneSpec && (zoneSpec.onHasTask ? parentDelegate : parentDelegate._hasTaskDlgt); - } - ZoneDelegate.prototype.fork = function (targetZone, zoneSpec) { - return this._forkZS - ? this._forkZS.onFork(this._forkDlgt, this.zone, targetZone, zoneSpec) - : new Zone(targetZone, zoneSpec); - }; - ZoneDelegate.prototype.intercept = function (targetZone, callback, source) { - return this._interceptZS - ? this._interceptZS.onIntercept(this._interceptDlgt, this.zone, targetZone, callback, source) - : callback; - }; - ZoneDelegate.prototype.invoke = function (targetZone, callback, applyThis, applyArgs, source) { - return this._invokeZS - ? this._invokeZS.onInvoke(this._invokeDlgt, this.zone, targetZone, callback, applyThis, applyArgs, source) - : callback.apply(applyThis, applyArgs); - }; - ZoneDelegate.prototype.handleError = function (targetZone, error) { - return this._handleErrorZS - ? this._handleErrorZS.onHandleError(this._handleErrorDlgt, this.zone, targetZone, error) - : true; - }; - ZoneDelegate.prototype.scheduleTask = function (targetZone, task) { - try { - if (this._scheduleTaskZS) { - return this._scheduleTaskZS.onScheduleTask(this._scheduleTaskDlgt, this.zone, targetZone, task); - } - else if (task.scheduleFn) { - task.scheduleFn(task); - } - else if (task.type == 'microTask') { - scheduleMicroTask(task); - } - else { - throw new Error('Task is missing scheduleFn.'); - } - return task; - } - finally { - if (targetZone == this.zone) { - this._updateTaskCount(task.type, 1); - } - } - }; - ZoneDelegate.prototype.invokeTask = function (targetZone, task, applyThis, applyArgs) { - try { - return this._invokeTaskZS - ? this._invokeTaskZS.onInvokeTask(this._invokeTaskDlgt, this.zone, targetZone, task, applyThis, applyArgs) - : task.callback.apply(applyThis, applyArgs); - } - finally { - if (targetZone == this.zone && (task.type != 'eventTask') && !(task.data && task.data.isPeriodic)) { - this._updateTaskCount(task.type, -1); - } - } - }; - ZoneDelegate.prototype.cancelTask = function (targetZone, task) { - var value; - if (this._cancelTaskZS) { - value = this._cancelTaskZS.onCancelTask(this._cancelTaskDlgt, this.zone, targetZone, task); - } - else if (!task.cancelFn) { - throw new Error('Task does not support cancellation, or is already canceled.'); - } - else { - value = task.cancelFn(task); - } - if (targetZone == this.zone) { - // this should not be in the finally block, because exceptions assume not canceled. - this._updateTaskCount(task.type, -1); - } - return value; - }; - ZoneDelegate.prototype.hasTask = function (targetZone, isEmpty) { - return this._hasTaskZS && this._hasTaskZS.onHasTask(this._hasTaskDlgt, this.zone, targetZone, isEmpty); - }; - ZoneDelegate.prototype._updateTaskCount = function (type, count) { - var counts = this._taskCounts; - var prev = counts[type]; - var next = counts[type] = prev + count; - if (next < 0) { - throw new Error('More tasks executed then were scheduled.'); - } - if (prev == 0 || next == 0) { - var isEmpty = { - microTask: counts.microTask > 0, - macroTask: counts.macroTask > 0, - eventTask: counts.eventTask > 0, - change: type - }; - try { - this.hasTask(this.zone, isEmpty); - } - finally { - if (this._parentDelegate) { - this._parentDelegate._updateTaskCount(type, count); - } - } - } - }; - return ZoneDelegate; - }()); - var ZoneTask = (function () { - function ZoneTask(type, zone, source, callback, options, scheduleFn, cancelFn) { - this.runCount = 0; - this.type = type; - this.zone = zone; - this.source = source; - this.data = options; - this.scheduleFn = scheduleFn; - this.cancelFn = cancelFn; - this.callback = callback; - var self = this; - this.invoke = function () { - _numberOfNestedTaskFrames++; - try { - return zone.runTask(self, this, arguments); - } - finally { - if (_numberOfNestedTaskFrames == 1) { - drainMicroTaskQueue(); - } - _numberOfNestedTaskFrames--; - } - }; - } - ZoneTask.prototype.toString = function () { - if (this.data && typeof this.data.handleId !== 'undefined') { - return this.data.handleId; - } - else { - return this.toString(); - } - }; - return ZoneTask; - }()); - function __symbol__(name) { return '__zone_symbol__' + name; } - ; - var symbolSetTimeout = __symbol__('setTimeout'); - var symbolPromise = __symbol__('Promise'); - var symbolThen = __symbol__('then'); - var _currentZone = new Zone(null, null); - var _currentTask = null; - var _microTaskQueue = []; - var _isDrainingMicrotaskQueue = false; - var _uncaughtPromiseErrors = []; - var _numberOfNestedTaskFrames = 0; - function scheduleQueueDrain() { - // if we are not running in any task, and there has not been anything scheduled - // we must bootstrap the initial task creation by manually scheduling the drain - if (_numberOfNestedTaskFrames == 0 && _microTaskQueue.length == 0) { - // We are not running in Task, so we need to kickstart the microtask queue. - if (global[symbolPromise]) { - global[symbolPromise].resolve(0)[symbolThen](drainMicroTaskQueue); - } - else { - global[symbolSetTimeout](drainMicroTaskQueue, 0); - } - } - } - function scheduleMicroTask(task) { - scheduleQueueDrain(); - _microTaskQueue.push(task); - } - function consoleError(e) { - var rejection = e && e.rejection; - if (rejection) { - console.error('Unhandled Promise rejection:', rejection instanceof Error ? rejection.message : rejection, '; Zone:', e.zone.name, '; Task:', e.task && e.task.source, '; Value:', rejection, rejection instanceof Error ? rejection.stack : undefined); - } - console.error(e); - } - function drainMicroTaskQueue() { - if (!_isDrainingMicrotaskQueue) { - _isDrainingMicrotaskQueue = true; - while (_microTaskQueue.length) { - var queue = _microTaskQueue; - _microTaskQueue = []; - for (var i = 0; i < queue.length; i++) { - var task = queue[i]; - try { - task.zone.runTask(task, null, null); - } - catch (e) { - consoleError(e); - } - } - } - while (_uncaughtPromiseErrors.length) { - var _loop_1 = function() { - var uncaughtPromiseError = _uncaughtPromiseErrors.shift(); - try { - uncaughtPromiseError.zone.runGuarded(function () { throw uncaughtPromiseError; }); - } - catch (e) { - consoleError(e); - } - }; - while (_uncaughtPromiseErrors.length) { - _loop_1(); - } - } - _isDrainingMicrotaskQueue = false; - } - } - function isThenable(value) { - return value && value.then; - } - function forwardResolution(value) { return value; } - function forwardRejection(rejection) { return ZoneAwarePromise.reject(rejection); } - var symbolState = __symbol__('state'); - var symbolValue = __symbol__('value'); - var source = 'Promise.then'; - var UNRESOLVED = null; - var RESOLVED = true; - var REJECTED = false; - var REJECTED_NO_CATCH = 0; - function makeResolver(promise, state) { - return function (v) { - resolvePromise(promise, state, v); - // Do not return value or you will break the Promise spec. - }; - } - function resolvePromise(promise, state, value) { - if (promise[symbolState] === UNRESOLVED) { - if (value instanceof ZoneAwarePromise && value[symbolState] !== UNRESOLVED) { - clearRejectedNoCatch(value); - resolvePromise(promise, value[symbolState], value[symbolValue]); - } - else if (isThenable(value)) { - value.then(makeResolver(promise, state), makeResolver(promise, false)); - } - else { - promise[symbolState] = state; - var queue = promise[symbolValue]; - promise[symbolValue] = value; - for (var i = 0; i < queue.length;) { - scheduleResolveOrReject(promise, queue[i++], queue[i++], queue[i++], queue[i++]); - } - if (queue.length == 0 && state == REJECTED) { - promise[symbolState] = REJECTED_NO_CATCH; - try { - throw new Error("Uncaught (in promise): " + value); - } - catch (e) { - var error = e; - error.rejection = value; - error.promise = promise; - error.zone = Zone.current; - error.task = Zone.currentTask; - _uncaughtPromiseErrors.push(error); - scheduleQueueDrain(); - } - } - } - } - // Resolving an already resolved promise is a noop. - return promise; - } - function clearRejectedNoCatch(promise) { - if (promise[symbolState] === REJECTED_NO_CATCH) { - promise[symbolState] = REJECTED; - for (var i = 0; i < _uncaughtPromiseErrors.length; i++) { - if (promise === _uncaughtPromiseErrors[i].promise) { - _uncaughtPromiseErrors.splice(i, 1); - break; - } - } - } - } - function scheduleResolveOrReject(promise, zone, chainPromise, onFulfilled, onRejected) { - clearRejectedNoCatch(promise); - var delegate = promise[symbolState] ? onFulfilled || forwardResolution : onRejected || forwardRejection; - zone.scheduleMicroTask(source, function () { - try { - resolvePromise(chainPromise, true, zone.run(delegate, null, [promise[symbolValue]])); - } - catch (error) { - resolvePromise(chainPromise, false, error); - } - }); - } - var ZoneAwarePromise = (function () { - function ZoneAwarePromise(executor) { - var promise = this; - if (!(promise instanceof ZoneAwarePromise)) { - throw new Error('Must be an instanceof Promise.'); - } - promise[symbolState] = UNRESOLVED; - promise[symbolValue] = []; // queue; - try { - executor && executor(makeResolver(promise, RESOLVED), makeResolver(promise, REJECTED)); - } - catch (e) { - resolvePromise(promise, false, e); - } - } - ZoneAwarePromise.resolve = function (value) { - return resolvePromise(new this(null), RESOLVED, value); - }; - ZoneAwarePromise.reject = function (error) { - return resolvePromise(new this(null), REJECTED, error); - }; - ZoneAwarePromise.race = function (values) { - var resolve; - var reject; - var promise = new this(function (res, rej) { resolve = res; reject = rej; }); - function onResolve(value) { promise && (promise = null || resolve(value)); } - function onReject(error) { promise && (promise = null || reject(error)); } - for (var _i = 0, values_1 = values; _i < values_1.length; _i++) { - var value = values_1[_i]; - if (!isThenable(value)) { - value = this.resolve(value); - } - value.then(onResolve, onReject); - } - return promise; - }; - ZoneAwarePromise.all = function (values) { - var resolve; - var reject; - var promise = new this(function (res, rej) { resolve = res; reject = rej; }); - var count = 0; - var resolvedValues = []; - function onReject(error) { promise && reject(error); promise = null; } - for (var _i = 0, values_2 = values; _i < values_2.length; _i++) { - var value = values_2[_i]; - if (!isThenable(value)) { - value = this.resolve(value); - } - value.then((function (index) { return function (value) { - resolvedValues[index] = value; - count--; - if (promise && !count) { - resolve(resolvedValues); - } - promise == null; - }; })(count), onReject); - count++; - } - if (!count) - resolve(resolvedValues); - return promise; - }; - ZoneAwarePromise.prototype.then = function (onFulfilled, onRejected) { - var chainPromise = new this.constructor(null); - var zone = Zone.current; - if (this[symbolState] == UNRESOLVED) { - this[symbolValue].push(zone, chainPromise, onFulfilled, onRejected); - } - else { - scheduleResolveOrReject(this, zone, chainPromise, onFulfilled, onRejected); - } - return chainPromise; - }; - ZoneAwarePromise.prototype.catch = function (onRejected) { - return this.then(null, onRejected); - }; - return ZoneAwarePromise; - }()); - var NativePromise = global[__symbol__('Promise')] = global.Promise; - global.Promise = ZoneAwarePromise; - if (NativePromise) { - var NativePromiseProtototype = NativePromise.prototype; - var NativePromiseThen_1 = NativePromiseProtototype[__symbol__('then')] - = NativePromiseProtototype.then; - NativePromiseProtototype.then = function (onResolve, onReject) { - var nativePromise = this; - return new ZoneAwarePromise(function (resolve, reject) { - NativePromiseThen_1.call(nativePromise, resolve, reject); - }).then(onResolve, onReject); - }; - } - // This is not part of public API, but it is usefull for tests, so we expose it. - Promise[Zone.__symbol__('uncaughtPromiseErrors')] = _uncaughtPromiseErrors; - return global.Zone = Zone; - })(typeof window === 'undefined' ? global : window); + var eventNames = 'copy cut paste abort blur focus canplay canplaythrough change click contextmenu dblclick drag dragend dragenter dragleave dragover dragstart drop durationchange emptied ended input invalid keydown keypress keyup load loadeddata loadedmetadata loadstart message mousedown mouseenter mouseleave mousemove mouseout mouseover mouseup pause play playing progress ratechange reset scroll seeked seeking select show stalled submit suspend timeupdate volumechange waiting mozfullscreenchange mozfullscreenerror mozpointerlockchange mozpointerlockerror error webglcontextrestored webglcontextlost webglcontextcreationerror'.split(' '); + function propertyDescriptorPatch(_global) { + if (isNode) { + return; + } + var supportsWebSocket = typeof WebSocket !== 'undefined'; + if (canPatchViaPropertyDescriptor()) { + // for browsers that we can patch the descriptor: Chrome & Firefox + if (isBrowser) { + patchOnProperties(HTMLElement.prototype, eventNames); + } + patchOnProperties(XMLHttpRequest.prototype, null); + if (typeof IDBIndex !== 'undefined') { + patchOnProperties(IDBIndex.prototype, null); + patchOnProperties(IDBRequest.prototype, null); + patchOnProperties(IDBOpenDBRequest.prototype, null); + patchOnProperties(IDBDatabase.prototype, null); + patchOnProperties(IDBTransaction.prototype, null); + patchOnProperties(IDBCursor.prototype, null); + } + if (supportsWebSocket) { + patchOnProperties(WebSocket.prototype, null); + } + } + else { + // Safari, Android browsers (Jelly Bean) + patchViaCapturingAllTheEvents(); + patchClass('XMLHttpRequest'); + if (supportsWebSocket) { + apply(_global); + } + } + } + function canPatchViaPropertyDescriptor() { + if (isBrowser && !Object.getOwnPropertyDescriptor(HTMLElement.prototype, 'onclick') + && typeof Element !== 'undefined') { + // WebKit https://bugs.webkit.org/show_bug.cgi?id=134364 + // IDL interface attributes are not configurable + var desc = Object.getOwnPropertyDescriptor(Element.prototype, 'onclick'); + if (desc && !desc.configurable) + return false; + } + Object.defineProperty(XMLHttpRequest.prototype, 'onreadystatechange', { + get: function () { + return true; + } + }); + var req = new XMLHttpRequest(); + var result = !!req.onreadystatechange; + Object.defineProperty(XMLHttpRequest.prototype, 'onreadystatechange', {}); + return result; + } - /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()))) + var unboundKey = zoneSymbol('unbound'); + // Whenever any eventListener fires, we check the eventListener target and all parents + // for `onwhatever` properties and replace them with zone-bound functions + // - Chrome (for now) + function patchViaCapturingAllTheEvents() { + var _loop_1 = function(i) { + var property = eventNames[i]; + var onproperty = 'on' + property; + document.addEventListener(property, function (event) { + var elt = event.target, bound, source; + if (elt) { + source = elt.constructor['name'] + '.' + onproperty; + } + else { + source = 'unknown.' + onproperty; + } + while (elt) { + if (elt[onproperty] && !elt[onproperty][unboundKey]) { + bound = Zone.current.wrap(elt[onproperty], source); + bound[unboundKey] = elt[onproperty]; + elt[onproperty] = bound; + } + elt = elt.parentElement; + } + }, true); + }; + for (var i = 0; i < eventNames.length; i++) { + _loop_1(i); + } + + } - /***/ }, - /* 2 */ - /***/ function(module, exports, __webpack_require__) { + function patchTimer(window, setName, cancelName, nameSuffix) { + var setNative = null; + var clearNative = null; + setName += nameSuffix; + cancelName += nameSuffix; + function scheduleTask(task) { + var data = task.data; + data.args[0] = task.invoke; + data.handleId = setNative.apply(window, data.args); + return task; + } + function clearTask(task) { + return clearNative(task.data.handleId); + } + setNative = patchMethod(window, setName, function (delegate) { return function (self, args) { + if (typeof args[0] === 'function') { + var zone = Zone.current; + var options = { + handleId: null, + isPeriodic: nameSuffix === 'Interval', + delay: (nameSuffix === 'Timeout' || nameSuffix === 'Interval') ? args[1] || 0 : null, + args: args + }; + var task = zone.scheduleMacroTask(setName, args[0], options, scheduleTask, clearTask); + if (!task) { + return task; + } + // Node.js must additionally support the ref and unref functions. + var handle = task.data.handleId; + if (handle.ref && handle.unref) { + task.ref = handle.ref.bind(handle); + task.unref = handle.unref.bind(handle); + } + return task; + } + else { + // cause an error by calling it directly. + return delegate.apply(window, args); + } + }; }); + clearNative = patchMethod(window, cancelName, function (delegate) { return function (self, args) { + var task = args[0]; + if (task && typeof task.type === 'string') { + if (task.cancelFn && task.data.isPeriodic || task.runCount === 0) { + // Do not cancel already canceled functions + task.zone.cancelTask(task); + } + } + else { + // cause an error by calling it directly. + delegate.apply(window, args); + } + }; }); + } - "use strict"; - var utils_1 = __webpack_require__(3); - var WTF_ISSUE_555 = 'Anchor,Area,Audio,BR,Base,BaseFont,Body,Button,Canvas,Content,DList,Directory,Div,Embed,FieldSet,Font,Form,Frame,FrameSet,HR,Head,Heading,Html,IFrame,Image,Input,Keygen,LI,Label,Legend,Link,Map,Marquee,Media,Menu,Meta,Meter,Mod,OList,Object,OptGroup,Option,Output,Paragraph,Pre,Progress,Quote,Script,Select,Source,Span,Style,TableCaption,TableCell,TableCol,Table,TableRow,TableSection,TextArea,Title,Track,UList,Unknown,Video'; - var NO_EVENT_TARGET = 'ApplicationCache,EventSource,FileReader,InputMethodContext,MediaController,MessagePort,Node,Performance,SVGElementInstance,SharedWorker,TextTrack,TextTrackCue,TextTrackList,WebKitNamedFlow,Window,Worker,WorkerGlobalScope,XMLHttpRequest,XMLHttpRequestEventTarget,XMLHttpRequestUpload,IDBRequest,IDBOpenDBRequest,IDBDatabase,IDBTransaction,IDBCursor,DBIndex'.split(','); - var EVENT_TARGET = 'EventTarget'; - function eventTargetPatch(_global) { - var apis = []; - var isWtf = _global['wtf']; - if (isWtf) { - // Workaround for: https://github.com/google/tracing-framework/issues/555 - apis = WTF_ISSUE_555.split(',').map(function (v) { return 'HTML' + v + 'Element'; }).concat(NO_EVENT_TARGET); - } - else if (_global[EVENT_TARGET]) { - apis.push(EVENT_TARGET); - } - else { - // Note: EventTarget is not available in all browsers, - // if it's not available, we instead patch the APIs in the IDL that inherit from EventTarget - apis = NO_EVENT_TARGET; - } - for (var i = 0; i < apis.length; i++) { - var type = _global[apis[i]]; - utils_1.patchEventTargetMethods(type && type.prototype); - } - } - exports.eventTargetPatch = eventTargetPatch; + var set = 'set'; + var clear = 'clear'; + var blockingMethods = ['alert', 'prompt', 'confirm']; + var _global = typeof window === 'object' && window || typeof self === 'object' && self || global; + patchTimer(_global, set, clear, 'Timeout'); + patchTimer(_global, set, clear, 'Interval'); + patchTimer(_global, set, clear, 'Immediate'); + patchTimer(_global, 'request', 'cancel', 'AnimationFrame'); + patchTimer(_global, 'mozRequest', 'mozCancel', 'AnimationFrame'); + patchTimer(_global, 'webkitRequest', 'webkitCancel', 'AnimationFrame'); + for (var i = 0; i < blockingMethods.length; i++) { + var name = blockingMethods[i]; + patchMethod(_global, name, function (delegate, symbol, name) { + return function (s, args) { + return Zone.current.run(delegate, _global, args, name); + }; + }); + } + eventTargetPatch(_global); + propertyDescriptorPatch(_global); + patchClass('MutationObserver'); + patchClass('WebKitMutationObserver'); + patchClass('FileReader'); + propertyPatch(); + registerElementPatch(_global); + // Treat XMLHTTPRequest as a macrotask. + patchXHR(_global); + var XHR_TASK = zoneSymbol('xhrTask'); + var XHR_SYNC = zoneSymbol('xhrSync'); + function patchXHR(window) { + function findPendingTask(target) { + var pendingTask = target[XHR_TASK]; + return pendingTask; + } + function scheduleTask(task) { + var data = task.data; + data.target.addEventListener('readystatechange', function () { + if (data.target.readyState === data.target.DONE) { + if (!data.aborted) { + task.invoke(); + } + } + }); + var storedTask = data.target[XHR_TASK]; + if (!storedTask) { + data.target[XHR_TASK] = task; + } + sendNative.apply(data.target, data.args); + return task; + } + function placeholderCallback() { + } + function clearTask(task) { + var data = task.data; + // Note - ideally, we would call data.target.removeEventListener here, but it's too late + // to prevent it from firing. So instead, we store info for the event listener. + data.aborted = true; + return abortNative.apply(data.target, data.args); + } + var openNative = patchMethod(window.XMLHttpRequest.prototype, 'open', function () { return function (self, args) { + self[XHR_SYNC] = args[2] == false; + return openNative.apply(self, args); + }; }); + var sendNative = patchMethod(window.XMLHttpRequest.prototype, 'send', function () { return function (self, args) { + var zone = Zone.current; + if (self[XHR_SYNC]) { + // if the XHR is sync there is no task to schedule, just execute the code. + return sendNative.apply(self, args); + } + else { + var options = { + target: self, + isPeriodic: false, + delay: null, + args: args, + aborted: false + }; + return zone.scheduleMacroTask('XMLHttpRequest.send', placeholderCallback, options, scheduleTask, clearTask); + } + }; }); + var abortNative = patchMethod(window.XMLHttpRequest.prototype, 'abort', function (delegate) { return function (self, args) { + var task = findPendingTask(self); + if (task && typeof task.type == 'string') { + // If the XHR has already completed, do nothing. + if (task.cancelFn == null) { + return; + } + task.zone.cancelTask(task); + } + // Otherwise, we are trying to abort an XHR which has not yet been sent, so there is no task to cancel. Do nothing. + }; }); + } + /// GEO_LOCATION + if (_global['navigator'] && _global['navigator'].geolocation) { + patchPrototype(_global['navigator'].geolocation, [ + 'getCurrentPosition', + 'watchPosition' + ]); + } + }))); - /***/ }, - /* 3 */ - /***/ function(module, exports) { - - /* WEBPACK VAR INJECTION */(function(global) {/** - * Suppress closure compiler errors about unknown 'process' variable - * @fileoverview - * @suppress {undefinedVars} - */ - "use strict"; - exports.zoneSymbol = Zone['__symbol__']; - var _global = typeof window == 'undefined' ? global : window; - function bindArguments(args, source) { - for (var i = args.length - 1; i >= 0; i--) { - if (typeof args[i] === 'function') { - args[i] = Zone.current.wrap(args[i], source + '_' + i); - } - } - return args; - } - exports.bindArguments = bindArguments; - ; - function patchPrototype(prototype, fnNames) { - var source = prototype.constructor['name']; - var _loop_1 = function(i) { - var name_1 = fnNames[i]; - var delegate = prototype[name_1]; - if (delegate) { - prototype[name_1] = (function (delegate) { - return function () { - return delegate.apply(this, bindArguments(arguments, source + '.' + name_1)); - }; - })(delegate); - } - }; - for (var i = 0; i < fnNames.length; i++) { - _loop_1(i); - } - } - exports.patchPrototype = patchPrototype; - ; - exports.isWebWorker = (typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope); - exports.isNode = (typeof process !== 'undefined' && {}.toString.call(process) === '[object process]'); - exports.isBrowser = !exports.isNode && !exports.isWebWorker && !!(typeof window !== 'undefined' && window['HTMLElement']); - function patchProperty(obj, prop) { - var desc = Object.getOwnPropertyDescriptor(obj, prop) || { - enumerable: true, - configurable: true - }; - // A property descriptor cannot have getter/setter and be writable - // deleting the writable and value properties avoids this error: - // - // TypeError: property descriptors must not specify a value or be writable when a - // getter or setter has been specified - delete desc.writable; - delete desc.value; - // substr(2) cuz 'onclick' -> 'click', etc - var eventName = prop.substr(2); - var _prop = '_' + prop; - desc.set = function (fn) { - if (this[_prop]) { - this.removeEventListener(eventName, this[_prop]); - } - if (typeof fn === 'function') { - var wrapFn = function (event) { - var result; - result = fn.apply(this, arguments); - if (result != undefined && !result) - event.preventDefault(); - }; - this[_prop] = wrapFn; - this.addEventListener(eventName, wrapFn, false); - } - else { - this[_prop] = null; - } - }; - // The getter would return undefined for unassigned properties but the default value of an unassigned property is null - desc.get = function () { - return this[_prop] || null; - }; - Object.defineProperty(obj, prop, desc); - } - exports.patchProperty = patchProperty; - ; - function patchOnProperties(obj, properties) { - var onProperties = []; - for (var prop in obj) { - if (prop.substr(0, 2) == 'on') { - onProperties.push(prop); - } - } - for (var j = 0; j < onProperties.length; j++) { - patchProperty(obj, onProperties[j]); - } - if (properties) { - for (var i = 0; i < properties.length; i++) { - patchProperty(obj, 'on' + properties[i]); - } - } - } - exports.patchOnProperties = patchOnProperties; - ; - var EVENT_TASKS = exports.zoneSymbol('eventTasks'); - var ADD_EVENT_LISTENER = 'addEventListener'; - var REMOVE_EVENT_LISTENER = 'removeEventListener'; - var SYMBOL_ADD_EVENT_LISTENER = exports.zoneSymbol(ADD_EVENT_LISTENER); - var SYMBOL_REMOVE_EVENT_LISTENER = exports.zoneSymbol(REMOVE_EVENT_LISTENER); - function findExistingRegisteredTask(target, handler, name, capture, remove) { - var eventTasks = target[EVENT_TASKS]; - if (eventTasks) { - for (var i = 0; i < eventTasks.length; i++) { - var eventTask = eventTasks[i]; - var data = eventTask.data; - if (data.handler === handler - && data.useCapturing === capture - && data.eventName === name) { - if (remove) { - eventTasks.splice(i, 1); - } - return eventTask; - } - } - } - return null; - } - function attachRegisteredEvent(target, eventTask) { - var eventTasks = target[EVENT_TASKS]; - if (!eventTasks) { - eventTasks = target[EVENT_TASKS] = []; - } - eventTasks.push(eventTask); - } - function scheduleEventListener(eventTask) { - var meta = eventTask.data; - attachRegisteredEvent(meta.target, eventTask); - return meta.target[SYMBOL_ADD_EVENT_LISTENER](meta.eventName, eventTask.invoke, meta.useCapturing); - } - function cancelEventListener(eventTask) { - var meta = eventTask.data; - findExistingRegisteredTask(meta.target, eventTask.invoke, meta.eventName, meta.useCapturing, true); - meta.target[SYMBOL_REMOVE_EVENT_LISTENER](meta.eventName, eventTask.invoke, meta.useCapturing); - } - function zoneAwareAddEventListener(self, args) { - var eventName = args[0]; - var handler = args[1]; - var useCapturing = args[2] || false; - // - Inside a Web Worker, `this` is undefined, the context is `global` - // - When `addEventListener` is called on the global context in strict mode, `this` is undefined - // see https://github.com/angular/zone.js/issues/190 - var target = self || _global; - var delegate = null; - if (typeof handler == 'function') { - delegate = handler; - } - else if (handler && handler.handleEvent) { - delegate = function (event) { return handler.handleEvent(event); }; - } - var validZoneHandler = false; - try { - // In cross site contexts (such as WebDriver frameworks like Selenium), - // accessing the handler object here will cause an exception to be thrown which - // will fail tests prematurely. - validZoneHandler = handler && handler.toString() === "[object FunctionWrapper]"; - } - catch (e) { - // Returning nothing here is fine, because objects in a cross-site context are unusable - return; - } - // Ignore special listeners of IE11 & Edge dev tools, see https://github.com/angular/zone.js/issues/150 - if (!delegate || validZoneHandler) { - return target[SYMBOL_ADD_EVENT_LISTENER](eventName, handler, useCapturing); - } - var eventTask = findExistingRegisteredTask(target, handler, eventName, useCapturing, false); - if (eventTask) { - // we already registered, so this will have noop. - return target[SYMBOL_ADD_EVENT_LISTENER](eventName, eventTask.invoke, useCapturing); - } - var zone = Zone.current; - var source = target.constructor['name'] + '.addEventListener:' + eventName; - var data = { - target: target, - eventName: eventName, - name: eventName, - useCapturing: useCapturing, - handler: handler - }; - zone.scheduleEventTask(source, delegate, data, scheduleEventListener, cancelEventListener); - } - function zoneAwareRemoveEventListener(self, args) { - var eventName = args[0]; - var handler = args[1]; - var useCapturing = args[2] || false; - // - Inside a Web Worker, `this` is undefined, the context is `global` - // - When `addEventListener` is called on the global context in strict mode, `this` is undefined - // see https://github.com/angular/zone.js/issues/190 - var target = self || _global; - var eventTask = findExistingRegisteredTask(target, handler, eventName, useCapturing, true); - if (eventTask) { - eventTask.zone.cancelTask(eventTask); - } - else { - target[SYMBOL_REMOVE_EVENT_LISTENER](eventName, handler, useCapturing); - } - } - function patchEventTargetMethods(obj) { - if (obj && obj.addEventListener) { - patchMethod(obj, ADD_EVENT_LISTENER, function () { return zoneAwareAddEventListener; }); - patchMethod(obj, REMOVE_EVENT_LISTENER, function () { return zoneAwareRemoveEventListener; }); - return true; - } - else { - return false; - } - } - exports.patchEventTargetMethods = patchEventTargetMethods; - ; - var originalInstanceKey = exports.zoneSymbol('originalInstance'); - // wrap some native API on `window` - function patchClass(className) { - var OriginalClass = _global[className]; - if (!OriginalClass) - return; - _global[className] = function () { - var a = bindArguments(arguments, className); - switch (a.length) { - case 0: - this[originalInstanceKey] = new OriginalClass(); - break; - case 1: - this[originalInstanceKey] = new OriginalClass(a[0]); - break; - case 2: - this[originalInstanceKey] = new OriginalClass(a[0], a[1]); - break; - case 3: - this[originalInstanceKey] = new OriginalClass(a[0], a[1], a[2]); - break; - case 4: - this[originalInstanceKey] = new OriginalClass(a[0], a[1], a[2], a[3]); - break; - default: throw new Error('Arg list too long.'); - } - }; - var instance = new OriginalClass(function () { }); - var prop; - for (prop in instance) { - // https://bugs.webkit.org/show_bug.cgi?id=44721 - if (className === 'XMLHttpRequest' && prop === 'responseBlob') - continue; - (function (prop) { - if (typeof instance[prop] === 'function') { - _global[className].prototype[prop] = function () { - return this[originalInstanceKey][prop].apply(this[originalInstanceKey], arguments); - }; - } - else { - Object.defineProperty(_global[className].prototype, prop, { - set: function (fn) { - if (typeof fn === 'function') { - this[originalInstanceKey][prop] = Zone.current.wrap(fn, className + '.' + prop); - } - else { - this[originalInstanceKey][prop] = fn; - } - }, - get: function () { - return this[originalInstanceKey][prop]; - } - }); - } - }(prop)); - } - for (prop in OriginalClass) { - if (prop !== 'prototype' && OriginalClass.hasOwnProperty(prop)) { - _global[className][prop] = OriginalClass[prop]; - } - } - } - exports.patchClass = patchClass; - ; - function createNamedFn(name, delegate) { - try { - return (Function('f', "return function " + name + "(){return f(this, arguments)}"))(delegate); - } - catch (e) { - // if we fail, we must be CSP, just return delegate. - return function () { - return delegate(this, arguments); - }; - } - } - exports.createNamedFn = createNamedFn; - function patchMethod(target, name, patchFn) { - var proto = target; - while (proto && !proto.hasOwnProperty(name)) { - proto = Object.getPrototypeOf(proto); - } - if (!proto && target[name]) { - // somehow we did not find it, but we can see it. This happens on IE for Window properties. - proto = target; - } - var delegateName = exports.zoneSymbol(name); - var delegate; - if (proto && !(delegate = proto[delegateName])) { - delegate = proto[delegateName] = proto[name]; - proto[name] = createNamedFn(name, patchFn(delegate, delegateName, name)); - } - return delegate; - } - exports.patchMethod = patchMethod; - - /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()))) - - /***/ }, - /* 4 */ - /***/ function(module, exports, __webpack_require__) { - - "use strict"; - var utils_1 = __webpack_require__(3); - /* - * This is necessary for Chrome and Chrome mobile, to enable - * things like redefining `createdCallback` on an element. - */ - var _defineProperty = Object.defineProperty; - var _getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor; - var _create = Object.create; - var unconfigurablesKey = utils_1.zoneSymbol('unconfigurables'); - function propertyPatch() { - Object.defineProperty = function (obj, prop, desc) { - if (isUnconfigurable(obj, prop)) { - throw new TypeError('Cannot assign to read only property \'' + prop + '\' of ' + obj); - } - var originalConfigurableFlag = desc.configurable; - if (prop !== 'prototype') { - desc = rewriteDescriptor(obj, prop, desc); - } - return _tryDefineProperty(obj, prop, desc, originalConfigurableFlag); - }; - Object.defineProperties = function (obj, props) { - Object.keys(props).forEach(function (prop) { - Object.defineProperty(obj, prop, props[prop]); - }); - return obj; - }; - Object.create = function (obj, proto) { - if (typeof proto === 'object' && !Object.isFrozen(proto)) { - Object.keys(proto).forEach(function (prop) { - proto[prop] = rewriteDescriptor(obj, prop, proto[prop]); - }); - } - return _create(obj, proto); - }; - Object.getOwnPropertyDescriptor = function (obj, prop) { - var desc = _getOwnPropertyDescriptor(obj, prop); - if (isUnconfigurable(obj, prop)) { - desc.configurable = false; - } - return desc; - }; - } - exports.propertyPatch = propertyPatch; - ; - function _redefineProperty(obj, prop, desc) { - var originalConfigurableFlag = desc.configurable; - desc = rewriteDescriptor(obj, prop, desc); - return _tryDefineProperty(obj, prop, desc, originalConfigurableFlag); - } - exports._redefineProperty = _redefineProperty; - ; - function isUnconfigurable(obj, prop) { - return obj && obj[unconfigurablesKey] && obj[unconfigurablesKey][prop]; - } - function rewriteDescriptor(obj, prop, desc) { - desc.configurable = true; - if (!desc.configurable) { - if (!obj[unconfigurablesKey]) { - _defineProperty(obj, unconfigurablesKey, { writable: true, value: {} }); - } - obj[unconfigurablesKey][prop] = true; - } - return desc; - } - function _tryDefineProperty(obj, prop, desc, originalConfigurableFlag) { - try { - return _defineProperty(obj, prop, desc); - } - catch (e) { - if (desc.configurable) { - // In case of errors, when the configurable flag was likely set by rewriteDescriptor(), let's retry with the original flag value - if (typeof originalConfigurableFlag == 'undefined') { - delete desc.configurable; - } - else { - desc.configurable = originalConfigurableFlag; - } - return _defineProperty(obj, prop, desc); - } - else { - throw e; - } - } - } - - - /***/ }, - /* 5 */ - /***/ function(module, exports, __webpack_require__) { - - "use strict"; - var define_property_1 = __webpack_require__(4); - var utils_1 = __webpack_require__(3); - function registerElementPatch(_global) { - if (!utils_1.isBrowser || !('registerElement' in _global.document)) { - return; - } - var _registerElement = document.registerElement; - var callbacks = [ - 'createdCallback', - 'attachedCallback', - 'detachedCallback', - 'attributeChangedCallback' - ]; - document.registerElement = function (name, opts) { - if (opts && opts.prototype) { - callbacks.forEach(function (callback) { - var source = 'Document.registerElement::' + callback; - if (opts.prototype.hasOwnProperty(callback)) { - var descriptor = Object.getOwnPropertyDescriptor(opts.prototype, callback); - if (descriptor && descriptor.value) { - descriptor.value = Zone.current.wrap(descriptor.value, source); - define_property_1._redefineProperty(opts.prototype, callback, descriptor); - } - else { - opts.prototype[callback] = Zone.current.wrap(opts.prototype[callback], source); - } - } - else if (opts.prototype[callback]) { - opts.prototype[callback] = Zone.current.wrap(opts.prototype[callback], source); - } - }); - } - return _registerElement.apply(document, [name, opts]); - }; - } - exports.registerElementPatch = registerElementPatch; - - - /***/ }, - /* 6 */ - /***/ function(module, exports, __webpack_require__) { - - "use strict"; - var webSocketPatch = __webpack_require__(7); - var utils_1 = __webpack_require__(3); - var eventNames = 'copy cut paste abort blur focus canplay canplaythrough change click contextmenu dblclick drag dragend dragenter dragleave dragover dragstart drop durationchange emptied ended input invalid keydown keypress keyup load loadeddata loadedmetadata loadstart message mousedown mouseenter mouseleave mousemove mouseout mouseover mouseup pause play playing progress ratechange reset scroll seeked seeking select show stalled submit suspend timeupdate volumechange waiting mozfullscreenchange mozfullscreenerror mozpointerlockchange mozpointerlockerror error webglcontextrestored webglcontextlost webglcontextcreationerror'.split(' '); - function propertyDescriptorPatch(_global) { - if (utils_1.isNode) { - return; - } - var supportsWebSocket = typeof WebSocket !== 'undefined'; - if (canPatchViaPropertyDescriptor()) { - // for browsers that we can patch the descriptor: Chrome & Firefox - if (utils_1.isBrowser) { - utils_1.patchOnProperties(HTMLElement.prototype, eventNames); - } - utils_1.patchOnProperties(XMLHttpRequest.prototype, null); - if (typeof IDBIndex !== 'undefined') { - utils_1.patchOnProperties(IDBIndex.prototype, null); - utils_1.patchOnProperties(IDBRequest.prototype, null); - utils_1.patchOnProperties(IDBOpenDBRequest.prototype, null); - utils_1.patchOnProperties(IDBDatabase.prototype, null); - utils_1.patchOnProperties(IDBTransaction.prototype, null); - utils_1.patchOnProperties(IDBCursor.prototype, null); - } - if (supportsWebSocket) { - utils_1.patchOnProperties(WebSocket.prototype, null); - } - } - else { - // Safari, Android browsers (Jelly Bean) - patchViaCapturingAllTheEvents(); - utils_1.patchClass('XMLHttpRequest'); - if (supportsWebSocket) { - webSocketPatch.apply(_global); - } - } - } - exports.propertyDescriptorPatch = propertyDescriptorPatch; - function canPatchViaPropertyDescriptor() { - if (utils_1.isBrowser && !Object.getOwnPropertyDescriptor(HTMLElement.prototype, 'onclick') - && typeof Element !== 'undefined') { - // WebKit https://bugs.webkit.org/show_bug.cgi?id=134364 - // IDL interface attributes are not configurable - var desc = Object.getOwnPropertyDescriptor(Element.prototype, 'onclick'); - if (desc && !desc.configurable) - return false; - } - Object.defineProperty(XMLHttpRequest.prototype, 'onreadystatechange', { - get: function () { - return true; - } - }); - var req = new XMLHttpRequest(); - var result = !!req.onreadystatechange; - Object.defineProperty(XMLHttpRequest.prototype, 'onreadystatechange', {}); - return result; - } - ; - var unboundKey = utils_1.zoneSymbol('unbound'); - // Whenever any eventListener fires, we check the eventListener target and all parents - // for `onwhatever` properties and replace them with zone-bound functions - // - Chrome (for now) - function patchViaCapturingAllTheEvents() { - var _loop_1 = function(i) { - var property = eventNames[i]; - var onproperty = 'on' + property; - document.addEventListener(property, function (event) { - var elt = event.target, bound, source; - if (elt) { - source = elt.constructor['name'] + '.' + onproperty; - } - else { - source = 'unknown.' + onproperty; - } - while (elt) { - if (elt[onproperty] && !elt[onproperty][unboundKey]) { - bound = Zone.current.wrap(elt[onproperty], source); - bound[unboundKey] = elt[onproperty]; - elt[onproperty] = bound; - } - elt = elt.parentElement; - } - }, true); - }; - for (var i = 0; i < eventNames.length; i++) { - _loop_1(i); - } - ; - } - ; - - - /***/ }, - /* 7 */ - /***/ function(module, exports, __webpack_require__) { - - "use strict"; - var utils_1 = __webpack_require__(3); - // we have to patch the instance since the proto is non-configurable - function apply(_global) { - var WS = _global.WebSocket; - // On Safari window.EventTarget doesn't exist so need to patch WS add/removeEventListener - // On older Chrome, no need since EventTarget was already patched - if (!_global.EventTarget) { - utils_1.patchEventTargetMethods(WS.prototype); - } - _global.WebSocket = function (a, b) { - var socket = arguments.length > 1 ? new WS(a, b) : new WS(a); - var proxySocket; - // Safari 7.0 has non-configurable own 'onmessage' and friends properties on the socket instance - var onmessageDesc = Object.getOwnPropertyDescriptor(socket, 'onmessage'); - if (onmessageDesc && onmessageDesc.configurable === false) { - proxySocket = Object.create(socket); - ['addEventListener', 'removeEventListener', 'send', 'close'].forEach(function (propName) { - proxySocket[propName] = function () { - return socket[propName].apply(socket, arguments); - }; - }); - } - else { - // we can patch the real socket - proxySocket = socket; - } - utils_1.patchOnProperties(proxySocket, ['close', 'error', 'message', 'open']); - return proxySocket; - }; - for (var prop in WS) { - _global.WebSocket[prop] = WS[prop]; - } - } - exports.apply = apply; - - - /***/ }, - /* 8 */ - /***/ function(module, exports, __webpack_require__) { - - "use strict"; - var utils_1 = __webpack_require__(3); - function patchTimer(window, setName, cancelName, nameSuffix) { - var setNative = null; - var clearNative = null; - setName += nameSuffix; - cancelName += nameSuffix; - function scheduleTask(task) { - var data = task.data; - data.args[0] = task.invoke; - data.handleId = setNative.apply(window, data.args); - return task; - } - function clearTask(task) { - return clearNative(task.data.handleId); - } - setNative = utils_1.patchMethod(window, setName, function (delegate) { return function (self, args) { - if (typeof args[0] === 'function') { - var zone = Zone.current; - var options = { - handleId: null, - isPeriodic: nameSuffix === 'Interval', - delay: (nameSuffix === 'Timeout' || nameSuffix === 'Interval') ? args[1] || 0 : null, - args: args - }; - var task = zone.scheduleMacroTask(setName, args[0], options, scheduleTask, clearTask); - if (!task) { - return task; - } - // Node.js must additionally support the ref and unref functions. - var handle = task.data.handleId; - if (handle.ref && handle.unref) { - task.ref = handle.ref.bind(handle); - task.unref = handle.unref.bind(handle); - } - return task; - } - else { - // cause an error by calling it directly. - return delegate.apply(window, args); - } - }; }); - clearNative = utils_1.patchMethod(window, cancelName, function (delegate) { return function (self, args) { - var task = args[0]; - if (task && typeof task.type === 'string') { - if (task.cancelFn && task.data.isPeriodic || task.runCount === 0) { - // Do not cancel already canceled functions - task.zone.cancelTask(task); - } - } - else { - // cause an error by calling it directly. - delegate.apply(window, args); - } - }; }); - } - exports.patchTimer = patchTimer; - - - /***/ } - /******/ ]); - /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(309))) + /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()), __webpack_require__(309))) /***/ }, /* 309 */ @@ -9184,8 +9136,8 @@ /* WEBPACK VAR INJECTION */(function(process) {"use strict"; var platform_browser_dynamic_1 = __webpack_require__(311); - var app_module_1 = __webpack_require__(334); - process.stdout = __webpack_require__(562)(); + var app_module_1 = __webpack_require__(333); + process.stdout = __webpack_require__(647)(); platform_browser_dynamic_1.platformBrowserDynamic().bootstrapModule(app_module_1.AppModule); /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(309))) @@ -9195,12 +9147,12 @@ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(global) {/** - * @license Angular v2.0.0-rc.6 + * @license Angular v2.1.0-rc.0 * (c) 2010-2016 Google, Inc. https://angular.io/ * License: MIT */ (function (global, factory) { - true ? factory(exports, __webpack_require__(312), __webpack_require__(313), __webpack_require__(332)) : + true ? factory(exports, __webpack_require__(312), __webpack_require__(313), __webpack_require__(331)) : typeof define === 'function' && define.amd ? define(['exports', '@angular/compiler', '@angular/core', '@angular/platform-browser'], factory) : (factory((global.ng = global.ng || {}, global.ng.platformBrowserDynamic = global.ng.platformBrowserDynamic || {}),global.ng.compiler,global.ng.core,global.ng.platformBrowser)); }(this, function (exports,_angular_compiler,_angular_core,_angular_platformBrowser) { 'use strict'; @@ -9270,8 +9222,6 @@ } throw new Error('Invalid integer literal when parsing ' + text + ' in base ' + radix); }; - // TODO: NaN is a valid literal but is returned by parseFloat to indicate an error. - NumberWrapper.parseFloat = function (text) { return parseFloat(text); }; Object.defineProperty(NumberWrapper, "NaN", { get: function () { return NaN; }, enumerable: true, @@ -9410,7 +9360,7 @@ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(global) {/** - * @license Angular v2.0.0-rc.6 + * @license Angular v2.1.0-rc.0 * (c) 2010-2016 Google, Inc. https://angular.io/ * License: MIT */ @@ -9483,7 +9433,7 @@ } var res = token.toString(); var newLineIndex = res.indexOf('\n'); - return (newLineIndex === -1) ? res : res.substring(0, newLineIndex); + return newLineIndex === -1 ? res : res.substring(0, newLineIndex); } var StringWrapper = (function () { function StringWrapper() { @@ -9593,8 +9543,6 @@ } throw new Error('Invalid integer literal when parsing ' + text + ' in base ' + radix); }; - // TODO: NaN is a valid literal but is returned by parseFloat to indicate an error. - NumberWrapper.parseFloat = function (text) { return parseFloat(text); }; Object.defineProperty(NumberWrapper, "NaN", { get: function () { return NaN; }, enumerable: true, @@ -9670,7 +9618,8 @@ return AttrAst; }()); /** - * A binding for an element property (e.g. `[property]="expression"`). + * A binding for an element property (e.g. `[property]="expression"`) or an animation trigger (e.g. + * `[@trigger]="stateExp"`) */ var BoundElementPropertyAst = (function () { function BoundElementPropertyAst(name, type, securityContext, value, unit, sourceSpan) { @@ -9684,15 +9633,22 @@ BoundElementPropertyAst.prototype.visit = function (visitor, context) { return visitor.visitElementProperty(this, context); }; + Object.defineProperty(BoundElementPropertyAst.prototype, "isAnimation", { + get: function () { return this.type === exports.PropertyBindingType.Animation; }, + enumerable: true, + configurable: true + }); return BoundElementPropertyAst; }()); /** - * A binding for an element event (e.g. `(event)="handler()"`). + * A binding for an element event (e.g. `(event)="handler()"`) or an animation trigger event (e.g. + * `(@trigger.phase)="callback($event)"`). */ var BoundEventAst = (function () { - function BoundEventAst(name, target, handler, sourceSpan) { + function BoundEventAst(name, target, phase, handler, sourceSpan) { this.name = name; this.target = target; + this.phase = phase; this.handler = handler; this.sourceSpan = sourceSpan; } @@ -9711,6 +9667,11 @@ enumerable: true, configurable: true }); + Object.defineProperty(BoundEventAst.prototype, "isAnimation", { + get: function () { return !!this.phase; }, + enumerable: true, + configurable: true + }); return BoundEventAst; }()); /** @@ -9897,20 +9858,18 @@ return result; } - var Map$1 = global$1.Map; - var Set$1 = global$1.Set; // Safari and Internet Explorer do not support the iterable parameter to the // Map constructor. We work around that by manually adding the items. var createMapFromPairs = (function () { try { - if (new Map$1([[1, 2]]).size === 1) { - return function createMapFromPairs(pairs) { return new Map$1(pairs); }; + if (new Map([[1, 2]]).size === 1) { + return function createMapFromPairs(pairs) { return new Map(pairs); }; } } catch (e) { } return function createMapAndPopulateFromPairs(pairs) { - var map = new Map$1(); + var map = new Map(); for (var i = 0; i < pairs.length; i++) { var pair = pairs[i]; map.set(pair[0], pair[1]); @@ -9918,22 +9877,8 @@ return map; }; })(); - var createMapFromMap = (function () { - try { - if (new Map$1(new Map$1())) { - return function createMapFromMap(m) { return new Map$1(m); }; - } - } - catch (e) { - } - return function createMapAndPopulateFromMap(m) { - var map = new Map$1(); - m.forEach(function (v, k) { map.set(k, v); }); - return map; - }; - })(); var _clearValues = (function () { - if ((new Map$1()).keys().next) { + if ((new Map()).keys().next) { return function _clearValues(m) { var keyIterator = m.keys(); var k; @@ -9952,7 +9897,7 @@ // TODO(mlaval): remove the work around once we have a working polyfill of Array.from var _arrayFromMap = (function () { try { - if ((new Map$1()).values().next) { + if ((new Map()).values().next) { return function createArrayFromMap(m, getValues) { return getValues ? Array.from(m.values()) : Array.from(m.keys()); }; @@ -9961,7 +9906,7 @@ catch (e) { } return function createArrayFromMapWithForeach(m, getValues) { - var res = ListWrapper.createFixedSize(m.size), i = 0; + var res = new Array(m.size), i = 0; m.forEach(function (v, k) { res[i] = getValues ? v : k; i++; @@ -9972,9 +9917,8 @@ var MapWrapper = (function () { function MapWrapper() { } - MapWrapper.clone = function (m) { return createMapFromMap(m); }; MapWrapper.createFromStringMap = function (stringMap) { - var result = new Map$1(); + var result = new Map(); for (var prop in stringMap) { result.set(prop, stringMap[prop]); } @@ -9986,7 +9930,6 @@ return r; }; MapWrapper.createFromPairs = function (pairs) { return createMapFromPairs(pairs); }; - MapWrapper.clearValues = function (m) { _clearValues(m); }; MapWrapper.iterable = function (m) { return m; }; MapWrapper.keys = function (m) { return _arrayFromMap(m, false); }; MapWrapper.values = function (m) { return _arrayFromMap(m, true); }; @@ -9998,36 +9941,6 @@ var StringMapWrapper = (function () { function StringMapWrapper() { } - StringMapWrapper.create = function () { - // Note: We are not using Object.create(null) here due to - // performance! - // http://jsperf.com/ng2-object-create-null - return {}; - }; - StringMapWrapper.contains = function (map, key) { - return map.hasOwnProperty(key); - }; - StringMapWrapper.get = function (map, key) { - return map.hasOwnProperty(key) ? map[key] : undefined; - }; - StringMapWrapper.set = function (map, key, value) { map[key] = value; }; - StringMapWrapper.keys = function (map) { return Object.keys(map); }; - StringMapWrapper.values = function (map) { - return Object.keys(map).map(function (k) { return map[k]; }); - }; - StringMapWrapper.isEmpty = function (map) { - for (var prop in map) { - return false; - } - return true; - }; - StringMapWrapper.delete = function (map, key) { delete map[key]; }; - StringMapWrapper.forEach = function (map, callback) { - for (var _i = 0, _a = Object.keys(map); _i < _a.length; _i++) { - var k = _a[_i]; - callback(map[k], k); - } - }; StringMapWrapper.merge = function (m1, m2) { var m = {}; for (var _i = 0, _a = Object.keys(m1); _i < _a.length; _i++) { @@ -10046,9 +9959,8 @@ if (k1.length != k2.length) { return false; } - var key; for (var i = 0; i < k1.length; i++) { - key = k1[i]; + var key = k1[i]; if (m1[key] !== m2[key]) { return false; } @@ -10187,35 +10099,390 @@ } return target; } - // Safari and Internet Explorer do not support the iterable parameter to the - // Set constructor. We work around that by manually adding the items. - var createSetFromList = (function () { - var test = new Set$1([1, 2, 3]); - if (test.size === 3) { - return function createSetFromList(lst) { return new Set$1(lst); }; - } - else { - return function createSetAndPopulateFromList(lst) { - var res = new Set$1(lst); - if (res.size !== lst.length) { - for (var i = 0; i < lst.length; i++) { - res.add(lst[i]); - } - } - return res; - }; - } - })(); - var SetWrapper = (function () { - function SetWrapper() { - } - SetWrapper.createFromList = function (lst) { return createSetFromList(lst); }; - SetWrapper.has = function (s, key) { return s.has(key); }; - SetWrapper.delete = function (m, k) { m.delete(k); }; - return SetWrapper; - }()); - var _EMPTY_ATTR_VALUE = ''; + /** + * @license + * Copyright Google Inc. All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.io/license + */ + var TagContentType; + (function (TagContentType) { + TagContentType[TagContentType["RAW_TEXT"] = 0] = "RAW_TEXT"; + TagContentType[TagContentType["ESCAPABLE_RAW_TEXT"] = 1] = "ESCAPABLE_RAW_TEXT"; + TagContentType[TagContentType["PARSABLE_DATA"] = 2] = "PARSABLE_DATA"; + })(TagContentType || (TagContentType = {})); + function splitNsName(elementName) { + if (elementName[0] != ':') { + return [null, elementName]; + } + var colonIndex = elementName.indexOf(':', 1); + if (colonIndex == -1) { + throw new Error("Unsupported format \"" + elementName + "\" expecting \":namespace:name\""); + } + return [elementName.slice(1, colonIndex), elementName.slice(colonIndex + 1)]; + } + function getNsPrefix(fullName) { + return fullName === null ? null : splitNsName(fullName)[0]; + } + function mergeNsAndName(prefix, localName) { + return prefix ? ":" + prefix + ":" + localName : localName; + } + // see http://www.w3.org/TR/html51/syntax.html#named-character-references + // see https://html.spec.whatwg.org/multipage/entities.json + // This list is not exhaustive to keep the compiler footprint low. + // The `{` / `ƫ` syntax should be used when the named character reference does not exist. + var NAMED_ENTITIES = { + 'Aacute': '\u00C1', + 'aacute': '\u00E1', + 'Acirc': '\u00C2', + 'acirc': '\u00E2', + 'acute': '\u00B4', + 'AElig': '\u00C6', + 'aelig': '\u00E6', + 'Agrave': '\u00C0', + 'agrave': '\u00E0', + 'alefsym': '\u2135', + 'Alpha': '\u0391', + 'alpha': '\u03B1', + 'amp': '&', + 'and': '\u2227', + 'ang': '\u2220', + 'apos': '\u0027', + 'Aring': '\u00C5', + 'aring': '\u00E5', + 'asymp': '\u2248', + 'Atilde': '\u00C3', + 'atilde': '\u00E3', + 'Auml': '\u00C4', + 'auml': '\u00E4', + 'bdquo': '\u201E', + 'Beta': '\u0392', + 'beta': '\u03B2', + 'brvbar': '\u00A6', + 'bull': '\u2022', + 'cap': '\u2229', + 'Ccedil': '\u00C7', + 'ccedil': '\u00E7', + 'cedil': '\u00B8', + 'cent': '\u00A2', + 'Chi': '\u03A7', + 'chi': '\u03C7', + 'circ': '\u02C6', + 'clubs': '\u2663', + 'cong': '\u2245', + 'copy': '\u00A9', + 'crarr': '\u21B5', + 'cup': '\u222A', + 'curren': '\u00A4', + 'dagger': '\u2020', + 'Dagger': '\u2021', + 'darr': '\u2193', + 'dArr': '\u21D3', + 'deg': '\u00B0', + 'Delta': '\u0394', + 'delta': '\u03B4', + 'diams': '\u2666', + 'divide': '\u00F7', + 'Eacute': '\u00C9', + 'eacute': '\u00E9', + 'Ecirc': '\u00CA', + 'ecirc': '\u00EA', + 'Egrave': '\u00C8', + 'egrave': '\u00E8', + 'empty': '\u2205', + 'emsp': '\u2003', + 'ensp': '\u2002', + 'Epsilon': '\u0395', + 'epsilon': '\u03B5', + 'equiv': '\u2261', + 'Eta': '\u0397', + 'eta': '\u03B7', + 'ETH': '\u00D0', + 'eth': '\u00F0', + 'Euml': '\u00CB', + 'euml': '\u00EB', + 'euro': '\u20AC', + 'exist': '\u2203', + 'fnof': '\u0192', + 'forall': '\u2200', + 'frac12': '\u00BD', + 'frac14': '\u00BC', + 'frac34': '\u00BE', + 'frasl': '\u2044', + 'Gamma': '\u0393', + 'gamma': '\u03B3', + 'ge': '\u2265', + 'gt': '>', + 'harr': '\u2194', + 'hArr': '\u21D4', + 'hearts': '\u2665', + 'hellip': '\u2026', + 'Iacute': '\u00CD', + 'iacute': '\u00ED', + 'Icirc': '\u00CE', + 'icirc': '\u00EE', + 'iexcl': '\u00A1', + 'Igrave': '\u00CC', + 'igrave': '\u00EC', + 'image': '\u2111', + 'infin': '\u221E', + 'int': '\u222B', + 'Iota': '\u0399', + 'iota': '\u03B9', + 'iquest': '\u00BF', + 'isin': '\u2208', + 'Iuml': '\u00CF', + 'iuml': '\u00EF', + 'Kappa': '\u039A', + 'kappa': '\u03BA', + 'Lambda': '\u039B', + 'lambda': '\u03BB', + 'lang': '\u27E8', + 'laquo': '\u00AB', + 'larr': '\u2190', + 'lArr': '\u21D0', + 'lceil': '\u2308', + 'ldquo': '\u201C', + 'le': '\u2264', + 'lfloor': '\u230A', + 'lowast': '\u2217', + 'loz': '\u25CA', + 'lrm': '\u200E', + 'lsaquo': '\u2039', + 'lsquo': '\u2018', + 'lt': '<', + 'macr': '\u00AF', + 'mdash': '\u2014', + 'micro': '\u00B5', + 'middot': '\u00B7', + 'minus': '\u2212', + 'Mu': '\u039C', + 'mu': '\u03BC', + 'nabla': '\u2207', + 'nbsp': '\u00A0', + 'ndash': '\u2013', + 'ne': '\u2260', + 'ni': '\u220B', + 'not': '\u00AC', + 'notin': '\u2209', + 'nsub': '\u2284', + 'Ntilde': '\u00D1', + 'ntilde': '\u00F1', + 'Nu': '\u039D', + 'nu': '\u03BD', + 'Oacute': '\u00D3', + 'oacute': '\u00F3', + 'Ocirc': '\u00D4', + 'ocirc': '\u00F4', + 'OElig': '\u0152', + 'oelig': '\u0153', + 'Ograve': '\u00D2', + 'ograve': '\u00F2', + 'oline': '\u203E', + 'Omega': '\u03A9', + 'omega': '\u03C9', + 'Omicron': '\u039F', + 'omicron': '\u03BF', + 'oplus': '\u2295', + 'or': '\u2228', + 'ordf': '\u00AA', + 'ordm': '\u00BA', + 'Oslash': '\u00D8', + 'oslash': '\u00F8', + 'Otilde': '\u00D5', + 'otilde': '\u00F5', + 'otimes': '\u2297', + 'Ouml': '\u00D6', + 'ouml': '\u00F6', + 'para': '\u00B6', + 'permil': '\u2030', + 'perp': '\u22A5', + 'Phi': '\u03A6', + 'phi': '\u03C6', + 'Pi': '\u03A0', + 'pi': '\u03C0', + 'piv': '\u03D6', + 'plusmn': '\u00B1', + 'pound': '\u00A3', + 'prime': '\u2032', + 'Prime': '\u2033', + 'prod': '\u220F', + 'prop': '\u221D', + 'Psi': '\u03A8', + 'psi': '\u03C8', + 'quot': '\u0022', + 'radic': '\u221A', + 'rang': '\u27E9', + 'raquo': '\u00BB', + 'rarr': '\u2192', + 'rArr': '\u21D2', + 'rceil': '\u2309', + 'rdquo': '\u201D', + 'real': '\u211C', + 'reg': '\u00AE', + 'rfloor': '\u230B', + 'Rho': '\u03A1', + 'rho': '\u03C1', + 'rlm': '\u200F', + 'rsaquo': '\u203A', + 'rsquo': '\u2019', + 'sbquo': '\u201A', + 'Scaron': '\u0160', + 'scaron': '\u0161', + 'sdot': '\u22C5', + 'sect': '\u00A7', + 'shy': '\u00AD', + 'Sigma': '\u03A3', + 'sigma': '\u03C3', + 'sigmaf': '\u03C2', + 'sim': '\u223C', + 'spades': '\u2660', + 'sub': '\u2282', + 'sube': '\u2286', + 'sum': '\u2211', + 'sup': '\u2283', + 'sup1': '\u00B9', + 'sup2': '\u00B2', + 'sup3': '\u00B3', + 'supe': '\u2287', + 'szlig': '\u00DF', + 'Tau': '\u03A4', + 'tau': '\u03C4', + 'there4': '\u2234', + 'Theta': '\u0398', + 'theta': '\u03B8', + 'thetasym': '\u03D1', + 'thinsp': '\u2009', + 'THORN': '\u00DE', + 'thorn': '\u00FE', + 'tilde': '\u02DC', + 'times': '\u00D7', + 'trade': '\u2122', + 'Uacute': '\u00DA', + 'uacute': '\u00FA', + 'uarr': '\u2191', + 'uArr': '\u21D1', + 'Ucirc': '\u00DB', + 'ucirc': '\u00FB', + 'Ugrave': '\u00D9', + 'ugrave': '\u00F9', + 'uml': '\u00A8', + 'upsih': '\u03D2', + 'Upsilon': '\u03A5', + 'upsilon': '\u03C5', + 'Uuml': '\u00DC', + 'uuml': '\u00FC', + 'weierp': '\u2118', + 'Xi': '\u039E', + 'xi': '\u03BE', + 'Yacute': '\u00DD', + 'yacute': '\u00FD', + 'yen': '\u00A5', + 'yuml': '\u00FF', + 'Yuml': '\u0178', + 'Zeta': '\u0396', + 'zeta': '\u03B6', + 'zwj': '\u200D', + 'zwnj': '\u200C', + }; + + var HtmlTagDefinition = (function () { + function HtmlTagDefinition(_a) { + var _this = this; + var _b = _a === void 0 ? {} : _a, closedByChildren = _b.closedByChildren, requiredParents = _b.requiredParents, implicitNamespacePrefix = _b.implicitNamespacePrefix, _c = _b.contentType, contentType = _c === void 0 ? TagContentType.PARSABLE_DATA : _c, _d = _b.closedByParent, closedByParent = _d === void 0 ? false : _d, _e = _b.isVoid, isVoid = _e === void 0 ? false : _e, _f = _b.ignoreFirstLf, ignoreFirstLf = _f === void 0 ? false : _f; + this.closedByChildren = {}; + this.closedByParent = false; + this.canSelfClose = false; + if (closedByChildren && closedByChildren.length > 0) { + closedByChildren.forEach(function (tagName) { return _this.closedByChildren[tagName] = true; }); + } + this.isVoid = isVoid; + this.closedByParent = closedByParent || isVoid; + if (requiredParents && requiredParents.length > 0) { + this.requiredParents = {}; + // The first parent is the list is automatically when none of the listed parents are present + this.parentToAdd = requiredParents[0]; + requiredParents.forEach(function (tagName) { return _this.requiredParents[tagName] = true; }); + } + this.implicitNamespacePrefix = implicitNamespacePrefix; + this.contentType = contentType; + this.ignoreFirstLf = ignoreFirstLf; + } + HtmlTagDefinition.prototype.requireExtraParent = function (currentParent) { + if (!this.requiredParents) { + return false; + } + if (!currentParent) { + return true; + } + var lcParent = currentParent.toLowerCase(); + return this.requiredParents[lcParent] != true && lcParent != 'template'; + }; + HtmlTagDefinition.prototype.isClosedByChild = function (name) { + return this.isVoid || name.toLowerCase() in this.closedByChildren; + }; + return HtmlTagDefinition; + }()); + // see http://www.w3.org/TR/html51/syntax.html#optional-tags + // This implementation does not fully conform to the HTML5 spec. + var TAG_DEFINITIONS = { + 'base': new HtmlTagDefinition({ isVoid: true }), + 'meta': new HtmlTagDefinition({ isVoid: true }), + 'area': new HtmlTagDefinition({ isVoid: true }), + 'embed': new HtmlTagDefinition({ isVoid: true }), + 'link': new HtmlTagDefinition({ isVoid: true }), + 'img': new HtmlTagDefinition({ isVoid: true }), + 'input': new HtmlTagDefinition({ isVoid: true }), + 'param': new HtmlTagDefinition({ isVoid: true }), + 'hr': new HtmlTagDefinition({ isVoid: true }), + 'br': new HtmlTagDefinition({ isVoid: true }), + 'source': new HtmlTagDefinition({ isVoid: true }), + 'track': new HtmlTagDefinition({ isVoid: true }), + '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' + ], + closedByParent: true + }), + 'thead': new HtmlTagDefinition({ closedByChildren: ['tbody', 'tfoot'] }), + 'tbody': new HtmlTagDefinition({ closedByChildren: ['tbody', 'tfoot'], closedByParent: true }), + 'tfoot': new HtmlTagDefinition({ closedByChildren: ['tbody'], closedByParent: true }), + 'tr': new HtmlTagDefinition({ + closedByChildren: ['tr'], + requiredParents: ['tbody', 'tfoot', 'thead'], + closedByParent: true + }), + 'td': new HtmlTagDefinition({ closedByChildren: ['td', 'th'], closedByParent: true }), + 'th': new HtmlTagDefinition({ closedByChildren: ['td', 'th'], closedByParent: true }), + 'col': new HtmlTagDefinition({ requiredParents: ['colgroup'], isVoid: true }), + 'svg': new HtmlTagDefinition({ implicitNamespacePrefix: 'svg' }), + 'math': new HtmlTagDefinition({ implicitNamespacePrefix: 'math' }), + 'li': new HtmlTagDefinition({ closedByChildren: ['li'], closedByParent: true }), + 'dt': new HtmlTagDefinition({ closedByChildren: ['dt', 'dd'] }), + 'dd': new HtmlTagDefinition({ closedByChildren: ['dt', 'dd'], closedByParent: true }), + 'rb': new HtmlTagDefinition({ closedByChildren: ['rb', 'rt', 'rtc', 'rp'], closedByParent: true }), + 'rt': new HtmlTagDefinition({ closedByChildren: ['rb', 'rt', 'rtc', 'rp'], closedByParent: true }), + 'rtc': new HtmlTagDefinition({ closedByChildren: ['rb', 'rtc', 'rp'], closedByParent: true }), + 'rp': new HtmlTagDefinition({ closedByChildren: ['rb', 'rt', 'rtc', 'rp'], closedByParent: true }), + 'optgroup': new HtmlTagDefinition({ closedByChildren: ['optgroup'], closedByParent: true }), + 'option': new HtmlTagDefinition({ closedByChildren: ['option', 'optgroup'], closedByParent: true }), + 'pre': new HtmlTagDefinition({ ignoreFirstLf: true }), + 'listing': new HtmlTagDefinition({ ignoreFirstLf: true }), + 'style': new HtmlTagDefinition({ contentType: TagContentType.RAW_TEXT }), + 'script': new HtmlTagDefinition({ contentType: TagContentType.RAW_TEXT }), + 'title': new HtmlTagDefinition({ contentType: TagContentType.ESCAPABLE_RAW_TEXT }), + 'textarea': new HtmlTagDefinition({ contentType: TagContentType.ESCAPABLE_RAW_TEXT, ignoreFirstLf: true }), + }; + var _DEFAULT_TAG_DEFINITION = new HtmlTagDefinition(); + function getHtmlTagDefinition(tagName) { + return TAG_DEFINITIONS[tagName.toLowerCase()] || _DEFAULT_TAG_DEFINITION; + } + var _SELECTOR_REGEXP = new RegExp('(\\:not\\()|' + '([-\\w]+)|' + '(?:\\.([-\\w]+))|' + @@ -10238,8 +10505,8 @@ CssSelector.parse = function (selector) { var results = []; var _addResult = function (res, cssSel) { - if (cssSel.notSelectors.length > 0 && isBlank(cssSel.element) && - ListWrapper.isEmpty(cssSel.classNames) && ListWrapper.isEmpty(cssSel.attrs)) { + if (cssSel.notSelectors.length > 0 && !cssSel.element && cssSel.classNames.length == 0 && + cssSel.attrs.length == 0) { cssSel.element = '*'; } res.push(cssSel); @@ -10249,8 +10516,8 @@ var current = cssSelector; var inNot = false; _SELECTOR_REGEXP.lastIndex = 0; - while (isPresent(match = _SELECTOR_REGEXP.exec(selector))) { - if (isPresent(match[1])) { + while (match = _SELECTOR_REGEXP.exec(selector)) { + if (match[1]) { if (inNot) { throw new Error('Nesting :not is not allowed in a selector'); } @@ -10258,20 +10525,20 @@ current = new CssSelector(); cssSelector.notSelectors.push(current); } - if (isPresent(match[2])) { + if (match[2]) { current.setElement(match[2]); } - if (isPresent(match[3])) { + if (match[3]) { current.addClassName(match[3]); } - if (isPresent(match[4])) { + if (match[4]) { current.addAttribute(match[4], match[5]); } - if (isPresent(match[6])) { + if (match[6]) { inNot = false; current = cssSelector; } - if (isPresent(match[7])) { + if (match[7]) { if (inNot) { throw new Error('Multiple selectors in :not are not supported'); } @@ -10293,7 +10560,7 @@ }; /** Gets a template string for an element that matches the selector. */ CssSelector.prototype.getMatchingElementTemplate = function () { - var tagName = isPresent(this.element) ? this.element : 'div'; + var tagName = this.element || 'div'; var classAttr = this.classNames.length > 0 ? " class=\"" + this.classNames.join(' ') + "\"" : ''; var attrs = ''; for (var i = 0; i < this.attrs.length; i += 2) { @@ -10301,39 +10568,24 @@ var attrValue = this.attrs[i + 1] !== '' ? "=\"" + this.attrs[i + 1] + "\"" : ''; attrs += " " + attrName + attrValue; } - return "<" + tagName + classAttr + attrs + ">"; + return getHtmlTagDefinition(tagName).isVoid ? "<" + tagName + classAttr + attrs + "/>" : + "<" + tagName + classAttr + attrs + ">"; }; CssSelector.prototype.addAttribute = function (name, value) { - if (value === void 0) { value = _EMPTY_ATTR_VALUE; } - this.attrs.push(name); - if (isPresent(value)) { - value = value.toLowerCase(); - } - else { - value = _EMPTY_ATTR_VALUE; - } - this.attrs.push(value); + if (value === void 0) { value = ''; } + this.attrs.push(name, value && value.toLowerCase() || ''); }; CssSelector.prototype.addClassName = function (name) { this.classNames.push(name.toLowerCase()); }; CssSelector.prototype.toString = function () { - var res = ''; - if (isPresent(this.element)) { - res += this.element; + var res = this.element || ''; + if (this.classNames) { + this.classNames.forEach(function (klass) { return res += "." + klass; }); } - if (isPresent(this.classNames)) { - for (var i = 0; i < this.classNames.length; i++) { - res += '.' + this.classNames[i]; - } - } - if (isPresent(this.attrs)) { - for (var i = 0; i < this.attrs.length;) { - var attrName = this.attrs[i++]; - var attrValue = this.attrs[i++]; - res += '[' + attrName; - if (attrValue.length > 0) { - res += '=' + attrValue; - } - res += ']'; + if (this.attrs) { + for (var i = 0; i < this.attrs.length; i += 2) { + var name_1 = this.attrs[i]; + var value = this.attrs[i + 1]; + res += "[" + name_1 + (value ? '=' + value : '') + "]"; } } this.notSelectors.forEach(function (notSelector) { return res += ":not(" + notSelector + ")"; }); @@ -10347,12 +10599,12 @@ */ var SelectorMatcher = (function () { function SelectorMatcher() { - this._elementMap = new Map(); - this._elementPartialMap = new Map(); - this._classMap = new Map(); - this._classPartialMap = new Map(); - this._attrValueMap = new Map(); - this._attrValuePartialMap = new Map(); + this._elementMap = {}; + this._elementPartialMap = {}; + this._classMap = {}; + this._classPartialMap = {}; + this._attrValueMap = {}; + this._attrValuePartialMap = {}; this._listContexts = []; } SelectorMatcher.createNotMatcher = function (notSelectors) { @@ -10381,7 +10633,7 @@ var classNames = cssSelector.classNames; var attrs = cssSelector.attrs; var selectable = new SelectorContext(cssSelector, callbackCtxt, listContext); - if (isPresent(element)) { + if (element) { var isTerminal = attrs.length === 0 && classNames.length === 0; if (isTerminal) { this._addTerminal(matcher._elementMap, element, selectable); @@ -10390,10 +10642,10 @@ matcher = this._addPartial(matcher._elementPartialMap, element); } } - if (isPresent(classNames)) { - for (var index = 0; index < classNames.length; index++) { - var isTerminal = attrs.length === 0 && index === classNames.length - 1; - var className = classNames[index]; + if (classNames) { + for (var i = 0; i < classNames.length; i++) { + var isTerminal = attrs.length === 0 && i === classNames.length - 1; + var className = classNames[i]; if (isTerminal) { this._addTerminal(matcher._classMap, className, selectable); } @@ -10402,45 +10654,45 @@ } } } - if (isPresent(attrs)) { - for (var index = 0; index < attrs.length;) { - var isTerminal = index === attrs.length - 2; - var attrName = attrs[index++]; - var attrValue = attrs[index++]; + if (attrs) { + for (var i = 0; i < attrs.length; i += 2) { + var isTerminal = i === attrs.length - 2; + var name_2 = attrs[i]; + var value = attrs[i + 1]; if (isTerminal) { var terminalMap = matcher._attrValueMap; - var terminalValuesMap = terminalMap.get(attrName); - if (isBlank(terminalValuesMap)) { - terminalValuesMap = new Map(); - terminalMap.set(attrName, terminalValuesMap); + var terminalValuesMap = terminalMap[name_2]; + if (!terminalValuesMap) { + terminalValuesMap = {}; + terminalMap[name_2] = terminalValuesMap; } - this._addTerminal(terminalValuesMap, attrValue, selectable); + this._addTerminal(terminalValuesMap, value, selectable); } else { - var parttialMap = matcher._attrValuePartialMap; - var partialValuesMap = parttialMap.get(attrName); - if (isBlank(partialValuesMap)) { - partialValuesMap = new Map(); - parttialMap.set(attrName, partialValuesMap); + var partialMap = matcher._attrValuePartialMap; + var partialValuesMap = partialMap[name_2]; + if (!partialValuesMap) { + partialValuesMap = {}; + partialMap[name_2] = partialValuesMap; } - matcher = this._addPartial(partialValuesMap, attrValue); + matcher = this._addPartial(partialValuesMap, value); } } } }; SelectorMatcher.prototype._addTerminal = function (map, name, selectable) { - var terminalList = map.get(name); - if (isBlank(terminalList)) { + var terminalList = map[name]; + if (!terminalList) { terminalList = []; - map.set(name, terminalList); + map[name] = terminalList; } terminalList.push(selectable); }; SelectorMatcher.prototype._addPartial = function (map, name) { - var matcher = map.get(name); - if (isBlank(matcher)) { + var matcher = map[name]; + if (!matcher) { matcher = new SelectorMatcher(); - map.set(name, matcher); + map[name] = matcher; } return matcher; }; @@ -10462,9 +10714,9 @@ result = this._matchTerminal(this._elementMap, element, cssSelector, matchedCallback) || result; result = this._matchPartial(this._elementPartialMap, element, cssSelector, matchedCallback) || result; - if (isPresent(classNames)) { - for (var index = 0; index < classNames.length; index++) { - var className = classNames[index]; + if (classNames) { + for (var i = 0; i < classNames.length; i++) { + var className = classNames[i]; result = this._matchTerminal(this._classMap, className, cssSelector, matchedCallback) || result; result = @@ -10472,56 +10724,55 @@ result; } } - if (isPresent(attrs)) { - for (var index = 0; index < attrs.length;) { - var attrName = attrs[index++]; - var attrValue = attrs[index++]; - 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, attrValue, cssSelector, matchedCallback) || - result; - var partialValuesMap = this._attrValuePartialMap.get(attrName); - if (!StringWrapper.equals(attrValue, _EMPTY_ATTR_VALUE)) { - result = this._matchPartial(partialValuesMap, _EMPTY_ATTR_VALUE, cssSelector, matchedCallback) || - result; + if (attrs) { + for (var i = 0; i < attrs.length; i += 2) { + var name_3 = attrs[i]; + var value = attrs[i + 1]; + var terminalValuesMap = this._attrValueMap[name_3]; + if (value) { + result = + this._matchTerminal(terminalValuesMap, '', cssSelector, matchedCallback) || result; } result = - this._matchPartial(partialValuesMap, attrValue, cssSelector, matchedCallback) || result; + this._matchTerminal(terminalValuesMap, value, cssSelector, matchedCallback) || result; + var partialValuesMap = this._attrValuePartialMap[name_3]; + if (value) { + result = this._matchPartial(partialValuesMap, '', cssSelector, matchedCallback) || result; + } + result = + this._matchPartial(partialValuesMap, value, cssSelector, matchedCallback) || result; } } return result; }; /** @internal */ SelectorMatcher.prototype._matchTerminal = function (map, name, cssSelector, matchedCallback) { - if (isBlank(map) || isBlank(name)) { + if (!map || typeof name !== 'string') { return false; } - var selectables = map.get(name); - var starSelectables = map.get('*'); - if (isPresent(starSelectables)) { + var selectables = map[name]; + var starSelectables = map['*']; + if (starSelectables) { selectables = selectables.concat(starSelectables); } - if (isBlank(selectables)) { + if (!selectables) { return false; } var selectable; var result = false; - for (var index = 0; index < selectables.length; index++) { - selectable = selectables[index]; + for (var i = 0; i < selectables.length; i++) { + selectable = selectables[i]; result = selectable.finalize(cssSelector, matchedCallback) || result; } return result; }; /** @internal */ SelectorMatcher.prototype._matchPartial = function (map, name, cssSelector, matchedCallback) { - if (isBlank(map) || isBlank(name)) { + if (!map || typeof name !== 'string') { return false; } - var nestedSelector = map.get(name); - if (isBlank(nestedSelector)) { + var nestedSelector = map[name]; + if (!nestedSelector) { return false; } // TODO(perf): get rid of recursion and measure again @@ -10548,14 +10799,12 @@ } SelectorContext.prototype.finalize = function (cssSelector, callback) { var result = true; - if (this.notSelectors.length > 0 && - (isBlank(this.listContext) || !this.listContext.alreadyMatched)) { + if (this.notSelectors.length > 0 && (!this.listContext || !this.listContext.alreadyMatched)) { var notMatcher = SelectorMatcher.createNotMatcher(this.notSelectors); result = !notMatcher.match(cssSelector, null); } - if (result && isPresent(callback) && - (isBlank(this.listContext) || !this.listContext.alreadyMatched)) { - if (isPresent(this.listContext)) { + if (result && callback && (!this.listContext || !this.listContext.alreadyMatched)) { + if (this.listContext) { this.listContext.alreadyMatched = true; } callback(this.selector, this.cbContext); @@ -10586,7 +10835,7 @@ function Type(modifiers) { if (modifiers === void 0) { modifiers = null; } this.modifiers = modifiers; - if (isBlank(modifiers)) { + if (!modifiers) { this.modifiers = []; } } @@ -11051,7 +11300,7 @@ function Statement(modifiers) { if (modifiers === void 0) { modifiers = null; } this.modifiers = modifiers; - if (isBlank(modifiers)) { + if (!modifiers) { this.modifiers = []; } } @@ -11116,7 +11365,7 @@ if (type === void 0) { type = null; } this.type = type; this.modifiers = modifiers; - if (isBlank(modifiers)) { + if (!modifiers) { this.modifiers = []; } } @@ -11504,10 +11753,16 @@ return StringWrapper.replaceAllMapped(input, CAMEL_CASE_REGEXP, function (m) { return '-' + m[1].toLowerCase(); }); } function splitAtColon(input, defaultValues) { - var colonIndex = input.indexOf(':'); - if (colonIndex == -1) + return _splitAt(input, ':', defaultValues); + } + function splitAtPeriod(input, defaultValues) { + return _splitAt(input, '.', defaultValues); + } + function _splitAt(input, character, defaultValues) { + var characterIndex = input.indexOf(character); + if (characterIndex == -1) return defaultValues; - return [input.slice(0, colonIndex).trim(), input.slice(colonIndex + 1).trim()]; + return [input.slice(0, characterIndex).trim(), input.slice(characterIndex + 1).trim()]; } function sanitizeIdentifier(name) { return StringWrapper.replaceAll(name, /\W/g, '_'); @@ -11536,9 +11791,7 @@ ValueTransformer.prototype.visitStringMap = function (map, context) { var _this = this; var result = {}; - StringMapWrapper.forEach(map, function (value /** TODO #9100 */, key /** TODO #9100 */) { - result[key] = visitValue(value, _this, context); - }); + Object.keys(map).forEach(function (key) { result[key] = visitValue(map[key], _this, context); }); return result; }; ValueTransformer.prototype.visitPrimitive = function (value, context) { return value; }; @@ -11870,7 +12123,8 @@ var hostProperties = {}; var hostAttributes = {}; if (isPresent(host)) { - StringMapWrapper.forEach(host, function (value, key) { + Object.keys(host).forEach(function (key) { + var value = host[key]; var matches = key.match(HOST_REG_EXP); if (matches === null) { hostAttributes[key] = value; @@ -11976,7 +12230,7 @@ */ var CompileNgModuleMetadata = (function () { function CompileNgModuleMetadata(_a) { - var _b = _a === void 0 ? {} : _a, type = _b.type, providers = _b.providers, declaredDirectives = _b.declaredDirectives, exportedDirectives = _b.exportedDirectives, declaredPipes = _b.declaredPipes, exportedPipes = _b.exportedPipes, entryComponents = _b.entryComponents, bootstrapComponents = _b.bootstrapComponents, importedModules = _b.importedModules, exportedModules = _b.exportedModules, schemas = _b.schemas, transitiveModule = _b.transitiveModule; + var _b = _a === void 0 ? {} : _a, type = _b.type, providers = _b.providers, declaredDirectives = _b.declaredDirectives, exportedDirectives = _b.exportedDirectives, declaredPipes = _b.declaredPipes, exportedPipes = _b.exportedPipes, entryComponents = _b.entryComponents, bootstrapComponents = _b.bootstrapComponents, importedModules = _b.importedModules, exportedModules = _b.exportedModules, schemas = _b.schemas, transitiveModule = _b.transitiveModule, id = _b.id; this.type = type; this.declaredDirectives = _normalizeArray(declaredDirectives); this.exportedDirectives = _normalizeArray(exportedDirectives); @@ -11988,6 +12242,7 @@ this.importedModules = _normalizeArray(importedModules); this.exportedModules = _normalizeArray(exportedModules); this.schemas = _normalizeArray(schemas); + this.id = id; this.transitiveModule = transitiveModule; } Object.defineProperty(CompileNgModuleMetadata.prototype, "identifier", { @@ -12831,7 +13086,7 @@ this.advance(); } var str = this.input.substring(start, this.index); - var value = simple ? NumberWrapper.parseIntAutoRadix(str) : NumberWrapper.parseFloat(str); + var value = simple ? NumberWrapper.parseIntAutoRadix(str) : parseFloat(str); return newNumberToken(start, value); }; _Scanner.prototype.scanString = function () { @@ -13773,7 +14028,7 @@ ExpansionCase.prototype.visit = function (visitor, context) { return visitor.visitExpansionCase(this, context); }; return ExpansionCase; }()); - var Attribute = (function () { + var Attribute$1 = (function () { function Attribute(name, value, sourceSpan) { this.name = name; this.value = value; @@ -13814,294 +14069,6 @@ return result; } - /** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ - var TagContentType; - (function (TagContentType) { - TagContentType[TagContentType["RAW_TEXT"] = 0] = "RAW_TEXT"; - TagContentType[TagContentType["ESCAPABLE_RAW_TEXT"] = 1] = "ESCAPABLE_RAW_TEXT"; - TagContentType[TagContentType["PARSABLE_DATA"] = 2] = "PARSABLE_DATA"; - })(TagContentType || (TagContentType = {})); - function splitNsName(elementName) { - if (elementName[0] != ':') { - return [null, elementName]; - } - var colonIndex = elementName.indexOf(':', 1); - if (colonIndex == -1) { - throw new Error("Unsupported format \"" + elementName + "\" expecting \":namespace:name\""); - } - return [elementName.slice(1, colonIndex), elementName.slice(colonIndex + 1)]; - } - function getNsPrefix(fullName) { - return fullName === null ? null : splitNsName(fullName)[0]; - } - function mergeNsAndName(prefix, localName) { - return prefix ? ":" + prefix + ":" + localName : localName; - } - // see http://www.w3.org/TR/html51/syntax.html#named-character-references - // see https://html.spec.whatwg.org/multipage/entities.json - // This list is not exhaustive to keep the compiler footprint low. - // The `{` / `ƫ` syntax should be used when the named character reference does not exist. - var NAMED_ENTITIES = { - 'Aacute': '\u00C1', - 'aacute': '\u00E1', - 'Acirc': '\u00C2', - 'acirc': '\u00E2', - 'acute': '\u00B4', - 'AElig': '\u00C6', - 'aelig': '\u00E6', - 'Agrave': '\u00C0', - 'agrave': '\u00E0', - 'alefsym': '\u2135', - 'Alpha': '\u0391', - 'alpha': '\u03B1', - 'amp': '&', - 'and': '\u2227', - 'ang': '\u2220', - 'apos': '\u0027', - 'Aring': '\u00C5', - 'aring': '\u00E5', - 'asymp': '\u2248', - 'Atilde': '\u00C3', - 'atilde': '\u00E3', - 'Auml': '\u00C4', - 'auml': '\u00E4', - 'bdquo': '\u201E', - 'Beta': '\u0392', - 'beta': '\u03B2', - 'brvbar': '\u00A6', - 'bull': '\u2022', - 'cap': '\u2229', - 'Ccedil': '\u00C7', - 'ccedil': '\u00E7', - 'cedil': '\u00B8', - 'cent': '\u00A2', - 'Chi': '\u03A7', - 'chi': '\u03C7', - 'circ': '\u02C6', - 'clubs': '\u2663', - 'cong': '\u2245', - 'copy': '\u00A9', - 'crarr': '\u21B5', - 'cup': '\u222A', - 'curren': '\u00A4', - 'dagger': '\u2020', - 'Dagger': '\u2021', - 'darr': '\u2193', - 'dArr': '\u21D3', - 'deg': '\u00B0', - 'Delta': '\u0394', - 'delta': '\u03B4', - 'diams': '\u2666', - 'divide': '\u00F7', - 'Eacute': '\u00C9', - 'eacute': '\u00E9', - 'Ecirc': '\u00CA', - 'ecirc': '\u00EA', - 'Egrave': '\u00C8', - 'egrave': '\u00E8', - 'empty': '\u2205', - 'emsp': '\u2003', - 'ensp': '\u2002', - 'Epsilon': '\u0395', - 'epsilon': '\u03B5', - 'equiv': '\u2261', - 'Eta': '\u0397', - 'eta': '\u03B7', - 'ETH': '\u00D0', - 'eth': '\u00F0', - 'Euml': '\u00CB', - 'euml': '\u00EB', - 'euro': '\u20AC', - 'exist': '\u2203', - 'fnof': '\u0192', - 'forall': '\u2200', - 'frac12': '\u00BD', - 'frac14': '\u00BC', - 'frac34': '\u00BE', - 'frasl': '\u2044', - 'Gamma': '\u0393', - 'gamma': '\u03B3', - 'ge': '\u2265', - 'gt': '>', - 'harr': '\u2194', - 'hArr': '\u21D4', - 'hearts': '\u2665', - 'hellip': '\u2026', - 'Iacute': '\u00CD', - 'iacute': '\u00ED', - 'Icirc': '\u00CE', - 'icirc': '\u00EE', - 'iexcl': '\u00A1', - 'Igrave': '\u00CC', - 'igrave': '\u00EC', - 'image': '\u2111', - 'infin': '\u221E', - 'int': '\u222B', - 'Iota': '\u0399', - 'iota': '\u03B9', - 'iquest': '\u00BF', - 'isin': '\u2208', - 'Iuml': '\u00CF', - 'iuml': '\u00EF', - 'Kappa': '\u039A', - 'kappa': '\u03BA', - 'Lambda': '\u039B', - 'lambda': '\u03BB', - 'lang': '\u27E8', - 'laquo': '\u00AB', - 'larr': '\u2190', - 'lArr': '\u21D0', - 'lceil': '\u2308', - 'ldquo': '\u201C', - 'le': '\u2264', - 'lfloor': '\u230A', - 'lowast': '\u2217', - 'loz': '\u25CA', - 'lrm': '\u200E', - 'lsaquo': '\u2039', - 'lsquo': '\u2018', - 'lt': '<', - 'macr': '\u00AF', - 'mdash': '\u2014', - 'micro': '\u00B5', - 'middot': '\u00B7', - 'minus': '\u2212', - 'Mu': '\u039C', - 'mu': '\u03BC', - 'nabla': '\u2207', - 'nbsp': '\u00A0', - 'ndash': '\u2013', - 'ne': '\u2260', - 'ni': '\u220B', - 'not': '\u00AC', - 'notin': '\u2209', - 'nsub': '\u2284', - 'Ntilde': '\u00D1', - 'ntilde': '\u00F1', - 'Nu': '\u039D', - 'nu': '\u03BD', - 'Oacute': '\u00D3', - 'oacute': '\u00F3', - 'Ocirc': '\u00D4', - 'ocirc': '\u00F4', - 'OElig': '\u0152', - 'oelig': '\u0153', - 'Ograve': '\u00D2', - 'ograve': '\u00F2', - 'oline': '\u203E', - 'Omega': '\u03A9', - 'omega': '\u03C9', - 'Omicron': '\u039F', - 'omicron': '\u03BF', - 'oplus': '\u2295', - 'or': '\u2228', - 'ordf': '\u00AA', - 'ordm': '\u00BA', - 'Oslash': '\u00D8', - 'oslash': '\u00F8', - 'Otilde': '\u00D5', - 'otilde': '\u00F5', - 'otimes': '\u2297', - 'Ouml': '\u00D6', - 'ouml': '\u00F6', - 'para': '\u00B6', - 'permil': '\u2030', - 'perp': '\u22A5', - 'Phi': '\u03A6', - 'phi': '\u03C6', - 'Pi': '\u03A0', - 'pi': '\u03C0', - 'piv': '\u03D6', - 'plusmn': '\u00B1', - 'pound': '\u00A3', - 'prime': '\u2032', - 'Prime': '\u2033', - 'prod': '\u220F', - 'prop': '\u221D', - 'Psi': '\u03A8', - 'psi': '\u03C8', - 'quot': '\u0022', - 'radic': '\u221A', - 'rang': '\u27E9', - 'raquo': '\u00BB', - 'rarr': '\u2192', - 'rArr': '\u21D2', - 'rceil': '\u2309', - 'rdquo': '\u201D', - 'real': '\u211C', - 'reg': '\u00AE', - 'rfloor': '\u230B', - 'Rho': '\u03A1', - 'rho': '\u03C1', - 'rlm': '\u200F', - 'rsaquo': '\u203A', - 'rsquo': '\u2019', - 'sbquo': '\u201A', - 'Scaron': '\u0160', - 'scaron': '\u0161', - 'sdot': '\u22C5', - 'sect': '\u00A7', - 'shy': '\u00AD', - 'Sigma': '\u03A3', - 'sigma': '\u03C3', - 'sigmaf': '\u03C2', - 'sim': '\u223C', - 'spades': '\u2660', - 'sub': '\u2282', - 'sube': '\u2286', - 'sum': '\u2211', - 'sup': '\u2283', - 'sup1': '\u00B9', - 'sup2': '\u00B2', - 'sup3': '\u00B3', - 'supe': '\u2287', - 'szlig': '\u00DF', - 'Tau': '\u03A4', - 'tau': '\u03C4', - 'there4': '\u2234', - 'Theta': '\u0398', - 'theta': '\u03B8', - 'thetasym': '\u03D1', - 'thinsp': '\u2009', - 'THORN': '\u00DE', - 'thorn': '\u00FE', - 'tilde': '\u02DC', - 'times': '\u00D7', - 'trade': '\u2122', - 'Uacute': '\u00DA', - 'uacute': '\u00FA', - 'uarr': '\u2191', - 'uArr': '\u21D1', - 'Ucirc': '\u00DB', - 'ucirc': '\u00FB', - 'Ugrave': '\u00D9', - 'ugrave': '\u00F9', - 'uml': '\u00A8', - 'upsih': '\u03D2', - 'Upsilon': '\u03A5', - 'upsilon': '\u03C5', - 'Uuml': '\u00DC', - 'uuml': '\u00FC', - 'weierp': '\u2118', - 'Xi': '\u039E', - 'xi': '\u03BE', - 'Yacute': '\u00DD', - 'yacute': '\u00FD', - 'yen': '\u00A5', - 'yuml': '\u00FF', - 'Yuml': '\u0178', - 'Zeta': '\u0396', - 'zeta': '\u03B6', - 'zwj': '\u200D', - 'zwnj': '\u200C', - }; - /** * @license * Copyright Google Inc. All Rights Reserved. @@ -14874,7 +14841,7 @@ // read = while (this._peek.type === TokenType$1.EXPANSION_CASE_VALUE) { var expCase = this._parseExpansionCase(); - if (isBlank(expCase)) + if (!expCase) return; // error cases.push(expCase); } @@ -14897,7 +14864,7 @@ // read until } var start = this._advance(); var exp = this._collectExpansionExpTokens(start); - if (isBlank(exp)) + if (!exp) return null; var end = this._advance(); exp.push(new Token$1(TokenType$1.EOF, [], end.sourceSpan)); @@ -15049,7 +15016,7 @@ value = valueToken.parts[0]; end = valueToken.sourceSpan.end; } - return new Attribute(fullName, value, new ParseSourceSpan(attrName.sourceSpan.start, end)); + return new Attribute$1(fullName, value, new ParseSourceSpan(attrName.sourceSpan.start, end)); }; _TreeBuilder.prototype._getParentElement = function () { return this._elementStack.length > 0 ? ListWrapper.last(this._elementStack) : null; @@ -15363,101 +15330,6 @@ return IcuPlaceholder; }()); - var HtmlTagDefinition = (function () { - function HtmlTagDefinition(_a) { - var _this = this; - var _b = _a === void 0 ? {} : _a, closedByChildren = _b.closedByChildren, requiredParents = _b.requiredParents, implicitNamespacePrefix = _b.implicitNamespacePrefix, _c = _b.contentType, contentType = _c === void 0 ? TagContentType.PARSABLE_DATA : _c, _d = _b.closedByParent, closedByParent = _d === void 0 ? false : _d, _e = _b.isVoid, isVoid = _e === void 0 ? false : _e, _f = _b.ignoreFirstLf, ignoreFirstLf = _f === void 0 ? false : _f; - this.closedByChildren = {}; - this.closedByParent = false; - this.canSelfClose = false; - if (closedByChildren && closedByChildren.length > 0) { - closedByChildren.forEach(function (tagName) { return _this.closedByChildren[tagName] = true; }); - } - this.isVoid = isVoid; - this.closedByParent = closedByParent || isVoid; - if (requiredParents && requiredParents.length > 0) { - this.requiredParents = {}; - // The first parent is the list is automatically when none of the listed parents are present - this.parentToAdd = requiredParents[0]; - requiredParents.forEach(function (tagName) { return _this.requiredParents[tagName] = true; }); - } - this.implicitNamespacePrefix = implicitNamespacePrefix; - this.contentType = contentType; - this.ignoreFirstLf = ignoreFirstLf; - } - HtmlTagDefinition.prototype.requireExtraParent = function (currentParent) { - if (!this.requiredParents) { - return false; - } - if (!currentParent) { - return true; - } - var lcParent = currentParent.toLowerCase(); - return this.requiredParents[lcParent] != true && lcParent != 'template'; - }; - HtmlTagDefinition.prototype.isClosedByChild = function (name) { - return this.isVoid || name.toLowerCase() in this.closedByChildren; - }; - return HtmlTagDefinition; - }()); - // see http://www.w3.org/TR/html51/syntax.html#optional-tags - // This implementation does not fully conform to the HTML5 spec. - var TAG_DEFINITIONS = { - 'base': new HtmlTagDefinition({ isVoid: true }), - 'meta': new HtmlTagDefinition({ isVoid: true }), - 'area': new HtmlTagDefinition({ isVoid: true }), - 'embed': new HtmlTagDefinition({ isVoid: true }), - 'link': new HtmlTagDefinition({ isVoid: true }), - 'img': new HtmlTagDefinition({ isVoid: true }), - 'input': new HtmlTagDefinition({ isVoid: true }), - 'param': new HtmlTagDefinition({ isVoid: true }), - 'hr': new HtmlTagDefinition({ isVoid: true }), - 'br': new HtmlTagDefinition({ isVoid: true }), - 'source': new HtmlTagDefinition({ isVoid: true }), - 'track': new HtmlTagDefinition({ isVoid: true }), - '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' - ], - closedByParent: true - }), - 'thead': new HtmlTagDefinition({ closedByChildren: ['tbody', 'tfoot'] }), - 'tbody': new HtmlTagDefinition({ closedByChildren: ['tbody', 'tfoot'], closedByParent: true }), - 'tfoot': new HtmlTagDefinition({ closedByChildren: ['tbody'], closedByParent: true }), - 'tr': new HtmlTagDefinition({ - closedByChildren: ['tr'], - requiredParents: ['tbody', 'tfoot', 'thead'], - closedByParent: true - }), - 'td': new HtmlTagDefinition({ closedByChildren: ['td', 'th'], closedByParent: true }), - 'th': new HtmlTagDefinition({ closedByChildren: ['td', 'th'], closedByParent: true }), - 'col': new HtmlTagDefinition({ requiredParents: ['colgroup'], isVoid: true }), - 'svg': new HtmlTagDefinition({ implicitNamespacePrefix: 'svg' }), - 'math': new HtmlTagDefinition({ implicitNamespacePrefix: 'math' }), - 'li': new HtmlTagDefinition({ closedByChildren: ['li'], closedByParent: true }), - 'dt': new HtmlTagDefinition({ closedByChildren: ['dt', 'dd'] }), - 'dd': new HtmlTagDefinition({ closedByChildren: ['dt', 'dd'], closedByParent: true }), - 'rb': new HtmlTagDefinition({ closedByChildren: ['rb', 'rt', 'rtc', 'rp'], closedByParent: true }), - 'rt': new HtmlTagDefinition({ closedByChildren: ['rb', 'rt', 'rtc', 'rp'], closedByParent: true }), - 'rtc': new HtmlTagDefinition({ closedByChildren: ['rb', 'rtc', 'rp'], closedByParent: true }), - 'rp': new HtmlTagDefinition({ closedByChildren: ['rb', 'rt', 'rtc', 'rp'], closedByParent: true }), - 'optgroup': new HtmlTagDefinition({ closedByChildren: ['optgroup'], closedByParent: true }), - 'option': new HtmlTagDefinition({ closedByChildren: ['option', 'optgroup'], closedByParent: true }), - 'pre': new HtmlTagDefinition({ ignoreFirstLf: true }), - 'listing': new HtmlTagDefinition({ ignoreFirstLf: true }), - 'style': new HtmlTagDefinition({ contentType: TagContentType.RAW_TEXT }), - 'script': new HtmlTagDefinition({ contentType: TagContentType.RAW_TEXT }), - 'title': new HtmlTagDefinition({ contentType: TagContentType.ESCAPABLE_RAW_TEXT }), - 'textarea': new HtmlTagDefinition({ contentType: TagContentType.ESCAPABLE_RAW_TEXT, ignoreFirstLf: true }), - }; - var _DEFAULT_TAG_DEFINITION = new HtmlTagDefinition(); - function getHtmlTagDefinition(tagName) { - return TAG_DEFINITIONS[tagName.toLowerCase()] || _DEFAULT_TAG_DEFINITION; - } - /** * @license * Copyright Google Inc. All Rights Reserved. @@ -15945,7 +15817,7 @@ // add a translatable message _Visitor.prototype._addMessage = function (ast, meaningAndDesc) { if (ast.length == 0 || - ast.length == 1 && ast[0] instanceof Attribute && !ast[0].value) { + ast.length == 1 && ast[0] instanceof Attribute$1 && !ast[0].value) { // Do not create empty messages return; } @@ -15992,7 +15864,7 @@ if (nodes) { if (nodes[0] instanceof Text) { var value = nodes[0].value; - translatedAttributes.push(new Attribute(attr.name, value, attr.sourceSpan)); + translatedAttributes.push(new Attribute$1(attr.name, value, attr.sourceSpan)); } else { _this._reportError(el, "Unexpected translation for attribute \"" + attr.name + "\" (id=\"" + id + "\")"); @@ -16198,6 +16070,11 @@ * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ + var __extends$8 = (this && this.__extends) || function (d, b) { + for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; var _Visitor$1 = (function () { function _Visitor() { } @@ -16270,6 +16147,14 @@ Text.prototype.visit = function (visitor) { return visitor.visitText(this); }; return Text; }()); + var CR = (function (_super) { + __extends$8(CR, _super); + function CR(ws) { + if (ws === void 0) { ws = 0; } + _super.call(this, "\n" + new Array(ws + 1).join(' ')); + } + return CR; + }(Text$2)); var _ESCAPED_CHARS = [ [/&/g, '&'], [/"/g, '"'], @@ -16289,10 +16174,6 @@ var _SOURCE_TAG = 'source'; var _TARGET_TAG = 'target'; var _UNIT_TAG = 'trans-unit'; - var _CR = function (ws) { - if (ws === void 0) { ws = 0; } - return new Text$2("\n" + new Array(ws).join(' ')); - }; // http://docs.oasis-open.org/xliff/v1.2/os/xliff-core.html // http://docs.oasis-open.org/xliff/v1.2/xliff-profile-html/xliff-profile-html-1.2.html var Xliff = (function () { @@ -16306,20 +16187,22 @@ Object.keys(messageMap).forEach(function (id) { var message = messageMap[id]; var transUnit = new Tag(_UNIT_TAG, { id: id, datatype: 'html' }); - transUnit.children.push(_CR(8), new Tag(_SOURCE_TAG, {}, visitor.serialize(message.nodes)), _CR(8), new Tag(_TARGET_TAG)); + transUnit.children.push(new CR(8), new Tag(_SOURCE_TAG, {}, visitor.serialize(message.nodes)), new CR(8), new Tag(_TARGET_TAG)); if (message.description) { - transUnit.children.push(_CR(8), new Tag('note', { priority: '1', from: 'description' }, [new Text$2(message.description)])); + transUnit.children.push(new CR(8), new Tag('note', { priority: '1', from: 'description' }, [new Text$2(message.description)])); } if (message.meaning) { - transUnit.children.push(_CR(8), new Tag('note', { priority: '1', from: 'meaning' }, [new Text$2(message.meaning)])); + transUnit.children.push(new CR(8), new Tag('note', { priority: '1', from: 'meaning' }, [new Text$2(message.meaning)])); } - transUnit.children.push(_CR(6)); - transUnits.push(_CR(6), transUnit); + transUnit.children.push(new CR(6)); + transUnits.push(new CR(6), transUnit); }); - var body = new Tag('body', {}, transUnits.concat([_CR(4)])); - var file = new Tag('file', { 'source-language': _SOURCE_LANG, datatype: 'plaintext', original: 'ng2.template' }, [_CR(4), body, _CR(2)]); - var xliff = new Tag('xliff', { version: _VERSION, xmlns: _XMLNS }, [_CR(2), file, _CR()]); - return serialize([new Declaration({ version: '1.0', encoding: 'UTF-8' }), _CR(), xliff]); + var body = new Tag('body', {}, transUnits.concat([new CR(4)])); + var file = new Tag('file', { 'source-language': _SOURCE_LANG, datatype: 'plaintext', original: 'ng2.template' }, [new CR(4), body, new CR(2)]); + var xliff = new Tag('xliff', { version: _VERSION, xmlns: _XMLNS }, [new CR(2), file, new CR()]); + return serialize([ + new Declaration({ version: '1.0', encoding: 'UTF-8' }), new CR(), xliff, new CR() + ]); }; Xliff.prototype.load = function (content, url, messageBundle) { var _this = this; @@ -16373,12 +16256,13 @@ return nodes; }; _WriteVisitor.prototype.visitTagPlaceholder = function (ph, context) { - var startTagPh = new Tag(_PLACEHOLDER_TAG, { id: ph.startName, ctype: ph.tag }); + var ctype = getCtypeForTag(ph.tag); + var startTagPh = new Tag(_PLACEHOLDER_TAG, { id: ph.startName, ctype: ctype }); if (ph.isVoid) { // void tags have no children nor closing tags return [startTagPh]; } - var closeTagPh = new Tag(_PLACEHOLDER_TAG, { id: ph.closeName, ctype: ph.tag }); + var closeTagPh = new Tag(_PLACEHOLDER_TAG, { id: ph.closeName, ctype: ctype }); return [startTagPh].concat(this.serialize(ph.children), [closeTagPh]); }; _WriteVisitor.prototype.visitPlaceholder = function (ph, context) { @@ -16499,6 +16383,16 @@ }; return _LoadVisitor; }()); + function getCtypeForTag(tag) { + switch (tag.toLowerCase()) { + case 'br': + return 'lb'; + case 'img': + return 'image'; + default: + return "x-" + tag; + } + } var _MESSAGES_TAG = 'messagebundle'; var _MESSAGE_TAG = 'msg'; @@ -16511,7 +16405,6 @@ Xmb.prototype.write = function (messageMap) { var visitor = new _Visitor$2(); var rootNode = new Tag(_MESSAGES_TAG); - rootNode.children.push(new Text$2('\n')); Object.keys(messageMap).forEach(function (id) { var message = messageMap[id]; var attrs = { id: id }; @@ -16521,14 +16414,16 @@ if (message.meaning) { attrs['meaning'] = message.meaning; } - rootNode.children.push(new Text$2(' '), new Tag(_MESSAGE_TAG, attrs, visitor.serialize(message.nodes)), new Text$2('\n')); + rootNode.children.push(new CR(2), new Tag(_MESSAGE_TAG, attrs, visitor.serialize(message.nodes))); }); + rootNode.children.push(new CR()); return serialize([ new Declaration({ version: '1.0', encoding: 'UTF-8' }), - new Text$2('\n'), + new CR(), new Doctype(_MESSAGES_TAG, _DOCTYPE), - new Text$2('\n'), + new CR(), rootNode, + new CR(), ]); }; Xmb.prototype.load = function (content, url, messageBundle) { @@ -16804,6 +16699,7 @@ var AppView = _angular_core.__core_private__.AppView; var DebugAppView = _angular_core.__core_private__.DebugAppView; var NgModuleInjector = _angular_core.__core_private__.NgModuleInjector; + var registerModuleFactory = _angular_core.__core_private__.registerModuleFactory; var ViewType = _angular_core.__core_private__.ViewType; var MAX_INTERPOLATION_VALUES = _angular_core.__core_private__.MAX_INTERPOLATION_VALUES; var checkBinding = _angular_core.__core_private__.checkBinding; @@ -16838,7 +16734,6 @@ var AnimationGroupPlayer = _angular_core.__core_private__.AnimationGroupPlayer; var AnimationKeyframe = _angular_core.__core_private__.AnimationKeyframe; var AnimationStyles = _angular_core.__core_private__.AnimationStyles; - var AnimationOutput = _angular_core.__core_private__.AnimationOutput; var ANY_STATE = _angular_core.__core_private__.ANY_STATE; var DEFAULT_STATE = _angular_core.__core_private__.DEFAULT_STATE; var EMPTY_ANIMATION_STATE = _angular_core.__core_private__.EMPTY_STATE; @@ -16938,6 +16833,11 @@ runtime: NgModuleInjector, moduleUrl: assetUrl('core', 'linker/ng_module_factory') }; + Identifiers.RegisterModuleFactoryFn = { + name: 'registerModuleFactory', + runtime: registerModuleFactory, + moduleUrl: assetUrl('core', 'linker/ng_module_factory_loader') + }; Identifiers.ValueUnwrapper = { name: 'ValueUnwrapper', moduleUrl: CD_MODULE_URL, runtime: ValueUnwrapper }; Identifiers.Injector = { name: 'Injector', @@ -17086,11 +16986,6 @@ moduleUrl: assetUrl('core', 'i18n/tokens'), runtime: _angular_core.TRANSLATIONS_FORMAT }; - Identifiers.AnimationOutput = { - name: 'AnimationOutput', - moduleUrl: assetUrl('core', 'animation/animation_output'), - runtime: AnimationOutput - }; return Identifiers; }()); function resolveIdentifier(identifier) { @@ -17118,13 +17013,13 @@ * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ - var __extends$8 = (this && this.__extends) || function (d, b) { + var __extends$9 = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var HtmlParser = (function (_super) { - __extends$8(HtmlParser, _super); + __extends$9(HtmlParser, _super); function HtmlParser() { _super.call(this, getHtmlTagDefinition); } @@ -17148,7 +17043,7 @@ * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ - var __extends$9 = (this && this.__extends) || function (d, b) { + var __extends$10 = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); @@ -17191,7 +17086,7 @@ return ExpansionResult; }()); var ExpansionError = (function (_super) { - __extends$9(ExpansionError, _super); + __extends$10(ExpansionError, _super); function ExpansionError(span, errorMsg) { _super.call(this, span, errorMsg); } @@ -17230,18 +17125,18 @@ } var expansionResult = expandNodes(c.expression); errors.push.apply(errors, expansionResult.errors); - return new Element("template", [new Attribute('ngPluralCase', "" + c.value, c.valueSourceSpan)], expansionResult.nodes, c.sourceSpan, c.sourceSpan, c.sourceSpan); + return new Element("template", [new Attribute$1('ngPluralCase', "" + c.value, c.valueSourceSpan)], expansionResult.nodes, c.sourceSpan, c.sourceSpan, c.sourceSpan); }); - var switchAttr = new Attribute('[ngPlural]', ast.switchValue, ast.switchValueSourceSpan); + var switchAttr = new Attribute$1('[ngPlural]', ast.switchValue, ast.switchValueSourceSpan); return new Element('ng-container', [switchAttr], children, ast.sourceSpan, ast.sourceSpan, ast.sourceSpan); } function _expandDefaultForm(ast, errors) { var children = ast.cases.map(function (c) { var expansionResult = expandNodes(c.expression); errors.push.apply(errors, expansionResult.errors); - return new Element("template", [new Attribute('ngSwitchCase', "" + c.value, c.valueSourceSpan)], expansionResult.nodes, c.sourceSpan, c.sourceSpan, c.sourceSpan); + return new Element("template", [new Attribute$1('ngSwitchCase', "" + c.value, c.valueSourceSpan)], expansionResult.nodes, c.sourceSpan, c.sourceSpan, c.sourceSpan); }); - var switchAttr = new Attribute('[ngSwitch]', ast.switchValue, ast.switchValueSourceSpan); + var switchAttr = new Attribute$1('[ngSwitch]', ast.switchValue, ast.switchValueSourceSpan); return new Element('ng-container', [switchAttr], children, ast.sourceSpan, ast.sourceSpan, ast.sourceSpan); } @@ -17252,13 +17147,13 @@ * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ - var __extends$10 = (this && this.__extends) || function (d, b) { + var __extends$11 = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var ProviderError = (function (_super) { - __extends$10(ProviderError, _super); + __extends$11(ProviderError, _super); function ProviderError(message, span) { _super.call(this, span, message); } @@ -17281,9 +17176,9 @@ return ProviderViewContext; }()); var ProviderElementContext = (function () { - function ProviderElementContext(_viewContext, _parent, _isViewRoot, _directiveAsts, attrs, refs, _sourceSpan) { + function ProviderElementContext(viewContext, _parent, _isViewRoot, _directiveAsts, attrs, refs, _sourceSpan) { var _this = this; - this._viewContext = _viewContext; + this.viewContext = viewContext; this._parent = _parent; this._isViewRoot = _isViewRoot; this._directiveAsts = _directiveAsts; @@ -17295,7 +17190,7 @@ attrs.forEach(function (attrAst) { return _this._attrs[attrAst.name] = attrAst.value; }); var directivesMeta = _directiveAsts.map(function (directiveAst) { return directiveAst.directive; }); this._allProviders = - _resolveProvidersFromDirectives(directivesMeta, _sourceSpan, _viewContext.errors); + _resolveProvidersFromDirectives(directivesMeta, _sourceSpan, viewContext.errors); this._contentQueries = _getContentQueries(directivesMeta); var queriedTokens = new Map(); MapWrapper.values(this._allProviders).forEach(function (provider) { @@ -17366,7 +17261,7 @@ } currentEl = currentEl._parent; } - queries = this._viewContext.viewQueries.get(token.reference); + queries = this.viewContext.viewQueries.get(token.reference); if (isPresent(queries)) { ListWrapper.addAll(result, queries); } @@ -17375,10 +17270,9 @@ ProviderElementContext.prototype._getOrCreateLocalProvider = function (requestingProviderType, token, eager) { var _this = this; var resolvedProvider = this._allProviders.get(token.reference); - if (isBlank(resolvedProvider) || - ((requestingProviderType === exports.ProviderAstType.Directive || - requestingProviderType === exports.ProviderAstType.PublicService) && - resolvedProvider.providerType === exports.ProviderAstType.PrivateService) || + if (!resolvedProvider || ((requestingProviderType === exports.ProviderAstType.Directive || + requestingProviderType === exports.ProviderAstType.PublicService) && + resolvedProvider.providerType === exports.ProviderAstType.PrivateService) || ((requestingProviderType === exports.ProviderAstType.PrivateService || requestingProviderType === exports.ProviderAstType.PublicService) && resolvedProvider.providerType === exports.ProviderAstType.Builtin)) { @@ -17389,7 +17283,7 @@ return transformedProviderAst; } if (isPresent(this._seenProviders.get(token.reference))) { - this._viewContext.errors.push(new ProviderError("Cannot instantiate cyclic dependency! " + token.name, this._sourceSpan)); + this.viewContext.errors.push(new ProviderError("Cannot instantiate cyclic dependency! " + token.name, this._sourceSpan)); return null; } this._seenProviders.set(token.reference, true); @@ -17473,13 +17367,13 @@ result = this._getLocalDependency(requestingProviderType, dep, eager); } if (dep.isSelf) { - if (isBlank(result) && dep.isOptional) { + if (!result && dep.isOptional) { result = new CompileDiDependencyMetadata({ isValue: true, value: null }); } } else { // check parent elements - while (isBlank(result) && isPresent(currElement._parent)) { + while (!result && isPresent(currElement._parent)) { var prevElement = currElement; currElement = currElement._parent; if (prevElement._isViewRoot) { @@ -17488,10 +17382,10 @@ result = currElement._getLocalDependency(exports.ProviderAstType.PublicService, dep, currEager); } // check @Host restriction - if (isBlank(result)) { - if (!dep.isHost || this._viewContext.component.type.isHost || - this._viewContext.component.type.reference === dep.token.reference || - isPresent(this._viewContext.viewProviders.get(dep.token.reference))) { + if (!result) { + if (!dep.isHost || this.viewContext.component.type.isHost || + this.viewContext.component.type.reference === dep.token.reference || + isPresent(this.viewContext.viewProviders.get(dep.token.reference))) { result = dep; } else { @@ -17501,8 +17395,8 @@ } } } - if (isBlank(result)) { - this._viewContext.errors.push(new ProviderError("No provider for " + dep.token.name, this._sourceSpan)); + if (!result) { + this.viewContext.errors.push(new ProviderError("No provider for " + dep.token.name, this._sourceSpan)); } return result; }; @@ -17536,7 +17430,7 @@ NgModuleProviderAnalyzer.prototype._getOrCreateLocalProvider = function (token, eager) { var _this = this; var resolvedProvider = this._allProviders.get(token.reference); - if (isBlank(resolvedProvider)) { + if (!resolvedProvider) { return null; } var transformedProviderAst = this._transformedProviders.get(token.reference); @@ -17628,7 +17522,7 @@ } function _normalizeProviders(providers, sourceSpan, targetErrors, targetProviders) { if (targetProviders === void 0) { targetProviders = null; } - if (isBlank(targetProviders)) { + if (!targetProviders) { targetProviders = []; } if (isPresent(providers)) { @@ -17675,7 +17569,7 @@ if (isPresent(resolvedProvider) && resolvedProvider.multiProvider !== provider.multi) { targetErrors.push(new ProviderError("Mixing multi and non multi provider is not possible for token " + resolvedProvider.token.name, sourceSpan)); } - if (isBlank(resolvedProvider)) { + if (!resolvedProvider) { var lifecycleHooks = provider.token.identifier && provider.token.identifier instanceof CompileTypeMetadata ? provider.token.identifier.lifecycleHooks : []; @@ -17719,7 +17613,7 @@ function _addQueryToTokenMap(map, query) { query.selectors.forEach(function (token) { var entry = map.get(token.reference); - if (isBlank(entry)) { + if (!entry) { entry = []; map.set(token.reference, entry); } @@ -18210,6 +18104,10 @@ this._assertOnlyOneComponent(directiveAsts, element.sourceSpan); var ngContentIndex_1 = hasInlineTemplates ? null : parent.findNgContentIndex(projectionSelector); parsedElement = new ElementAst(nodeName, attrs, elementProps, events, references, providerContext.transformedDirectiveAsts, providerContext.transformProviders, providerContext.transformedHasViewContainer, children, hasInlineTemplates ? null : ngContentIndex_1, element.sourceSpan); + this._findComponentDirectives(directiveAsts) + .forEach(function (componentDirectiveAst) { return _this._validateElementAnimationInputOutputs(componentDirectiveAst.hostProperties, componentDirectiveAst.hostEvents, componentDirectiveAst.directive.template); }); + var componentTemplate = providerContext.viewContext.component.template; + this._validateElementAnimationInputOutputs(elementProps, events, componentTemplate); } if (hasInlineTemplates) { var templateCssSelector = createElementCssSelector(TEMPLATE_ELEMENT, templateMatchableAttrs); @@ -18223,6 +18121,26 @@ } return parsedElement; }; + TemplateParseVisitor.prototype._validateElementAnimationInputOutputs = function (inputs, outputs, template) { + var _this = this; + var triggerLookup = new Set(); + template.animations.forEach(function (entry) { triggerLookup.add(entry.name); }); + var animationInputs = inputs.filter(function (input) { return input.isAnimation; }); + animationInputs.forEach(function (input) { + var name = input.name; + if (!triggerLookup.has(name)) { + _this._reportError("Couldn't find an animation entry for \"" + name + "\"", input.sourceSpan); + } + }); + outputs.forEach(function (output) { + if (output.isAnimation) { + var found = animationInputs.find(function (input) { return input.name == output.name; }); + if (!found) { + _this._reportError("Unable to listen on (@" + output.name + "." + output.phase + ") because the animation trigger [@" + output.name + "] isn't being used on the same element", output.sourceSpan); + } + } + }); + }; TemplateParseVisitor.prototype._parseInlineTemplateBinding = function (attr, targetMatchableAttrs, targetProps, targetVars) { var templateBindingsSource = null; if (this._normalizeAttributeName(attr.name) == TEMPLATE_ATTR) { @@ -18276,14 +18194,14 @@ this._parseReference(identifier, value, srcSpan, targetRefs); } else if (bindParts[KW_ON_IDX]) { - this._parseEvent(bindParts[IDENT_KW_IDX], value, srcSpan, targetMatchableAttrs, targetEvents); + this._parseEventOrAnimationEvent(bindParts[IDENT_KW_IDX], value, srcSpan, targetMatchableAttrs, targetEvents); } else if (bindParts[KW_BINDON_IDX]) { this._parsePropertyOrAnimation(bindParts[IDENT_KW_IDX], value, srcSpan, targetMatchableAttrs, targetProps, targetAnimationProps); this._parseAssignmentEvent(bindParts[IDENT_KW_IDX], value, srcSpan, targetMatchableAttrs, targetEvents); } else if (bindParts[KW_AT_IDX]) { - if (name[0] == '@' && isPresent(value) && value.length > 0) { + if (_isAnimationLabel(name) && isPresent(value) && value.length > 0) { this._reportError("Assigning animation triggers via @prop=\"exp\" attributes with an expression is invalid." + " Use property bindings (e.g. [@prop]=\"exp\") or use an attribute without a value (e.g. @prop) instead.", srcSpan, ParseErrorLevel.FATAL); } @@ -18297,7 +18215,7 @@ this._parsePropertyOrAnimation(bindParts[IDENT_PROPERTY_IDX], value, srcSpan, targetMatchableAttrs, targetProps, targetAnimationProps); } else if (bindParts[IDENT_EVENT_IDX]) { - this._parseEvent(bindParts[IDENT_EVENT_IDX], value, srcSpan, targetMatchableAttrs, targetEvents); + this._parseEventOrAnimationEvent(bindParts[IDENT_EVENT_IDX], value, srcSpan, targetMatchableAttrs, targetEvents); } } else { @@ -18326,7 +18244,7 @@ }; TemplateParseVisitor.prototype._parsePropertyOrAnimation = function (name, expression, sourceSpan, targetMatchableAttrs, targetProps, targetAnimationProps) { var animatePropLength = ANIMATE_PROP_PREFIX.length; - var isAnimationProp = name[0] == '@'; + var isAnimationProp = _isAnimationLabel(name); var animationPrefixLength = 1; if (name.substring(0, animatePropLength) == ANIMATE_PROP_PREFIX) { isAnimationProp = true; @@ -18363,16 +18281,43 @@ targetProps.push(new BoundElementOrDirectiveProperty(name, ast, false, sourceSpan)); }; TemplateParseVisitor.prototype._parseAssignmentEvent = function (name, expression, sourceSpan, targetMatchableAttrs, targetEvents) { - this._parseEvent(name + "Change", expression + "=$event", sourceSpan, targetMatchableAttrs, targetEvents); + this._parseEventOrAnimationEvent(name + "Change", expression + "=$event", sourceSpan, targetMatchableAttrs, targetEvents); + }; + TemplateParseVisitor.prototype._parseEventOrAnimationEvent = function (name, expression, sourceSpan, targetMatchableAttrs, targetEvents) { + if (_isAnimationLabel(name)) { + name = name.substr(1); + this._parseAnimationEvent(name, expression, sourceSpan, targetEvents); + } + else { + this._parseEvent(name, expression, sourceSpan, targetMatchableAttrs, targetEvents); + } + }; + TemplateParseVisitor.prototype._parseAnimationEvent = function (name, expression, sourceSpan, targetEvents) { + var matches = splitAtPeriod(name, [name, '']); + var eventName = matches[0]; + var phase = matches[1].toLowerCase(); + if (phase) { + switch (phase) { + case 'start': + case 'done': + var ast = this._parseAction(expression, sourceSpan); + targetEvents.push(new BoundEventAst(eventName, null, phase, ast, sourceSpan)); + break; + default: + this._reportError("The provided animation output phase value \"" + phase + "\" for \"@" + eventName + "\" is not supported (use start or done)", sourceSpan); + break; + } + } + else { + this._reportError("The animation trigger output event (@" + eventName + ") is missing its phase value name (start or done are currently supported)", sourceSpan); + } }; TemplateParseVisitor.prototype._parseEvent = function (name, expression, sourceSpan, targetMatchableAttrs, targetEvents) { // long format: 'target: eventName' - var parts = splitAtColon(name, [null, name]); - var target = parts[0]; - var eventName = parts[1]; + var _a = splitAtColon(name, [null, name]), target = _a[0], eventName = _a[1]; var ast = this._parseAction(expression, sourceSpan); targetMatchableAttrs.push([name, ast.source]); - targetEvents.push(new BoundEventAst(eventName, target, ast, sourceSpan)); + targetEvents.push(new BoundEventAst(eventName, target, null, ast, sourceSpan)); // Don't detect directives for event names for now, // so don't add the event name to the matchableAttrs }; @@ -18439,7 +18384,8 @@ TemplateParseVisitor.prototype._createDirectiveHostPropertyAsts = function (elementName, hostProps, sourceSpan, targetPropertyAsts) { var _this = this; if (hostProps) { - StringMapWrapper.forEach(hostProps, function (expression, propName) { + Object.keys(hostProps).forEach(function (propName) { + var expression = hostProps[propName]; if (isString(expression)) { var exprAst = _this._parseBinding(expression, sourceSpan); targetPropertyAsts.push(_this._createElementPropertyAst(elementName, propName, exprAst, sourceSpan)); @@ -18453,9 +18399,10 @@ TemplateParseVisitor.prototype._createDirectiveHostEventAsts = function (hostListeners, sourceSpan, targetEventAsts) { var _this = this; if (hostListeners) { - StringMapWrapper.forEach(hostListeners, function (expression, propName) { + Object.keys(hostListeners).forEach(function (propName) { + var expression = hostListeners[propName]; if (isString(expression)) { - _this._parseEvent(propName, expression, sourceSpan, [], targetEventAsts); + _this._parseEventOrAnimationEvent(propName, expression, sourceSpan, [], targetEventAsts); } else { _this._reportError("Value of the host listener \"" + propName + "\" needs to be a string representing an expression but got \"" + expression + "\" (" + typeof expression + ")", sourceSpan); @@ -18468,12 +18415,13 @@ var boundPropsByName_1 = new Map(); boundProps.forEach(function (boundProp) { var prevValue = boundPropsByName_1.get(boundProp.name); - if (isBlank(prevValue) || prevValue.isLiteral) { + if (!prevValue || prevValue.isLiteral) { // give [a]="b" a higher precedence than a="b" on the same element boundPropsByName_1.set(boundProp.name, boundProp); } }); - StringMapWrapper.forEach(directiveProperties, function (elProp, dirProp) { + Object.keys(directiveProperties).forEach(function (dirProp) { + var elProp = directiveProperties[dirProp]; var boundProp = boundPropsByName_1.get(elProp); // Bindings are optional, so this binding only needs to be set up if an expression is given. if (boundProp) { @@ -18492,7 +18440,7 @@ }); }); props.forEach(function (prop) { - if (!prop.isLiteral && isBlank(boundDirectivePropsIndex.get(prop.name))) { + if (!prop.isLiteral && !boundDirectivePropsIndex.get(prop.name)) { boundElementProps.push(_this._createElementPropertyAst(elementName, prop.name, prop.expression, prop.sourceSpan)); } }); @@ -18506,7 +18454,7 @@ var securityContext; if (parts.length === 1) { var partValue = parts[0]; - if (partValue[0] == '@') { + if (_isAnimationLabel(partValue)) { boundPropertyName = partValue.substr(1); bindingType = exports.PropertyBindingType.Animation; securityContext = _angular_core.SecurityContext.NONE; @@ -18515,13 +18463,13 @@ boundPropertyName = this._schemaRegistry.getMappedPropName(partValue); securityContext = this._schemaRegistry.securityContext(elementName, boundPropertyName); bindingType = exports.PropertyBindingType.Property; - this._assertNoEventBinding(boundPropertyName, sourceSpan); + this._validatePropertyOrAttributeName(boundPropertyName, sourceSpan, false); if (!this._schemaRegistry.hasProperty(elementName, boundPropertyName, this._schemas)) { var errorMsg = "Can't bind to '" + boundPropertyName + "' since it isn't a known property of '" + elementName + "'."; if (elementName.indexOf('-') > -1) { errorMsg += ("\n1. If '" + elementName + "' is an Angular component and it has '" + boundPropertyName + "' input, then verify that it is part of this module.") + - ("\n2. If '" + elementName + "' is a Web Component then add \"CUSTOM_ELEMENTS_SCHEMA\" to the '@NgModule.schema' of this component to suppress this message.\n"); + ("\n2. If '" + elementName + "' is a Web Component then add \"CUSTOM_ELEMENTS_SCHEMA\" to the '@NgModule.schemas' of this component to suppress this message.\n"); } this._reportError(errorMsg, sourceSpan); } @@ -18530,7 +18478,7 @@ else { if (parts[0] == ATTRIBUTE_PREFIX) { boundPropertyName = parts[1]; - this._assertNoEventBinding(boundPropertyName, sourceSpan); + this._validatePropertyOrAttributeName(boundPropertyName, sourceSpan, true); // NB: For security purposes, use the mapped property name, not the attribute name. var mapPropName = this._schemaRegistry.getMappedPropName(boundPropertyName); securityContext = this._schemaRegistry.securityContext(elementName, mapPropName); @@ -18561,21 +18509,25 @@ } return new BoundElementPropertyAst(boundPropertyName, bindingType, securityContext, ast, unit, sourceSpan); }; - TemplateParseVisitor.prototype._assertNoEventBinding = function (propName, sourceSpan) { - if (propName.toLowerCase().startsWith('on')) { - this._reportError(("Binding to event attribute '" + propName + "' is disallowed ") + - ("for security reasons, please use (" + propName.slice(2) + ")=..."), sourceSpan, ParseErrorLevel.FATAL); + /** + * @param propName the name of the property / attribute + * @param sourceSpan + * @param isAttr true when binding to an attribute + * @private + */ + TemplateParseVisitor.prototype._validatePropertyOrAttributeName = function (propName, sourceSpan, isAttr) { + var report = isAttr ? this._schemaRegistry.validateAttribute(propName) : + this._schemaRegistry.validateProperty(propName); + if (report.error) { + this._reportError(report.msg, sourceSpan, ParseErrorLevel.FATAL); } }; + TemplateParseVisitor.prototype._findComponentDirectives = function (directives) { + return directives.filter(function (directive) { return directive.directive.isComponent; }); + }; TemplateParseVisitor.prototype._findComponentDirectiveNames = function (directives) { - var componentTypeNames = []; - directives.forEach(function (directive) { - var typeName = directive.directive.type.name; - if (directive.directive.isComponent) { - componentTypeNames.push(typeName); - } - }); - return componentTypeNames; + return this._findComponentDirectives(directives) + .map(function (directive) { return directive.directive.type.name; }); }; TemplateParseVisitor.prototype._assertOnlyOneComponent = function (directives, sourceSpan) { var componentTypeNames = this._findComponentDirectiveNames(directives); @@ -18597,7 +18549,7 @@ if (!matchElement && !this._schemaRegistry.hasElement(elName, this._schemas)) { var errorMsg = ("'" + elName + "' is not a known element:\n") + ("1. If '" + elName + "' is an Angular component, then verify that it is part of this module.\n") + - ("2. If '" + elName + "' is a Web Component then add \"CUSTOM_ELEMENTS_SCHEMA\" to the '@NgModule.schema' of this component to suppress this message."); + ("2. If '" + elName + "' is a Web Component then add \"CUSTOM_ELEMENTS_SCHEMA\" to the '@NgModule.schemas' of this component to suppress this message."); this._reportError(errorMsg, element.sourceSpan); } }; @@ -18615,7 +18567,8 @@ var _this = this; var allDirectiveEvents = new Set(); directives.forEach(function (directive) { - StringMapWrapper.forEach(directive.directive.outputs, function (eventName) { + Object.keys(directive.directive.outputs).forEach(function (k) { + var eventName = directive.directive.outputs[k]; allDirectiveEvents.add(eventName); }); }); @@ -18746,6 +18699,9 @@ }; return PipeCollector; }(RecursiveAstVisitor)); + function _isAnimationLabel(name) { + return name[0] == '@'; + } function unimplemented$1() { throw new Error('unimplemented'); @@ -18839,7 +18795,7 @@ * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ - var __extends$11 = (this && this.__extends) || function (d, b) { + var __extends$12 = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); @@ -18852,14 +18808,14 @@ return AnimationAst; }()); var AnimationStateAst = (function (_super) { - __extends$11(AnimationStateAst, _super); + __extends$12(AnimationStateAst, _super); function AnimationStateAst() { _super.apply(this, arguments); } return AnimationStateAst; }(AnimationAst)); var AnimationEntryAst = (function (_super) { - __extends$11(AnimationEntryAst, _super); + __extends$12(AnimationEntryAst, _super); function AnimationEntryAst(name, stateDeclarations, stateTransitions) { _super.call(this); this.name = name; @@ -18872,7 +18828,7 @@ return AnimationEntryAst; }(AnimationAst)); var AnimationStateDeclarationAst = (function (_super) { - __extends$11(AnimationStateDeclarationAst, _super); + __extends$12(AnimationStateDeclarationAst, _super); function AnimationStateDeclarationAst(stateName, styles) { _super.call(this); this.stateName = stateName; @@ -18891,7 +18847,7 @@ return AnimationStateTransitionExpression; }()); var AnimationStateTransitionAst = (function (_super) { - __extends$11(AnimationStateTransitionAst, _super); + __extends$12(AnimationStateTransitionAst, _super); function AnimationStateTransitionAst(stateChanges, animation) { _super.call(this); this.stateChanges = stateChanges; @@ -18903,7 +18859,7 @@ return AnimationStateTransitionAst; }(AnimationStateAst)); var AnimationStepAst = (function (_super) { - __extends$11(AnimationStepAst, _super); + __extends$12(AnimationStepAst, _super); function AnimationStepAst(startingStyles, keyframes, duration, delay, easing) { _super.call(this); this.startingStyles = startingStyles; @@ -18918,7 +18874,7 @@ return AnimationStepAst; }(AnimationAst)); var AnimationStylesAst = (function (_super) { - __extends$11(AnimationStylesAst, _super); + __extends$12(AnimationStylesAst, _super); function AnimationStylesAst(styles) { _super.call(this); this.styles = styles; @@ -18929,7 +18885,7 @@ return AnimationStylesAst; }(AnimationAst)); var AnimationKeyframeAst = (function (_super) { - __extends$11(AnimationKeyframeAst, _super); + __extends$12(AnimationKeyframeAst, _super); function AnimationKeyframeAst(offset, styles) { _super.call(this); this.offset = offset; @@ -18941,7 +18897,7 @@ return AnimationKeyframeAst; }(AnimationAst)); var AnimationWithStepsAst = (function (_super) { - __extends$11(AnimationWithStepsAst, _super); + __extends$12(AnimationWithStepsAst, _super); function AnimationWithStepsAst(steps) { _super.call(this); this.steps = steps; @@ -18949,7 +18905,7 @@ return AnimationWithStepsAst; }(AnimationAst)); var AnimationGroupAst = (function (_super) { - __extends$11(AnimationGroupAst, _super); + __extends$12(AnimationGroupAst, _super); function AnimationGroupAst(steps) { _super.call(this, steps); } @@ -18959,7 +18915,7 @@ return AnimationGroupAst; }(AnimationWithStepsAst)); var AnimationSequenceAst = (function (_super) { - __extends$11(AnimationSequenceAst, _super); + __extends$12(AnimationSequenceAst, _super); function AnimationSequenceAst(steps) { _super.call(this, steps); } @@ -18969,7 +18925,281 @@ return AnimationSequenceAst; }(AnimationWithStepsAst)); - var Math$2 = global$1.Math; + var AnimationEntryCompileResult = (function () { + function AnimationEntryCompileResult(name, statements, fnExp) { + this.name = name; + this.statements = statements; + this.fnExp = fnExp; + } + return AnimationEntryCompileResult; + }()); + var AnimationCompiler = (function () { + function AnimationCompiler() { + } + AnimationCompiler.prototype.compile = function (factoryNamePrefix, parsedAnimations) { + return parsedAnimations.map(function (entry) { + var factoryName = factoryNamePrefix + "_" + entry.name; + var visitor = new _AnimationBuilder(entry.name, factoryName); + return visitor.build(entry); + }); + }; + return AnimationCompiler; + }()); + var _ANIMATION_FACTORY_ELEMENT_VAR = variable('element'); + var _ANIMATION_DEFAULT_STATE_VAR = variable('defaultStateStyles'); + var _ANIMATION_FACTORY_VIEW_VAR = variable('view'); + var _ANIMATION_FACTORY_RENDERER_VAR = _ANIMATION_FACTORY_VIEW_VAR.prop('renderer'); + var _ANIMATION_CURRENT_STATE_VAR = variable('currentState'); + var _ANIMATION_NEXT_STATE_VAR = variable('nextState'); + var _ANIMATION_PLAYER_VAR = variable('player'); + var _ANIMATION_TIME_VAR = variable('totalTime'); + var _ANIMATION_START_STATE_STYLES_VAR = variable('startStateStyles'); + var _ANIMATION_END_STATE_STYLES_VAR = variable('endStateStyles'); + var _ANIMATION_COLLECTED_STYLES = variable('collectedStyles'); + var EMPTY_MAP$1 = literalMap([]); + var _AnimationBuilder = (function () { + function _AnimationBuilder(animationName, factoryName) { + this.animationName = animationName; + this._fnVarName = factoryName + '_factory'; + this._statesMapVarName = factoryName + '_states'; + this._statesMapVar = variable(this._statesMapVarName); + } + _AnimationBuilder.prototype.visitAnimationStyles = function (ast, context) { + var stylesArr = []; + if (context.isExpectingFirstStyleStep) { + stylesArr.push(_ANIMATION_START_STATE_STYLES_VAR); + context.isExpectingFirstStyleStep = false; + } + ast.styles.forEach(function (entry) { + stylesArr.push(literalMap(Object.keys(entry).map(function (key) { return [key, literal(entry[key])]; }))); + }); + return importExpr(resolveIdentifier(Identifiers.AnimationStyles)).instantiate([ + importExpr(resolveIdentifier(Identifiers.collectAndResolveStyles)).callFn([ + _ANIMATION_COLLECTED_STYLES, literalArr(stylesArr) + ]) + ]); + }; + _AnimationBuilder.prototype.visitAnimationKeyframe = function (ast, context) { + return importExpr(resolveIdentifier(Identifiers.AnimationKeyframe)).instantiate([ + literal(ast.offset), ast.styles.visit(this, context) + ]); + }; + _AnimationBuilder.prototype.visitAnimationStep = function (ast, context) { + var _this = this; + if (context.endStateAnimateStep === ast) { + return this._visitEndStateAnimation(ast, context); + } + var startingStylesExpr = ast.startingStyles.visit(this, context); + var keyframeExpressions = ast.keyframes.map(function (keyframeEntry) { return keyframeEntry.visit(_this, context); }); + return this._callAnimateMethod(ast, startingStylesExpr, literalArr(keyframeExpressions), context); + }; + /** @internal */ + _AnimationBuilder.prototype._visitEndStateAnimation = function (ast, context) { + var _this = this; + var startingStylesExpr = ast.startingStyles.visit(this, context); + var keyframeExpressions = ast.keyframes.map(function (keyframe) { return keyframe.visit(_this, context); }); + var keyframesExpr = importExpr(resolveIdentifier(Identifiers.balanceAnimationKeyframes)).callFn([ + _ANIMATION_COLLECTED_STYLES, _ANIMATION_END_STATE_STYLES_VAR, + literalArr(keyframeExpressions) + ]); + return this._callAnimateMethod(ast, startingStylesExpr, keyframesExpr, context); + }; + /** @internal */ + _AnimationBuilder.prototype._callAnimateMethod = function (ast, startingStylesExpr, keyframesExpr, context) { + context.totalTransitionTime += ast.duration + ast.delay; + return _ANIMATION_FACTORY_RENDERER_VAR.callMethod('animate', [ + _ANIMATION_FACTORY_ELEMENT_VAR, startingStylesExpr, keyframesExpr, literal(ast.duration), + literal(ast.delay), literal(ast.easing) + ]); + }; + _AnimationBuilder.prototype.visitAnimationSequence = function (ast, context) { + var _this = this; + var playerExprs = ast.steps.map(function (step) { return step.visit(_this, context); }); + return importExpr(resolveIdentifier(Identifiers.AnimationSequencePlayer)).instantiate([ + literalArr(playerExprs) + ]); + }; + _AnimationBuilder.prototype.visitAnimationGroup = function (ast, context) { + var _this = this; + var playerExprs = ast.steps.map(function (step) { return step.visit(_this, context); }); + return importExpr(resolveIdentifier(Identifiers.AnimationGroupPlayer)).instantiate([ + literalArr(playerExprs) + ]); + }; + _AnimationBuilder.prototype.visitAnimationStateDeclaration = function (ast, context) { + var flatStyles = {}; + _getStylesArray(ast).forEach(function (entry) { Object.keys(entry).forEach(function (key) { flatStyles[key] = entry[key]; }); }); + context.stateMap.registerState(ast.stateName, flatStyles); + }; + _AnimationBuilder.prototype.visitAnimationStateTransition = function (ast, context) { + var steps = ast.animation.steps; + var lastStep = steps[steps.length - 1]; + if (_isEndStateAnimateStep(lastStep)) { + context.endStateAnimateStep = lastStep; + } + context.totalTransitionTime = 0; + context.isExpectingFirstStyleStep = true; + var stateChangePreconditions = []; + ast.stateChanges.forEach(function (stateChange) { + stateChangePreconditions.push(_compareToAnimationStateExpr(_ANIMATION_CURRENT_STATE_VAR, stateChange.fromState) + .and(_compareToAnimationStateExpr(_ANIMATION_NEXT_STATE_VAR, stateChange.toState))); + if (stateChange.fromState != ANY_STATE) { + context.stateMap.registerState(stateChange.fromState); + } + if (stateChange.toState != ANY_STATE) { + context.stateMap.registerState(stateChange.toState); + } + }); + var animationPlayerExpr = ast.animation.visit(this, context); + var reducedStateChangesPrecondition = stateChangePreconditions.reduce(function (a, b) { return a.or(b); }); + var precondition = _ANIMATION_PLAYER_VAR.equals(NULL_EXPR).and(reducedStateChangesPrecondition); + var animationStmt = _ANIMATION_PLAYER_VAR.set(animationPlayerExpr).toStmt(); + var totalTimeStmt = _ANIMATION_TIME_VAR.set(literal(context.totalTransitionTime)).toStmt(); + return new IfStmt(precondition, [animationStmt, totalTimeStmt]); + }; + _AnimationBuilder.prototype.visitAnimationEntry = function (ast, context) { + var _this = this; + // visit each of the declarations first to build the context state map + ast.stateDeclarations.forEach(function (def) { return def.visit(_this, context); }); + // this should always be defined even if the user overrides it + context.stateMap.registerState(DEFAULT_STATE, {}); + var statements = []; + statements.push(_ANIMATION_FACTORY_VIEW_VAR + .callMethod('cancelActiveAnimation', [ + _ANIMATION_FACTORY_ELEMENT_VAR, literal(this.animationName), + _ANIMATION_NEXT_STATE_VAR.equals(literal(EMPTY_ANIMATION_STATE)) + ]) + .toStmt()); + statements.push(_ANIMATION_COLLECTED_STYLES.set(EMPTY_MAP$1).toDeclStmt()); + statements.push(_ANIMATION_PLAYER_VAR.set(NULL_EXPR).toDeclStmt()); + statements.push(_ANIMATION_TIME_VAR.set(literal(0)).toDeclStmt()); + statements.push(_ANIMATION_DEFAULT_STATE_VAR.set(this._statesMapVar.key(literal(DEFAULT_STATE))) + .toDeclStmt()); + statements.push(_ANIMATION_START_STATE_STYLES_VAR.set(this._statesMapVar.key(_ANIMATION_CURRENT_STATE_VAR)) + .toDeclStmt()); + statements.push(new IfStmt(_ANIMATION_START_STATE_STYLES_VAR.equals(NULL_EXPR), [_ANIMATION_START_STATE_STYLES_VAR.set(_ANIMATION_DEFAULT_STATE_VAR).toStmt()])); + statements.push(_ANIMATION_END_STATE_STYLES_VAR.set(this._statesMapVar.key(_ANIMATION_NEXT_STATE_VAR)) + .toDeclStmt()); + statements.push(new IfStmt(_ANIMATION_END_STATE_STYLES_VAR.equals(NULL_EXPR), [_ANIMATION_END_STATE_STYLES_VAR.set(_ANIMATION_DEFAULT_STATE_VAR).toStmt()])); + var RENDER_STYLES_FN = importExpr(resolveIdentifier(Identifiers.renderStyles)); + // before we start any animation we want to clear out the starting + // styles from the element's style property (since they were placed + // there at the end of the last animation + statements.push(RENDER_STYLES_FN + .callFn([ + _ANIMATION_FACTORY_ELEMENT_VAR, _ANIMATION_FACTORY_RENDERER_VAR, + importExpr(resolveIdentifier(Identifiers.clearStyles)) + .callFn([_ANIMATION_START_STATE_STYLES_VAR]) + ]) + .toStmt()); + ast.stateTransitions.forEach(function (transAst) { return statements.push(transAst.visit(_this, context)); }); + // this check ensures that the animation factory always returns a player + // so that the onDone callback can be used for tracking + statements.push(new IfStmt(_ANIMATION_PLAYER_VAR.equals(NULL_EXPR), [_ANIMATION_PLAYER_VAR + .set(importExpr(resolveIdentifier(Identifiers.NoOpAnimationPlayer)).instantiate([])) + .toStmt()])); + // once complete we want to apply the styles on the element + // since the destination state's values should persist once + // the animation sequence has completed. + statements.push(_ANIMATION_PLAYER_VAR + .callMethod('onDone', [fn([], [RENDER_STYLES_FN + .callFn([ + _ANIMATION_FACTORY_ELEMENT_VAR, _ANIMATION_FACTORY_RENDERER_VAR, + importExpr(resolveIdentifier(Identifiers.prepareFinalAnimationStyles)) + .callFn([ + _ANIMATION_START_STATE_STYLES_VAR, _ANIMATION_END_STATE_STYLES_VAR + ]) + ]) + .toStmt()])]) + .toStmt()); + statements.push(_ANIMATION_FACTORY_VIEW_VAR + .callMethod('queueAnimation', [ + _ANIMATION_FACTORY_ELEMENT_VAR, literal(this.animationName), + _ANIMATION_PLAYER_VAR, _ANIMATION_TIME_VAR, + _ANIMATION_CURRENT_STATE_VAR, _ANIMATION_NEXT_STATE_VAR + ]) + .toStmt()); + return fn([ + new FnParam(_ANIMATION_FACTORY_VIEW_VAR.name, importType(resolveIdentifier(Identifiers.AppView), [DYNAMIC_TYPE])), + new FnParam(_ANIMATION_FACTORY_ELEMENT_VAR.name, DYNAMIC_TYPE), + new FnParam(_ANIMATION_CURRENT_STATE_VAR.name, DYNAMIC_TYPE), + new FnParam(_ANIMATION_NEXT_STATE_VAR.name, DYNAMIC_TYPE) + ], statements); + }; + _AnimationBuilder.prototype.build = function (ast) { + var context = new _AnimationBuilderContext(); + var fnStatement = ast.visit(this, context).toDeclStmt(this._fnVarName); + var fnVariable = variable(this._fnVarName); + var lookupMap = []; + Object.keys(context.stateMap.states).forEach(function (stateName) { + var value = context.stateMap.states[stateName]; + var variableValue = EMPTY_MAP$1; + if (isPresent(value)) { + var styleMap_1 = []; + Object.keys(value).forEach(function (key) { styleMap_1.push([key, literal(value[key])]); }); + variableValue = literalMap(styleMap_1); + } + lookupMap.push([stateName, variableValue]); + }); + var compiledStatesMapStmt = this._statesMapVar.set(literalMap(lookupMap)).toDeclStmt(); + var statements = [compiledStatesMapStmt, fnStatement]; + return new AnimationEntryCompileResult(this.animationName, statements, fnVariable); + }; + return _AnimationBuilder; + }()); + var _AnimationBuilderContext = (function () { + function _AnimationBuilderContext() { + this.stateMap = new _AnimationBuilderStateMap(); + this.endStateAnimateStep = null; + this.isExpectingFirstStyleStep = false; + this.totalTransitionTime = 0; + } + return _AnimationBuilderContext; + }()); + var _AnimationBuilderStateMap = (function () { + function _AnimationBuilderStateMap() { + this._states = {}; + } + Object.defineProperty(_AnimationBuilderStateMap.prototype, "states", { + get: function () { return this._states; }, + enumerable: true, + configurable: true + }); + _AnimationBuilderStateMap.prototype.registerState = function (name, value) { + if (value === void 0) { value = null; } + var existingEntry = this._states[name]; + if (!existingEntry) { + this._states[name] = value; + } + }; + return _AnimationBuilderStateMap; + }()); + function _compareToAnimationStateExpr(value, animationState) { + var emptyStateLiteral = literal(EMPTY_ANIMATION_STATE); + switch (animationState) { + case EMPTY_ANIMATION_STATE: + return value.equals(emptyStateLiteral); + case ANY_STATE: + return literal(true); + default: + return value.equals(literal(animationState)); + } + } + function _isEndStateAnimateStep(step) { + // the final animation step is characterized by having only TWO + // keyframe values and it must have zero styles for both keyframes + if (step instanceof AnimationStepAst && step.duration > 0 && step.keyframes.length == 2) { + var styles1 = _getStylesArray(step.keyframes[0])[0]; + var styles2 = _getStylesArray(step.keyframes[1])[0]; + return Object.keys(styles1).length === 0 && Object.keys(styles2).length === 0; + } + return false; + } + function _getStylesArray(obj) { + return obj.styles.styles; + } + + var Math$1 = global$1.Math; var StylesCollectionEntry = (function () { function StylesCollectionEntry(time, value) { @@ -19029,7 +19259,7 @@ * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ - var __extends$12 = (this && this.__extends) || function (d, b) { + var __extends$13 = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); @@ -19038,62 +19268,73 @@ var _TERMINAL_KEYFRAME = 1; var _ONE_SECOND = 1000; var AnimationParseError = (function (_super) { - __extends$12(AnimationParseError, _super); - function AnimationParseError(message /** TODO #9100 */) { + __extends$13(AnimationParseError, _super); + function AnimationParseError(message) { _super.call(this, null, message); } AnimationParseError.prototype.toString = function () { return "" + this.msg; }; return AnimationParseError; }(ParseError)); - var ParsedAnimationResult = (function () { - function ParsedAnimationResult(ast, errors) { + var AnimationEntryParseResult = (function () { + function AnimationEntryParseResult(ast, errors) { this.ast = ast; this.errors = errors; } - return ParsedAnimationResult; + return AnimationEntryParseResult; }()); - function parseAnimationEntry(entry) { - var errors = []; - var stateStyles = {}; - var transitions = []; - var stateDeclarationAsts = []; - entry.definitions.forEach(function (def) { - if (def instanceof CompileAnimationStateDeclarationMetadata) { - _parseAnimationDeclarationStates(def, errors).forEach(function (ast) { - stateDeclarationAsts.push(ast); - stateStyles[ast.stateName] = ast.styles; - }); - } - else { - transitions.push(def); - } - }); - var stateTransitionAsts = transitions.map(function (transDef) { return _parseAnimationStateTransition(transDef, stateStyles, errors); }); - var ast = new AnimationEntryAst(entry.name, stateDeclarationAsts, stateTransitionAsts); - return new ParsedAnimationResult(ast, errors); - } - function parseAnimationOutputName(outputName, errors) { - var values = outputName.split('.'); - var name; - var phase = ''; - if (values.length > 1) { - name = values[0]; - var parsedPhase = values[1]; - switch (parsedPhase) { - case 'start': - case 'done': - phase = parsedPhase; - break; - default: - errors.push(new AnimationParseError("The provided animation output phase value \"" + parsedPhase + "\" for \"@" + name + "\" is not supported (use start or done)")); - } + var AnimationParser = (function () { + function AnimationParser() { } - else { - name = outputName; - errors.push(new AnimationParseError("The animation trigger output event (@" + name + ") is missing its phase value name (start or done are currently supported)")); - } - return new AnimationOutput(name, phase, outputName); - } + AnimationParser.prototype.parseComponent = function (component) { + var _this = this; + var errors = []; + var componentName = component.type.name; + var animationTriggerNames = new Set(); + var asts = component.template.animations.map(function (entry) { + var result = _this.parseEntry(entry); + var ast = result.ast; + var triggerName = ast.name; + if (animationTriggerNames.has(triggerName)) { + result.errors.push(new AnimationParseError("The animation trigger \"" + triggerName + "\" has already been registered for the " + componentName + " component")); + } + else { + animationTriggerNames.add(triggerName); + } + if (result.errors.length > 0) { + var errorMessage_1 = "- Unable to parse the animation sequence for \"" + triggerName + "\" on the " + componentName + " component due to the following errors:"; + result.errors.forEach(function (error) { errorMessage_1 += '\n-- ' + error.msg; }); + errors.push(errorMessage_1); + } + return ast; + }); + if (errors.length > 0) { + var errorString = errors.join('\n'); + throw new Error("Animation parse errors:\n" + errorString); + } + return asts; + }; + AnimationParser.prototype.parseEntry = function (entry) { + var errors = []; + var stateStyles = {}; + var transitions = []; + var stateDeclarationAsts = []; + entry.definitions.forEach(function (def) { + if (def instanceof CompileAnimationStateDeclarationMetadata) { + _parseAnimationDeclarationStates(def, errors).forEach(function (ast) { + stateDeclarationAsts.push(ast); + stateStyles[ast.stateName] = ast.styles; + }); + } + else { + transitions.push(def); + } + }); + var stateTransitionAsts = transitions.map(function (transDef) { return _parseAnimationStateTransition(transDef, stateStyles, errors); }); + var ast = new AnimationEntryAst(entry.name, stateDeclarationAsts, stateTransitionAsts); + return new AnimationEntryParseResult(ast, errors); + }; + return AnimationParser; + }()); function _parseAnimationDeclarationStates(stateMetadata, errors) { var styleValues = []; stateMetadata.styles.styles.forEach(function (stylesEntry) { @@ -19124,13 +19365,27 @@ if (errors.length == 0) { _fillAnimationAstStartingKeyframes(animationAst, styles, errors); } - var sequenceAst = (animationAst instanceof AnimationSequenceAst) ? + var stepsAst = (animationAst instanceof AnimationWithStepsAst) ? animationAst : new AnimationSequenceAst([animationAst]); - return new AnimationStateTransitionAst(transitionExprs, sequenceAst); + return new AnimationStateTransitionAst(transitionExprs, stepsAst); + } + function _parseAnimationAlias(alias, errors) { + switch (alias) { + case ':enter': + return 'void => *'; + case ':leave': + return '* => void'; + default: + errors.push(new AnimationParseError("the transition alias value \"" + alias + "\" is not supported")); + return '* => *'; + } } function _parseAnimationTransitionExpr(eventStr, errors) { var expressions = []; + if (eventStr[0] == ':') { + eventStr = _parseAnimationAlias(eventStr, errors); + } var match = eventStr.match(/^(\*|[-\w]+)\s*()\s*(\*|[-\w]+)$/); if (!isPresent(match) || match.length < 4) { errors.push(new AnimationParseError("the provided " + eventStr + " is not of a supported format")); @@ -19164,7 +19419,9 @@ } function _normalizeStyleSteps(entry, stateStyles, errors) { var steps = _normalizeStyleStepEntry(entry, stateStyles, errors); - return new CompileAnimationSequenceMetadata(steps); + return (entry instanceof CompileAnimationGroupMetadata) ? + new CompileAnimationGroupMetadata(steps) : + new CompileAnimationSequenceMetadata(steps); } function _mergeAnimationStyles(stylesList, newItem) { if (isStringMap(newItem) && stylesList.length > 0) { @@ -19282,9 +19539,9 @@ var offset = styleMetadata.offset; var keyframeStyles = {}; styleMetadata.styles.forEach(function (entry) { - StringMapWrapper.forEach(entry, function (value /** TODO #9100 */, prop /** TODO #9100 */) { + Object.keys(entry).forEach(function (prop) { if (prop != 'offset') { - keyframeStyles[prop] = value; + keyframeStyles[prop] = entry[prop]; } }); }); @@ -19317,20 +19574,23 @@ for (i = 1; i <= limit; i++) { var entry = rawKeyframes[i]; var styles = entry[1]; - StringMapWrapper.forEach(styles, function (value /** TODO #9100 */, prop /** TODO #9100 */) { + Object.keys(styles).forEach(function (prop) { if (!isPresent(firstKeyframeStyles[prop])) { firstKeyframeStyles[prop] = FILL_STYLE_FLAG; } }); } - for (i = limit - 1; i >= 0; i--) { + var _loop_1 = function() { var entry = rawKeyframes[i]; var styles = entry[1]; - StringMapWrapper.forEach(styles, function (value /** TODO #9100 */, prop /** TODO #9100 */) { + Object.keys(styles).forEach(function (prop) { if (!isPresent(lastKeyframeStyles[prop])) { - lastKeyframeStyles[prop] = value; + lastKeyframeStyles[prop] = styles[prop]; } }); + }; + for (i = limit - 1; i >= 0; i--) { + _loop_1(); } return rawKeyframes.map(function (entry) { return new AnimationKeyframeAst(entry[0], new AnimationStylesAst([entry[1]])); }); } @@ -19350,9 +19610,7 @@ entry.styles.forEach(function (stylesEntry) { // by this point we know that we only have stringmap values var map = stylesEntry; - StringMapWrapper.forEach(map, function (value /** TODO #9100 */, prop /** TODO #9100 */) { - collectedStyles.insertAtTime(prop, time, value); - }); + Object.keys(map).forEach(function (prop) { collectedStyles.insertAtTime(prop, time, map[prop]); }); }); previousStyles = entry.styles; return; @@ -19372,7 +19630,7 @@ var astDuration = innerAst.playTime; currentTime += astDuration; playTime += astDuration; - maxDuration = Math$2.max(astDuration, maxDuration); + maxDuration = Math$1.max(astDuration, maxDuration); steps.push(innerAst); }); if (isPresent(previousStyles)) { @@ -19406,9 +19664,7 @@ ast = new AnimationStepAst(new AnimationStylesAst([]), keyframes, timings.duration, timings.delay, timings.easing); playTime = timings.duration + timings.delay; currentTime += playTime; - keyframes.forEach(function (keyframe /** TODO #9100 */) { return keyframe.styles.styles.forEach(function (entry /** TODO #9100 */) { return StringMapWrapper.forEach(entry, function (value /** TODO #9100 */, prop /** TODO #9100 */) { - return collectedStyles.insertAtTime(prop, currentTime, value); - }); }); }); + keyframes.forEach(function (keyframe /** TODO #9100 */) { return keyframe.styles.styles.forEach(function (entry /** TODO #9100 */) { return Object.keys(entry).forEach(function (prop) { collectedStyles.insertAtTime(prop, currentTime, entry[prop]); }); }); }); } else { // if the code reaches this stage then an error @@ -19445,20 +19701,20 @@ errors.push(new AnimationParseError("The provided timing value \"" + exp + "\" is invalid.")); return new _AnimationTimings(0, 0, null); } - var durationMatch = NumberWrapper.parseFloat(matches[1]); + var durationMatch = parseFloat(matches[1]); var durationUnit = matches[2]; if (durationUnit == 's') { durationMatch *= _ONE_SECOND; } - duration = Math$2.floor(durationMatch); + duration = Math$1.floor(durationMatch); var delayMatch = matches[3]; var delayUnit = matches[4]; if (isPresent(delayMatch)) { - var delayVal = NumberWrapper.parseFloat(delayMatch); + var delayVal = parseFloat(delayMatch); if (isPresent(delayUnit) && delayUnit == 's') { delayVal *= _ONE_SECOND; } - delay = Math$2.floor(delayVal); + delay = Math$1.floor(delayVal); } var easingVal = matches[5]; if (!isBlank(easingVal)) { @@ -19474,7 +19730,8 @@ var values = {}; var endTime = startTime + duration; endKeyframe.styles.styles.forEach(function (styleData) { - StringMapWrapper.forEach(styleData, function (val /** TODO #9100 */, prop /** TODO #9100 */) { + Object.keys(styleData).forEach(function (prop) { + var val = styleData[prop]; if (prop == 'offset') return; var resultIndex = collectedStyles.indexOfAtOrBeforeTime(prop, startTime); @@ -19499,399 +19756,6 @@ return new AnimationKeyframeAst(_INITIAL_KEYFRAME, new AnimationStylesAst([values])); } - var animationCompilationCache = new Map(); - var CompiledAnimationTriggerResult = (function () { - function CompiledAnimationTriggerResult(name, statesMapStatement, statesVariableName, fnStatement, fnVariable) { - this.name = name; - this.statesMapStatement = statesMapStatement; - this.statesVariableName = statesVariableName; - this.fnStatement = fnStatement; - this.fnVariable = fnVariable; - } - return CompiledAnimationTriggerResult; - }()); - var CompiledComponentAnimationResult = (function () { - function CompiledComponentAnimationResult(outputs, triggers) { - this.outputs = outputs; - this.triggers = triggers; - } - return CompiledComponentAnimationResult; - }()); - var AnimationCompiler = (function () { - function AnimationCompiler() { - } - AnimationCompiler.prototype.compileComponent = function (component, template) { - var compiledAnimations = []; - var groupedErrors = []; - var triggerLookup = {}; - var componentName = component.type.name; - component.template.animations.forEach(function (entry) { - var result = parseAnimationEntry(entry); - var triggerName = entry.name; - if (result.errors.length > 0) { - var errorMessage = "Unable to parse the animation sequence for \"" + triggerName + "\" due to the following errors:"; - result.errors.forEach(function (error) { errorMessage += '\n-- ' + error.msg; }); - groupedErrors.push(errorMessage); - } - if (triggerLookup[triggerName]) { - groupedErrors.push("The animation trigger \"" + triggerName + "\" has already been registered on \"" + componentName + "\""); - } - else { - var factoryName = componentName + "_" + entry.name; - var visitor = new _AnimationBuilder(triggerName, factoryName); - var compileResult = visitor.build(result.ast); - compiledAnimations.push(compileResult); - triggerLookup[entry.name] = compileResult; - } - }); - var validatedProperties = _validateAnimationProperties(compiledAnimations, template); - validatedProperties.errors.forEach(function (error) { groupedErrors.push(error.msg); }); - if (groupedErrors.length > 0) { - var errorMessageStr = "Animation parsing for " + component.type.name + " has failed due to the following errors:"; - groupedErrors.forEach(function (error) { return errorMessageStr += "\n- " + error; }); - throw new Error(errorMessageStr); - } - animationCompilationCache.set(component, compiledAnimations); - return new CompiledComponentAnimationResult(validatedProperties.outputs, compiledAnimations); - }; - return AnimationCompiler; - }()); - var _ANIMATION_FACTORY_ELEMENT_VAR = variable('element'); - var _ANIMATION_DEFAULT_STATE_VAR = variable('defaultStateStyles'); - var _ANIMATION_FACTORY_VIEW_VAR = variable('view'); - var _ANIMATION_FACTORY_RENDERER_VAR = _ANIMATION_FACTORY_VIEW_VAR.prop('renderer'); - var _ANIMATION_CURRENT_STATE_VAR = variable('currentState'); - var _ANIMATION_NEXT_STATE_VAR = variable('nextState'); - var _ANIMATION_PLAYER_VAR = variable('player'); - var _ANIMATION_TIME_VAR = variable('totalTime'); - var _ANIMATION_START_STATE_STYLES_VAR = variable('startStateStyles'); - var _ANIMATION_END_STATE_STYLES_VAR = variable('endStateStyles'); - var _ANIMATION_COLLECTED_STYLES = variable('collectedStyles'); - var EMPTY_MAP$1 = literalMap([]); - var _AnimationBuilder = (function () { - function _AnimationBuilder(animationName, factoryName) { - this.animationName = animationName; - this._fnVarName = factoryName + '_factory'; - this._statesMapVarName = factoryName + '_states'; - this._statesMapVar = variable(this._statesMapVarName); - } - _AnimationBuilder.prototype.visitAnimationStyles = function (ast, context) { - var stylesArr = []; - if (context.isExpectingFirstStyleStep) { - stylesArr.push(_ANIMATION_START_STATE_STYLES_VAR); - context.isExpectingFirstStyleStep = false; - } - ast.styles.forEach(function (entry) { - stylesArr.push(literalMap(StringMapWrapper.keys(entry).map(function (key) { return [key, literal(entry[key])]; }))); - }); - return importExpr(resolveIdentifier(Identifiers.AnimationStyles)).instantiate([ - importExpr(resolveIdentifier(Identifiers.collectAndResolveStyles)).callFn([ - _ANIMATION_COLLECTED_STYLES, literalArr(stylesArr) - ]) - ]); - }; - _AnimationBuilder.prototype.visitAnimationKeyframe = function (ast, context) { - return importExpr(resolveIdentifier(Identifiers.AnimationKeyframe)).instantiate([ - literal(ast.offset), ast.styles.visit(this, context) - ]); - }; - _AnimationBuilder.prototype.visitAnimationStep = function (ast, context) { - var _this = this; - if (context.endStateAnimateStep === ast) { - return this._visitEndStateAnimation(ast, context); - } - var startingStylesExpr = ast.startingStyles.visit(this, context); - var keyframeExpressions = ast.keyframes.map(function (keyframeEntry) { return keyframeEntry.visit(_this, context); }); - return this._callAnimateMethod(ast, startingStylesExpr, literalArr(keyframeExpressions), context); - }; - /** @internal */ - _AnimationBuilder.prototype._visitEndStateAnimation = function (ast, context) { - var _this = this; - var startingStylesExpr = ast.startingStyles.visit(this, context); - var keyframeExpressions = ast.keyframes.map(function (keyframe) { return keyframe.visit(_this, context); }); - var keyframesExpr = importExpr(resolveIdentifier(Identifiers.balanceAnimationKeyframes)).callFn([ - _ANIMATION_COLLECTED_STYLES, _ANIMATION_END_STATE_STYLES_VAR, - literalArr(keyframeExpressions) - ]); - return this._callAnimateMethod(ast, startingStylesExpr, keyframesExpr, context); - }; - /** @internal */ - _AnimationBuilder.prototype._callAnimateMethod = function (ast, startingStylesExpr, keyframesExpr, context) { - context.totalTransitionTime += ast.duration + ast.delay; - return _ANIMATION_FACTORY_RENDERER_VAR.callMethod('animate', [ - _ANIMATION_FACTORY_ELEMENT_VAR, startingStylesExpr, keyframesExpr, literal(ast.duration), - literal(ast.delay), literal(ast.easing) - ]); - }; - _AnimationBuilder.prototype.visitAnimationSequence = function (ast, context) { - var _this = this; - var playerExprs = ast.steps.map(function (step) { return step.visit(_this, context); }); - return importExpr(resolveIdentifier(Identifiers.AnimationSequencePlayer)).instantiate([ - literalArr(playerExprs) - ]); - }; - _AnimationBuilder.prototype.visitAnimationGroup = function (ast, context) { - var _this = this; - var playerExprs = ast.steps.map(function (step) { return step.visit(_this, context); }); - return importExpr(resolveIdentifier(Identifiers.AnimationGroupPlayer)).instantiate([ - literalArr(playerExprs) - ]); - }; - _AnimationBuilder.prototype.visitAnimationStateDeclaration = function (ast, context) { - var flatStyles = {}; - _getStylesArray(ast).forEach(function (entry) { - StringMapWrapper.forEach(entry, function (value, key) { flatStyles[key] = value; }); - }); - context.stateMap.registerState(ast.stateName, flatStyles); - }; - _AnimationBuilder.prototype.visitAnimationStateTransition = function (ast, context) { - var steps = ast.animation.steps; - var lastStep = steps[steps.length - 1]; - if (_isEndStateAnimateStep(lastStep)) { - context.endStateAnimateStep = lastStep; - } - context.totalTransitionTime = 0; - context.isExpectingFirstStyleStep = true; - var stateChangePreconditions = []; - ast.stateChanges.forEach(function (stateChange) { - stateChangePreconditions.push(_compareToAnimationStateExpr(_ANIMATION_CURRENT_STATE_VAR, stateChange.fromState) - .and(_compareToAnimationStateExpr(_ANIMATION_NEXT_STATE_VAR, stateChange.toState))); - if (stateChange.fromState != ANY_STATE) { - context.stateMap.registerState(stateChange.fromState); - } - if (stateChange.toState != ANY_STATE) { - context.stateMap.registerState(stateChange.toState); - } - }); - var animationPlayerExpr = ast.animation.visit(this, context); - var reducedStateChangesPrecondition = stateChangePreconditions.reduce(function (a, b) { return a.or(b); }); - var precondition = _ANIMATION_PLAYER_VAR.equals(NULL_EXPR).and(reducedStateChangesPrecondition); - var animationStmt = _ANIMATION_PLAYER_VAR.set(animationPlayerExpr).toStmt(); - var totalTimeStmt = _ANIMATION_TIME_VAR.set(literal(context.totalTransitionTime)).toStmt(); - return new IfStmt(precondition, [animationStmt, totalTimeStmt]); - }; - _AnimationBuilder.prototype.visitAnimationEntry = function (ast, context) { - var _this = this; - // visit each of the declarations first to build the context state map - ast.stateDeclarations.forEach(function (def) { return def.visit(_this, context); }); - // this should always be defined even if the user overrides it - context.stateMap.registerState(DEFAULT_STATE, {}); - var statements = []; - statements.push(_ANIMATION_FACTORY_VIEW_VAR - .callMethod('cancelActiveAnimation', [ - _ANIMATION_FACTORY_ELEMENT_VAR, literal(this.animationName), - _ANIMATION_NEXT_STATE_VAR.equals(literal(EMPTY_ANIMATION_STATE)) - ]) - .toStmt()); - statements.push(_ANIMATION_COLLECTED_STYLES.set(EMPTY_MAP$1).toDeclStmt()); - statements.push(_ANIMATION_PLAYER_VAR.set(NULL_EXPR).toDeclStmt()); - statements.push(_ANIMATION_TIME_VAR.set(literal(0)).toDeclStmt()); - statements.push(_ANIMATION_DEFAULT_STATE_VAR.set(this._statesMapVar.key(literal(DEFAULT_STATE))) - .toDeclStmt()); - statements.push(_ANIMATION_START_STATE_STYLES_VAR.set(this._statesMapVar.key(_ANIMATION_CURRENT_STATE_VAR)) - .toDeclStmt()); - statements.push(new IfStmt(_ANIMATION_START_STATE_STYLES_VAR.equals(NULL_EXPR), [_ANIMATION_START_STATE_STYLES_VAR.set(_ANIMATION_DEFAULT_STATE_VAR).toStmt()])); - statements.push(_ANIMATION_END_STATE_STYLES_VAR.set(this._statesMapVar.key(_ANIMATION_NEXT_STATE_VAR)) - .toDeclStmt()); - statements.push(new IfStmt(_ANIMATION_END_STATE_STYLES_VAR.equals(NULL_EXPR), [_ANIMATION_END_STATE_STYLES_VAR.set(_ANIMATION_DEFAULT_STATE_VAR).toStmt()])); - var RENDER_STYLES_FN = importExpr(resolveIdentifier(Identifiers.renderStyles)); - // before we start any animation we want to clear out the starting - // styles from the element's style property (since they were placed - // there at the end of the last animation - statements.push(RENDER_STYLES_FN - .callFn([ - _ANIMATION_FACTORY_ELEMENT_VAR, _ANIMATION_FACTORY_RENDERER_VAR, - importExpr(resolveIdentifier(Identifiers.clearStyles)) - .callFn([_ANIMATION_START_STATE_STYLES_VAR]) - ]) - .toStmt()); - ast.stateTransitions.forEach(function (transAst) { return statements.push(transAst.visit(_this, context)); }); - // this check ensures that the animation factory always returns a player - // so that the onDone callback can be used for tracking - statements.push(new IfStmt(_ANIMATION_PLAYER_VAR.equals(NULL_EXPR), [_ANIMATION_PLAYER_VAR - .set(importExpr(resolveIdentifier(Identifiers.NoOpAnimationPlayer)).instantiate([])) - .toStmt()])); - // once complete we want to apply the styles on the element - // since the destination state's values should persist once - // the animation sequence has completed. - statements.push(_ANIMATION_PLAYER_VAR - .callMethod('onDone', [fn([], [RENDER_STYLES_FN - .callFn([ - _ANIMATION_FACTORY_ELEMENT_VAR, _ANIMATION_FACTORY_RENDERER_VAR, - importExpr(resolveIdentifier(Identifiers.prepareFinalAnimationStyles)) - .callFn([ - _ANIMATION_START_STATE_STYLES_VAR, _ANIMATION_END_STATE_STYLES_VAR - ]) - ]) - .toStmt()])]) - .toStmt()); - statements.push(_ANIMATION_FACTORY_VIEW_VAR - .callMethod('queueAnimation', [ - _ANIMATION_FACTORY_ELEMENT_VAR, literal(this.animationName), - _ANIMATION_PLAYER_VAR, _ANIMATION_TIME_VAR, - _ANIMATION_CURRENT_STATE_VAR, _ANIMATION_NEXT_STATE_VAR - ]) - .toStmt()); - return fn([ - new FnParam(_ANIMATION_FACTORY_VIEW_VAR.name, importType(resolveIdentifier(Identifiers.AppView), [DYNAMIC_TYPE])), - new FnParam(_ANIMATION_FACTORY_ELEMENT_VAR.name, DYNAMIC_TYPE), - new FnParam(_ANIMATION_CURRENT_STATE_VAR.name, DYNAMIC_TYPE), - new FnParam(_ANIMATION_NEXT_STATE_VAR.name, DYNAMIC_TYPE) - ], statements); - }; - _AnimationBuilder.prototype.build = function (ast) { - var context = new _AnimationBuilderContext(); - var fnStatement = ast.visit(this, context).toDeclStmt(this._fnVarName); - var fnVariable = variable(this._fnVarName); - var lookupMap = []; - StringMapWrapper.forEach(context.stateMap.states, function (value, stateName) { - var variableValue = EMPTY_MAP$1; - if (isPresent(value)) { - var styleMap_1 = []; - StringMapWrapper.forEach(value, function (value, key) { - styleMap_1.push([key, literal(value)]); - }); - variableValue = literalMap(styleMap_1); - } - lookupMap.push([stateName, variableValue]); - }); - var compiledStatesMapExpr = this._statesMapVar.set(literalMap(lookupMap)).toDeclStmt(); - return new CompiledAnimationTriggerResult(this.animationName, compiledStatesMapExpr, this._statesMapVarName, fnStatement, fnVariable); - }; - return _AnimationBuilder; - }()); - var _AnimationBuilderContext = (function () { - function _AnimationBuilderContext() { - this.stateMap = new _AnimationBuilderStateMap(); - this.endStateAnimateStep = null; - this.isExpectingFirstStyleStep = false; - this.totalTransitionTime = 0; - } - return _AnimationBuilderContext; - }()); - var _AnimationBuilderStateMap = (function () { - function _AnimationBuilderStateMap() { - this._states = {}; - } - Object.defineProperty(_AnimationBuilderStateMap.prototype, "states", { - get: function () { return this._states; }, - enumerable: true, - configurable: true - }); - _AnimationBuilderStateMap.prototype.registerState = function (name, value) { - if (value === void 0) { value = null; } - var existingEntry = this._states[name]; - if (isBlank(existingEntry)) { - this._states[name] = value; - } - }; - return _AnimationBuilderStateMap; - }()); - function _compareToAnimationStateExpr(value, animationState) { - var emptyStateLiteral = literal(EMPTY_ANIMATION_STATE); - switch (animationState) { - case EMPTY_ANIMATION_STATE: - return value.equals(emptyStateLiteral); - case ANY_STATE: - return literal(true); - default: - return value.equals(literal(animationState)); - } - } - function _isEndStateAnimateStep(step) { - // the final animation step is characterized by having only TWO - // keyframe values and it must have zero styles for both keyframes - if (step instanceof AnimationStepAst && step.duration > 0 && step.keyframes.length == 2) { - var styles1 = _getStylesArray(step.keyframes[0])[0]; - var styles2 = _getStylesArray(step.keyframes[1])[0]; - return StringMapWrapper.isEmpty(styles1) && StringMapWrapper.isEmpty(styles2); - } - return false; - } - function _getStylesArray(obj) { - return obj.styles.styles; - } - function _validateAnimationProperties(compiledAnimations, template) { - var visitor = new _AnimationTemplatePropertyVisitor(compiledAnimations); - templateVisitAll(visitor, template); - return new AnimationPropertyValidationOutput(visitor.outputs, visitor.errors); - } - var AnimationPropertyValidationOutput = (function () { - function AnimationPropertyValidationOutput(outputs, errors) { - this.outputs = outputs; - this.errors = errors; - } - return AnimationPropertyValidationOutput; - }()); - var _AnimationTemplatePropertyVisitor = (function () { - function _AnimationTemplatePropertyVisitor(animations) { - this.errors = []; - this.outputs = []; - this._animationRegistry = this._buildCompileAnimationLookup(animations); - } - _AnimationTemplatePropertyVisitor.prototype._buildCompileAnimationLookup = function (animations) { - var map = {}; - animations.forEach(function (entry) { map[entry.name] = true; }); - return map; - }; - _AnimationTemplatePropertyVisitor.prototype._validateAnimationInputOutputPairs = function (inputAsts, outputAsts, animationRegistry, isHostLevel) { - var _this = this; - var detectedAnimationInputs = {}; - inputAsts.forEach(function (input) { - if (input.type == exports.PropertyBindingType.Animation) { - var triggerName = input.name; - if (isPresent(animationRegistry[triggerName])) { - detectedAnimationInputs[triggerName] = true; - } - else { - _this.errors.push(new AnimationParseError("Couldn't find an animation entry for " + triggerName)); - } - } - }); - outputAsts.forEach(function (output) { - if (output.name[0] == '@') { - var normalizedOutputData = parseAnimationOutputName(output.name.substr(1), _this.errors); - var triggerName = normalizedOutputData.name; - var triggerEventPhase = normalizedOutputData.phase; - if (!animationRegistry[triggerName]) { - _this.errors.push(new AnimationParseError("Couldn't find the corresponding " + (isHostLevel ? 'host-level ' : '') + "animation trigger definition for (@" + triggerName + ")")); - } - else if (!detectedAnimationInputs[triggerName]) { - _this.errors.push(new AnimationParseError("Unable to listen on (@" + triggerName + "." + triggerEventPhase + ") because the animation trigger [@" + triggerName + "] isn't being used on the same element")); - } - else { - _this.outputs.push(normalizedOutputData); - } - } - }); - }; - _AnimationTemplatePropertyVisitor.prototype.visitElement = function (ast, ctx) { - this._validateAnimationInputOutputPairs(ast.inputs, ast.outputs, this._animationRegistry, false); - var componentOnElement = ast.directives.find(function (directive) { return directive.directive.isComponent; }); - if (componentOnElement) { - var cachedComponentAnimations = animationCompilationCache.get(componentOnElement.directive); - if (cachedComponentAnimations) { - this._validateAnimationInputOutputPairs(componentOnElement.hostProperties, componentOnElement.hostEvents, this._buildCompileAnimationLookup(cachedComponentAnimations), true); - } - } - templateVisitAll(this, ast.children); - }; - _AnimationTemplatePropertyVisitor.prototype.visitEmbeddedTemplate = function (ast, ctx) { - templateVisitAll(this, ast.children); - }; - _AnimationTemplatePropertyVisitor.prototype.visitEvent = function (ast, ctx) { }; - _AnimationTemplatePropertyVisitor.prototype.visitBoundText = function (ast, ctx) { }; - _AnimationTemplatePropertyVisitor.prototype.visitText = function (ast, ctx) { }; - _AnimationTemplatePropertyVisitor.prototype.visitNgContent = function (ast, ctx) { }; - _AnimationTemplatePropertyVisitor.prototype.visitAttr = function (ast, ctx) { }; - _AnimationTemplatePropertyVisitor.prototype.visitDirective = function (ast, ctx) { }; - _AnimationTemplatePropertyVisitor.prototype.visitReference = function (ast, ctx) { }; - _AnimationTemplatePropertyVisitor.prototype.visitVariable = function (ast, ctx) { }; - _AnimationTemplatePropertyVisitor.prototype.visitDirectiveProperty = function (ast, ctx) { }; - _AnimationTemplatePropertyVisitor.prototype.visitElementProperty = function (ast, ctx) { }; - return _AnimationTemplatePropertyVisitor; - }()); - function convertValueToOutputAst(value, type) { if (type === void 0) { type = null; } return visitValue(value, new _ValueOutputAstTransformer(), type); @@ -19906,9 +19770,7 @@ _ValueOutputAstTransformer.prototype.visitStringMap = function (map, type) { var _this = this; var entries = []; - StringMapWrapper.forEach(map, function (value, key) { - entries.push([key, visitValue(value, _this, null)]); - }); + Object.keys(map).forEach(function (key) { entries.push([key, visitValue(map[key], _this, null)]); }); return literalMap(entries, type); }; _ValueOutputAstTransformer.prototype.visitPrimitive = function (value, type) { return literal(value, type); }; @@ -20046,7 +19908,7 @@ function createPureProxy(fn, argCount, pureProxyProp, view) { view.fields.push(new ClassField(pureProxyProp.name, null)); var pureProxyId = argCount < Identifiers.pureProxies.length ? Identifiers.pureProxies[argCount] : null; - if (isBlank(pureProxyId)) { + if (!pureProxyId) { throw new Error("Unsupported number of argument for pure functions: " + argCount); } view.createMethod.addStmt(THIS_EXPR.prop(pureProxyProp.name) @@ -20132,9 +19994,7 @@ })); } function mapNestedViews(declarationAppElement, view, expressions) { - var adjustedExpressions = expressions.map(function (expr) { - return replaceVarInExpression(THIS_EXPR.name, variable('nestedView'), expr); - }); + var adjustedExpressions = expressions.map(function (expr) { return replaceVarInExpression(THIS_EXPR.name, variable('nestedView'), expr); }); return declarationAppElement.callMethod('mapNestedViews', [ variable(view.className), fn([new FnParam('nestedView', view.classType)], [new ReturnStatement(literalArr(adjustedExpressions))], DYNAMIC_TYPE) @@ -20152,7 +20012,7 @@ function addQueryToTokenMap(map, query) { query.meta.selectors.forEach(function (selector) { var entry = map.get(selector.reference); - if (isBlank(entry)) { + if (!entry) { entry = []; map.set(selector.reference, entry); } @@ -20270,7 +20130,7 @@ * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ - var __extends$13 = (this && this.__extends) || function (d, b) { + var __extends$14 = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); @@ -20283,12 +20143,12 @@ this.renderNode = renderNode; this.sourceAst = sourceAst; } - CompileNode.prototype.isNull = function () { return isBlank(this.renderNode); }; + CompileNode.prototype.isNull = function () { return !this.renderNode; }; CompileNode.prototype.isRootElement = function () { return this.view != this.parent.view; }; return CompileNode; }()); var CompileElement = (function (_super) { - __extends$13(CompileElement, _super); + __extends$14(CompileElement, _super); function CompileElement(parent, view, nodeIndex, renderNode, sourceAst, component, _directives, _resolvedProvidersArray, hasViewContainer, hasEmbeddedView, references) { var _this = this; _super.call(this, parent, view, nodeIndex, renderNode, sourceAst); @@ -20352,7 +20212,7 @@ CompileElement.prototype.setComponentView = function (compViewExpr) { this._compViewExpr = compViewExpr; this.contentNodesByNgContentIndex = - ListWrapper.createFixedSize(this.component.template.ngContentSelectors.length); + new Array(this.component.template.ngContentSelectors.length); for (var i = 0; i < this.contentNodesByNgContentIndex.length; i++) { this.contentNodesByNgContentIndex[i] = []; } @@ -20414,7 +20274,7 @@ var queriesForProvider = _this._getQueriesFor(resolvedProvider.token); ListWrapper.addAll(queriesWithReads, queriesForProvider.map(function (query) { return new _QueryWithRead(query, resolvedProvider.token); })); }); - StringMapWrapper.forEach(this.referenceTokens, function (_, varName) { + Object.keys(this.referenceTokens).forEach(function (varName) { var token = _this.referenceTokens[varName]; var varValue; if (isPresent(token)) { @@ -20517,17 +20377,17 @@ CompileElement.prototype._getLocalDependency = function (requestingProviderType, dep) { var result = null; // constructor content query - if (isBlank(result) && isPresent(dep.query)) { + if (!result && isPresent(dep.query)) { result = this._addQuery(dep.query, null).queryList; } // constructor view query - if (isBlank(result) && isPresent(dep.viewQuery)) { + if (!result && isPresent(dep.viewQuery)) { result = createQueryList(dep.viewQuery, null, "_viewQuery_" + dep.viewQuery.selectors[0].name + "_" + this.nodeIndex + "_" + this._componentConstructorViewQueryLists.length, this.view); this._componentConstructorViewQueryLists.push(result); } if (isPresent(dep.token)) { // access builtins with special visibility - if (isBlank(result)) { + if (!result) { if (dep.token.reference === resolveIdentifierToken(Identifiers.ChangeDetectorRef).reference) { if (requestingProviderType === exports.ProviderAstType.Component) { @@ -20539,7 +20399,7 @@ } } // access regular providers on the element - if (isBlank(result)) { + if (!result) { var resolvedProvider = this._resolvedProviders.get(dep.token.reference); // don't allow directives / public services to access private services. // only components and private services can access private services. @@ -20559,18 +20419,18 @@ if (dep.isValue) { result = literal(dep.value); } - if (isBlank(result) && !dep.isSkipSelf) { + if (!result && !dep.isSkipSelf) { result = this._getLocalDependency(requestingProviderType, dep); } // check parent elements - while (isBlank(result) && !currElement.parent.isNull()) { + while (!result && !currElement.parent.isNull()) { currElement = currElement.parent; result = currElement._getLocalDependency(exports.ProviderAstType.PublicService, new CompileDiDependencyMetadata({ token: dep.token })); } - if (isBlank(result)) { + if (!result) { result = injectFromViewParentInjector(dep.token, dep.isOptional); } - if (isBlank(result)) { + if (!result) { result = NULL_EXPR; } return getPropertyInView(result, this.view, currElement.view); @@ -20601,7 +20461,7 @@ resolvedProviderValueExpr = providerValueExpressions[0]; type = providerValueExpressions[0].type; } - if (isBlank(type)) { + if (!type) { type = DYNAMIC_TYPE; } if (isEager) { @@ -20655,7 +20515,7 @@ if (meta.pure) { // pure pipes live on the component view pipe = compView.purePipes.get(name); - if (isBlank(pipe)) { + if (!pipe) { pipe = new CompilePipe(compView, meta); compView.purePipes.set(name, pipe); compView.pipes.push(pipe); @@ -20699,7 +20559,7 @@ break; } } - if (isBlank(pipeMeta)) { + if (!pipeMeta) { throw new Error("Illegal state: Could not find pipe " + name + " although the parser should have detected this error!"); } return pipeMeta; @@ -20733,6 +20593,7 @@ this.literalMapCount = 0; this.pipeCount = 0; this.createMethod = new CompileMethod(this); + this.animationBindingsMethod = new CompileMethod(this); this.injectorGetMethod = new CompileMethod(this); this.updateContentQueriesMethod = new CompileMethod(this); this.dirtyParentQueriesMethod = new CompileMethod(this); @@ -20790,7 +20651,7 @@ } var currView = this; var result = currView.locals.get(name); - while (isBlank(result) && isPresent(currView.declarationElement.view)) { + while (!result && isPresent(currView.declarationElement.view)) { currView = currView.declarationElement.view; result = currView.locals.get(name); } @@ -21146,7 +21007,7 @@ // // Notice that the first guard condition is the left hand of the left most safe access node // which comes in as leftMostSafe to this routine. - var guardedExpression = this.visit(leftMostSafe.receiver, mode); + var guardedExpression = this.visit(leftMostSafe.receiver, _Mode.Expression); var temporary; if (this.needsTemporary(leftMostSafe.receiver)) { // If the expression has method calls or pipes then we need to save the result into a @@ -21167,7 +21028,7 @@ this._nodeMap.set(leftMostSafe, new PropertyRead(leftMostSafe.span, leftMostSafe.receiver, leftMostSafe.name)); } // Recursively convert the node now without the guarded member access. - var access = this.visit(ast, mode); + var access = this.visit(ast, _Mode.Expression); // Remove the mapping. This is not strictly required as the converter only traverses each node // once but is safer if the conversion is changed to traverse the nodes more than once. this._nodeMap.delete(leftMostSafe); @@ -21176,7 +21037,7 @@ this.releaseTemporary(temporary); } // Produce the conditional - return condition.conditional(literal(null), access); + return convertToStatementIfNeeded(mode, condition.conditional(literal(null), access)); }; // Given a expression of the form a?.b.c?.d.e the the left most safe node is // the (a?.b). The . and ?. are left associative thus can be rewritten as: @@ -21272,18 +21133,12 @@ } } - var CompileElementAnimationOutput = (function () { - function CompileElementAnimationOutput(listener, output) { - this.listener = listener; - this.output = output; - } - return CompileElementAnimationOutput; - }()); var CompileEventListener = (function () { - function CompileEventListener(compileElement, eventTarget, eventName, listenerIndex) { + function CompileEventListener(compileElement, eventTarget, eventName, eventPhase, listenerIndex) { this.compileElement = compileElement; this.eventTarget = eventTarget; this.eventName = eventName; + this.eventPhase = eventPhase; this._hasComponentHostListener = false; this._actionResultExprs = []; this._method = new CompileMethod(compileElement.view); @@ -21291,10 +21146,11 @@ "_handle_" + santitizeEventName(eventName) + "_" + compileElement.nodeIndex + "_" + listenerIndex; this._eventParam = new FnParam(EventHandlerVars.event.name, importType(this.compileElement.view.genConfig.renderTypes.renderEvent)); } - CompileEventListener.getOrCreate = function (compileElement, eventTarget, eventName, targetEventListeners) { - var listener = targetEventListeners.find(function (listener) { return listener.eventTarget == eventTarget && listener.eventName == eventName; }); - if (isBlank(listener)) { - listener = new CompileEventListener(compileElement, eventTarget, eventName, targetEventListeners.length); + CompileEventListener.getOrCreate = function (compileElement, eventTarget, eventName, eventPhase, targetEventListeners) { + var listener = targetEventListeners.find(function (listener) { return listener.eventTarget == eventTarget && listener.eventName == eventName && + listener.eventPhase == eventPhase; }); + if (!listener) { + listener = new CompileEventListener(compileElement, eventTarget, eventName, eventPhase, targetEventListeners.length); targetEventListeners.push(listener); } return listener; @@ -21354,16 +21210,13 @@ // private is fine here as no child view will reference the event handler... this.compileElement.view.createMethod.addStmt(disposable.set(listenExpr).toDeclStmt(FUNCTION_TYPE, [StmtModifier.Private])); }; - CompileEventListener.prototype.listenToAnimation = function (output) { + CompileEventListener.prototype.listenToAnimation = function () { var outputListener = THIS_EXPR.callMethod('eventHandler', [THIS_EXPR.prop(this._methodName).callMethod(BuiltinMethod.Bind, [THIS_EXPR])]); // tie the property callback method to the view animations map var stmt = THIS_EXPR .callMethod('registerAnimationOutput', [ - this.compileElement.renderNode, - importExpr(resolveIdentifier(Identifiers.AnimationOutput)).instantiate([ - literal(output.name), literal(output.phase) - ]), - outputListener + this.compileElement.renderNode, literal(this.eventName), + literal(this.eventPhase), outputListener ]) .toStmt(); this.compileElement.view.createMethod.addStmt(stmt); @@ -21383,14 +21236,14 @@ var eventListeners = []; hostEvents.forEach(function (hostEvent) { compileElement.view.bindings.push(new CompileBinding(compileElement, hostEvent)); - var listener = CompileEventListener.getOrCreate(compileElement, hostEvent.target, hostEvent.name, eventListeners); + var listener = CompileEventListener.getOrCreate(compileElement, hostEvent.target, hostEvent.name, hostEvent.phase, eventListeners); listener.addAction(hostEvent, null, null); }); dirs.forEach(function (directiveAst) { var directiveInstance = compileElement.instances.get(identifierToken(directiveAst.directive.type).reference); directiveAst.hostEvents.forEach(function (hostEvent) { compileElement.view.bindings.push(new CompileBinding(compileElement, hostEvent)); - var listener = CompileEventListener.getOrCreate(compileElement, hostEvent.target, hostEvent.name, eventListeners); + var listener = CompileEventListener.getOrCreate(compileElement, hostEvent.target, hostEvent.name, hostEvent.phase, eventListeners); listener.addAction(hostEvent, directiveAst.directive, directiveInstance); }); }); @@ -21398,17 +21251,22 @@ return eventListeners; } function bindDirectiveOutputs(directiveAst, directiveInstance, eventListeners) { - StringMapWrapper.forEach(directiveAst.directive.outputs, function (eventName /** TODO #9100 */, observablePropName /** TODO #9100 */) { + Object.keys(directiveAst.directive.outputs).forEach(function (observablePropName) { + var eventName = directiveAst.directive.outputs[observablePropName]; eventListeners.filter(function (listener) { return listener.eventName == eventName; }).forEach(function (listener) { listener.listenToDirective(directiveInstance, observablePropName); }); }); } function bindRenderOutputs(eventListeners) { - eventListeners.forEach(function (listener) { return listener.listenToRenderer(); }); - } - function bindAnimationOutputs(eventListeners) { - eventListeners.forEach(function (entry) { entry.listener.listenToAnimation(entry.output); }); + eventListeners.forEach(function (listener) { + if (listener.eventPhase) { + listener.listenToAnimation(); + } + else { + listener.listenToRenderer(); + } + }); } function convertStmtIntoExpression(stmt) { if (stmt instanceof ExpressionStatement) { @@ -21483,10 +21341,9 @@ function createCurrValueExpr(exprIndex) { return variable("currVal_" + exprIndex); // fix syntax highlighting: ` } - var _animationViewCheckedFlagMap = new Map(); function bind(view, currValExpr, fieldExpr, parsedExpression, context, actions, method, bindingIndex) { var checkExpression = convertCdExpressionToIr(view, context, parsedExpression, DetectChangesVars.valUnwrapper, bindingIndex); - if (isBlank(checkExpression.expression)) { + if (!checkExpression.expression) { // e.g. an empty expression was given return; } @@ -21536,6 +21393,7 @@ var oldRenderValue = sanitizedValue(boundProp, fieldExpr); var renderValue = sanitizedValue(boundProp, currValExpr); var updateStmts = []; + var compileMethod = view.detectChangesRenderPropertiesMethod; switch (boundProp.type) { case exports.PropertyBindingType.Property: if (view.genConfig.logBindingUpdate) { @@ -21573,6 +21431,7 @@ if (isHostProp) { targetViewExpr = compileElement.appElement.prop('componentView'); } + compileMethod = view.animationBindingsMethod; var animationFnExpr = targetViewExpr.prop('componentType').prop('animations').key(literal(animationName)); // it's important to normalize the void value as `void` explicitly // so that the styles data can be obtained from the stringmap @@ -21588,15 +21447,9 @@ updateStmts.push(animationFnExpr.callFn([THIS_EXPR, renderNode, oldRenderVar, newRenderVar]).toStmt()); view.detachMethod.addStmt(animationFnExpr.callFn([THIS_EXPR, renderNode, oldRenderValue, emptyStateValue]) .toStmt()); - if (!_animationViewCheckedFlagMap.get(view)) { - _animationViewCheckedFlagMap.set(view, true); - var triggerStmt = THIS_EXPR.callMethod('triggerQueuedAnimations', []).toStmt(); - view.afterViewLifecycleCallbacksMethod.addStmt(triggerStmt); - view.detachMethod.addStmt(triggerStmt); - } break; } - bind(view, currValExpr, fieldExpr, boundProp.value, context, updateStmts, view.detectChangesRenderPropertiesMethod, view.bindings.length); + bind(view, currValExpr, fieldExpr, boundProp.value, context, updateStmts, compileMethod, view.bindings.length); }); } function sanitizedValue(boundProp, renderValue) { @@ -21695,19 +21548,15 @@ return new TryCatchStmt([tryStmt], [catchStmt]); } - function bindView(view, parsedTemplate, animationOutputs) { - var visitor = new ViewBinderVisitor(view, animationOutputs); + function bindView(view, parsedTemplate) { + var visitor = new ViewBinderVisitor(view); templateVisitAll(visitor, parsedTemplate); view.pipes.forEach(function (pipe) { bindPipeDestroyLifecycleCallbacks(pipe.meta, pipe.instance, pipe.view); }); } var ViewBinderVisitor = (function () { - function ViewBinderVisitor(view, animationOutputs) { - var _this = this; + function ViewBinderVisitor(view) { this.view = view; - this.animationOutputs = animationOutputs; this._nodeIndex = 0; - this._animationOutputsMap = {}; - animationOutputs.forEach(function (entry) { _this._animationOutputsMap[entry.fullPropertyName] = entry; }); } ViewBinderVisitor.prototype.visitBoundText = function (ast, parent) { var node = this.view.nodes[this._nodeIndex++]; @@ -21720,26 +21569,11 @@ }; ViewBinderVisitor.prototype.visitNgContent = function (ast, parent) { return null; }; ViewBinderVisitor.prototype.visitElement = function (ast, parent) { - var _this = this; var compileElement = this.view.nodes[this._nodeIndex++]; var eventListeners = []; - var animationEventListeners = []; collectEventListeners(ast.outputs, ast.directives, compileElement).forEach(function (entry) { - // TODO: figure out how to abstract this `if` statement elsewhere - if (entry.eventName[0] == '@') { - var animationOutputName = entry.eventName.substr(1); - var output = _this._animationOutputsMap[animationOutputName]; - // no need to report an error here since the parser will - // have caught the missing animation trigger definition - if (output) { - animationEventListeners.push(new CompileElementAnimationOutput(entry, output)); - } - } - else { - eventListeners.push(entry); - } + eventListeners.push(entry); }); - bindAnimationOutputs(animationEventListeners); bindRenderInputs(ast.inputs, compileElement); bindRenderOutputs(eventListeners); ast.directives.forEach(function (directiveAst) { @@ -21778,7 +21612,7 @@ var providerInstance = compileElement.instances.get(providerAst.token.reference); bindInjectableDestroyLifecycleCallbacks(providerAst, providerInstance, compileElement); }); - bindView(compileElement.embeddedView, ast.children, this.animationOutputs); + bindView(compileElement.embeddedView, ast.children); return null; }; ViewBinderVisitor.prototype.visitAttr = function (ast, ctx) { return null; }; @@ -21832,7 +21666,6 @@ this.view = view; this.targetDependencies = targetDependencies; this.nestedViewCount = 0; - this._animationCompiler = new AnimationCompiler(); } ViewBuilderVisitor.prototype._isRootNode = function (parent) { return parent.view !== this.view; }; ViewBuilderVisitor.prototype._addRootNodeAndProject = function (node) { @@ -22005,9 +21838,8 @@ var directives = ast.directives.map(function (directiveAst) { return directiveAst.directive; }); var compileElement = new CompileElement(parent, this.view, nodeIndex, renderNode, ast, null, directives, ast.providers, ast.hasViewContainer, true, ast.references); this.view.nodes.push(compileElement); - var compiledAnimations = this._animationCompiler.compileComponent(this.view.component, [ast]); this.nestedViewCount++; - var embeddedView = new CompileView(this.view.component, this.view.genConfig, this.view.pipeMetas, NULL_EXPR, compiledAnimations.triggers, this.view.viewIndex + this.nestedViewCount, compileElement, templateVariableBindings); + var embeddedView = new CompileView(this.view.component, this.view.genConfig, this.view.pipeMetas, NULL_EXPR, this.view.animations, this.view.viewIndex + this.nestedViewCount, compileElement, templateVariableBindings); this.nestedViewCount += buildView(embeddedView, ast.children, this.targetDependencies); compileElement.beforeChildren(); this._addRootNodeAndProject(compileElement); @@ -22059,9 +21891,10 @@ } function _mergeHtmlAndDirectiveAttrs(declaredHtmlAttrs, directives) { var result = {}; - StringMapWrapper.forEach(declaredHtmlAttrs, function (value, key) { result[key] = value; }); + Object.keys(declaredHtmlAttrs).forEach(function (key) { result[key] = declaredHtmlAttrs[key]; }); directives.forEach(function (directiveMeta) { - StringMapWrapper.forEach(directiveMeta.hostAttributes, function (value, name) { + Object.keys(directiveMeta.hostAttributes).forEach(function (name) { + var value = directiveMeta.hostAttributes[name]; var prevValue = result[name]; result[name] = isPresent(prevValue) ? mergeAttributeValue(name, prevValue, value) : value; }); @@ -22083,9 +21916,7 @@ } function mapToKeyValueArray(data) { var entryArray = []; - StringMapWrapper.forEach(data, function (value, name) { - entryArray.push([name, value]); - }); + Object.keys(data).forEach(function (name) { entryArray.push([name, data[name]]); }); // We need to sort to get a defined output order // for tests and for caching generated artifacts... ListWrapper.sort(entryArray, function (entry1, entry2) { return StringWrapper.compare(entry1[0], entry2[0]); }); @@ -22118,7 +21949,8 @@ if (isPresent(compileElement.component)) { componentToken = createDiTokenExpression(identifierToken(compileElement.component.type)); } - StringMapWrapper.forEach(compileElement.referenceTokens, function (token, varName) { + Object.keys(compileElement.referenceTokens).forEach(function (varName) { + var token = compileElement.referenceTokens[varName]; varTokenEntries.push([varName, isPresent(token) ? createDiTokenExpression(token) : NULL_EXPR]); }); } @@ -22178,17 +22010,16 @@ templateUrlInfo = view.component.template.templateUrl; } if (view.viewIndex === 0) { - var animationsExpr = literalMap(view.animations.map(function (entry) { return [entry.name, entry.fnVariable]; })); - initRenderCompTypeStmts = [new IfStmt(renderCompTypeVar.identical(NULL_EXPR), [ - renderCompTypeVar + var animationsExpr = literalMap(view.animations.map(function (entry) { return [entry.name, entry.fnExp]; })); + initRenderCompTypeStmts = [new IfStmt(renderCompTypeVar.identical(NULL_EXPR), [renderCompTypeVar .set(ViewConstructorVars.viewUtils.callMethod('createRenderComponentType', [ - literal(templateUrlInfo), + view.genConfig.genDebugInfo ? literal(templateUrlInfo) : literal(''), literal(view.component.template.ngContentSelectors.length), - ViewEncapsulationEnum.fromValue(view.component.template.encapsulation), view.styles, - animationsExpr + ViewEncapsulationEnum.fromValue(view.component.template.encapsulation), + view.styles, + animationsExpr, ])) - .toStmt() - ])]; + .toStmt()])]; } return fn(viewFactoryArgs, initRenderCompTypeStmts.concat([new ReturnStatement(variable(viewClass.name) .instantiate(viewClass.constructorMethod.params.map(function (param) { return variable(param.name); })))]), importType(resolveIdentifier(Identifiers.AppView), [getContextType(view)])) @@ -22223,12 +22054,14 @@ } function generateDetectChangesMethod(view) { var stmts = []; - if (view.detectChangesInInputsMethod.isEmpty() && view.updateContentQueriesMethod.isEmpty() && + if (view.animationBindingsMethod.isEmpty() && view.detectChangesInInputsMethod.isEmpty() && + view.updateContentQueriesMethod.isEmpty() && view.afterContentLifecycleCallbacksMethod.isEmpty() && view.detectChangesRenderPropertiesMethod.isEmpty() && view.updateViewQueriesMethod.isEmpty() && view.afterViewLifecycleCallbacksMethod.isEmpty()) { return stmts; } + ListWrapper.addAll(stmts, view.animationBindingsMethod.finish()); ListWrapper.addAll(stmts, view.detectChangesInInputsMethod.finish()); stmts.push(THIS_EXPR.callMethod('detectContentChildrenChanges', [DetectChangesVars.throwOnChange]) .toStmt()); @@ -22245,14 +22078,14 @@ } var varStmts = []; var readVars = findReadVarNames(stmts); - if (SetWrapper.has(readVars, DetectChangesVars.changed.name)) { + if (readVars.has(DetectChangesVars.changed.name)) { varStmts.push(DetectChangesVars.changed.set(literal(true)).toDeclStmt(BOOL_TYPE)); } - if (SetWrapper.has(readVars, DetectChangesVars.changes.name)) { + if (readVars.has(DetectChangesVars.changes.name)) { varStmts.push(DetectChangesVars.changes.set(NULL_EXPR) .toDeclStmt(new MapType(importType(resolveIdentifier(Identifiers.SimpleChange))))); } - if (SetWrapper.has(readVars, DetectChangesVars.valUnwrapper.name)) { + if (readVars.has(DetectChangesVars.valUnwrapper.name)) { varStmts.push(DetectChangesVars.valUnwrapper .set(importExpr(resolveIdentifier(Identifiers.ValueUnwrapper)).instantiate([])) .toDeclStmt(null, [StmtModifier.Final])); @@ -22299,20 +22132,14 @@ this._genConfig = _genConfig; this._animationCompiler = new AnimationCompiler(); } - ViewCompiler.prototype.compileComponent = function (component, template, styles, pipes) { + ViewCompiler.prototype.compileComponent = function (component, template, styles, pipes, compiledAnimations) { var dependencies = []; - var compiledAnimations = this._animationCompiler.compileComponent(component, template); + var view = new CompileView(component, this._genConfig, pipes, styles, compiledAnimations, 0, CompileElement.createNull(), []); var statements = []; - var animationTriggers = compiledAnimations.triggers; - animationTriggers.forEach(function (entry) { - statements.push(entry.statesMapStatement); - statements.push(entry.fnStatement); - }); - var view = new CompileView(component, this._genConfig, pipes, styles, animationTriggers, 0, CompileElement.createNull(), []); buildView(view, template, dependencies); // Need to separate binding from creation to be able to refer to // variables that have been declared after usage. - bindView(view, template, compiledAnimations.outputs); + bindView(view, template); finishView(view, statements); return new ViewCompileResult(statements, view.viewFactory.name, dependencies); }; @@ -22350,6 +22177,8 @@ this._outputEmitter = _outputEmitter; this._localeId = _localeId; this._translationFormat = _translationFormat; + this._animationParser = new AnimationParser(); + this._animationCompiler = new AnimationCompiler(); } OfflineCompiler.prototype.analyzeModules = function (ngModules) { var _this = this; @@ -22387,8 +22216,7 @@ return Promise .all([compMeta].concat(ngModule.transitiveModule.directives).map(function (dirMeta) { return _this._directiveNormalizer.normalizeDirective(dirMeta).asyncResult; })) .then(function (normalizedCompWithDirectives) { - var compMeta = normalizedCompWithDirectives[0]; - var dirMetas = normalizedCompWithDirectives.slice(1); + var compMeta = normalizedCompWithDirectives[0], dirMetas = normalizedCompWithDirectives.slice(1); _assertComponent(compMeta); // compile styles var stylesCompileResults = _this._styleCompiler.compileComponent(compMeta); @@ -22396,8 +22224,7 @@ outputSourceModules.push(_this._codgenStyles(compiledStyleSheet, fileSuffix)); }); // compile components - exportedVars.push(_this._compileComponentFactory(compMeta, fileSuffix, statements)); - exportedVars.push(_this._compileComponent(compMeta, dirMetas, ngModule.transitiveModule.pipes, ngModule.schemas, stylesCompileResults.componentStylesheet, fileSuffix, statements)); + exportedVars.push(_this._compileComponentFactory(compMeta, fileSuffix, statements), _this._compileComponent(compMeta, dirMetas, ngModule.transitiveModule.pipes, ngModule.schemas, stylesCompileResults.componentStylesheet, fileSuffix, statements)); }); })) .then(function () { @@ -22409,13 +22236,20 @@ }; OfflineCompiler.prototype._compileModule = function (ngModuleType, targetStatements) { var ngModule = this._metadataResolver.getNgModuleMetadata(ngModuleType); - var appCompileResult = this._ngModuleCompiler.compile(ngModule, [ - new CompileProviderMetadata({ token: resolveIdentifierToken(Identifiers.LOCALE_ID), useValue: this._localeId }), - new CompileProviderMetadata({ + var providers = []; + if (this._localeId) { + providers.push(new CompileProviderMetadata({ + token: resolveIdentifierToken(Identifiers.LOCALE_ID), + useValue: this._localeId, + })); + } + if (this._translationFormat) { + providers.push(new CompileProviderMetadata({ token: resolveIdentifierToken(Identifiers.TRANSLATIONS_FORMAT), useValue: this._translationFormat - }) - ]); + })); + } + var appCompileResult = this._ngModuleCompiler.compile(ngModule, providers); appCompileResult.dependencies.forEach(function (dep) { dep.placeholder.name = _componentFactoryName(dep.comp); dep.placeholder.moduleUrl = _ngfactoryModuleUrl(dep.comp.moduleUrl); @@ -22430,20 +22264,24 @@ targetStatements.push(variable(compFactoryVar) .set(importExpr(resolveIdentifier(Identifiers.ComponentFactory), [importType(compMeta.type)]) .instantiate([ - literal(compMeta.selector), variable(hostViewFactoryVar), - importExpr(compMeta.type) + literal(compMeta.selector), + variable(hostViewFactoryVar), + importExpr(compMeta.type), ], importType(resolveIdentifier(Identifiers.ComponentFactory), [importType(compMeta.type)], [TypeModifier.Const]))) .toDeclStmt(null, [StmtModifier.Final])); return compFactoryVar; }; OfflineCompiler.prototype._compileComponent = function (compMeta, directives, pipes, schemas, componentStyles, fileSuffix, targetStatements) { + var parsedAnimations = this._animationParser.parseComponent(compMeta); var parsedTemplate = this._templateParser.parse(compMeta, compMeta.template.template, directives, pipes, schemas, compMeta.type.name); var stylesExpr = componentStyles ? variable(componentStyles.stylesVar) : literalArr([]); - var viewResult = this._viewCompiler.compileComponent(compMeta, parsedTemplate, stylesExpr, pipes); + var compiledAnimations = this._animationCompiler.compile(compMeta.type.name, parsedAnimations); + var viewResult = this._viewCompiler.compileComponent(compMeta, parsedTemplate, stylesExpr, pipes, compiledAnimations); if (componentStyles) { - ListWrapper.addAll(targetStatements, _resolveStyleStatements(componentStyles, fileSuffix)); + targetStatements.push.apply(targetStatements, _resolveStyleStatements(componentStyles, fileSuffix)); } - ListWrapper.addAll(targetStatements, _resolveViewStatements(viewResult)); + compiledAnimations.forEach(function (entry) { entry.statements.forEach(function (statement) { targetStatements.push(statement); }); }); + targetStatements.push.apply(targetStatements, _resolveViewStatements(viewResult)); return viewResult.viewFactoryVar; }; OfflineCompiler.prototype._codgenStyles = function (stylesCompileResult, fileSuffix) { @@ -22491,16 +22329,14 @@ } } function _splitTypescriptSuffix(path) { - if (/\.d\.ts$/.test(path)) { - return [path.substring(0, path.length - 5), '.ts']; + if (path.endsWith('.d.ts')) { + return [path.slice(0, -5), '.ts']; } var lastDot = path.lastIndexOf('.'); if (lastDot !== -1) { return [path.substring(0, lastDot), path.substring(lastDot)]; } - else { - return [path, '']; - } + return [path, '']; } /** @@ -22919,26 +22755,24 @@ var visitor = new TemplatePreparseVisitor(); visitAll(visitor, rootNodesAndErrors.rootNodes); var templateStyles = this.normalizeStylesheet(new CompileStylesheetMetadata({ styles: visitor.styles, styleUrls: visitor.styleUrls, moduleUrl: templateAbsUrl })); - var allStyles = templateMetadataStyles.styles.concat(templateStyles.styles); - var allStyleUrls = templateMetadataStyles.styleUrls.concat(templateStyles.styleUrls); var encapsulation = templateMeta.encapsulation; if (isBlank(encapsulation)) { encapsulation = this._config.defaultEncapsulation; } - if (encapsulation === _angular_core.ViewEncapsulation.Emulated && allStyles.length === 0 && - allStyleUrls.length === 0) { + var styles = templateMetadataStyles.styles.concat(templateStyles.styles); + var styleUrls = templateMetadataStyles.styleUrls.concat(templateStyles.styleUrls); + if (encapsulation === _angular_core.ViewEncapsulation.Emulated && styles.length === 0 && + styleUrls.length === 0) { encapsulation = _angular_core.ViewEncapsulation.None; } return new CompileTemplateMetadata({ encapsulation: encapsulation, template: template, - templateUrl: templateAbsUrl, - styles: allStyles, - styleUrls: allStyleUrls, + templateUrl: templateAbsUrl, styles: styles, styleUrls: styleUrls, externalStylesheets: templateMeta.externalStylesheets, ngContentSelectors: visitor.ngContentSelectors, animations: templateMeta.animations, - interpolation: templateMeta.interpolation + interpolation: templateMeta.interpolation, }); }; DirectiveNormalizer.prototype.normalizeExternalStylesheets = function (templateMeta) { @@ -23052,16 +22886,12 @@ viewProviders: directive.viewProviders, queries: directive.queries, viewQueries: directive.viewQueries, - entryComponents: directive.entryComponents, - template: template + entryComponents: directive.entryComponents, template: template, }); } - function _isDirectiveMetadata(type) { - return type instanceof _angular_core.DirectiveMetadata; - } /* - * Resolve a `Type` for {@link DirectiveMetadata}. + * Resolve a `Type` for {@link Directive}. * * This interface can be overridden by the application developer to create custom behavior. * @@ -23073,14 +22903,14 @@ this._reflector = _reflector; } /** - * Return {@link DirectiveMetadata} for a given `Type`. + * Return {@link Directive} for a given `Type`. */ DirectiveResolver.prototype.resolve = function (type, throwIfNotFound) { if (throwIfNotFound === void 0) { throwIfNotFound = true; } var typeMetadata = this._reflector.annotations(_angular_core.resolveForwardRef(type)); - if (isPresent(typeMetadata)) { - var metadata = typeMetadata.find(_isDirectiveMetadata); - if (isPresent(metadata)) { + if (typeMetadata) { + var metadata = typeMetadata.find(isDirectiveMetadata); + if (metadata) { var propertyMetadata = this._reflector.propMetadata(type); return this._mergeWithPropertyMetadata(metadata, propertyMetadata, type); } @@ -23095,37 +22925,40 @@ var outputs = []; var host = {}; var queries = {}; - StringMapWrapper.forEach(propertyMetadata, function (metadata, propName) { - metadata.forEach(function (a) { - if (a instanceof _angular_core.InputMetadata) { - if (isPresent(a.bindingPropertyName)) { + Object.keys(propertyMetadata).forEach(function (propName) { + propertyMetadata[propName].forEach(function (a) { + if (a instanceof _angular_core.Input) { + if (a.bindingPropertyName) { inputs.push(propName + ": " + a.bindingPropertyName); } else { inputs.push(propName); } } - else if (a instanceof _angular_core.OutputMetadata) { - if (isPresent(a.bindingPropertyName)) { - outputs.push(propName + ": " + a.bindingPropertyName); + else if (a instanceof _angular_core.Output) { + var output = a; + if (output.bindingPropertyName) { + outputs.push(propName + ": " + output.bindingPropertyName); } else { outputs.push(propName); } } - else if (a instanceof _angular_core.HostBindingMetadata) { - if (isPresent(a.hostPropertyName)) { - host[("[" + a.hostPropertyName + "]")] = propName; + else if (a instanceof _angular_core.HostBinding) { + var hostBinding = a; + if (hostBinding.hostPropertyName) { + host[("[" + hostBinding.hostPropertyName + "]")] = propName; } else { host[("[" + propName + "]")] = propName; } } - else if (a instanceof _angular_core.HostListenerMetadata) { - var args = isPresent(a.args) ? a.args.join(', ') : ''; - host[("(" + a.eventName + ")")] = propName + "(" + args + ")"; + else if (a instanceof _angular_core.HostListener) { + var hostListener = a; + var args = hostListener.args || []; + host[("(" + hostListener.eventName + ")")] = propName + "(" + args.join(',') + ")"; } - else if (a instanceof _angular_core.QueryMetadata) { + else if (a instanceof _angular_core.Query) { queries[propName] = a; } }); @@ -23133,69 +22966,63 @@ return this._merge(dm, inputs, outputs, host, queries, directiveType); }; DirectiveResolver.prototype._extractPublicName = function (def) { return splitAtColon(def, [null, def])[1].trim(); }; - DirectiveResolver.prototype._merge = function (dm, inputs, outputs, host, queries, directiveType) { + DirectiveResolver.prototype._merge = function (directive, inputs, outputs, host, queries, directiveType) { var _this = this; - var mergedInputs; - if (isPresent(dm.inputs)) { - var inputNames_1 = dm.inputs.map(function (def) { return _this._extractPublicName(def); }); + var mergedInputs = inputs; + if (directive.inputs) { + var inputNames_1 = directive.inputs.map(function (def) { return _this._extractPublicName(def); }); inputs.forEach(function (inputDef) { var publicName = _this._extractPublicName(inputDef); if (inputNames_1.indexOf(publicName) > -1) { throw new Error("Input '" + publicName + "' defined multiple times in '" + stringify(directiveType) + "'"); } }); - mergedInputs = dm.inputs.concat(inputs); + mergedInputs.unshift.apply(mergedInputs, directive.inputs); } - else { - mergedInputs = inputs; - } - var mergedOutputs; - if (isPresent(dm.outputs)) { - var outputNames_1 = dm.outputs.map(function (def) { return _this._extractPublicName(def); }); + var mergedOutputs = outputs; + if (directive.outputs) { + var outputNames_1 = directive.outputs.map(function (def) { return _this._extractPublicName(def); }); outputs.forEach(function (outputDef) { var publicName = _this._extractPublicName(outputDef); if (outputNames_1.indexOf(publicName) > -1) { throw new Error("Output event '" + publicName + "' defined multiple times in '" + stringify(directiveType) + "'"); } }); - mergedOutputs = dm.outputs.concat(outputs); + mergedOutputs.unshift.apply(mergedOutputs, directive.outputs); } - else { - mergedOutputs = outputs; - } - var mergedHost = isPresent(dm.host) ? StringMapWrapper.merge(dm.host, host) : host; - var mergedQueries = isPresent(dm.queries) ? StringMapWrapper.merge(dm.queries, queries) : queries; - if (dm instanceof _angular_core.ComponentMetadata) { - return new _angular_core.ComponentMetadata({ - selector: dm.selector, + var mergedHost = directive.host ? StringMapWrapper.merge(directive.host, host) : host; + var mergedQueries = directive.queries ? StringMapWrapper.merge(directive.queries, queries) : queries; + if (directive instanceof _angular_core.Component) { + return new _angular_core.Component({ + selector: directive.selector, inputs: mergedInputs, outputs: mergedOutputs, host: mergedHost, - exportAs: dm.exportAs, - moduleId: dm.moduleId, + exportAs: directive.exportAs, + moduleId: directive.moduleId, queries: mergedQueries, - changeDetection: dm.changeDetection, - providers: dm.providers, - viewProviders: dm.viewProviders, - entryComponents: dm.entryComponents, - template: dm.template, - templateUrl: dm.templateUrl, - styles: dm.styles, - styleUrls: dm.styleUrls, - encapsulation: dm.encapsulation, - animations: dm.animations, - interpolation: dm.interpolation + changeDetection: directive.changeDetection, + providers: directive.providers, + viewProviders: directive.viewProviders, + entryComponents: directive.entryComponents, + template: directive.template, + templateUrl: directive.templateUrl, + styles: directive.styles, + styleUrls: directive.styleUrls, + encapsulation: directive.encapsulation, + animations: directive.animations, + interpolation: directive.interpolation }); } else { - return new _angular_core.DirectiveMetadata({ - selector: dm.selector, + return new _angular_core.Directive({ + selector: directive.selector, inputs: mergedInputs, outputs: mergedOutputs, host: mergedHost, - exportAs: dm.exportAs, + exportAs: directive.exportAs, queries: mergedQueries, - providers: dm.providers + providers: directive.providers }); } }; @@ -23208,6 +23035,9 @@ ]; return DirectiveResolver; }()); + function isDirectiveMetadata(type) { + return type instanceof _angular_core.Directive; + } var LIFECYCLE_INTERFACES = MapWrapper.createFromPairs([ [LifecycleHooks.OnInit, _angular_core.OnInit], @@ -23236,10 +23066,10 @@ } function _isNgModuleMetadata(obj) { - return obj instanceof _angular_core.NgModuleMetadata; + return obj instanceof _angular_core.NgModule; } /** - * Resolves types to {@link NgModuleMetadata}. + * Resolves types to {@link NgModule}. */ var NgModuleResolver = (function () { function NgModuleResolver(_reflector) { @@ -23270,10 +23100,10 @@ }()); function _isPipeMetadata(type) { - return type instanceof _angular_core.PipeMetadata; + return type instanceof _angular_core.Pipe; } /** - * Resolve a `Type` for {@link PipeMetadata}. + * Resolve a `Type` for {@link Pipe}. * * This interface can be overridden by the application developer to create custom behavior. * @@ -23285,7 +23115,7 @@ this._reflector = _reflector; } /** - * Return {@link PipeMetadata} for a given `Type`. + * Return {@link Pipe} for a given `Type`. */ PipeResolver.prototype.resolve = function (type, throwIfNotFound) { if (throwIfNotFound === void 0) { throwIfNotFound = true; } @@ -23318,7 +23148,7 @@ * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ - var __extends$14 = (this && this.__extends) || function (d, b) { + var __extends$15 = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); @@ -23343,7 +23173,7 @@ if (identifier.indexOf('(') >= 0) { // case: anonymous functions! var found = this._anonymousTypes.get(token); - if (isBlank(found)) { + if (!found) { this._anonymousTypes.set(token, this._anonymousTypeIndex++); found = this._anonymousTypes.get(token); } @@ -23355,7 +23185,7 @@ this._directiveCache.delete(type); this._pipeCache.delete(type); this._ngModuleOfTypes.delete(type); - // Clear all of the NgModuleMetadata as they contain transitive information! + // Clear all of the NgModule as they contain transitive information! this._ngModuleCache.clear(); }; CompileMetadataResolver.prototype.clearCache = function () { @@ -23374,7 +23204,7 @@ var styles = this.getAnimationStyleMetadata(value.styles); return new CompileAnimationStateDeclarationMetadata(value.stateNameExpr, styles); } - else if (value instanceof _angular_core.AnimationStateTransitionMetadata) { + if (value instanceof _angular_core.AnimationStateTransitionMetadata) { return new CompileAnimationStateTransitionMetadata(value.stateChangeExpr, this.getAnimationMetadata(value.steps)); } return null; @@ -23387,22 +23217,20 @@ if (value instanceof _angular_core.AnimationStyleMetadata) { return this.getAnimationStyleMetadata(value); } - else if (value instanceof _angular_core.AnimationKeyframesSequenceMetadata) { + if (value instanceof _angular_core.AnimationKeyframesSequenceMetadata) { return new CompileAnimationKeyframesSequenceMetadata(value.steps.map(function (entry) { return _this.getAnimationStyleMetadata(entry); })); } - else if (value instanceof _angular_core.AnimationAnimateMetadata) { + if (value instanceof _angular_core.AnimationAnimateMetadata) { var animateData = this .getAnimationMetadata(value.styles); return new CompileAnimationAnimateMetadata(value.timings, animateData); } - else if (value instanceof _angular_core.AnimationWithStepsMetadata) { + if (value instanceof _angular_core.AnimationWithStepsMetadata) { var steps = value.steps.map(function (step) { return _this.getAnimationMetadata(step); }); if (value instanceof _angular_core.AnimationGroupMetadata) { return new CompileAnimationGroupMetadata(steps); } - else { - return new CompileAnimationSequenceMetadata(steps); - } + return new CompileAnimationSequenceMetadata(steps); } return null; }; @@ -23411,7 +23239,7 @@ if (throwIfNotFound === void 0) { throwIfNotFound = true; } directiveType = _angular_core.resolveForwardRef(directiveType); var meta = this._directiveCache.get(directiveType); - if (isBlank(meta)) { + if (!meta) { var dirMeta = this._directiveResolver.resolve(directiveType, throwIfNotFound); if (!dirMeta) { return null; @@ -23422,32 +23250,31 @@ var moduleUrl = staticTypeModuleUrl(directiveType); var entryComponentMetadata = []; var selector = dirMeta.selector; - if (dirMeta instanceof _angular_core.ComponentMetadata) { - var cmpMeta = dirMeta; - assertArrayOfStrings('styles', cmpMeta.styles); - assertInterpolationSymbols('interpolation', cmpMeta.interpolation); - var animations = isPresent(cmpMeta.animations) ? - cmpMeta.animations.map(function (e) { return _this.getAnimationEntryMetadata(e); }) : + if (dirMeta instanceof _angular_core.Component) { + // Component + assertArrayOfStrings('styles', dirMeta.styles); + assertArrayOfStrings('styleUrls', dirMeta.styleUrls); + assertInterpolationSymbols('interpolation', dirMeta.interpolation); + var animations = dirMeta.animations ? + dirMeta.animations.map(function (e) { return _this.getAnimationEntryMetadata(e); }) : null; - assertArrayOfStrings('styles', cmpMeta.styles); - assertArrayOfStrings('styleUrls', cmpMeta.styleUrls); templateMeta = new CompileTemplateMetadata({ - encapsulation: cmpMeta.encapsulation, - template: cmpMeta.template, - templateUrl: cmpMeta.templateUrl, - styles: cmpMeta.styles, - styleUrls: cmpMeta.styleUrls, + encapsulation: dirMeta.encapsulation, + template: dirMeta.template, + templateUrl: dirMeta.templateUrl, + styles: dirMeta.styles, + styleUrls: dirMeta.styleUrls, animations: animations, - interpolation: cmpMeta.interpolation + interpolation: dirMeta.interpolation }); - changeDetectionStrategy = cmpMeta.changeDetection; - if (isPresent(dirMeta.viewProviders)) { + changeDetectionStrategy = dirMeta.changeDetection; + if (dirMeta.viewProviders) { viewProviders = this.getProvidersMetadata(dirMeta.viewProviders, entryComponentMetadata, "viewProviders for \"" + stringify(directiveType) + "\""); } - moduleUrl = componentModuleUrl(this._reflector, directiveType, cmpMeta); - if (cmpMeta.entryComponents) { + moduleUrl = componentModuleUrl(this._reflector, directiveType, dirMeta); + if (dirMeta.entryComponents) { entryComponentMetadata = - flattenArray(cmpMeta.entryComponents) + flattenArray(dirMeta.entryComponents) .map(function (type) { return _this.getTypeMetadata(type, staticTypeModuleUrl(type)); }) .concat(entryComponentMetadata); } @@ -23456,6 +23283,7 @@ } } else { + // Directive if (!selector) { throw new Error("Directive " + stringify(directiveType) + " has no selector, please add it!"); } @@ -23473,7 +23301,7 @@ meta = CompileDirectiveMetadata.create({ selector: selector, exportAs: dirMeta.exportAs, - isComponent: isPresent(templateMeta), + isComponent: !!templateMeta, type: this.getTypeMetadata(directiveType, moduleUrl), template: templateMeta, changeDetection: changeDetectionStrategy, @@ -23588,8 +23416,13 @@ .map(function (type) { return _this.getTypeMetadata(type, staticTypeModuleUrl(type)); })); } if (meta.bootstrap) { - bootstrapComponents.push.apply(bootstrapComponents, flattenArray(meta.bootstrap) - .map(function (type) { return _this.getTypeMetadata(type, staticTypeModuleUrl(type)); })); + var typeMetadata = flattenArray(meta.bootstrap).map(function (type) { + if (!isValidType(type)) { + throw new Error("Unexpected value '" + stringify(type) + "' used in the bootstrap property of module '" + stringify(moduleType) + "'"); + } + return _this.getTypeMetadata(type, staticTypeModuleUrl(type)); + }); + bootstrapComponents.push.apply(bootstrapComponents, typeMetadata); } entryComponents_1.push.apply(entryComponents_1, bootstrapComponents); if (meta.schemas) { @@ -23609,7 +23442,8 @@ exportedPipes: exportedPipes_1, importedModules: importedModules_1, exportedModules: exportedModules_1, - transitiveModule: transitiveModule_1 + transitiveModule: transitiveModule_1, + id: meta.id, }); transitiveModule_1.modules.push(compileMeta); this._verifyModule(compileMeta); @@ -23634,23 +23468,23 @@ if (this._directiveResolver.resolve(type, false) !== null) { return 'directive'; } - else if (this._pipeResolver.resolve(type, false) !== null) { + if (this._pipeResolver.resolve(type, false) !== null) { return 'pipe'; } - else if (this._ngModuleResolver.resolve(type, false) !== null) { + if (this._ngModuleResolver.resolve(type, false) !== null) { return 'module'; } - else if (type.provide) { + if (type.provide) { return 'provider'; } - else { - return 'value'; - } + return 'value'; }; CompileMetadataResolver.prototype._addTypeToModule = function (type, moduleType) { var oldModule = this._ngModuleOfTypes.get(type); if (oldModule && oldModule !== moduleType) { - throw new Error("Type " + stringify(type) + " is part of the declarations of 2 modules: " + stringify(oldModule) + " and " + stringify(moduleType) + "!"); + throw new Error(("Type " + stringify(type) + " is part of the declarations of 2 modules: " + stringify(oldModule) + " and " + stringify(moduleType) + "! ") + + ("Please consider moving " + stringify(type) + " to a higher module that imports " + stringify(oldModule) + " and " + stringify(moduleType) + ". ") + + ("You can also create a new NgModule that exports and includes " + stringify(type) + " then import that NgModule in " + stringify(oldModule) + " and " + stringify(moduleType) + ".")); } this._ngModuleOfTypes.set(type, moduleType); }; @@ -23711,7 +23545,7 @@ if (throwIfNotFound === void 0) { throwIfNotFound = true; } pipeType = _angular_core.resolveForwardRef(pipeType); var meta = this._pipeCache.get(pipeType); - if (isBlank(meta)) { + if (!meta) { var pipeMeta = this._pipeResolver.resolve(pipeType, throwIfNotFound); if (!pipeMeta) { return null; @@ -23728,10 +23562,7 @@ CompileMetadataResolver.prototype.getDependenciesMetadata = function (typeOrFunc, dependencies) { var _this = this; var hasUnknownDeps = false; - var params = isPresent(dependencies) ? dependencies : this._reflector.parameters(typeOrFunc); - if (isBlank(params)) { - params = []; - } + var params = dependencies || this._reflector.parameters(typeOrFunc) || []; var dependenciesMetadata = params.map(function (param) { var isAttribute = false; var isHost = false; @@ -23741,25 +23572,25 @@ var query = null; var viewQuery = null; var token = null; - if (isArray(param)) { + if (Array.isArray(param)) { param.forEach(function (paramEntry) { - if (paramEntry instanceof _angular_core.HostMetadata) { + if (paramEntry instanceof _angular_core.Host) { isHost = true; } - else if (paramEntry instanceof _angular_core.SelfMetadata) { + else if (paramEntry instanceof _angular_core.Self) { isSelf = true; } - else if (paramEntry instanceof _angular_core.SkipSelfMetadata) { + else if (paramEntry instanceof _angular_core.SkipSelf) { isSkipSelf = true; } - else if (paramEntry instanceof _angular_core.OptionalMetadata) { + else if (paramEntry instanceof _angular_core.Optional) { isOptional = true; } - else if (paramEntry instanceof _angular_core.AttributeMetadata) { + else if (paramEntry instanceof _angular_core.Attribute) { isAttribute = true; token = paramEntry.attributeName; } - else if (paramEntry instanceof _angular_core.QueryMetadata) { + else if (paramEntry instanceof _angular_core.Query) { if (paramEntry.isViewQuery) { viewQuery = paramEntry; } @@ -23767,7 +23598,7 @@ query = paramEntry; } } - else if (paramEntry instanceof _angular_core.InjectMetadata) { + else if (paramEntry instanceof _angular_core.Inject) { token = paramEntry.token; } else if (isValidType(paramEntry) && isBlank(token)) { @@ -23788,14 +23619,13 @@ isSelf: isSelf, isSkipSelf: isSkipSelf, isOptional: isOptional, - query: isPresent(query) ? _this.getQueryMetadata(query, null, typeOrFunc) : null, - viewQuery: isPresent(viewQuery) ? _this.getQueryMetadata(viewQuery, null, typeOrFunc) : null, + query: query ? _this.getQueryMetadata(query, null, typeOrFunc) : null, + viewQuery: viewQuery ? _this.getQueryMetadata(viewQuery, null, typeOrFunc) : null, token: _this.getTokenMetadata(token) }); }); if (hasUnknownDeps) { - var depsTokens = dependenciesMetadata.map(function (dep) { return dep ? stringify(dep.token) : '?'; }) - .join(', '); + var depsTokens = dependenciesMetadata.map(function (dep) { return dep ? stringify(dep.token) : '?'; }).join(', '); throw new Error("Can't resolve all parameters for " + stringify(typeOrFunc) + ": (" + depsTokens + ")."); } return dependenciesMetadata; @@ -23826,7 +23656,7 @@ provider = new ProviderMeta(provider.provide, provider); } var compileProvider; - if (isArray(provider)) { + if (Array.isArray(provider)) { compileProvider = _this.getProvidersMetadata(provider, targetEntryComponents, debugInfo); } else if (provider instanceof ProviderMeta) { @@ -23887,11 +23717,11 @@ var compileDeps; var compileTypeMetadata = null; var compileFactoryMetadata = null; - if (isPresent(provider.useClass)) { + if (provider.useClass) { compileTypeMetadata = this.getTypeMetadata(provider.useClass, staticTypeModuleUrl(provider.useClass), provider.dependencies); compileDeps = compileTypeMetadata.diDeps; } - else if (isPresent(provider.useFactory)) { + else if (provider.useFactory) { compileFactoryMetadata = this.getFactoryMetadata(provider.useFactory, staticTypeModuleUrl(provider.useFactory), provider.dependencies); compileDeps = compileFactoryMetadata.diDeps; } @@ -23900,8 +23730,7 @@ useClass: compileTypeMetadata, useValue: convertToCompileValue(provider.useValue, []), useFactory: compileFactoryMetadata, - useExisting: isPresent(provider.useExisting) ? this.getTokenMetadata(provider.useExisting) : - null, + useExisting: provider.useExisting ? this.getTokenMetadata(provider.useExisting) : null, deps: compileDeps, multi: provider.multi }); @@ -23909,21 +23738,23 @@ CompileMetadataResolver.prototype.getQueriesMetadata = function (queries, isViewQuery, directiveType) { var _this = this; var res = []; - StringMapWrapper.forEach(queries, function (query, propertyName) { + Object.keys(queries).forEach(function (propertyName) { + var query = queries[propertyName]; if (query.isViewQuery === isViewQuery) { res.push(_this.getQueryMetadata(query, propertyName, directiveType)); } }); return res; }; + CompileMetadataResolver.prototype._queryVarBindings = function (selector) { return selector.split(/\s*,\s*/); }; CompileMetadataResolver.prototype.getQueryMetadata = function (q, propertyName, typeOrFunc) { var _this = this; var selectors; - if (q.isVarBindingQuery) { - selectors = q.varBindings.map(function (varName) { return _this.getTokenMetadata(varName); }); + if (typeof q.selector === 'string') { + selectors = this._queryVarBindings(q.selector).map(function (varName) { return _this.getTokenMetadata(varName); }); } else { - if (!isPresent(q.selector)) { + if (!q.selector) { throw new Error("Can't construct a query for the property \"" + propertyName + "\" of \"" + stringify(typeOrFunc) + "\" since the query selector wasn't defined."); } selectors = [this.getTokenMetadata(q.selector)]; @@ -23931,9 +23762,8 @@ return new CompileQueryMetadata({ selectors: selectors, first: q.first, - descendants: q.descendants, - propertyName: propertyName, - read: isPresent(q.read) ? this.getTokenMetadata(q.read) : null + descendants: q.descendants, propertyName: propertyName, + read: q.read ? this.getTokenMetadata(q.read) : null }); }; CompileMetadataResolver.decorators = [ @@ -23971,7 +23801,7 @@ if (tree) { for (var i = 0; i < tree.length; i++) { var item = _angular_core.resolveForwardRef(tree[i]); - if (isArray(item)) { + if (Array.isArray(item)) { flattenArray(item, out); } else { @@ -23991,11 +23821,14 @@ if (isStaticSymbol(type)) { return staticTypeModuleUrl(type); } - if (isPresent(cmpMetadata.moduleId)) { - var moduleId = cmpMetadata.moduleId; + var moduleId = cmpMetadata.moduleId; + if (typeof moduleId === 'string') { var scheme = getUrlScheme(moduleId); - return isPresent(scheme) && scheme.length > 0 ? moduleId : - "package:" + moduleId + MODULE_SUFFIX; + return scheme ? moduleId : "package:" + moduleId + MODULE_SUFFIX; + } + else if (moduleId !== null && moduleId !== void 0) { + throw new Error(("moduleId should be a string in \"" + stringify(type) + "\". See https://goo.gl/wIDDiL for more information.\n") + + "If you're using Webpack you should inline the template and the styles, see https://goo.gl/X2J8zc."); } return reflector.importUri(type); } @@ -24003,7 +23836,7 @@ return visitValue(value, new _CompileValueConverter(), targetIdentifiers); } var _CompileValueConverter = (function (_super) { - __extends$14(_CompileValueConverter, _super); + __extends$15(_CompileValueConverter, _super); function _CompileValueConverter() { _super.apply(this, arguments); } @@ -24064,7 +23897,14 @@ .set(importExpr(resolveIdentifier(Identifiers.NgModuleFactory)) .instantiate([variable(injectorClass.name), importExpr(ngModuleMeta.type)], importType(resolveIdentifier(Identifiers.NgModuleFactory), [importType(ngModuleMeta.type)], [TypeModifier.Const]))) .toDeclStmt(null, [StmtModifier.Final]); - return new NgModuleCompileResult([injectorClass, ngModuleFactoryStmt], ngModuleFactoryVar, deps); + var stmts = [injectorClass, ngModuleFactoryStmt]; + if (ngModuleMeta.id) { + var registerFactoryStmt = importExpr(resolveIdentifier(Identifiers.RegisterModuleFactoryFn)) + .callFn([literal(ngModuleMeta.id), variable(ngModuleFactoryVar)]) + .toStmt(); + stmts.push(registerFactoryStmt); + } + return new NgModuleCompileResult(stmts, ngModuleFactoryVar, deps); }; NgModuleCompiler.decorators = [ { type: _angular_core.Injectable }, @@ -24154,7 +23994,7 @@ resolvedProviderValueExpr = providerValueExpressions[0]; type = providerValueExpressions[0].type; } - if (isBlank(type)) { + if (!type) { type = DYNAMIC_TYPE; } if (isEager) { @@ -24185,11 +24025,11 @@ resolveIdentifierToken(Identifiers.ComponentFactoryResolver).reference)) { result = THIS_EXPR; } - if (isBlank(result)) { + if (!result) { result = this._instances.get(dep.token.reference); } } - if (isBlank(result)) { + if (!result) { var args = [createDiTokenExpression(dep.token)]; if (dep.isOptional) { args.push(NULL_EXPR); @@ -24622,7 +24462,7 @@ * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ - var __extends$15 = (this && this.__extends) || function (d, b) { + var __extends$16 = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); @@ -24675,7 +24515,7 @@ return TypeScriptEmitter; }()); var _TsEmitterVisitor = (function (_super) { - __extends$15(_TsEmitterVisitor, _super); + __extends$16(_TsEmitterVisitor, _super); function _TsEmitterVisitor(_moduleUrl) { _super.call(this, false); this._moduleUrl = _moduleUrl; @@ -24693,6 +24533,20 @@ _TsEmitterVisitor.prototype.visitLiteralExpr = function (ast, ctx) { _super.prototype.visitLiteralExpr.call(this, ast, ctx, '(null as any)'); }; + // Temporary workaround to support strictNullCheck enabled consumers of ngc emit. + // In SNC mode, [] have the type never[], so we cast here to any[]. + // TODO: narrow the cast to a more explicit type, or use a pattern that does not + // start with [].concat. see https://github.com/angular/angular/pull/11846 + _TsEmitterVisitor.prototype.visitLiteralArrayExpr = function (ast, ctx) { + if (ast.entries.length === 0) { + ctx.print('('); + } + var result = _super.prototype.visitLiteralArrayExpr.call(this, ast, ctx); + if (ast.entries.length === 0) { + ctx.print(' as any[])'); + } + return result; + }; _TsEmitterVisitor.prototype.visitExternalExpr = function (ast, ctx) { this._visitIdentifier(ast.value, ast.typeParams, ctx); return null; @@ -25268,13 +25122,13 @@ * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ - var __extends$17 = (this && this.__extends) || function (d, b) { + var __extends$18 = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var AbstractJsEmitterVisitor = (function (_super) { - __extends$17(AbstractJsEmitterVisitor, _super); + __extends$18(AbstractJsEmitterVisitor, _super); function AbstractJsEmitterVisitor() { _super.call(this, false); } @@ -25433,7 +25287,7 @@ * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ - var __extends$16 = (this && this.__extends) || function (d, b) { + var __extends$17 = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); @@ -25445,7 +25299,7 @@ return evalExpression(sourceUrl, resultVar, ctx.toSource(), converter.getArgs()); } var JitEmitterVisitor = (function (_super) { - __extends$16(JitEmitterVisitor, _super); + __extends$17(JitEmitterVisitor, _super); function JitEmitterVisitor() { _super.apply(this, arguments); this._evalArgNames = []; @@ -25473,6 +25327,13 @@ return JitEmitterVisitor; }(AbstractJsEmitterVisitor)); + /** + * @license + * Copyright Google Inc. All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.io/license + */ /** * This file is a port of shadowCSS from webcomponents.js to TypeScript. * @@ -25636,7 +25497,13 @@ **/ ShadowCss.prototype._insertPolyfillDirectivesInCssText = function (cssText) { // Difference with webcomponents.js: does not handle comments - return StringWrapper.replaceAllMapped(cssText, _cssContentNextSelectorRe, function (m /** TODO #9100 */) { return m[1] + '{'; }); + return cssText.replace(_cssContentNextSelectorRe, function () { + var m = []; + for (var _i = 0; _i < arguments.length; _i++) { + m[_i - 0] = arguments[_i]; + } + return m[2] + '{'; + }); }; /* * Process styles to add rules which will only apply under the polyfill @@ -25655,11 +25522,13 @@ **/ ShadowCss.prototype._insertPolyfillRulesInCssText = function (cssText) { // Difference with webcomponents.js: does not handle comments - return StringWrapper.replaceAllMapped(cssText, _cssContentRuleRe, function (m /** TODO #9100 */) { - var rule = m[0]; - rule = StringWrapper.replace(rule, m[1], ''); - rule = StringWrapper.replace(rule, m[2], ''); - return m[3] + rule; + return cssText.replace(_cssContentRuleRe, function () { + var m = []; + for (var _i = 0; _i < arguments.length; _i++) { + m[_i - 0] = arguments[_i]; + } + var rule = m[0].replace(m[1], '').replace(m[2], ''); + return m[4] + rule; }); }; /* Ensure styles are scoped. Pseudo-scoping takes a rule like: @@ -25671,15 +25540,16 @@ * scopeName .foo { ... } */ ShadowCss.prototype._scopeCssText = function (cssText, scopeSelector, hostSelector) { - var unscoped = this._extractUnscopedRulesFromCssText(cssText); + var unscopedRules = this._extractUnscopedRulesFromCssText(cssText); + // replace :host and :host-context -shadowcsshost and -shadowcsshost respectively cssText = this._insertPolyfillHostInCssText(cssText); cssText = this._convertColonHost(cssText); cssText = this._convertColonHostContext(cssText); cssText = this._convertShadowDOMSelectors(cssText); - if (isPresent(scopeSelector)) { + if (scopeSelector) { cssText = this._scopeSelectors(cssText, scopeSelector, hostSelector); } - cssText = cssText + '\n' + unscoped; + cssText = cssText + '\n' + unscopedRules; return cssText.trim(); }; /* @@ -25703,9 +25573,7 @@ var m; _cssContentUnscopedRuleRe.lastIndex = 0; while ((m = _cssContentUnscopedRuleRe.exec(cssText)) !== null) { - var rule = m[0]; - rule = StringWrapper.replace(rule, m[2], ''); - rule = StringWrapper.replace(rule, m[1], m[3]); + var rule = m[0].replace(m[2], '').replace(m[1], m[4]); r += rule + '\n\n'; } return r; @@ -25715,7 +25583,7 @@ * * to * - * scopeName.foo > .bar + * .foo > .bar */ ShadowCss.prototype._convertColonHost = function (cssText) { return this._convertColonRule(cssText, _cssColonHostRe, this._colonHostPartReplacer); @@ -25725,7 +25593,7 @@ * * to * - * scopeName.foo > .bar, .foo scopeName > .bar { } + * .foo > .bar, .foo scopeName > .bar { } * * and * @@ -25733,21 +25601,25 @@ * * to * - * scopeName.foo .bar { ... } + * .foo .bar { ... } */ ShadowCss.prototype._convertColonHostContext = function (cssText) { return this._convertColonRule(cssText, _cssColonHostContextRe, this._colonHostContextPartReplacer); }; ShadowCss.prototype._convertColonRule = function (cssText, regExp, partReplacer) { - // p1 = :host, p2 = contents of (), p3 rest of rule - return StringWrapper.replaceAllMapped(cssText, regExp, function (m /** TODO #9100 */) { - if (isPresent(m[2])) { - var parts = m[2].split(','), r = []; + // m[1] = :host(-context), m[2] = contents of (), m[3] rest of rule + return cssText.replace(regExp, function () { + var m = []; + for (var _i = 0; _i < arguments.length; _i++) { + m[_i - 0] = arguments[_i]; + } + if (m[2]) { + var parts = m[2].split(','); + var r = []; for (var i = 0; i < parts.length; i++) { - var p = parts[i]; - if (isBlank(p)) + var p = parts[i].trim(); + if (!p) break; - p = p.trim(); r.push(partReplacer(_polyfillHostNoCombinator, p, m[3])); } return r.join(','); @@ -25758,7 +25630,7 @@ }); }; ShadowCss.prototype._colonHostContextPartReplacer = function (host, part, suffix) { - if (StringWrapper.contains(part, _polyfillHost)) { + if (part.indexOf(_polyfillHost) > -1) { return this._colonHostPartReplacer(host, part, suffix); } else { @@ -25766,14 +25638,14 @@ } }; ShadowCss.prototype._colonHostPartReplacer = function (host, part, suffix) { - return host + StringWrapper.replace(part, _polyfillHost, '') + suffix; + return host + part.replace(_polyfillHost, '') + suffix; }; /* * Convert combinators like ::shadow and pseudo-elements like ::content * by replacing with space. */ ShadowCss.prototype._convertShadowDOMSelectors = function (cssText) { - return _shadowDOMSelectorsRe.reduce(function (result, pattern) { return StringWrapper.replaceAll(result, pattern, ' '); }, cssText); + return _shadowDOMSelectorsRe.reduce(function (result, pattern) { return result.replace(pattern, ' '); }, cssText); }; // change a selector like 'div' to 'name div' ShadowCss.prototype._scopeSelectors = function (cssText, scopeSelector, hostSelector) { @@ -25781,11 +25653,12 @@ return processRules(cssText, function (rule) { var selector = rule.selector; var content = rule.content; - if (rule.selector[0] != '@' || rule.selector.startsWith('@page')) { + if (rule.selector[0] != '@') { selector = _this._scopeSelector(rule.selector, scopeSelector, hostSelector, _this.strictStyling); } - else if (rule.selector.startsWith('@media') || rule.selector.startsWith('@supports')) { + else if (rule.selector.startsWith('@media') || rule.selector.startsWith('@supports') || + rule.selector.startsWith('@page') || rule.selector.startsWith('@document')) { content = _this._scopeSelectors(rule.content, scopeSelector, hostSelector); } return new CssRule(selector, content); @@ -25818,8 +25691,7 @@ ShadowCss.prototype._makeScopeMatcher = function (scopeSelector) { var lre = /\[/g; var rre = /\]/g; - scopeSelector = StringWrapper.replaceAll(scopeSelector, lre, '\\['); - scopeSelector = StringWrapper.replaceAll(scopeSelector, rre, '\\]'); + scopeSelector = scopeSelector.replace(lre, '\\[').replace(rre, '\\]'); return new RegExp('^(' + scopeSelector + ')' + _selectorReSuffix, 'm'); }; ShadowCss.prototype._applySelectorScope = function (selector, scopeSelector, hostSelector) { @@ -25831,13 +25703,11 @@ // In Android browser, the lastIndex is not reset when the regex is used in String.replace() _polyfillHostRe.lastIndex = 0; if (_polyfillHostRe.test(selector)) { - var replaceBy = this.strictStyling ? "[" + hostSelector + "]" : scopeSelector; - selector = StringWrapper.replace(selector, _polyfillHostNoCombinator, replaceBy); - return StringWrapper.replaceAll(selector, _polyfillHostRe, replaceBy + ' '); - } - else { - return scopeSelector + ' ' + selector; + var replaceBy_1 = this.strictStyling ? "[" + hostSelector + "]" : scopeSelector; + return selector.replace(_polyfillHostNoCombinatorRe, function (hnc, selector) { return selector + replaceBy_1; }) + .replace(_polyfillHostRe, replaceBy_1 + ' '); } + return scopeSelector + ' ' + selector; }; // return a selector with [name] suffix on each simple selector // e.g. .foo.bar > .zot becomes .foo[name].bar[name] > .zot[name] /** @internal */ @@ -25854,7 +25724,7 @@ var attrName = '[' + scopeSelector + ']'; var _scopeSelectorPart = function (p) { var scopedP = p.trim(); - if (scopedP.length == 0) { + if (!scopedP) { return ''; } if (p.indexOf(_polyfillHostNoCombinator) > -1) { @@ -25872,21 +25742,33 @@ } return scopedP; }; - var sep = /( |>|\+|~)\s*/g; - var scopeAfter = selector.indexOf(_polyfillHostNoCombinator); - var scoped = ''; + var attrSelectorIndex = 0; + var attrSelectors = []; + // replace attribute selectors with placeholders to avoid issue with white space being treated + // as separator + selector = selector.replace(/\[[^\]]*\]/g, function (attrSelector) { + var replaceBy = "__attr_sel_" + attrSelectorIndex + "__"; + attrSelectors.push(attrSelector); + attrSelectorIndex++; + return replaceBy; + }); + var scopedSelector = ''; var startIndex = 0; var res; + var sep = /( |>|\+|~(?!=))\s*/g; + var scopeAfter = selector.indexOf(_polyfillHostNoCombinator); while ((res = sep.exec(selector)) !== null) { var separator = res[1]; var part = selector.slice(startIndex, res.index).trim(); // if a selector appears before :host-context it should not be shimmed as it // matches on ancestor elements and not on elements in the host's shadow var scopedPart = startIndex >= scopeAfter ? _scopeSelectorPart(part) : part; - scoped += scopedPart + " " + separator + " "; + scopedSelector += scopedPart + " " + separator + " "; startIndex = sep.lastIndex; } - return scoped + _scopeSelectorPart(selector.substring(startIndex)); + scopedSelector += _scopeSelectorPart(selector.substring(startIndex)); + // replace the placeholders with their original values + return scopedSelector.replace(/__attr_sel_(\d+)__/g, function (ph, index) { return attrSelectors[+index]; }); }; ShadowCss.prototype._insertPolyfillHostInCssText = function (selector) { return selector.replace(_colonHostContextRe, _polyfillHostContext) @@ -25894,9 +25776,9 @@ }; return ShadowCss; }()); - var _cssContentNextSelectorRe = /polyfill-next-selector[^}]*content:[\s]*?['"](.*?)['"][;\s]*}([^{]*?){/gim; - var _cssContentRuleRe = /(polyfill-rule)[^}]*(content:[\s]*['"](.*?)['"])[;\s]*[^}]*}/gim; - var _cssContentUnscopedRuleRe = /(polyfill-unscoped-rule)[^}]*(content:[\s]*['"](.*?)['"])[;\s]*[^}]*}/gim; + var _cssContentNextSelectorRe = /polyfill-next-selector[^}]*content:[\s]*?(['"])(.*?)\1[;\s]*}([^{]*?){/gim; + var _cssContentRuleRe = /(polyfill-rule)[^}]*(content:[\s]*(['"])(.*?)\3)[;\s]*[^}]*}/gim; + var _cssContentUnscopedRuleRe = /(polyfill-unscoped-rule)[^}]*(content:[\s]*(['"])(.*?)\3)[;\s]*[^}]*}/gim; var _polyfillHost = '-shadowcsshost'; // note: :host-context pre-processed to -shadowcsshostcontext. var _polyfillHostContext = '-shadowcsscontext'; @@ -25906,6 +25788,7 @@ var _cssColonHostRe = new RegExp('(' + _polyfillHost + _parenSuffix, 'gim'); var _cssColonHostContextRe = new RegExp('(' + _polyfillHostContext + _parenSuffix, 'gim'); var _polyfillHostNoCombinator = _polyfillHost + '-no-combinator'; + var _polyfillHostNoCombinatorRe = /-shadowcsshost-no-combinator([^\s]*)/; var _shadowDOMSelectorsRe = [ /::shadow/g, /::content/g, @@ -25920,13 +25803,13 @@ var _colonHostContextRe = /:host-context/gim; var _commentRe = /\/\*\s*[\s\S]*?\*\//g; function stripComments(input) { - return StringWrapper.replaceAllMapped(input, _commentRe, function (_ /** TODO #9100 */) { return ''; }); + return input.replace(_commentRe, ''); } - // all comments except inline source mapping ("/* #sourceMappingURL= ... */") - var _sourceMappingUrlRe = /[\s\S]*(\/\*\s*#\s*sourceMappingURL=[\s\S]+?\*\/)\s*$/; + // all comments except inline source mapping + var _sourceMappingUrlRe = /\/\*\s*#\s*sourceMappingURL=[\s\S]+?\*\//; function extractSourceMappingUrl(input) { var matcher = input.match(_sourceMappingUrlRe); - return matcher ? matcher[1] : ''; + return matcher ? matcher[0] : ''; } var _ruleRe = /(\s*)([^;\{\}]+?)(\s*)((?:{%BLOCK%}?\s*;?)|(?:\s*;))/g; var _curlyRe = /([{}])/g; @@ -25943,14 +25826,18 @@ function processRules(input, ruleCallback) { var inputWithEscapedBlocks = escapeBlocks(input); var nextBlockIndex = 0; - return StringWrapper.replaceAllMapped(inputWithEscapedBlocks.escapedString, _ruleRe, function (m /** TODO #9100 */) { + return inputWithEscapedBlocks.escapedString.replace(_ruleRe, function () { + var m = []; + for (var _i = 0; _i < arguments.length; _i++) { + m[_i - 0] = arguments[_i]; + } var selector = m[2]; var content = ''; var suffix = m[4]; var contentPrefix = ''; - if (isPresent(m[4]) && m[4].startsWith('{' + BLOCK_PLACEHOLDER)) { + if (suffix && suffix.startsWith('{' + BLOCK_PLACEHOLDER)) { content = inputWithEscapedBlocks.blocks[nextBlockIndex++]; - suffix = m[4].substring(BLOCK_PLACEHOLDER.length + 1); + suffix = suffix.substring(BLOCK_PLACEHOLDER.length + 1); contentPrefix = '{'; } var rule = ruleCallback(new CssRule(selector, content)); @@ -25965,7 +25852,7 @@ return StringWithEscapedBlocks; }()); function escapeBlocks(input) { - var inputParts = StringWrapper.split(input, _curlyRe); + var inputParts = input.split(_curlyRe); var resultParts = []; var escapedBlocks = []; var bracketCount = 0; @@ -26104,6 +25991,8 @@ this._compiledTemplateCache = new Map(); this._compiledHostTemplateCache = new Map(); this._compiledNgModuleCache = new Map(); + this._animationParser = new AnimationParser(); + this._animationCompiler = new AnimationCompiler(); } Object.defineProperty(RuntimeCompiler.prototype, "injector", { get: function () { return this._injector; }, @@ -26238,7 +26127,7 @@ }; RuntimeCompiler.prototype._createCompiledHostTemplate = function (compType) { var compiledTemplate = this._compiledHostTemplateCache.get(compType); - if (isBlank(compiledTemplate)) { + if (!compiledTemplate) { var compMeta = this._metadataResolver.getDirectiveMetadata(compType); assertComponent(compMeta); var hostMeta = createHostComponentMeta(compMeta); @@ -26249,7 +26138,7 @@ }; RuntimeCompiler.prototype._createCompiledTemplate = function (compMeta, ngModule) { var compiledTemplate = this._compiledTemplateCache.get(compMeta.type.reference); - if (isBlank(compiledTemplate)) { + if (!compiledTemplate) { assertComponent(compMeta); compiledTemplate = new CompiledTemplate(false, compMeta.selector, compMeta.type, ngModule.transitiveModule.directives, ngModule.transitiveModule.pipes, ngModule.schemas, this._templateNormalizer.normalizeDirective(compMeta)); this._compiledTemplateCache.set(compMeta.type.reference, compiledTemplate); @@ -26287,8 +26176,10 @@ stylesCompileResult.externalStylesheets.forEach(function (r) { externalStylesheetsByModuleUrl.set(r.meta.moduleUrl, r); }); this._resolveStylesCompileResult(stylesCompileResult.componentStylesheet, externalStylesheetsByModuleUrl); var viewCompMetas = template.viewComponentTypes.map(function (compType) { return _this._assertComponentLoaded(compType, false).normalizedCompMeta; }); + var parsedAnimations = this._animationParser.parseComponent(compMeta); var parsedTemplate = this._templateParser.parse(compMeta, compMeta.template.template, template.viewDirectives.concat(viewCompMetas), template.viewPipes, template.schemas, compMeta.type.name); - var compileResult = this._viewCompiler.compileComponent(compMeta, parsedTemplate, variable(stylesCompileResult.componentStylesheet.stylesVar), template.viewPipes); + var compiledAnimations = this._animationCompiler.compile(compMeta.type.name, parsedAnimations); + var compileResult = this._viewCompiler.compileComponent(compMeta, parsedTemplate, variable(stylesCompileResult.componentStylesheet.stylesVar), template.viewPipes, compiledAnimations); compileResult.dependencies.forEach(function (dep) { var depTemplate; if (dep instanceof ViewFactoryDependency) { @@ -26305,6 +26196,7 @@ } }); var statements = stylesCompileResult.componentStylesheet.statements.concat(compileResult.statements); + compiledAnimations.forEach(function (entry) { entry.statements.forEach(function (statement) { statements.push(statement); }); }); var factory; if (!this._compilerConfig.useJit) { factory = interpretStatements(statements, compileResult.viewFactoryVar); @@ -26506,7 +26398,7 @@ * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ - var __extends$18 = (this && this.__extends) || function (d, b) { + var __extends$19 = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); @@ -26532,7 +26424,8 @@ * An `element` may inherit additional properties from `parentElement` If no `^parentElement` is * specified then `""` (blank) element is assumed. * - * NOTE: The blank element inherits from root `*` element, the super element of all elements. + * NOTE: The blank element inherits from root `[Element]` element, the super element of all + * elements. * * NOTE an element prefix such as `:svg:` has no special meaning to the schema. * @@ -26568,11 +26461,12 @@ // dom_security_schema.ts. Reach out to mprobst & rjamet for details. // // ================================================================================================= - var SCHEMA = ([ - '*|textContent,%classList,className,id,innerHTML,*beforecopy,*beforecut,*beforepaste,*copy,*cut,*paste,*search,*selectstart,*webkitfullscreenchange,*webkitfullscreenerror,*wheel,outerHTML,#scrollLeft,#scrollTop', - 'abbr,address,article,aside,b,bdi,bdo,cite,code,dd,dfn,dt,em,figcaption,figure,footer,header,i,kbd,main,mark,nav,noscript,rb,rp,rt,rtc,ruby,s,samp,section,small,strong,sub,sup,u,var,wbr^*|accessKey,contentEditable,dir,!draggable,!hidden,innerText,lang,*abort,*beforecopy,*beforecut,*beforepaste,*blur,*cancel,*canplay,*canplaythrough,*change,*click,*close,*contextmenu,*copy,*cuechange,*cut,*dblclick,*drag,*dragend,*dragenter,*dragleave,*dragover,*dragstart,*drop,*durationchange,*emptied,*ended,*error,*focus,*input,*invalid,*keydown,*keypress,*keyup,*load,*loadeddata,*loadedmetadata,*loadstart,*message,*mousedown,*mouseenter,*mouseleave,*mousemove,*mouseout,*mouseover,*mouseup,*mousewheel,*mozfullscreenchange,*mozfullscreenerror,*mozpointerlockchange,*mozpointerlockerror,*paste,*pause,*play,*playing,*progress,*ratechange,*reset,*resize,*scroll,*search,*seeked,*seeking,*select,*selectstart,*show,*stalled,*submit,*suspend,*timeupdate,*toggle,*volumechange,*waiting,*webglcontextcreationerror,*webglcontextlost,*webglcontextrestored,*webkitfullscreenchange,*webkitfullscreenerror,*wheel,outerText,!spellcheck,%style,#tabIndex,title,!translate', - 'media^abbr|!autoplay,!controls,%crossOrigin,#currentTime,!defaultMuted,#defaultPlaybackRate,!disableRemotePlayback,!loop,!muted,*encrypted,#playbackRate,preload,src,%srcObject,#volume', - ':svg:^abbr|*abort,*blur,*cancel,*canplay,*canplaythrough,*change,*click,*close,*contextmenu,*cuechange,*dblclick,*drag,*dragend,*dragenter,*dragleave,*dragover,*dragstart,*drop,*durationchange,*emptied,*ended,*error,*focus,*input,*invalid,*keydown,*keypress,*keyup,*load,*loadeddata,*loadedmetadata,*loadstart,*mousedown,*mouseenter,*mouseleave,*mousemove,*mouseout,*mouseover,*mouseup,*mousewheel,*pause,*play,*playing,*progress,*ratechange,*reset,*resize,*scroll,*seeked,*seeking,*select,*show,*stalled,*submit,*suspend,*timeupdate,*toggle,*volumechange,*waiting,%style,#tabIndex', + var SCHEMA = [ + '[Element]|textContent,%classList,className,id,innerHTML,*beforecopy,*beforecut,*beforepaste,*copy,*cut,*paste,*search,*selectstart,*webkitfullscreenchange,*webkitfullscreenerror,*wheel,outerHTML,#scrollLeft,#scrollTop', + '[HTMLElement]^[Element]|accessKey,contentEditable,dir,!draggable,!hidden,innerText,lang,*abort,*beforecopy,*beforecut,*beforepaste,*blur,*cancel,*canplay,*canplaythrough,*change,*click,*close,*contextmenu,*copy,*cuechange,*cut,*dblclick,*drag,*dragend,*dragenter,*dragleave,*dragover,*dragstart,*drop,*durationchange,*emptied,*ended,*error,*focus,*input,*invalid,*keydown,*keypress,*keyup,*load,*loadeddata,*loadedmetadata,*loadstart,*message,*mousedown,*mouseenter,*mouseleave,*mousemove,*mouseout,*mouseover,*mouseup,*mousewheel,*mozfullscreenchange,*mozfullscreenerror,*mozpointerlockchange,*mozpointerlockerror,*paste,*pause,*play,*playing,*progress,*ratechange,*reset,*resize,*scroll,*search,*seeked,*seeking,*select,*selectstart,*show,*stalled,*submit,*suspend,*timeupdate,*toggle,*volumechange,*waiting,*webglcontextcreationerror,*webglcontextlost,*webglcontextrestored,*webkitfullscreenchange,*webkitfullscreenerror,*wheel,outerText,!spellcheck,%style,#tabIndex,title,!translate', + 'abbr,address,article,aside,b,bdi,bdo,cite,code,dd,dfn,dt,em,figcaption,figure,footer,header,i,kbd,main,mark,nav,noscript,rb,rp,rt,rtc,ruby,s,samp,section,small,strong,sub,sup,u,var,wbr^[HTMLElement]|accessKey,contentEditable,dir,!draggable,!hidden,innerText,lang,*abort,*beforecopy,*beforecut,*beforepaste,*blur,*cancel,*canplay,*canplaythrough,*change,*click,*close,*contextmenu,*copy,*cuechange,*cut,*dblclick,*drag,*dragend,*dragenter,*dragleave,*dragover,*dragstart,*drop,*durationchange,*emptied,*ended,*error,*focus,*input,*invalid,*keydown,*keypress,*keyup,*load,*loadeddata,*loadedmetadata,*loadstart,*message,*mousedown,*mouseenter,*mouseleave,*mousemove,*mouseout,*mouseover,*mouseup,*mousewheel,*mozfullscreenchange,*mozfullscreenerror,*mozpointerlockchange,*mozpointerlockerror,*paste,*pause,*play,*playing,*progress,*ratechange,*reset,*resize,*scroll,*search,*seeked,*seeking,*select,*selectstart,*show,*stalled,*submit,*suspend,*timeupdate,*toggle,*volumechange,*waiting,*webglcontextcreationerror,*webglcontextlost,*webglcontextrestored,*webkitfullscreenchange,*webkitfullscreenerror,*wheel,outerText,!spellcheck,%style,#tabIndex,title,!translate', + 'media^[HTMLElement]|!autoplay,!controls,%crossOrigin,#currentTime,!defaultMuted,#defaultPlaybackRate,!disableRemotePlayback,!loop,!muted,*encrypted,#playbackRate,preload,src,%srcObject,#volume', + ':svg:^[HTMLElement]|*abort,*blur,*cancel,*canplay,*canplaythrough,*change,*click,*close,*contextmenu,*cuechange,*dblclick,*drag,*dragend,*dragenter,*dragleave,*dragover,*dragstart,*drop,*durationchange,*emptied,*ended,*error,*focus,*input,*invalid,*keydown,*keypress,*keyup,*load,*loadeddata,*loadedmetadata,*loadstart,*mousedown,*mouseenter,*mouseleave,*mousemove,*mouseout,*mouseover,*mouseup,*mousewheel,*pause,*play,*playing,*progress,*ratechange,*reset,*resize,*scroll,*seeked,*seeking,*select,*show,*stalled,*submit,*suspend,*timeupdate,*toggle,*volumechange,*waiting,%style,#tabIndex', ':svg:graphics^:svg:|', ':svg:animation^:svg:|*begin,*end,*repeat', ':svg:geometry^:svg:|', @@ -26580,75 +26474,74 @@ ':svg:gradient^:svg:|', ':svg:textContent^:svg:graphics|', ':svg:textPositioning^:svg:textContent|', - 'abbr^*|accessKey,contentEditable,dir,!draggable,!hidden,innerText,lang,*abort,*beforecopy,*beforecut,*beforepaste,*blur,*cancel,*canplay,*canplaythrough,*change,*click,*close,*contextmenu,*copy,*cuechange,*cut,*dblclick,*drag,*dragend,*dragenter,*dragleave,*dragover,*dragstart,*drop,*durationchange,*emptied,*ended,*error,*focus,*input,*invalid,*keydown,*keypress,*keyup,*load,*loadeddata,*loadedmetadata,*loadstart,*message,*mousedown,*mouseenter,*mouseleave,*mousemove,*mouseout,*mouseover,*mouseup,*mousewheel,*mozfullscreenchange,*mozfullscreenerror,*mozpointerlockchange,*mozpointerlockerror,*paste,*pause,*play,*playing,*progress,*ratechange,*reset,*resize,*scroll,*search,*seeked,*seeking,*select,*selectstart,*show,*stalled,*submit,*suspend,*timeupdate,*toggle,*volumechange,*waiting,*webglcontextcreationerror,*webglcontextlost,*webglcontextrestored,*webkitfullscreenchange,*webkitfullscreenerror,*wheel,outerText,!spellcheck,%style,#tabIndex,title,!translate', - 'a^abbr|charset,coords,download,hash,host,hostname,href,hreflang,name,password,pathname,ping,port,protocol,referrerPolicy,rel,rev,search,shape,target,text,type,username', - 'area^abbr|alt,coords,hash,host,hostname,href,!noHref,password,pathname,ping,port,protocol,referrerPolicy,search,shape,target,username', + 'a^[HTMLElement]|charset,coords,download,hash,host,hostname,href,hreflang,name,password,pathname,ping,port,protocol,referrerPolicy,rel,rev,search,shape,target,text,type,username', + 'area^[HTMLElement]|alt,coords,hash,host,hostname,href,!noHref,password,pathname,ping,port,protocol,referrerPolicy,search,shape,target,username', 'audio^media|', - 'br^abbr|clear', - 'base^abbr|href,target', - 'body^abbr|aLink,background,bgColor,link,*beforeunload,*blur,*error,*focus,*hashchange,*languagechange,*load,*message,*offline,*online,*pagehide,*pageshow,*popstate,*rejectionhandled,*resize,*scroll,*storage,*unhandledrejection,*unload,text,vLink', - 'button^abbr|!autofocus,!disabled,formAction,formEnctype,formMethod,!formNoValidate,formTarget,name,type,value', - 'canvas^abbr|#height,#width', - 'content^abbr|select', - 'dl^abbr|!compact', - 'datalist^abbr|', - 'details^abbr|!open', - 'dialog^abbr|!open,returnValue', - 'dir^abbr|!compact', - 'div^abbr|align', - 'embed^abbr|align,height,name,src,type,width', - 'fieldset^abbr|!disabled,name', - 'font^abbr|color,face,size', - 'form^abbr|acceptCharset,action,autocomplete,encoding,enctype,method,name,!noValidate,target', - 'frame^abbr|frameBorder,longDesc,marginHeight,marginWidth,name,!noResize,scrolling,src', - 'frameset^abbr|cols,*beforeunload,*blur,*error,*focus,*hashchange,*languagechange,*load,*message,*offline,*online,*pagehide,*pageshow,*popstate,*rejectionhandled,*resize,*scroll,*storage,*unhandledrejection,*unload,rows', - 'hr^abbr|align,color,!noShade,size,width', - 'head^abbr|', - 'h1,h2,h3,h4,h5,h6^abbr|align', - 'html^abbr|version', - 'iframe^abbr|align,!allowFullscreen,frameBorder,height,longDesc,marginHeight,marginWidth,name,referrerPolicy,%sandbox,scrolling,src,srcdoc,width', - 'img^abbr|align,alt,border,%crossOrigin,#height,#hspace,!isMap,longDesc,lowsrc,name,referrerPolicy,sizes,src,srcset,useMap,#vspace,#width', - 'input^abbr|accept,align,alt,autocapitalize,autocomplete,!autofocus,!checked,!defaultChecked,defaultValue,dirName,!disabled,%files,formAction,formEnctype,formMethod,!formNoValidate,formTarget,#height,!incremental,!indeterminate,max,#maxLength,min,#minLength,!multiple,name,pattern,placeholder,!readOnly,!required,selectionDirection,#selectionEnd,#selectionStart,#size,src,step,type,useMap,value,%valueAsDate,#valueAsNumber,#width', - 'keygen^abbr|!autofocus,challenge,!disabled,keytype,name', - 'li^abbr|type,#value', - 'label^abbr|htmlFor', - 'legend^abbr|align', - 'link^abbr|as,charset,%crossOrigin,!disabled,href,hreflang,integrity,media,rel,%relList,rev,%sizes,target,type', - 'map^abbr|name', - 'marquee^abbr|behavior,bgColor,direction,height,#hspace,#loop,#scrollAmount,#scrollDelay,!trueSpeed,#vspace,width', - 'menu^abbr|!compact', - 'meta^abbr|content,httpEquiv,name,scheme', - 'meter^abbr|#high,#low,#max,#min,#optimum,#value', - 'ins,del^abbr|cite,dateTime', - 'ol^abbr|!compact,!reversed,#start,type', - 'object^abbr|align,archive,border,code,codeBase,codeType,data,!declare,height,#hspace,name,standby,type,useMap,#vspace,width', - 'optgroup^abbr|!disabled,label', - 'option^abbr|!defaultSelected,!disabled,label,!selected,text,value', - 'output^abbr|defaultValue,%htmlFor,name,value', - 'p^abbr|align', - 'param^abbr|name,type,value,valueType', - 'picture^abbr|', - 'pre^abbr|#width', - 'progress^abbr|#max,#value', - 'q,blockquote,cite^abbr|', - 'script^abbr|!async,charset,%crossOrigin,!defer,event,htmlFor,integrity,src,text,type', - 'select^abbr|!autofocus,!disabled,#length,!multiple,name,!required,#selectedIndex,#size,value', - 'shadow^abbr|', - 'source^abbr|media,sizes,src,srcset,type', - 'span^abbr|', - 'style^abbr|!disabled,media,type', - 'caption^abbr|align', - 'th,td^abbr|abbr,align,axis,bgColor,ch,chOff,#colSpan,headers,height,!noWrap,#rowSpan,scope,vAlign,width', - 'col,colgroup^abbr|align,ch,chOff,#span,vAlign,width', - 'table^abbr|align,bgColor,border,%caption,cellPadding,cellSpacing,frame,rules,summary,%tFoot,%tHead,width', - 'tr^abbr|align,bgColor,ch,chOff,vAlign', - 'tfoot,thead,tbody^abbr|align,ch,chOff,vAlign', - 'template^abbr|', - 'textarea^abbr|autocapitalize,!autofocus,#cols,defaultValue,dirName,!disabled,#maxLength,#minLength,name,placeholder,!readOnly,!required,#rows,selectionDirection,#selectionEnd,#selectionStart,value,wrap', - 'title^abbr|text', - 'track^abbr|!default,kind,label,src,srclang', - 'ul^abbr|!compact,type', - 'unknown^abbr|', + 'br^[HTMLElement]|clear', + 'base^[HTMLElement]|href,target', + 'body^[HTMLElement]|aLink,background,bgColor,link,*beforeunload,*blur,*error,*focus,*hashchange,*languagechange,*load,*message,*offline,*online,*pagehide,*pageshow,*popstate,*rejectionhandled,*resize,*scroll,*storage,*unhandledrejection,*unload,text,vLink', + 'button^[HTMLElement]|!autofocus,!disabled,formAction,formEnctype,formMethod,!formNoValidate,formTarget,name,type,value', + 'canvas^[HTMLElement]|#height,#width', + 'content^[HTMLElement]|select', + 'dl^[HTMLElement]|!compact', + 'datalist^[HTMLElement]|', + 'details^[HTMLElement]|!open', + 'dialog^[HTMLElement]|!open,returnValue', + 'dir^[HTMLElement]|!compact', + 'div^[HTMLElement]|align', + 'embed^[HTMLElement]|align,height,name,src,type,width', + 'fieldset^[HTMLElement]|!disabled,name', + 'font^[HTMLElement]|color,face,size', + 'form^[HTMLElement]|acceptCharset,action,autocomplete,encoding,enctype,method,name,!noValidate,target', + 'frame^[HTMLElement]|frameBorder,longDesc,marginHeight,marginWidth,name,!noResize,scrolling,src', + 'frameset^[HTMLElement]|cols,*beforeunload,*blur,*error,*focus,*hashchange,*languagechange,*load,*message,*offline,*online,*pagehide,*pageshow,*popstate,*rejectionhandled,*resize,*scroll,*storage,*unhandledrejection,*unload,rows', + 'hr^[HTMLElement]|align,color,!noShade,size,width', + 'head^[HTMLElement]|', + 'h1,h2,h3,h4,h5,h6^[HTMLElement]|align', + 'html^[HTMLElement]|version', + 'iframe^[HTMLElement]|align,!allowFullscreen,frameBorder,height,longDesc,marginHeight,marginWidth,name,referrerPolicy,%sandbox,scrolling,src,srcdoc,width', + 'img^[HTMLElement]|align,alt,border,%crossOrigin,#height,#hspace,!isMap,longDesc,lowsrc,name,referrerPolicy,sizes,src,srcset,useMap,#vspace,#width', + 'input^[HTMLElement]|accept,align,alt,autocapitalize,autocomplete,!autofocus,!checked,!defaultChecked,defaultValue,dirName,!disabled,%files,formAction,formEnctype,formMethod,!formNoValidate,formTarget,#height,!incremental,!indeterminate,max,#maxLength,min,#minLength,!multiple,name,pattern,placeholder,!readOnly,!required,selectionDirection,#selectionEnd,#selectionStart,#size,src,step,type,useMap,value,%valueAsDate,#valueAsNumber,#width', + 'keygen^[HTMLElement]|!autofocus,challenge,!disabled,keytype,name', + 'li^[HTMLElement]|type,#value', + 'label^[HTMLElement]|htmlFor', + 'legend^[HTMLElement]|align', + 'link^[HTMLElement]|as,charset,%crossOrigin,!disabled,href,hreflang,integrity,media,rel,%relList,rev,%sizes,target,type', + 'map^[HTMLElement]|name', + 'marquee^[HTMLElement]|behavior,bgColor,direction,height,#hspace,#loop,#scrollAmount,#scrollDelay,!trueSpeed,#vspace,width', + 'menu^[HTMLElement]|!compact', + 'meta^[HTMLElement]|content,httpEquiv,name,scheme', + 'meter^[HTMLElement]|#high,#low,#max,#min,#optimum,#value', + 'ins,del^[HTMLElement]|cite,dateTime', + 'ol^[HTMLElement]|!compact,!reversed,#start,type', + 'object^[HTMLElement]|align,archive,border,code,codeBase,codeType,data,!declare,height,#hspace,name,standby,type,useMap,#vspace,width', + 'optgroup^[HTMLElement]|!disabled,label', + 'option^[HTMLElement]|!defaultSelected,!disabled,label,!selected,text,value', + 'output^[HTMLElement]|defaultValue,%htmlFor,name,value', + 'p^[HTMLElement]|align', + 'param^[HTMLElement]|name,type,value,valueType', + 'picture^[HTMLElement]|', + 'pre^[HTMLElement]|#width', + 'progress^[HTMLElement]|#max,#value', + 'q,blockquote,cite^[HTMLElement]|', + 'script^[HTMLElement]|!async,charset,%crossOrigin,!defer,event,htmlFor,integrity,src,text,type', + 'select^[HTMLElement]|!autofocus,!disabled,#length,!multiple,name,!required,#selectedIndex,#size,value', + 'shadow^[HTMLElement]|', + 'source^[HTMLElement]|media,sizes,src,srcset,type', + 'span^[HTMLElement]|', + 'style^[HTMLElement]|!disabled,media,type', + 'caption^[HTMLElement]|align', + 'th,td^[HTMLElement]|abbr,align,axis,bgColor,ch,chOff,#colSpan,headers,height,!noWrap,#rowSpan,scope,vAlign,width', + 'col,colgroup^[HTMLElement]|align,ch,chOff,#span,vAlign,width', + 'table^[HTMLElement]|align,bgColor,border,%caption,cellPadding,cellSpacing,frame,rules,summary,%tFoot,%tHead,width', + 'tr^[HTMLElement]|align,bgColor,ch,chOff,vAlign', + 'tfoot,thead,tbody^[HTMLElement]|align,ch,chOff,vAlign', + 'template^[HTMLElement]|', + 'textarea^[HTMLElement]|autocapitalize,!autofocus,#cols,defaultValue,dirName,!disabled,#maxLength,#minLength,name,placeholder,!readOnly,!required,#rows,selectionDirection,#selectionEnd,#selectionStart,value,wrap', + 'title^[HTMLElement]|text', + 'track^[HTMLElement]|!default,kind,label,src,srclang', + 'ul^[HTMLElement]|!compact,type', + 'unknown^[HTMLElement]|', 'video^media|#height,poster,#width', ':svg:a^:svg:graphics|', ':svg:animate^:svg:animation|', @@ -26715,27 +26608,31 @@ ':svg:title^:svg:|', ':svg:use^:svg:graphics|', ':svg:view^:svg:|#zoomAndPan', - ]); + 'data^[HTMLElement]|value', + 'menuitem^[HTMLElement]|type,label,icon,!disabled,!checked,radiogroup,!default', + 'summary^[HTMLElement]|', + 'time^[HTMLElement]|dateTime', + ]; var _ATTR_TO_PROP = { 'class': 'className', 'formaction': 'formAction', 'innerHtml': 'innerHTML', 'readonly': 'readOnly', - 'tabindex': 'tabIndex' + 'tabindex': 'tabIndex', }; var DomElementSchemaRegistry = (function (_super) { - __extends$18(DomElementSchemaRegistry, _super); + __extends$19(DomElementSchemaRegistry, _super); function DomElementSchemaRegistry() { var _this = this; _super.call(this); this._schema = {}; SCHEMA.forEach(function (encodedType) { + var type = {}; var _a = encodedType.split('|'), strType = _a[0], strProperties = _a[1]; var properties = strProperties.split(','); var _b = strType.split('^'), typeNames = _b[0], superName = _b[1]; - var type = {}; typeNames.split(',').forEach(function (tag) { return _this._schema[tag.toLowerCase()] = type; }); - var superType = _this._schema[superName]; + var superType = superName && _this._schema[superName.toLowerCase()]; if (superType) { Object.keys(superType).forEach(function (prop) { type[prop] = superType[prop]; }); } @@ -26821,6 +26718,28 @@ }; DomElementSchemaRegistry.prototype.getMappedPropName = function (propName) { return _ATTR_TO_PROP[propName] || propName; }; DomElementSchemaRegistry.prototype.getDefaultComponentElementName = function () { return 'ng-component'; }; + DomElementSchemaRegistry.prototype.validateProperty = function (name) { + if (name.toLowerCase().startsWith('on')) { + var msg = ("Binding to event property '" + name + "' is disallowed for security reasons, ") + + ("please use (" + name.slice(2) + ")=...") + + ("\nIf '" + name + "' is a directive input, make sure the directive is imported by the") + + " current module."; + return { error: true, msg: msg }; + } + else { + return { error: false }; + } + }; + DomElementSchemaRegistry.prototype.validateAttribute = function (name) { + if (name.toLowerCase().startsWith('on')) { + var msg = ("Binding to event attribute '" + name + "' is disallowed for security reasons, ") + + ("please use (" + name.slice(2) + ")=..."); + return { error: true, msg: msg }; + } + else { + return { error: false }; + } + }; DomElementSchemaRegistry.decorators = [ { type: _angular_core.Injectable }, ]; @@ -26853,8 +26772,8 @@ }, deps: [ HtmlParser, - [new _angular_core.OptionalMetadata(), new _angular_core.Inject(_angular_core.TRANSLATIONS)], - [new _angular_core.OptionalMetadata(), new _angular_core.Inject(_angular_core.TRANSLATIONS_FORMAT)], + [new _angular_core.Optional(), new _angular_core.Inject(_angular_core.TRANSLATIONS)], + [new _angular_core.Optional(), new _angular_core.Inject(_angular_core.TRANSLATIONS_FORMAT)], ] }, TemplateParser, @@ -27073,7 +26992,7 @@ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(global) {/** - * @license Angular v2.0.0-rc.6 + * @license Angular v2.1.0-rc.0 * (c) 2010-2016 Google, Inc. https://angular.io/ * License: MIT */ @@ -27110,12 +27029,8 @@ // exports the original value of the symbol. var global$1 = globalScope; function getTypeNameForDebugging(type) { - if (type['name']) { - return type['name']; - } - return typeof type; + return type['name'] || typeof type; } - var Math = global$1.Math; // TODO: remove calls to assert in production environment // Note: Can't just export this and import in in other files // as `assert` is a reserved keyword in Dart @@ -27134,11 +27049,6 @@ function isFunction(obj) { return typeof obj === 'function'; } - function isPromise(obj) { - // allow any Promise/A+ compliant thenable. - // It's up to the caller to ensure that obj.then conforms to the spec - return isPresent(obj) && isFunction(obj.then); - } function isArray(obj) { return Array.isArray(obj); } @@ -27157,7 +27067,7 @@ } var res = token.toString(); var newLineIndex = res.indexOf('\n'); - return (newLineIndex === -1) ? res : res.substring(0, newLineIndex); + return newLineIndex === -1 ? res : res.substring(0, newLineIndex); } var StringWrapper = (function () { function StringWrapper() { @@ -27258,8 +27168,6 @@ } throw new Error('Invalid integer literal when parsing ' + text + ' in base ' + radix); }; - // TODO: NaN is a valid literal but is returned by parseFloat to indicate an error. - NumberWrapper.parseFloat = function (text) { return parseFloat(text); }; Object.defineProperty(NumberWrapper, "NaN", { get: function () { return NaN; }, enumerable: true, @@ -27312,299 +27220,6 @@ return !isJsObject(obj); } - /** - * Allows to refer to references which are not yet defined. - * - * For instance, `forwardRef` is used when the `token` which we need to refer to for the purposes of - * DI is declared, - * but not yet defined. It is also used when the `token` which we use when creating a query is not - * yet defined. - * - * ### Example - * {@example core/di/ts/forward_ref/forward_ref_spec.ts region='forward_ref'} - * @experimental - */ - function forwardRef(forwardRefFn) { - forwardRefFn.__forward_ref__ = forwardRef; - forwardRefFn.toString = function () { return stringify(this()); }; - return forwardRefFn; - } - /** - * Lazily retrieves the reference value from a forwardRef. - * - * Acts as the identity function when given a non-forward-ref value. - * - * ### Example ([live demo](http://plnkr.co/edit/GU72mJrk1fiodChcmiDR?p=preview)) - * - * {@example core/di/ts/forward_ref/forward_ref_spec.ts region='resolve_forward_ref'} - * - * See: {@link forwardRef} - * @experimental - */ - function resolveForwardRef(type) { - if (isFunction(type) && type.hasOwnProperty('__forward_ref__') && - type.__forward_ref__ === forwardRef) { - return type(); - } - else { - return type; - } - } - - /** - * A parameter metadata that specifies a dependency. - * - * ### Example ([live demo](http://plnkr.co/edit/6uHYJK?p=preview)) - * - * ```typescript - * class Engine {} - * - * @Injectable() - * class Car { - * engine; - * constructor(@Inject("MyEngine") engine:Engine) { - * this.engine = engine; - * } - * } - * - * var injector = Injector.resolveAndCreate([ - * {provide: "MyEngine", useClass: Engine}, - * Car - * ]); - * - * expect(injector.get(Car).engine instanceof Engine).toBe(true); - * ``` - * - * When `@Inject()` is not present, {@link Injector} will use the type annotation of the parameter. - * - * ### Example - * - * ```typescript - * class Engine {} - * - * @Injectable() - * class Car { - * constructor(public engine: Engine) {} //same as constructor(@Inject(Engine) engine:Engine) - * } - * - * var injector = Injector.resolveAndCreate([Engine, Car]); - * expect(injector.get(Car).engine instanceof Engine).toBe(true); - * ``` - * @stable - */ - var InjectMetadata = (function () { - function InjectMetadata(token) { - this.token = token; - } - InjectMetadata.prototype.toString = function () { return "@Inject(" + stringify(this.token) + ")"; }; - return InjectMetadata; - }()); - /** - * A parameter metadata that marks a dependency as optional. {@link Injector} provides `null` if - * the dependency is not found. - * - * ### Example ([live demo](http://plnkr.co/edit/AsryOm?p=preview)) - * - * ```typescript - * class Engine {} - * - * @Injectable() - * class Car { - * engine; - * constructor(@Optional() engine:Engine) { - * this.engine = engine; - * } - * } - * - * var injector = Injector.resolveAndCreate([Car]); - * expect(injector.get(Car).engine).toBeNull(); - * ``` - * @stable - */ - var OptionalMetadata = (function () { - function OptionalMetadata() { - } - OptionalMetadata.prototype.toString = function () { return "@Optional()"; }; - return OptionalMetadata; - }()); - /** - * `DependencyMetadata` is used by the framework to extend DI. - * This is internal to Angular and should not be used directly. - * @stable - */ - var DependencyMetadata = (function () { - function DependencyMetadata() { - } - Object.defineProperty(DependencyMetadata.prototype, "token", { - get: function () { return null; }, - enumerable: true, - configurable: true - }); - return DependencyMetadata; - }()); - /** - * A marker metadata that marks a class as available to {@link Injector} for creation. - * - * ### Example ([live demo](http://plnkr.co/edit/Wk4DMQ?p=preview)) - * - * ```typescript - * @Injectable() - * class UsefulService {} - * - * @Injectable() - * class NeedsService { - * constructor(public service:UsefulService) {} - * } - * - * var injector = Injector.resolveAndCreate([NeedsService, UsefulService]); - * expect(injector.get(NeedsService).service instanceof UsefulService).toBe(true); - * ``` - * {@link Injector} will throw {@link NoAnnotationError} when trying to instantiate a class that - * does not have `@Injectable` marker, as shown in the example below. - * - * ```typescript - * class UsefulService {} - * - * class NeedsService { - * constructor(public service:UsefulService) {} - * } - * - * var injector = Injector.resolveAndCreate([NeedsService, UsefulService]); - * expect(() => injector.get(NeedsService)).toThrowError(); - * ``` - * @stable - */ - var InjectableMetadata = (function () { - function InjectableMetadata() { - } - return InjectableMetadata; - }()); - /** - * Specifies that an {@link Injector} should retrieve a dependency only from itself. - * - * ### Example ([live demo](http://plnkr.co/edit/NeagAg?p=preview)) - * - * ```typescript - * class Dependency { - * } - * - * @Injectable() - * class NeedsDependency { - * dependency; - * constructor(@Self() dependency:Dependency) { - * this.dependency = dependency; - * } - * } - * - * var inj = Injector.resolveAndCreate([Dependency, NeedsDependency]); - * var nd = inj.get(NeedsDependency); - * - * expect(nd.dependency instanceof Dependency).toBe(true); - * - * var inj = Injector.resolveAndCreate([Dependency]); - * var child = inj.resolveAndCreateChild([NeedsDependency]); - * expect(() => child.get(NeedsDependency)).toThrowError(); - * ``` - * @stable - */ - var SelfMetadata = (function () { - function SelfMetadata() { - } - SelfMetadata.prototype.toString = function () { return "@Self()"; }; - return SelfMetadata; - }()); - /** - * Specifies that the dependency resolution should start from the parent injector. - * - * ### Example ([live demo](http://plnkr.co/edit/Wchdzb?p=preview)) - * - * ```typescript - * class Dependency { - * } - * - * @Injectable() - * class NeedsDependency { - * dependency; - * constructor(@SkipSelf() dependency:Dependency) { - * this.dependency = dependency; - * } - * } - * - * var parent = Injector.resolveAndCreate([Dependency]); - * var child = parent.resolveAndCreateChild([NeedsDependency]); - * expect(child.get(NeedsDependency).dependency instanceof Depedency).toBe(true); - * - * var inj = Injector.resolveAndCreate([Dependency, NeedsDependency]); - * expect(() => inj.get(NeedsDependency)).toThrowError(); - * ``` - * @stable - */ - var SkipSelfMetadata = (function () { - function SkipSelfMetadata() { - } - SkipSelfMetadata.prototype.toString = function () { return "@SkipSelf()"; }; - return SkipSelfMetadata; - }()); - /** - * Specifies that an injector should retrieve a dependency from any injector until reaching the - * closest host. - * - * In Angular, a component element is automatically declared as a host for all the injectors in - * its view. - * - * ### Example ([live demo](http://plnkr.co/edit/GX79pV?p=preview)) - * - * In the following example `App` contains `ParentCmp`, which contains `ChildDirective`. - * So `ParentCmp` is the host of `ChildDirective`. - * - * `ChildDirective` depends on two services: `HostService` and `OtherService`. - * `HostService` is defined at `ParentCmp`, and `OtherService` is defined at `App`. - * - *```typescript - * class OtherService {} - * class HostService {} - * - * @Directive({ - * selector: 'child-directive' - * }) - * class ChildDirective { - * constructor(@Optional() @Host() os:OtherService, @Optional() @Host() hs:HostService){ - * console.log("os is null", os); - * console.log("hs is NOT null", hs); - * } - * } - * - * @Component({ - * selector: 'parent-cmp', - * providers: [HostService], - * template: ` - * Dir: - * `, - * directives: [ChildDirective] - * }) - * class ParentCmp { - * } - * - * @Component({ - * selector: 'app', - * providers: [OtherService], - * template: ` - * Parent: - * `, - * directives: [ParentCmp] - * }) - * class App { - * } - *``` - * @stable - */ - var HostMetadata = (function () { - function HostMetadata() { - } - HostMetadata.prototype.toString = function () { return "@Host()"; }; - return HostMetadata; - }()); - var _nextClassId = 0; function extractAnnotation(annotation) { if (isFunction(annotation) && annotation.hasOwnProperty('annotation')) { @@ -27764,22 +27379,24 @@ return constructor; } var Reflect = global$1.Reflect; - function makeDecorator(annotationCls, chainFn) { + function makeDecorator(name, props, parentClass, chainFn) { if (chainFn === void 0) { chainFn = null; } + var metaCtor = makeMetadataCtor([props]); function DecoratorFactory(objOrType) { if (!(Reflect && Reflect.getMetadata)) { throw 'reflect-metadata shim is required when using class decorators'; } - var annotationInstance = new annotationCls(objOrType); - if (this instanceof annotationCls) { - return annotationInstance; + if (this instanceof DecoratorFactory) { + metaCtor.call(this, objOrType); + return this; } else { + var annotationInstance_1 = new DecoratorFactory(objOrType); var chainAnnotation = isFunction(this) && this.annotations instanceof Array ? this.annotations : []; - chainAnnotation.push(annotationInstance); + chainAnnotation.push(annotationInstance_1); var TypeDecorator = function TypeDecorator(cls) { var annotations = Reflect.getOwnMetadata('annotations', cls) || []; - annotations.push(annotationInstance); + annotations.push(annotationInstance_1); Reflect.defineMetadata('annotations', annotations, cls); return cls; }; @@ -27790,25 +27407,51 @@ return TypeDecorator; } } - DecoratorFactory.prototype = Object.create(annotationCls.prototype); - DecoratorFactory.annotationCls = annotationCls; + if (parentClass) { + DecoratorFactory.prototype = Object.create(parentClass.prototype); + } + DecoratorFactory.prototype.toString = function () { return ("@" + name); }; + DecoratorFactory.annotationCls = DecoratorFactory; return DecoratorFactory; } - function makeParamDecorator(annotationCls) { + function makeMetadataCtor(props) { + function ctor() { + var _this = this; + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i - 0] = arguments[_i]; + } + props.forEach(function (prop, i) { + var argVal = args[i]; + if (Array.isArray(prop)) { + // plain parameter + var val = !argVal || argVal === undefined ? prop[1] : argVal; + _this[prop[0]] = val; + } + else { + for (var propName in prop) { + var val = !argVal || argVal[propName] === undefined ? prop[propName] : argVal[propName]; + _this[propName] = val; + } + } + }); + } + return ctor; + } + function makeParamDecorator(name, props, parentClass) { + var metaCtor = makeMetadataCtor(props); function ParamDecoratorFactory() { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i - 0] = arguments[_i]; } - var annotationInstance = Object.create(annotationCls.prototype); - annotationCls.apply(annotationInstance, args); - if (this instanceof annotationCls) { - return annotationInstance; - } - else { - ParamDecorator.annotation = annotationInstance; - return ParamDecorator; + if (this instanceof ParamDecoratorFactory) { + metaCtor.apply(this, args); + return this; } + var annotationInstance = new ((_a = ParamDecoratorFactory).bind.apply(_a, [void 0].concat(args)))(); + ParamDecorator.annotation = annotationInstance; + return ParamDecorator; function ParamDecorator(cls, unusedKey, index) { var parameters = Reflect.getMetadata('parameters', cls) || []; // there might be gaps if some in between parameters do not have annotations. @@ -27822,23 +27465,28 @@ Reflect.defineMetadata('parameters', parameters, cls); return cls; } + var _a; } - ParamDecoratorFactory.prototype = Object.create(annotationCls.prototype); - ParamDecoratorFactory.annotationCls = annotationCls; + if (parentClass) { + ParamDecoratorFactory.prototype = Object.create(parentClass.prototype); + } + ParamDecoratorFactory.prototype.toString = function () { return ("@" + name); }; + ParamDecoratorFactory.annotationCls = ParamDecoratorFactory; return ParamDecoratorFactory; } - function makePropDecorator(annotationCls) { + function makePropDecorator(name, props, parentClass) { + var metaCtor = makeMetadataCtor(props); function PropDecoratorFactory() { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i - 0] = arguments[_i]; } - var decoratorInstance = Object.create(annotationCls.prototype); - annotationCls.apply(decoratorInstance, args); - if (this instanceof annotationCls) { - return decoratorInstance; + if (this instanceof PropDecoratorFactory) { + metaCtor.apply(this, args); + return this; } else { + var decoratorInstance = new ((_a = PropDecoratorFactory).bind.apply(_a, [void 0].concat(args)))(); return function PropDecorator(target, name) { var meta = Reflect.getOwnMetadata('propMetadata', target.constructor) || {}; meta[name] = meta[name] || []; @@ -27846,48 +27494,58 @@ Reflect.defineMetadata('propMetadata', meta, target.constructor); }; } + var _a; } - PropDecoratorFactory.prototype = Object.create(annotationCls.prototype); - PropDecoratorFactory.annotationCls = annotationCls; + if (parentClass) { + PropDecoratorFactory.prototype = Object.create(parentClass.prototype); + } + PropDecoratorFactory.prototype.toString = function () { return ("@" + name); }; + PropDecoratorFactory.annotationCls = PropDecoratorFactory; return PropDecoratorFactory; } /** - * Factory for creating {@link InjectMetadata}. + * Inject decorator and metadata. + * * @stable * @Annotation */ - var Inject = makeParamDecorator(InjectMetadata); + var Inject = makeParamDecorator('Inject', [['token', undefined]]); /** - * Factory for creating {@link OptionalMetadata}. + * Optional decorator and metadata. + * * @stable * @Annotation */ - var Optional = makeParamDecorator(OptionalMetadata); + var Optional = makeParamDecorator('Optional', []); /** - * Factory for creating {@link InjectableMetadata}. + * Injectable decorator and metadata. + * * @stable * @Annotation */ - var Injectable = makeDecorator(InjectableMetadata); + var Injectable = makeParamDecorator('Injectable', []); /** - * Factory for creating {@link SelfMetadata}. + * Self decorator and metadata. + * * @stable * @Annotation */ - var Self = makeParamDecorator(SelfMetadata); + var Self = makeParamDecorator('Self', []); /** - * Factory for creating {@link HostMetadata}. + * SkipSelf decorator and metadata. + * * @stable * @Annotation */ - var Host = makeParamDecorator(HostMetadata); + var SkipSelf = makeParamDecorator('SkipSelf', []); /** - * Factory for creating {@link SkipSelfMetadata}. + * Host decorator and metadata. + * * @stable * @Annotation */ - var SkipSelf = makeParamDecorator(SkipSelfMetadata); + var Host = makeParamDecorator('Host', []); /** * Creates a token that can be used in a DI Provider. @@ -27927,18 +27585,6 @@ return OpaqueToken; }()); - /** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ - var __extends = (this && this.__extends) || function (d, b) { - for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; /** * This token can be used to create a virtual provider that will populate the * `entryComponents` fields of components and ng modules based on its `useValue`. @@ -27962,7 +27608,7 @@ * // user code * let routes = [ * {path: '/root', component: RootComp}, - * {path: /teams', component: TeamsComp} + * {path: '/teams', component: TeamsComp} * ]; * * @NgModule({ @@ -27975,470 +27621,127 @@ */ var ANALYZE_FOR_ENTRY_COMPONENTS = new OpaqueToken('AnalyzeForEntryComponents'); /** - * Specifies that a constant attribute value should be injected. + * Attribute decorator and metadata. * - * The directive can inject constant string literals of host element attributes. + * @stable + * @Annotation + */ + var Attribute = makeParamDecorator('Attribute', [['attributeName', undefined]]); + /** + * Base class for query metadata. * - * ### Example + * See {@link ContentChildren}, {@link ContentChild}, {@link ViewChildren}, {@link ViewChild} for + * more information. * - * Suppose we have an `` element and want to know its `type`. - * - * ```html - * - * ``` - * - * A decorator can inject string literal `text` like so: - * - * {@example core/ts/metadata/metadata.ts region='attributeMetadata'} * @stable */ - var AttributeMetadata = (function (_super) { - __extends(AttributeMetadata, _super); - function AttributeMetadata(attributeName) { - _super.call(this); - this.attributeName = attributeName; + var Query = (function () { + function Query() { } - Object.defineProperty(AttributeMetadata.prototype, "token", { - get: function () { - // Normally one would default a token to a type of an injected value but here - // the type of a variable is "string" and we can't use primitive type as a return value - // so we use instance of Attribute instead. This doesn't matter much in practice as arguments - // with @Attribute annotation are injected by ElementInjector that doesn't take tokens into - // account. - return this; - }, - enumerable: true, - configurable: true - }); - AttributeMetadata.prototype.toString = function () { return "@Attribute(" + stringify(this.attributeName) + ")"; }; - return AttributeMetadata; - }(DependencyMetadata)); + return Query; + }()); /** - * Declares an injectable parameter to be a live list of directives or variable - * bindings from the content children of a directive. + * ContentChildren decorator and metadata. * - * ### Example ([live demo](http://plnkr.co/edit/lY9m8HLy7z06vDoUaSN2?p=preview)) - * - * Assume that `` component would like to get a list its children `` - * components as shown in this example: - * - * ```html - * - * ... - * {{o.text}} - * - * ``` - * - * The preferred solution is to query for `Pane` directives using this decorator. - * - * ```javascript - * @Component({ - * selector: 'pane', - * inputs: ['title'] - * }) - * class Pane { - * title:string; - * } - * - * @Component({ - * selector: 'tabs', - * template: ` - *
    - *
  • {{pane.title}}
  • - *
- * - * ` - * }) - * class Tabs { - * @ContentChildren(Pane) panes: QueryList; - * } - * ``` - * - * A query can look for variable bindings by passing in a string with desired binding symbol. - * - * ### Example ([live demo](http://plnkr.co/edit/sT2j25cH1dURAyBRCKx1?p=preview)) - * ```html - * - *
...
- *
- * - * @Component({ selector: 'seeker' }) - * class Seeker { - * @ContentChildren('findme') elList; - * } - * ``` - * - * In this case the object that is injected depend on the type of the variable - * binding. It can be an ElementRef, a directive or a component. - * - * Passing in a comma separated list of variable bindings will query for all of them. - * - * ```html - * - *
...
- *
...
- *
- * - * @Component({ - * selector: 'seeker' - * }) - * class Seeker { - * @ContentChildren('findMe, findMeToo') elList: QueryList; - * } - * ``` - * - * Configure whether query looks for direct children or all descendants - * of the querying element, by using the `descendants` parameter. - * It is set to `false` by default. - * - * ### Example ([live demo](http://plnkr.co/edit/wtGeB977bv7qvA5FTYl9?p=preview)) - * ```html - * - * a - * b - * - * c - * - * - * ``` - * - * When querying for items, the first container will see only `a` and `b` by default, - * but with `ContentChildren(TextDirective, {descendants: true})` it will see `c` too. - * - * The queried directives are kept in a depth-first pre-order with respect to their - * positions in the DOM. - * - * ContentChildren does not look deep into any subcomponent views. - * - * ContentChildren is updated as part of the change-detection cycle. Since change detection - * happens after construction of a directive, QueryList will always be empty when observed in the - * constructor. - * - * The injected object is an unmodifiable live list. - * See {@link QueryList} for more details. - * @stable + * @stable + * @Annotation */ - var QueryMetadata = (function (_super) { - __extends(QueryMetadata, _super); - function QueryMetadata(_selector, _a) { - var _b = _a === void 0 ? {} : _a, _c = _b.descendants, descendants = _c === void 0 ? false : _c, _d = _b.first, first = _d === void 0 ? false : _d, _e = _b.read, read = _e === void 0 ? null : _e; - _super.call(this); - this._selector = _selector; - this.descendants = descendants; - this.first = first; - this.read = read; + var ContentChildren = makePropDecorator('ContentChildren', [ + ['selector', undefined], { + first: false, + isViewQuery: false, + descendants: false, + read: undefined, } - Object.defineProperty(QueryMetadata.prototype, "isViewQuery", { - /** - * always `false` to differentiate it with {@link ViewQueryMetadata}. - */ - get: function () { return false; }, - enumerable: true, - configurable: true - }); - Object.defineProperty(QueryMetadata.prototype, "selector", { - /** - * what this is querying for. - */ - get: function () { return resolveForwardRef(this._selector); }, - enumerable: true, - configurable: true - }); - Object.defineProperty(QueryMetadata.prototype, "isVarBindingQuery", { - /** - * whether this is querying for a variable binding or a directive. - */ - get: function () { return isString(this.selector); }, - enumerable: true, - configurable: true - }); - Object.defineProperty(QueryMetadata.prototype, "varBindings", { - /** - * returns a list of variable bindings this is querying for. - * Only applicable if this is a variable bindings query. - */ - get: function () { return StringWrapper.split(this.selector, /\s*,\s*/g); }, - enumerable: true, - configurable: true - }); - QueryMetadata.prototype.toString = function () { return "@Query(" + stringify(this.selector) + ")"; }; - return QueryMetadata; - }(DependencyMetadata)); - // TODO: add an example after ContentChildren and ViewChildren are in master + ], Query); /** - * Configures a content query. + * @whatItDoes Configures a content query. + * + * @howToUse + * + * {@example core/di/ts/contentChild/content_child_howto.ts region='HowTo'} + * + * @description + * + * You can use ContentChild to get the first element or the directive matching the selector from the + * content DOM. If the content DOM changes, and a new child matches the selector, + * the property will be updated. * * Content queries are set before the `ngAfterContentInit` callback is called. * - * ### Example + * **Metadata Properties**: * - * ``` - * @Directive({ - * selector: 'someDir' - * }) - * class SomeDir { - * @ContentChildren(ChildDirective) contentChildren: QueryList; + * * **selector** - the directive type or the name used for querying. + * * **read** - read a different token from the queried element. + * + * Let's look at an example: + * + * {@example core/di/ts/contentChild/content_child_example.ts region='Component'} + * + * **npm package**: `@angular/core` * - * ngAfterContentInit() { - * // contentChildren is set - * } - * } - * ``` * @stable + * @Annotation */ - var ContentChildrenMetadata = (function (_super) { - __extends(ContentChildrenMetadata, _super); - function ContentChildrenMetadata(_selector, _a) { - var _b = _a === void 0 ? {} : _a, _c = _b.descendants, descendants = _c === void 0 ? false : _c, _d = _b.read, read = _d === void 0 ? null : _d; - _super.call(this, _selector, { descendants: descendants, read: read }); + var ContentChild = makePropDecorator('ContentChild', [ + ['selector', undefined], { + first: true, + isViewQuery: false, + descendants: true, + read: undefined, } - return ContentChildrenMetadata; - }(QueryMetadata)); - // TODO: add an example after ContentChild and ViewChild are in master + ], Query); /** - * Configures a content query. + * @whatItDoes Configures a view query. * - * Content queries are set before the `ngAfterContentInit` callback is called. + * @howToUse * - * ### Example + * {@example core/di/ts/viewChildren/view_children_howto.ts region='HowTo'} * - * ``` - * @Directive({ - * selector: 'someDir' - * }) - * class SomeDir { - * @ContentChild(ChildDirective) contentChild; + * @description + * + * You can use ViewChildren to get the {@link QueryList} of elements or directives from the + * view DOM. Any time a child element is added, removed, or moved, the query list will be updated, + * and the changes observable of the query list will emit a new value. + * + * View queries are set before the `ngAfterViewInit` callback is called. + * + * **Metadata Properties**: + * + * * **selector** - the directive type or the name used for querying. + * * **read** - read a different token from the queried elements. + * + * Let's look at an example: + * + * {@example core/di/ts/viewChildren/view_children_example.ts region='Component'} + * + * **npm package**: `@angular/core` * - * ngAfterContentInit() { - * // contentChild is set - * } - * } - * ``` * @stable + * @Annotation */ - var ContentChildMetadata = (function (_super) { - __extends(ContentChildMetadata, _super); - function ContentChildMetadata(_selector, _a) { - var _b = (_a === void 0 ? {} : _a).read, read = _b === void 0 ? null : _b; - _super.call(this, _selector, { descendants: true, first: true, read: read }); + var ViewChildren = makePropDecorator('ViewChildren', [ + ['selector', undefined], { + first: false, + isViewQuery: true, + descendants: true, + read: undefined, } - return ContentChildMetadata; - }(QueryMetadata)); + ], Query); /** - * Similar to {@link ContentChildMetadata}, but querying the component view, instead - * of the content children. + * ViewChild decorator and metadata. * - * ### Example ([live demo](http://plnkr.co/edit/eNsFHDf7YjyM6IzKxM1j?p=preview)) - * - * ```javascript - * @Component({ - * ..., - * template: ` - * a - * b - * c - * ` - * }) - * class MyComponent { - * shown: boolean; - * - * constructor(private @ViewChildren(Item) items:QueryList) { - * items.changes.subscribe(() => console.log(items.length)); - * } - * } - * ``` - * - * As `shown` is flipped between true and false, items will contain zero of one - * items. - * - * Specifies that a {@link QueryList} should be injected. - * - * The injected object is an iterable and observable live list. - * See {@link QueryList} for more details. * @stable + * @Annotation */ - var ViewQueryMetadata = (function (_super) { - __extends(ViewQueryMetadata, _super); - function ViewQueryMetadata(_selector, _a) { - var _b = _a === void 0 ? {} : _a, _c = _b.descendants, descendants = _c === void 0 ? false : _c, _d = _b.first, first = _d === void 0 ? false : _d, _e = _b.read, read = _e === void 0 ? null : _e; - _super.call(this, _selector, { descendants: descendants, first: first, read: read }); + var ViewChild = makePropDecorator('ViewChild', [ + ['selector', undefined], { + first: true, + isViewQuery: true, + descendants: true, + read: undefined, } - Object.defineProperty(ViewQueryMetadata.prototype, "isViewQuery", { - /** - * always `true` to differentiate it with {@link QueryMetadata}. - */ - get: function () { return true; }, - enumerable: true, - configurable: true - }); - return ViewQueryMetadata; - }(QueryMetadata)); - /** - * Declares a list of child element references. - * - * Angular automatically updates the list when the DOM is updated. - * - * `ViewChildren` takes an argument to select elements. - * - * - If the argument is a type, directives or components with the type will be bound. - * - * - If the argument is a string, the string is interpreted as a list of comma-separated selectors. - * For each selector, an element containing the matching template variable (e.g. `#child`) will be - * bound. - * - * View children are set before the `ngAfterViewInit` callback is called. - * - * ### Example - * - * With type selector: - * - * ``` - * @Component({ - * selector: 'child-cmp', - * template: '

child

' - * }) - * class ChildCmp { - * doSomething() {} - * } - * - * @Component({ - * selector: 'some-cmp', - * template: ` - * - * - * - * `, - * directives: [ChildCmp] - * }) - * class SomeCmp { - * @ViewChildren(ChildCmp) children:QueryList; - * - * ngAfterViewInit() { - * // children are set - * this.children.toArray().forEach((child)=>child.doSomething()); - * } - * } - * ``` - * - * With string selector: - * - * ``` - * @Component({ - * selector: 'child-cmp', - * template: '

child

' - * }) - * class ChildCmp { - * doSomething() {} - * } - * - * @Component({ - * selector: 'some-cmp', - * template: ` - * - * - * - * `, - * directives: [ChildCmp] - * }) - * class SomeCmp { - * @ViewChildren('child1,child2,child3') children:QueryList; - * - * ngAfterViewInit() { - * // children are set - * this.children.toArray().forEach((child)=>child.doSomething()); - * } - * } - * ``` - * @stable - */ - var ViewChildrenMetadata = (function (_super) { - __extends(ViewChildrenMetadata, _super); - function ViewChildrenMetadata(_selector, _a) { - var _b = (_a === void 0 ? {} : _a).read, read = _b === void 0 ? null : _b; - _super.call(this, _selector, { descendants: true, read: read }); - } - ViewChildrenMetadata.prototype.toString = function () { return "@ViewChildren(" + stringify(this.selector) + ")"; }; - return ViewChildrenMetadata; - }(ViewQueryMetadata)); - /** - * - * Declares a reference of child element. - * - * `ViewChildren` takes an argument to select elements. - * - * - If the argument is a type, a directive or a component with the type will be bound. - * - If the argument is a string, the string is interpreted as a selector. An element containing the - matching template variable (e.g. `#child`) will be bound. - * - * In either case, `@ViewChild()` assigns the first (looking from above) element if there are - multiple matches. - * - * View child is set before the `ngAfterViewInit` callback is called. - * - * ### Example - * - * With type selector: - * - * ``` - * @Component({ - * selector: 'child-cmp', - * template: '

child

' - * }) - * class ChildCmp { - * doSomething() {} - * } - * - * @Component({ - * selector: 'some-cmp', - * template: '', - * directives: [ChildCmp] - * }) - * class SomeCmp { - * @ViewChild(ChildCmp) child:ChildCmp; - * - * ngAfterViewInit() { - * // child is set - * this.child.doSomething(); - * } - * } - * ``` - * - * With string selector: - * - * ``` - * @Component({ - * selector: 'child-cmp', - * template: '

child

' - * }) - * class ChildCmp { - * doSomething() {} - * } - * - * @Component({ - * selector: 'some-cmp', - * template: '', - * directives: [ChildCmp] - * }) - * class SomeCmp { - * @ViewChild('child') child:ChildCmp; - * - * ngAfterViewInit() { - * // child is set - * this.child.doSomething(); - * } - * } - * ``` - * @stable - */ - var ViewChildMetadata = (function (_super) { - __extends(ViewChildMetadata, _super); - function ViewChildMetadata(_selector, _a) { - var _b = (_a === void 0 ? {} : _a).read, read = _b === void 0 ? null : _b; - _super.call(this, _selector, { descendants: true, first: true, read: read }); - } - return ViewChildMetadata; - }(ViewQueryMetadata)); + ], Query); /** * Describes within the change detector which strategy will be used the next time change @@ -28492,18 +27795,414 @@ */ ChangeDetectorStatus[ChangeDetectorStatus["Destroyed"] = 5] = "Destroyed"; })(ChangeDetectorStatus || (ChangeDetectorStatus = {})); - /** - * List of possible {@link ChangeDetectionStrategy} values. - */ - var CHANGE_DETECTION_STRATEGY_VALUES = [ - exports.ChangeDetectionStrategy.OnPush, - exports.ChangeDetectionStrategy.Default, - ]; function isDefaultChangeDetectionStrategy(changeDetectionStrategy) { return isBlank(changeDetectionStrategy) || changeDetectionStrategy === exports.ChangeDetectionStrategy.Default; } + /** + * Directive decorator and metadata. + * + * @stable + * @Annotation + */ + var Directive = makeDecorator('Directive', { + selector: undefined, + inputs: undefined, + outputs: undefined, + host: undefined, + providers: undefined, + exportAs: undefined, + queries: undefined + }); + /** + * Component decorator and metadata. + * + * @stable + * @Annotation + */ + var Component = makeDecorator('Component', { + selector: undefined, + inputs: undefined, + outputs: undefined, + host: undefined, + exportAs: undefined, + moduleId: undefined, + providers: undefined, + viewProviders: undefined, + changeDetection: exports.ChangeDetectionStrategy.Default, + queries: undefined, + templateUrl: undefined, + template: undefined, + styleUrls: undefined, + styles: undefined, + animations: undefined, + encapsulation: undefined, + interpolation: undefined, + entryComponents: undefined + }, Directive); + /** + * Pipe decorator and metadata. + * + * @stable + * @Annotation + */ + var Pipe = makeDecorator('Pipe', { + name: undefined, + pure: true, + }); + /** + * Input decorator and metadata. + * + * @stable + * @Annotation + */ + var Input = makePropDecorator('Input', [['bindingPropertyName', undefined]]); + /** + * Output decorator and metadata. + * + * @stable + * @Annotation + */ + var Output = makePropDecorator('Output', [['bindingPropertyName', undefined]]); + /** + * HostBinding decorator and metadata. + * + * @stable + * @Annotation + */ + var HostBinding = makePropDecorator('HostBinding', [['hostPropertyName', undefined]]); + /** + * HostBinding decorator and metadata. + * + * @stable + * @Annotation + */ + var HostListener = makePropDecorator('HostListener', [['eventName', undefined], ['args', []]]); + + /** + * @license + * Copyright Google Inc. All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.io/license + */ + /** + * @stable + */ + var LifecycleHooks; + (function (LifecycleHooks) { + LifecycleHooks[LifecycleHooks["OnInit"] = 0] = "OnInit"; + LifecycleHooks[LifecycleHooks["OnDestroy"] = 1] = "OnDestroy"; + LifecycleHooks[LifecycleHooks["DoCheck"] = 2] = "DoCheck"; + LifecycleHooks[LifecycleHooks["OnChanges"] = 3] = "OnChanges"; + LifecycleHooks[LifecycleHooks["AfterContentInit"] = 4] = "AfterContentInit"; + LifecycleHooks[LifecycleHooks["AfterContentChecked"] = 5] = "AfterContentChecked"; + LifecycleHooks[LifecycleHooks["AfterViewInit"] = 6] = "AfterViewInit"; + LifecycleHooks[LifecycleHooks["AfterViewChecked"] = 7] = "AfterViewChecked"; + })(LifecycleHooks || (LifecycleHooks = {})); + var LIFECYCLE_HOOKS_VALUES = [ + LifecycleHooks.OnInit, LifecycleHooks.OnDestroy, LifecycleHooks.DoCheck, LifecycleHooks.OnChanges, + LifecycleHooks.AfterContentInit, LifecycleHooks.AfterContentChecked, LifecycleHooks.AfterViewInit, + LifecycleHooks.AfterViewChecked + ]; + /** + * @whatItDoes Lifecycle hook that is called when any data-bound property of a directive changes. + * @howToUse + * {@example core/ts/metadata/lifecycle_hooks_spec.ts region='OnChanges'} + * + * @description + * `ngOnChanges` is called right after the data-bound properties have been checked and before view + * and content children are checked if at least one of them has changed. + * The `changes` parameter contains the changed properties. + * + * See {@linkDocs guide/lifecycle-hooks#onchanges "Lifecycle Hooks Guide"}. + * + * @stable + */ + var OnChanges = (function () { + function OnChanges() { + } + return OnChanges; + }()); + /** + * @whatItDoes Lifecycle hook that is called after data-bound properties of a directive are + * initialized. + * @howToUse + * {@example core/ts/metadata/lifecycle_hooks_spec.ts region='OnInit'} + * + * @description + * `ngOnInit` is called right after the directive's data-bound properties have been checked for the + * first time, and before any of its children have been checked. It is invoked only once when the + * directive is instantiated. + * + * See {@linkDocs guide/lifecycle-hooks "Lifecycle Hooks Guide"}. + * + * @stable + */ + var OnInit = (function () { + function OnInit() { + } + return OnInit; + }()); + /** + * @whatItDoes Lifecycle hook that is called when Angular dirty checks a directive. + * @howToUse + * {@example core/ts/metadata/lifecycle_hooks_spec.ts region='DoCheck'} + * + * @description + * `ngDoCheck` gets called to check the changes in the directives in addition to the default + * algorithm. The default change detection algorithm looks for differences by comparing + * bound-property values by reference across change detection runs. + * + * Note that a directive typically should not use both `DoCheck` and {@link OnChanges} to respond to + * changes on the same input, as `ngOnChanges` will continue to be called when the default change + * detector detects changes. + * + * See {@link KeyValueDiffers} and {@link IterableDiffers} for implementing custom dirty checking + * for collections. + * + * See {@linkDocs guide/lifecycle-hooks#docheck "Lifecycle Hooks Guide"}. + * + * @stable + */ + var DoCheck = (function () { + function DoCheck() { + } + return DoCheck; + }()); + /** + * @whatItDoes Lifecycle hook that is called when a directive or pipe is destroyed. + * @howToUse + * {@example core/ts/metadata/lifecycle_hooks_spec.ts region='OnDestroy'} + * + * @description + * `ngOnDestroy` callback is typically used for any custom cleanup that needs to occur when the + * instance is destroyed. + * + * See {@linkDocs guide/lifecycle-hooks "Lifecycle Hooks Guide"}. + * + * @stable + */ + var OnDestroy = (function () { + function OnDestroy() { + } + return OnDestroy; + }()); + /** + * + * @whatItDoes Lifecycle hook that is called after a directive's content has been fully + * initialized. + * @howToUse + * {@example core/ts/metadata/lifecycle_hooks_spec.ts region='AfterContentInit'} + * + * @description + * See {@linkDocs guide/lifecycle-hooks#aftercontent "Lifecycle Hooks Guide"}. + * + * @stable + */ + var AfterContentInit = (function () { + function AfterContentInit() { + } + return AfterContentInit; + }()); + /** + * @whatItDoes Lifecycle hook that is called after every check of a directive's content. + * @howToUse + * {@example core/ts/metadata/lifecycle_hooks_spec.ts region='AfterContentChecked'} + * + * @description + * See {@linkDocs guide/lifecycle-hooks#aftercontent "Lifecycle Hooks Guide"}. + * + * @stable + */ + var AfterContentChecked = (function () { + function AfterContentChecked() { + } + return AfterContentChecked; + }()); + /** + * @whatItDoes Lifecycle hook that is called after a component's view has been fully + * initialized. + * @howToUse + * {@example core/ts/metadata/lifecycle_hooks_spec.ts region='AfterViewInit'} + * + * @description + * See {@linkDocs guide/lifecycle-hooks#afterview "Lifecycle Hooks Guide"}. + * + * @stable + */ + var AfterViewInit = (function () { + function AfterViewInit() { + } + return AfterViewInit; + }()); + /** + * @whatItDoes Lifecycle hook that is called after every check of a component's view. + * @howToUse + * {@example core/ts/metadata/lifecycle_hooks_spec.ts region='AfterViewChecked'} + * + * @description + * See {@linkDocs guide/lifecycle-hooks#afterview "Lifecycle Hooks Guide"}. + * + * @stable + */ + var AfterViewChecked = (function () { + function AfterViewChecked() { + } + return AfterViewChecked; + }()); + + /** + * Defines a schema that will allow: + * - any non-Angular elements with a `-` in their name, + * - any properties on elements with a `-` in their name which is the common rule for custom + * elements. + * + * @stable + */ + var CUSTOM_ELEMENTS_SCHEMA = { + name: 'custom-elements' + }; + /** + * Defines a schema that will allow any property on any element. + * + * @experimental + */ + var NO_ERRORS_SCHEMA = { + name: 'no-errors-schema' + }; + /** + * NgModule decorator and metadata. + * + * @stable + * @Annotation + */ + var NgModule = makeDecorator('NgModule', { + providers: undefined, + declarations: undefined, + imports: undefined, + exports: undefined, + entryComponents: undefined, + bootstrap: undefined, + schemas: undefined, + id: undefined, + }); + + /** + * @license + * Copyright Google Inc. All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.io/license + */ + /** + * Defines template and style encapsulation options available for Component's {@link Component}. + * + * See {@link ViewMetadata#encapsulation}. + * @stable + */ + exports.ViewEncapsulation; + (function (ViewEncapsulation) { + /** + * Emulate `Native` scoping of styles by adding an attribute containing surrogate id to the Host + * Element and pre-processing the style rules provided via + * {@link ViewMetadata#styles} or {@link ViewMetadata#stylesUrls}, and adding the new Host Element + * attribute to all selectors. + * + * This is the default option. + */ + ViewEncapsulation[ViewEncapsulation["Emulated"] = 0] = "Emulated"; + /** + * Use the native encapsulation mechanism of the renderer. + * + * For the DOM this means using [Shadow DOM](https://w3c.github.io/webcomponents/spec/shadow/) and + * creating a ShadowRoot for Component's Host Element. + */ + ViewEncapsulation[ViewEncapsulation["Native"] = 1] = "Native"; + /** + * Don't provide any template or style encapsulation. + */ + ViewEncapsulation[ViewEncapsulation["None"] = 2] = "None"; + })(exports.ViewEncapsulation || (exports.ViewEncapsulation = {})); + /** + * Metadata properties available for configuring Views. + * + * For details on the `@Component` annotation, see {@link Component}. + * + * ### Example + * + * ``` + * @Component({ + * selector: 'greet', + * template: 'Hello {{name}}!', + * }) + * class Greet { + * name: string; + * + * constructor() { + * this.name = 'World'; + * } + * } + * ``` + * + * @deprecated Use Component instead. + * + * {@link Component} + */ + var ViewMetadata = (function () { + function ViewMetadata(_a) { + var _b = _a === void 0 ? {} : _a, templateUrl = _b.templateUrl, template = _b.template, encapsulation = _b.encapsulation, styles = _b.styles, styleUrls = _b.styleUrls, animations = _b.animations, interpolation = _b.interpolation; + this.templateUrl = templateUrl; + this.template = template; + this.styleUrls = styleUrls; + this.styles = styles; + this.encapsulation = encapsulation; + this.animations = animations; + this.interpolation = interpolation; + } + return ViewMetadata; + }()); + + /** + * Allows to refer to references which are not yet defined. + * + * For instance, `forwardRef` is used when the `token` which we need to refer to for the purposes of + * DI is declared, + * but not yet defined. It is also used when the `token` which we use when creating a query is not + * yet defined. + * + * ### Example + * {@example core/di/ts/forward_ref/forward_ref_spec.ts region='forward_ref'} + * @experimental + */ + function forwardRef(forwardRefFn) { + forwardRefFn.__forward_ref__ = forwardRef; + forwardRefFn.toString = function () { return stringify(this()); }; + return forwardRefFn; + } + /** + * Lazily retrieves the reference value from a forwardRef. + * + * Acts as the identity function when given a non-forward-ref value. + * + * ### Example ([live demo](http://plnkr.co/edit/GU72mJrk1fiodChcmiDR?p=preview)) + * + * {@example core/di/ts/forward_ref/forward_ref_spec.ts region='resolve_forward_ref'} + * + * See: {@link forwardRef} + * @experimental + */ + function resolveForwardRef(type) { + if (isFunction(type) && type.hasOwnProperty('__forward_ref__') && + type.__forward_ref__ === forwardRef) { + return type(); + } + else { + return type; + } + } + /** * @license * Copyright Google Inc. All Rights Reserved. @@ -28511,7 +28210,7 @@ * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ - var __extends$2 = (this && this.__extends) || function (d, b) { + var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); @@ -28523,7 +28222,7 @@ * @stable */ var BaseError = (function (_super) { - __extends$2(BaseError, _super); + __extends(BaseError, _super); function BaseError(message) { // Errors don't use current this, instead they create a new instance. // We have to do forward all of our api to the nativeInstance. @@ -28554,7 +28253,7 @@ * @stable */ var WrappedError = (function (_super) { - __extends$2(WrappedError, _super); + __extends(WrappedError, _super); function WrappedError(message, error) { _super.call(this, message + " caused by: " + (error instanceof Error ? error.message : error)); this.originalError = error; @@ -28585,6 +28284,23 @@ return _NullInjector; }()); /** + * @whatItDoes Injector interface + * @howToUse + * ``` + * const injector: Injector = ...; + * injector.get(...); + * ``` + * + * @description + * For more details, see the {@linkDocs guide/dependency-injection "Dependency Injection Guide"}. + * + * ### Example + * + * {@example core/di/ts/injector_spec.ts region='Injector'} + * + * `Injector` returns itself when given `Injector` as a token: + * {@example core/di/ts/injector_spec.ts region='injectInjector'} + * * @stable */ var Injector = (function () { @@ -28596,23 +28312,6 @@ * - Throws {@link NoProviderError} if no `notFoundValue` that is not equal to * Injector.THROW_IF_NOT_FOUND is given * - Returns the `notFoundValue` otherwise - * - * ### Example ([live demo](http://plnkr.co/edit/HeXSHg?p=preview)) - * - * ```typescript - * var injector = ReflectiveInjector.resolveAndCreate([ - * {provide: "validToken", useValue: "Value"} - * ]); - * expect(injector.get("validToken")).toEqual("Value"); - * expect(() => injector.get("invalidToken")).toThrowError(); - * ``` - * - * `Injector` returns itself when given `Injector` as a token. - * - * ```typescript - * var injector = ReflectiveInjector.resolveAndCreate([]); - * expect(injector.get(Injector)).toBe(injector); - * ``` */ Injector.prototype.get = function (token, notFoundValue) { return unimplemented(); }; Injector.THROW_IF_NOT_FOUND = _THROW_IF_NOT_FOUND; @@ -28620,20 +28319,18 @@ return Injector; }()); - var Map$1 = global$1.Map; - var Set = global$1.Set; // Safari and Internet Explorer do not support the iterable parameter to the // Map constructor. We work around that by manually adding the items. var createMapFromPairs = (function () { try { - if (new Map$1([[1, 2]]).size === 1) { - return function createMapFromPairs(pairs) { return new Map$1(pairs); }; + if (new Map([[1, 2]]).size === 1) { + return function createMapFromPairs(pairs) { return new Map(pairs); }; } } catch (e) { } return function createMapAndPopulateFromPairs(pairs) { - var map = new Map$1(); + var map = new Map(); for (var i = 0; i < pairs.length; i++) { var pair = pairs[i]; map.set(pair[0], pair[1]); @@ -28641,22 +28338,8 @@ return map; }; })(); - var createMapFromMap = (function () { - try { - if (new Map$1(new Map$1())) { - return function createMapFromMap(m) { return new Map$1(m); }; - } - } - catch (e) { - } - return function createMapAndPopulateFromMap(m) { - var map = new Map$1(); - m.forEach(function (v, k) { map.set(k, v); }); - return map; - }; - })(); var _clearValues = (function () { - if ((new Map$1()).keys().next) { + if ((new Map()).keys().next) { return function _clearValues(m) { var keyIterator = m.keys(); var k; @@ -28675,7 +28358,7 @@ // TODO(mlaval): remove the work around once we have a working polyfill of Array.from var _arrayFromMap = (function () { try { - if ((new Map$1()).values().next) { + if ((new Map()).values().next) { return function createArrayFromMap(m, getValues) { return getValues ? Array.from(m.values()) : Array.from(m.keys()); }; @@ -28684,7 +28367,7 @@ catch (e) { } return function createArrayFromMapWithForeach(m, getValues) { - var res = ListWrapper.createFixedSize(m.size), i = 0; + var res = new Array(m.size), i = 0; m.forEach(function (v, k) { res[i] = getValues ? v : k; i++; @@ -28695,9 +28378,8 @@ var MapWrapper = (function () { function MapWrapper() { } - MapWrapper.clone = function (m) { return createMapFromMap(m); }; MapWrapper.createFromStringMap = function (stringMap) { - var result = new Map$1(); + var result = new Map(); for (var prop in stringMap) { result.set(prop, stringMap[prop]); } @@ -28709,7 +28391,6 @@ return r; }; MapWrapper.createFromPairs = function (pairs) { return createMapFromPairs(pairs); }; - MapWrapper.clearValues = function (m) { _clearValues(m); }; MapWrapper.iterable = function (m) { return m; }; MapWrapper.keys = function (m) { return _arrayFromMap(m, false); }; MapWrapper.values = function (m) { return _arrayFromMap(m, true); }; @@ -28721,36 +28402,6 @@ var StringMapWrapper = (function () { function StringMapWrapper() { } - StringMapWrapper.create = function () { - // Note: We are not using Object.create(null) here due to - // performance! - // http://jsperf.com/ng2-object-create-null - return {}; - }; - StringMapWrapper.contains = function (map, key) { - return map.hasOwnProperty(key); - }; - StringMapWrapper.get = function (map, key) { - return map.hasOwnProperty(key) ? map[key] : undefined; - }; - StringMapWrapper.set = function (map, key, value) { map[key] = value; }; - StringMapWrapper.keys = function (map) { return Object.keys(map); }; - StringMapWrapper.values = function (map) { - return Object.keys(map).map(function (k) { return map[k]; }); - }; - StringMapWrapper.isEmpty = function (map) { - for (var prop in map) { - return false; - } - return true; - }; - StringMapWrapper.delete = function (map, key) { delete map[key]; }; - StringMapWrapper.forEach = function (map, callback) { - for (var _i = 0, _a = Object.keys(map); _i < _a.length; _i++) { - var k = _a[_i]; - callback(map[k], k); - } - }; StringMapWrapper.merge = function (m1, m2) { var m = {}; for (var _i = 0, _a = Object.keys(m1); _i < _a.length; _i++) { @@ -28769,9 +28420,8 @@ if (k1.length != k2.length) { return false; } - var key; for (var i = 0; i < k1.length; i++) { - key = k1[i]; + var key = k1[i]; if (m1[key] !== m2[key]) { return false; } @@ -28914,7 +28564,7 @@ if (!isJsObject(obj)) return false; return isArray(obj) || - (!(obj instanceof Map$1) && + (!(obj instanceof Map) && getSymbolIterator() in obj); // JS Iterable have a Symbol.iterator prop } function areIterablesEqual(a, b, comparator) { @@ -28945,33 +28595,6 @@ } } } - // Safari and Internet Explorer do not support the iterable parameter to the - // Set constructor. We work around that by manually adding the items. - var createSetFromList = (function () { - var test = new Set([1, 2, 3]); - if (test.size === 3) { - return function createSetFromList(lst) { return new Set(lst); }; - } - else { - return function createSetAndPopulateFromList(lst) { - var res = new Set(lst); - if (res.size !== lst.length) { - for (var i = 0; i < lst.length; i++) { - res.add(lst[i]); - } - } - return res; - }; - } - })(); - var SetWrapper = (function () { - function SetWrapper() { - } - SetWrapper.createFromList = function (lst) { return createSetFromList(lst); }; - SetWrapper.has = function (s, key) { return s.has(key); }; - SetWrapper.delete = function (m, k) { m.delete(k); }; - return SetWrapper; - }()); /** * @license @@ -28980,7 +28603,7 @@ * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ - var __extends$3 = (this && this.__extends) || function (d, b) { + var __extends$1 = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); @@ -29009,7 +28632,7 @@ * @stable */ var AbstractProviderError = (function (_super) { - __extends$3(AbstractProviderError, _super); + __extends$1(AbstractProviderError, _super); function AbstractProviderError(injector, key, constructResolvingMessage) { _super.call(this, 'DI Error'); this.keys = [key]; @@ -29040,7 +28663,7 @@ * @stable */ var NoProviderError = (function (_super) { - __extends$3(NoProviderError, _super); + __extends$1(NoProviderError, _super); function NoProviderError(injector, key) { _super.call(this, injector, key, function (keys) { var first = stringify(ListWrapper.first(keys).token); @@ -29067,7 +28690,7 @@ * @stable */ var CyclicDependencyError = (function (_super) { - __extends$3(CyclicDependencyError, _super); + __extends$1(CyclicDependencyError, _super); function CyclicDependencyError(injector, key) { _super.call(this, injector, key, function (keys) { return "Cannot instantiate cyclic dependency!" + constructResolvingPath(keys); @@ -29103,7 +28726,7 @@ * @stable */ var InstantiationError = (function (_super) { - __extends$3(InstantiationError, _super); + __extends$1(InstantiationError, _super); function InstantiationError(injector, originalException, originalStack, key) { _super.call(this, 'DI Error', originalException); this.keys = [key]; @@ -29140,7 +28763,7 @@ * @stable */ var InvalidProviderError = (function (_super) { - __extends$3(InvalidProviderError, _super); + __extends$1(InvalidProviderError, _super); function InvalidProviderError(provider) { _super.call(this, "Invalid provider - only instances of Provider and Type are allowed, got: " + provider); } @@ -29176,7 +28799,7 @@ * @stable */ var NoAnnotationError = (function (_super) { - __extends$3(NoAnnotationError, _super); + __extends$1(NoAnnotationError, _super); function NoAnnotationError(typeOrFunc, params) { _super.call(this, NoAnnotationError._genMessage(typeOrFunc, params)); } @@ -29184,7 +28807,7 @@ var signature = []; for (var i = 0, ii = params.length; i < ii; i++) { var parameter = params[i]; - if (isBlank(parameter) || parameter.length == 0) { + if (!parameter || parameter.length == 0) { signature.push('?'); } else { @@ -29213,7 +28836,7 @@ * @stable */ var OutOfBoundsError = (function (_super) { - __extends$3(OutOfBoundsError, _super); + __extends$1(OutOfBoundsError, _super); function OutOfBoundsError(index) { _super.call(this, "Index " + index + " is out-of-bounds."); } @@ -29233,7 +28856,7 @@ * ``` */ var MixingMultiProvidersWithRegularProvidersError = (function (_super) { - __extends$3(MixingMultiProvidersWithRegularProvidersError, _super); + __extends$1(MixingMultiProvidersWithRegularProvidersError, _super); function MixingMultiProvidersWithRegularProvidersError(provider1, provider2) { _super.call(this, 'Cannot mix multi providers and regular providers, got: ' + provider1.toString() + ' ' + provider2.toString()); @@ -29264,7 +28887,7 @@ function ReflectiveKey(token, id) { this.token = token; this.id = id; - if (isBlank(token)) { + if (!token) { throw new Error('Token must be defined!'); } } @@ -29326,7 +28949,9 @@ * found in the LICENSE file at https://angular.io/license */ /** - * Runtime representation a type that a Component or other object is instances of. + * @whatItDoes Represents a type that a Component or other object is instances of. + * + * @description * * An example of a `Type` is `MyCustomComponent` class, which in JavaScript is be represented by * the `MyCustomComponent` constructor function. @@ -29493,9 +29118,7 @@ var decoratorType = decoratorInvocation.type; var annotationCls = decoratorType.annotationCls; var annotationArgs = decoratorInvocation.args ? decoratorInvocation.args : []; - var annotation = Object.create(annotationCls.prototype); - annotationCls.apply(annotation, annotationArgs); - return annotation; + return new (annotationCls.bind.apply(annotationCls, [void 0].concat(annotationArgs)))(); }); } @@ -29523,7 +29146,7 @@ * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ - var __extends$4 = (this && this.__extends) || function (d, b) { + var __extends$2 = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); @@ -29533,19 +29156,20 @@ * to power dependency injection and compilation. */ var Reflector = (function (_super) { - __extends$4(Reflector, _super); + __extends$2(Reflector, _super); function Reflector(reflectionCapabilities) { _super.call(this); - /** @internal */ - this._injectableInfo = new Map$1(); - /** @internal */ - this._getters = new Map$1(); - /** @internal */ - this._setters = new Map$1(); - /** @internal */ - this._methods = new Map$1(); - this._usedKeys = null; this.reflectionCapabilities = reflectionCapabilities; + /** @internal */ + this._injectableInfo = new Map(); + /** @internal */ + this._getters = new Map(); + /** @internal */ + this._setters = new Map(); + /** @internal */ + this._methods = new Map(); + /** @internal */ + this._usedKeys = null; } Reflector.prototype.updateCapabilities = function (caps) { this.reflectionCapabilities = caps; }; Reflector.prototype.isReflectionEnabled = function () { return this.reflectionCapabilities.isReflectionEnabled(); }; @@ -29565,7 +29189,7 @@ throw new Error('Usage tracking is disabled'); } var allTypes = MapWrapper.keys(this._injectableInfo); - return allTypes.filter(function (key) { return !SetWrapper.has(_this._usedKeys, key); }); + return allTypes.filter(function (key) { return !_this._usedKeys.has(key); }); }; Reflector.prototype.registerFunction = function (func, funcInfo) { this._injectableInfo.set(func, funcInfo); @@ -29673,7 +29297,7 @@ return Reflector; }(ReflectorReader)); function _mergeMaps(target, config) { - StringMapWrapper.forEach(config, function (v, k) { return target.set(k, v); }); + Object.keys(config).forEach(function (k) { target.set(k, config[k]); }); } /** @@ -29828,7 +29452,7 @@ return res; } function constructDependencies(typeOrFunc, dependencies) { - if (isBlank(dependencies)) { + if (!dependencies) { return _dependenciesFor(typeOrFunc); } else { @@ -29838,7 +29462,7 @@ } function _dependenciesFor(typeOrFunc) { var params = reflector.parameters(typeOrFunc); - if (isBlank(params)) + if (!params) return []; if (params.some(isBlank)) { throw new NoAnnotationError(typeOrFunc, params); @@ -29850,7 +29474,7 @@ var token = null; var optional = false; if (!isArray(metadata)) { - if (metadata instanceof InjectMetadata) { + if (metadata instanceof Inject) { return _createDependency(metadata.token, optional, null, null, depProps); } else { @@ -29864,27 +29488,21 @@ if (paramMetadata instanceof Type) { token = paramMetadata; } - else if (paramMetadata instanceof InjectMetadata) { + else if (paramMetadata instanceof Inject) { token = paramMetadata.token; } - else if (paramMetadata instanceof OptionalMetadata) { + else if (paramMetadata instanceof Optional) { optional = true; } - else if (paramMetadata instanceof SelfMetadata) { + else if (paramMetadata instanceof Self) { upperBoundVisibility = paramMetadata; } - else if (paramMetadata instanceof HostMetadata) { + else if (paramMetadata instanceof Host) { upperBoundVisibility = paramMetadata; } - else if (paramMetadata instanceof SkipSelfMetadata) { + else if (paramMetadata instanceof SkipSelf) { lowerBoundVisibility = paramMetadata; } - else if (paramMetadata instanceof DependencyMetadata) { - if (isPresent(paramMetadata.token)) { - token = paramMetadata.token; - } - depProps.push(paramMetadata); - } } token = resolveForwardRef(token); if (isPresent(token)) { @@ -29998,7 +29616,7 @@ function ReflectiveProtoInjectorDynamicStrategy(protoInj, providers) { this.providers = providers; var len = providers.length; - this.keyIds = ListWrapper.createFixedSize(len); + this.keyIds = new Array(len); for (var i = 0; i < len; i++) { this.keyIds[i] = providers[i].key.id; } @@ -30143,7 +29761,7 @@ function ReflectiveInjectorDynamicStrategy(protoStrategy, injector) { this.protoStrategy = protoStrategy; this.injector = injector; - this.objs = ListWrapper.createFixedSize(protoStrategy.providers.length); + this.objs = new Array(protoStrategy.providers.length); ListWrapper.fill(this.objs, UNDEFINED); } ReflectiveInjectorDynamicStrategy.prototype.resetConstructionCounter = function () { this.injector._constructionCounter = 0; }; @@ -30487,7 +30105,7 @@ }; ReflectiveInjector_.prototype._instantiateProvider = function (provider) { if (provider.multiProvider) { - var res = ListWrapper.createFixedSize(provider.resolvedFactories.length); + var res = new Array(provider.resolvedFactories.length); for (var i = 0; i < provider.resolvedFactories.length; ++i) { res[i] = this._instantiate(provider, provider.resolvedFactories[i]); } @@ -30631,7 +30249,7 @@ if (key === INJECTOR_KEY) { return this; } - if (upperBoundVisibility instanceof SelfMetadata) { + if (upperBoundVisibility instanceof Self) { return this._getByKeySelf(key, notFoundValue); } else { @@ -30655,7 +30273,7 @@ /** @internal */ ReflectiveInjector_.prototype._getByKeyDefault = function (key, notFoundValue, lowerBoundVisibility) { var inj; - if (lowerBoundVisibility instanceof SkipSelfMetadata) { + if (lowerBoundVisibility instanceof SkipSelf) { inj = this._parent; } else { @@ -30703,2345 +30321,20 @@ * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ - var __extends$1 = (this && this.__extends) || function (d, b) { - for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; /** - * Directives allow you to attach behavior to elements in the DOM. + * @whatItDoes Provides a hook for centralized exception handling. * - * {@link DirectiveMetadata}s with an embedded view are called {@link ComponentMetadata}s. + * @description * - * A directive consists of a single directive annotation and a controller class. When the - * directive's `selector` matches - * elements in the DOM, the following steps occur: - * - * 1. For each directive, the `ElementInjector` attempts to resolve the directive's constructor - * arguments. - * 2. Angular instantiates directives for each matched element using `ElementInjector` in a - * depth-first order, - * as declared in the HTML. - * - * ## Understanding How Injection Works - * - * There are three stages of injection resolution. - * - *Pre-existing Injectors*: - * - The terminal {@link Injector} cannot resolve dependencies. It either throws an error or, if - * the dependency was - * specified as `@Optional`, returns `null`. - * - The platform injector resolves browser singleton resources, such as: cookies, title, - * location, and others. - * - *Component Injectors*: Each component instance has its own {@link Injector}, and they follow - * the same parent-child hierarchy - * as the component instances in the DOM. - * - *Element Injectors*: Each component instance has a Shadow DOM. Within the Shadow DOM each - * element has an `ElementInjector` - * which follow the same parent-child hierarchy as the DOM elements themselves. - * - * When a template is instantiated, it also must instantiate the corresponding directives in a - * depth-first order. The - * current `ElementInjector` resolves the constructor dependencies for each directive. - * - * Angular then resolves dependencies as follows, according to the order in which they appear in the - * {@link ComponentMetadata}: - * - * 1. Dependencies on the current element - * 2. Dependencies on element injectors and their parents until it encounters a Shadow DOM boundary - * 3. Dependencies on component injectors and their parents until it encounters the root component - * 4. Dependencies on pre-existing injectors - * - * - * The `ElementInjector` can inject other directives, element-specific special objects, or it can - * delegate to the parent - * injector. - * - * To inject other directives, declare the constructor parameter as: - * - `directive:DirectiveType`: a directive on the current element only - * - `@Host() directive:DirectiveType`: any directive that matches the type between the current - * element and the - * Shadow DOM root. - * - `@Query(DirectiveType) query:QueryList`: A live collection of direct child - * directives. - * - `@QueryDescendants(DirectiveType) query:QueryList`: A live collection of any - * child directives. - * - * To inject element-specific special objects, declare the constructor parameter as: - * - `element: ElementRef` to obtain a reference to logical element in the view. - * - `viewContainer: ViewContainerRef` to control child template instantiation, for - * {@link DirectiveMetadata} directives only - * - `bindingPropagation: BindingPropagation` to control change detection in a more granular way. - * - * ### Example - * - * The following example demonstrates how dependency injection resolves constructor arguments in - * practice. - * - * - * Assume this HTML template: - * - * ``` - *
- *
- *
- *
- *
- *
- *
- *
- *
- *
- * ``` - * - * With the following `dependency` decorator and `SomeService` injectable class. - * - * ``` - * @Injectable() - * class SomeService { - * } - * - * @Directive({ - * selector: '[dependency]', - * inputs: [ - * 'id: dependency' - * ] - * }) - * class Dependency { - * id:string; - * } - * ``` - * - * Let's step through the different ways in which `MyDirective` could be declared... - * - * - * ### No injection - * - * Here the constructor is declared with no arguments, therefore nothing is injected into - * `MyDirective`. - * - * ``` - * @Directive({ selector: '[my-directive]' }) - * class MyDirective { - * constructor() { - * } - * } - * ``` - * - * This directive would be instantiated with no dependencies. - * - * - * ### Component-level injection - * - * Directives can inject any injectable instance from the closest component injector or any of its - * parents. - * - * Here, the constructor declares a parameter, `someService`, and injects the `SomeService` type - * from the parent - * component's injector. - * ``` - * @Directive({ selector: '[my-directive]' }) - * class MyDirective { - * constructor(someService: SomeService) { - * } - * } - * ``` - * - * This directive would be instantiated with a dependency on `SomeService`. - * - * - * ### Injecting a directive from the current element - * - * Directives can inject other directives declared on the current element. - * - * ``` - * @Directive({ selector: '[my-directive]' }) - * class MyDirective { - * constructor(dependency: Dependency) { - * expect(dependency.id).toEqual(3); - * } - * } - * ``` - * This directive would be instantiated with `Dependency` declared at the same element, in this case - * `dependency="3"`. - * - * ### Injecting a directive from any ancestor elements - * - * Directives can inject other directives declared on any ancestor element (in the current Shadow - * DOM), i.e. on the current element, the - * parent element, or its parents. - * ``` - * @Directive({ selector: '[my-directive]' }) - * class MyDirective { - * constructor(@Host() dependency: Dependency) { - * expect(dependency.id).toEqual(2); - * } - * } - * ``` - * - * `@Host` checks the current element, the parent, as well as its parents recursively. If - * `dependency="2"` didn't - * exist on the direct parent, this injection would - * have returned - * `dependency="1"`. - * - * - * ### Injecting a live collection of direct child directives - * - * - * A directive can also query for other child directives. Since parent directives are instantiated - * before child directives, a directive can't simply inject the list of child directives. Instead, - * the directive injects a {@link QueryList}, which updates its contents as children are added, - * removed, or moved by a directive that uses a {@link ViewContainerRef} such as a `ngFor`, an - * `ngIf`, or an `ngSwitch`. - * - * ``` - * @Directive({ selector: '[my-directive]' }) - * class MyDirective { - * constructor(@Query(Dependency) dependencies:QueryList) { - * } - * } - * ``` - * - * This directive would be instantiated with a {@link QueryList} which contains `Dependency` 4 and - * `Dependency` 6. Here, `Dependency` 5 would not be included, because it is not a direct child. - * - * ### Injecting a live collection of descendant directives - * - * By passing the descendant flag to `@Query` above, we can include the children of the child - * elements. - * - * ``` - * @Directive({ selector: '[my-directive]' }) - * class MyDirective { - * constructor(@Query(Dependency, {descendants: true}) dependencies:QueryList) { - * } - * } - * ``` - * - * This directive would be instantiated with a Query which would contain `Dependency` 4, 5 and 6. - * - * ### Optional injection - * - * The normal behavior of directives is to return an error when a specified dependency cannot be - * resolved. If you - * would like to inject `null` on unresolved dependency instead, you can annotate that dependency - * with `@Optional()`. - * This explicitly permits the author of a template to treat some of the surrounding directives as - * optional. - * - * ``` - * @Directive({ selector: '[my-directive]' }) - * class MyDirective { - * constructor(@Optional() dependency:Dependency) { - * } - * } - * ``` - * - * This directive would be instantiated with a `Dependency` directive found on the current element. - * If none can be - * found, the injector supplies `null` instead of throwing an error. - * - * ### Example - * - * Here we use a decorator directive to simply define basic tool-tip behavior. - * - * ``` - * @Directive({ - * selector: '[tooltip]', - * inputs: [ - * 'text: tooltip' - * ], - * host: { - * '(mouseenter)': 'onMouseEnter()', - * '(mouseleave)': 'onMouseLeave()' - * } - * }) - * class Tooltip{ - * text:string; - * overlay:Overlay; // NOT YET IMPLEMENTED - * overlayManager:OverlayManager; // NOT YET IMPLEMENTED - * - * constructor(overlayManager:OverlayManager) { - * this.overlay = overlay; - * } - * - * onMouseEnter() { - * // exact signature to be determined - * this.overlay = this.overlayManager.open(text, ...); - * } - * - * onMouseLeave() { - * this.overlay.close(); - * this.overlay = null; - * } - * } - * ``` - * In our HTML template, we can then add this behavior to a `
` or any other element with the - * `tooltip` selector, - * like so: - * - * ``` - *
- * ``` - * - * Directives can also control the instantiation, destruction, and positioning of inline template - * elements: - * - * A directive uses a {@link ViewContainerRef} to instantiate, insert, move, and destroy views at - * runtime. - * The {@link ViewContainerRef} is created as a result of `