265 lines
8.9 KiB
TypeScript
Raw Normal View History

/**
* @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
*/
import {ɵparseCookieValue as parseCookieValue} from '@angular/common';
import {ɵglobal as global} from '@angular/core';
import {setRootDomAdapter} from '../dom/dom_adapter';
import {GenericBrowserDomAdapter} from './generic_browser_adapter';
const DOM_KEY_LOCATION_NUMPAD = 3;
// Map to convert some key or keyIdentifier values to what will be returned by getEventKey
2016-09-27 17:30:26 -07:00
const _keyMap: {[k: string]: string} = {
// The following values are here for cross-browser compatibility and to match the W3C standard
// cf http://www.w3.org/TR/DOM-Level-3-Events-key/
'\b': 'Backspace',
'\t': 'Tab',
'\x7F': 'Delete',
'\x1B': 'Escape',
'Del': 'Delete',
'Esc': 'Escape',
'Left': 'ArrowLeft',
'Right': 'ArrowRight',
'Up': 'ArrowUp',
'Down': 'ArrowDown',
'Menu': 'ContextMenu',
'Scroll': 'ScrollLock',
'Win': 'OS'
};
// There is a bug in Chrome for numeric keypad keys:
// https://code.google.com/p/chromium/issues/detail?id=155654
// 1, 2, 3 ... are reported as A, B, C ...
2016-09-27 17:30:26 -07:00
const _chromeNumKeyPadMap = {
'A': '1',
'B': '2',
'C': '3',
'D': '4',
'E': '5',
'F': '6',
'G': '7',
'H': '8',
'I': '9',
'J': '*',
'K': '+',
'M': '-',
'N': '.',
'O': '/',
'\x60': '0',
'\x90': 'NumLock'
};
const nodeContains: (this: Node, other: Node) => boolean = (() => {
if (global['Node']) {
return global['Node'].prototype.contains || function(this: Node, node: any) {
return !!(this.compareDocumentPosition(node) & 16);
};
}
return undefined as any;
})();
/**
* A `DomAdapter` powered by full browser DOM APIs.
*
* @security Tread carefully! Interacting with the DOM directly is dangerous and
* can introduce XSS risks.
*/
/* tslint:disable:requireParameterType no-console */
export class BrowserDomAdapter extends GenericBrowserDomAdapter {
static makeCurrent() { setRootDomAdapter(new BrowserDomAdapter()); }
2016-09-27 17:30:26 -07:00
setProperty(el: Node, name: string, value: any) { (<any>el)[name] = value; }
getProperty(el: Node, name: string): any { return (<any>el)[name]; }
log(error: string): void {
if (window.console) {
window.console.log && window.console.log(error);
}
}
logGroup(error: string): void {
if (window.console) {
window.console.group && window.console.group(error);
}
}
logGroupEnd(): void {
if (window.console) {
window.console.groupEnd && window.console.groupEnd();
}
}
querySelector(el: HTMLElement, selector: string): any { return el.querySelector(selector); }
2016-09-27 17:30:26 -07:00
querySelectorAll(el: any, selector: string): any[] { return el.querySelectorAll(selector); }
onAndCancel(el: Node, evt: any, listener: any): Function {
el.addEventListener(evt, listener, false);
// Needed to follow Dart's subscription semantic, until fix of
// https://code.google.com/p/dart/issues/detail?id=17406
return () => { el.removeEventListener(evt, listener, false); };
}
2016-09-27 17:30:26 -07:00
dispatchEvent(el: Node, evt: any) { el.dispatchEvent(evt); }
nextSibling(el: Node): Node|null { return el.nextSibling; }
parentElement(el: Node): Node|null { return el.parentNode; }
2016-09-27 17:30:26 -07:00
clearNodes(el: Node) {
feat(compiler): attach components and project light dom during compilation. Closes #2529 BREAKING CHANGES: - shadow dom emulation no longer supports the `<content>` tag. Use the new `<ng-content>` instead (works with all shadow dom strategies). - removed `DomRenderer.setViewRootNodes` and `AppViewManager.getComponentView` -> use `DomRenderer.getNativeElementSync(elementRef)` and change shadow dom directly - the `Renderer` interface has changed: * `createView` now also has to support sub views * the notion of a container has been removed. Instead, the renderer has to implement methods to attach views next to elements or other views. * a RenderView now contains multiple RenderFragments. Fragments are used to move DOM nodes around. Internal changes / design changes: - Introduce notion of view fragments on render side - DomProtoViews and DomViews on render side are merged, AppProtoViews are not merged, AppViews are partially merged (they share arrays with the other merged AppViews but we keep individual AppView instances for now). - DomProtoViews always have a `<template>` element as root * needed for storing subviews * we have less chunks of DOM to clone now - remove fake ElementBinder / Bound element for root text bindings and model them explicitly. This removes a lot of special cases we had! - AppView shares data with nested component views - some methods in AppViewManager (create, hydrate, dehydrate) are iterative now * now possible as we have all child AppViews / ElementRefs already in an array!
2015-06-24 13:46:39 -07:00
while (el.firstChild) {
el.removeChild(el.firstChild);
}
}
2016-09-27 17:30:26 -07:00
appendChild(el: Node, node: Node) { el.appendChild(node); }
removeChild(el: Node, node: Node) { el.removeChild(node); }
remove(node: Node): Node {
if (node.parentNode) {
node.parentNode.removeChild(node);
}
feat(compiler): attach components and project light dom during compilation. Closes #2529 BREAKING CHANGES: - shadow dom emulation no longer supports the `<content>` tag. Use the new `<ng-content>` instead (works with all shadow dom strategies). - removed `DomRenderer.setViewRootNodes` and `AppViewManager.getComponentView` -> use `DomRenderer.getNativeElementSync(elementRef)` and change shadow dom directly - the `Renderer` interface has changed: * `createView` now also has to support sub views * the notion of a container has been removed. Instead, the renderer has to implement methods to attach views next to elements or other views. * a RenderView now contains multiple RenderFragments. Fragments are used to move DOM nodes around. Internal changes / design changes: - Introduce notion of view fragments on render side - DomProtoViews and DomViews on render side are merged, AppProtoViews are not merged, AppViews are partially merged (they share arrays with the other merged AppViews but we keep individual AppView instances for now). - DomProtoViews always have a `<template>` element as root * needed for storing subviews * we have less chunks of DOM to clone now - remove fake ElementBinder / Bound element for root text bindings and model them explicitly. This removes a lot of special cases we had! - AppView shares data with nested component views - some methods in AppViewManager (create, hydrate, dehydrate) are iterative now * now possible as we have all child AppViews / ElementRefs already in an array!
2015-06-24 13:46:39 -07:00
return node;
}
2017-02-14 21:03:18 -08:00
insertBefore(parent: Node, ref: Node, node: Node) { parent.insertBefore(node, ref); }
2016-09-27 17:30:26 -07:00
setText(el: Node, value: string) { el.textContent = value; }
getValue(el: any): string { return el.value; }
createComment(text: string): Comment { return this.getDefaultDocument().createComment(text); }
createElement(tagName: string, doc?: Document): HTMLElement {
doc = doc || this.getDefaultDocument();
return doc.createElement(tagName);
}
createElementNS(ns: string, tagName: string, doc?: Document): Element {
doc = doc || this.getDefaultDocument();
return doc.createElementNS(ns, tagName);
}
createTextNode(text: string, doc?: Document): Text {
doc = doc || this.getDefaultDocument();
return doc.createTextNode(text);
}
getHost(el: HTMLElement): HTMLElement { return (<any>el).host; }
2016-09-27 17:30:26 -07:00
getElementsByTagName(element: any, name: string): HTMLElement[] {
return element.getElementsByTagName(name);
}
2016-09-27 17:30:26 -07:00
addClass(element: any, className: string) { element.classList.add(className); }
removeClass(element: any, className: string) { element.classList.remove(className); }
setStyle(element: any, styleName: string, styleValue: string) {
element.style[styleName] = styleValue;
}
removeStyle(element: any, stylename: string) {
// IE requires '' instead of null
// see https://github.com/angular/angular/issues/7916
element.style[stylename] = '';
}
2016-09-27 17:30:26 -07:00
getStyle(element: any, stylename: string): string { return element.style[stylename]; }
getAttribute(element: Element, attribute: string): string|null {
return element.getAttribute(attribute);
}
2016-09-27 17:30:26 -07:00
setAttribute(element: Element, name: string, value: string) { element.setAttribute(name, value); }
setAttributeNS(element: Element, ns: string, name: string, value: string) {
element.setAttributeNS(ns, name, value);
}
2016-09-27 17:30:26 -07:00
removeAttribute(element: Element, attribute: string) { element.removeAttribute(attribute); }
removeAttributeNS(element: Element, ns: string, name: string) {
element.removeAttributeNS(ns, name);
}
createHtmlDocument(): HTMLDocument {
return document.implementation.createHTMLDocument('fakeTitle');
}
getDefaultDocument(): Document { return document; }
getTitle(doc: Document): string { return doc.title; }
setTitle(doc: Document, newTitle: string) { doc.title = newTitle || ''; }
2016-09-27 17:30:26 -07:00
elementMatches(n: any, selector: string): boolean {
if (this.isElementNode(n)) {
2016-09-27 17:30:26 -07:00
return n.matches && n.matches(selector) ||
n.msMatchesSelector && n.msMatchesSelector(selector) ||
n.webkitMatchesSelector && n.webkitMatchesSelector(selector);
}
2016-09-27 17:30:26 -07:00
return false;
}
isElementNode(node: Node): boolean { return node.nodeType === Node.ELEMENT_NODE; }
2016-09-27 17:30:26 -07:00
isShadowRoot(node: any): boolean { return node instanceof DocumentFragment; }
2016-09-27 17:30:26 -07:00
getEventKey(event: any): string {
let key = event.key;
2017-03-02 09:37:01 -08:00
if (key == null) {
key = event.keyIdentifier;
// keyIdentifier is defined in the old draft of DOM Level 3 Events implemented by Chrome and
2016-09-27 17:30:26 -07:00
// Safari cf
// http://www.w3.org/TR/2007/WD-DOM-Level-3-Events-20071221/events.html#Events-KeyboardEvents-Interfaces
2017-03-02 09:37:01 -08:00
if (key == null) {
return 'Unidentified';
}
if (key.startsWith('U+')) {
key = String.fromCharCode(parseInt(key.substring(2), 16));
if (event.location === DOM_KEY_LOCATION_NUMPAD && _chromeNumKeyPadMap.hasOwnProperty(key)) {
// There is a bug in Chrome for numeric keypad keys:
// https://code.google.com/p/chromium/issues/detail?id=155654
// 1, 2, 3 ... are reported as A, B, C ...
2016-09-27 17:30:26 -07:00
key = (_chromeNumKeyPadMap as any)[key];
}
}
}
2016-09-27 17:30:26 -07:00
return _keyMap[key] || key;
}
getGlobalEventTarget(doc: Document, target: string): EventTarget|null {
2016-09-27 17:30:26 -07:00
if (target === 'window') {
return window;
2016-09-27 17:30:26 -07:00
}
if (target === 'document') {
return doc;
2016-09-27 17:30:26 -07:00
}
if (target === 'body') {
return doc.body;
}
return null;
}
getHistory(): History { return window.history; }
getLocation(): Location { return window.location; }
getBaseHref(doc: Document): string|null {
2016-09-27 17:30:26 -07:00
const href = getBaseElementHref();
2017-03-02 09:37:01 -08:00
return href == null ? null : relativePath(href);
}
resetBaseElement(): void { baseElement = null; }
getUserAgent(): string { return window.navigator.userAgent; }
performanceNow(): number {
// performance.now() is not available in all browsers, see
// http://caniuse.com/#search=performance.now
2016-09-27 17:30:26 -07:00
return window.performance && window.performance.now ? window.performance.now() :
new Date().getTime();
}
supportsCookies(): boolean { return true; }
getCookie(name: string): string|null { return parseCookieValue(document.cookie, name); }
}
let baseElement: HTMLElement|null = null;
function getBaseElementHref(): string|null {
2016-09-27 17:30:26 -07:00
if (!baseElement) {
baseElement = document.querySelector('base') !;
2016-09-27 17:30:26 -07:00
if (!baseElement) {
return null;
}
}
return baseElement.getAttribute('href');
}
// based on urlUtils.js in AngularJS 1
2016-09-27 17:30:26 -07:00
let urlParsingNode: any;
function relativePath(url: any): string {
if (!urlParsingNode) {
urlParsingNode = document.createElement('a');
}
urlParsingNode.setAttribute('href', url);
return (urlParsingNode.pathname.charAt(0) === '/') ? urlParsingNode.pathname :
'/' + urlParsingNode.pathname;
}