refactor(BrowserAdapter): cleanup

This commit is contained in:
Victor Berchet 2016-09-27 17:30:26 -07:00 committed by Chuck Jazdzewski
parent 1c012a035f
commit ca3f9926f9
3 changed files with 137 additions and 199 deletions

View File

@ -7,21 +7,21 @@
*/
import {setRootDomAdapter} from '../dom/dom_adapter';
import {DateWrapper, global, isBlank, isFunction, isPresent, setValueOnPath} from '../facade/lang';
import {global, isBlank, isPresent, setValueOnPath} from '../facade/lang';
import {GenericBrowserDomAdapter} from './generic_browser_adapter';
var _attrToPropMap = {
const _attrToPropMap = {
'class': 'className',
'innerHtml': 'innerHTML',
'readonly': 'readOnly',
'tabindex': 'tabIndex'
'tabindex': 'tabIndex',
};
const DOM_KEY_LOCATION_NUMPAD = 3;
// Map to convert some key or keyIdentifier values to what will be returned by getEventKey
var _keyMap = {
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',
@ -42,7 +42,7 @@ var _keyMap = {
// 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 ...
var _chromeNumKeyPadMap = {
const _chromeNumKeyPadMap = {
'A': '1',
'B': '2',
'C': '3',
@ -71,67 +71,45 @@ var _chromeNumKeyPadMap = {
export class BrowserDomAdapter extends GenericBrowserDomAdapter {
parse(templateHtml: string) { throw new Error('parse not implemented'); }
static makeCurrent() { setRootDomAdapter(new BrowserDomAdapter()); }
hasProperty(element: any /** TODO #9100 */, name: string): boolean { return name in element; }
setProperty(el: /*element*/ any, name: string, value: any) { el[name] = value; }
getProperty(el: /*element*/ any, name: string): any { return el[name]; }
invoke(el: /*element*/ any, methodName: string, args: any[]): any {
el[methodName].apply(el, args);
}
hasProperty(element: Node, name: string): boolean { return name in element; }
setProperty(el: Node, name: string, value: any) { (<any>el)[name] = value; }
getProperty(el: Node, name: string): any { return (<any>el)[name]; }
invoke(el: Node, methodName: string, args: any[]): any { (<any>el)[methodName](...args); }
// TODO(tbosch): move this into a separate environment class once we have it
logError(error: any /** TODO #9100 */) {
if (window.console.error) {
window.console.error(error);
} else {
window.console.log(error);
}
logError(error: string) { (window.console.error || window.console.log)(error); }
log(error: string) { window.console.log(error); }
logGroup(error: string) {
window.console.group && window.console.group(error);
this.logError(error);
}
log(error: any /** TODO #9100 */) { window.console.log(error); }
logGroup(error: any /** TODO #9100 */) {
if (window.console.group) {
window.console.group(error);
this.logError(error);
} else {
window.console.log(error);
}
}
logGroupEnd() {
if (window.console.groupEnd) {
window.console.groupEnd();
}
}
logGroupEnd() { window.console.groupEnd && window.console.groupEnd(); }
get attrToPropMap(): any { return _attrToPropMap; }
query(selector: string): any { return document.querySelector(selector); }
querySelector(el: any /** TODO #9100 */, selector: string): HTMLElement {
return el.querySelector(selector);
querySelector(el: Element, selector: string): HTMLElement {
return el.querySelector(selector) as HTMLElement;
}
querySelectorAll(el: any /** TODO #9100 */, selector: string): any[] {
return el.querySelectorAll(selector);
}
on(el: any /** TODO #9100 */, evt: any /** TODO #9100 */, listener: any /** TODO #9100 */) {
el.addEventListener(evt, listener, false);
}
onAndCancel(
el: any /** TODO #9100 */, evt: any /** TODO #9100 */,
listener: any /** TODO #9100 */): Function {
querySelectorAll(el: any, selector: string): any[] { return el.querySelectorAll(selector); }
on(el: Node, evt: any, listener: any) { el.addEventListener(evt, listener, false); }
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); };
}
dispatchEvent(el: any /** TODO #9100 */, evt: any /** TODO #9100 */) { el.dispatchEvent(evt); }
dispatchEvent(el: Node, evt: any) { el.dispatchEvent(evt); }
createMouseEvent(eventType: string): MouseEvent {
var evt: MouseEvent = document.createEvent('MouseEvent');
const evt: MouseEvent = document.createEvent('MouseEvent');
evt.initEvent(eventType, true, true);
return evt;
}
createEvent(eventType: any /** TODO #9100 */): Event {
var evt: Event = document.createEvent('Event');
createEvent(eventType: any): Event {
const evt: Event = document.createEvent('Event');
evt.initEvent(eventType, true, true);
return evt;
}
@ -142,11 +120,11 @@ export class BrowserDomAdapter extends GenericBrowserDomAdapter {
isPrevented(evt: Event): boolean {
return evt.defaultPrevented || isPresent(evt.returnValue) && !evt.returnValue;
}
getInnerHTML(el: any /** TODO #9100 */): string { return el.innerHTML; }
getTemplateContent(el: any /** TODO #9100 */): Node {
getInnerHTML(el: HTMLElement): string { return el.innerHTML; }
getTemplateContent(el: Node): Node {
return 'content' in el && el instanceof HTMLTemplateElement ? el.content : null;
}
getOuterHTML(el: any /** TODO #9100 */): string { return el.outerHTML; }
getOuterHTML(el: HTMLElement): string { return el.outerHTML; }
nodeName(node: Node): string { return node.nodeName; }
nodeValue(node: Node): string { return node.nodeValue; }
type(node: HTMLInputElement): string { return node.type; }
@ -157,72 +135,62 @@ export class BrowserDomAdapter extends GenericBrowserDomAdapter {
return node;
}
}
firstChild(el: any /** TODO #9100 */): Node { return el.firstChild; }
nextSibling(el: any /** TODO #9100 */): Node { return el.nextSibling; }
parentElement(el: any /** TODO #9100 */): Node { return el.parentNode; }
childNodes(el: any /** TODO #9100 */): Node[] { return el.childNodes; }
childNodesAsList(el: any /** TODO #9100 */): any[] {
var childNodes = el.childNodes;
var res = new Array(childNodes.length);
for (var i = 0; i < childNodes.length; i++) {
firstChild(el: Node): Node { return el.firstChild; }
nextSibling(el: Node): Node { return el.nextSibling; }
parentElement(el: Node): Node { return el.parentNode; }
childNodes(el: any): Node[] { return el.childNodes; }
childNodesAsList(el: Node): any[] {
const childNodes = el.childNodes;
const res = new Array(childNodes.length);
for (let i = 0; i < childNodes.length; i++) {
res[i] = childNodes[i];
}
return res;
}
clearNodes(el: any /** TODO #9100 */) {
clearNodes(el: Node) {
while (el.firstChild) {
el.removeChild(el.firstChild);
}
}
appendChild(el: any /** TODO #9100 */, node: any /** TODO #9100 */) { el.appendChild(node); }
removeChild(el: any /** TODO #9100 */, node: any /** TODO #9100 */) { el.removeChild(node); }
replaceChild(el: Node, newChild: any /** TODO #9100 */, oldChild: any /** TODO #9100 */) {
el.replaceChild(newChild, oldChild);
}
remove(node: any /** TODO #9100 */): Node {
appendChild(el: Node, node: Node) { el.appendChild(node); }
removeChild(el: Node, node: Node) { el.removeChild(node); }
replaceChild(el: Node, newChild: Node, oldChild: Node) { el.replaceChild(newChild, oldChild); }
remove(node: Node): Node {
if (node.parentNode) {
node.parentNode.removeChild(node);
}
return node;
}
insertBefore(el: any /** TODO #9100 */, node: any /** TODO #9100 */) {
el.parentNode.insertBefore(node, el);
insertBefore(el: Node, node: Node) { el.parentNode.insertBefore(node, el); }
insertAllBefore(el: Node, nodes: Node[]) {
nodes.forEach((n: any) => el.parentNode.insertBefore(n, el));
}
insertAllBefore(el: any /** TODO #9100 */, nodes: any /** TODO #9100 */) {
nodes.forEach((n: any /** TODO #9100 */) => el.parentNode.insertBefore(n, el));
}
insertAfter(el: any /** TODO #9100 */, node: any /** TODO #9100 */) {
el.parentNode.insertBefore(node, el.nextSibling);
}
setInnerHTML(el: any /** TODO #9100 */, value: any /** TODO #9100 */) { el.innerHTML = value; }
getText(el: any /** TODO #9100 */): string { return el.textContent; }
// TODO(vicb): removed Element type because it does not support StyleElement
setText(el: any /** TODO #9100 */, value: string) { el.textContent = value; }
getValue(el: any /** TODO #9100 */): string { return el.value; }
setValue(el: any /** TODO #9100 */, value: string) { el.value = value; }
getChecked(el: any /** TODO #9100 */): boolean { return el.checked; }
setChecked(el: any /** TODO #9100 */, value: boolean) { el.checked = value; }
insertAfter(el: Node, node: any) { el.parentNode.insertBefore(node, el.nextSibling); }
setInnerHTML(el: Element, value: string) { el.innerHTML = value; }
getText(el: Node): string { return el.textContent; }
setText(el: Node, value: string) { el.textContent = value; }
getValue(el: any): string { return el.value; }
setValue(el: any, value: string) { el.value = value; }
getChecked(el: any): boolean { return el.checked; }
setChecked(el: any, value: boolean) { el.checked = value; }
createComment(text: string): Comment { return document.createComment(text); }
createTemplate(html: any /** TODO #9100 */): HTMLElement {
var t = document.createElement('template');
createTemplate(html: any): HTMLElement {
const t = document.createElement('template');
t.innerHTML = html;
return t;
}
createElement(tagName: any /* TODO #9100 */, doc = document): HTMLElement {
return doc.createElement(tagName);
}
createElementNS(ns: any /* TODO #9100 */, tagName: any /* TODO #9100 */, doc = document):
Element {
createElement(tagName: string, doc = document): HTMLElement { return doc.createElement(tagName); }
createElementNS(ns: string, tagName: string, doc = document): Element {
return doc.createElementNS(ns, tagName);
}
createTextNode(text: string, doc = document): Text { return doc.createTextNode(text); }
createScriptTag(attrName: string, attrValue: string, doc = document): HTMLScriptElement {
var el = <HTMLScriptElement>doc.createElement('SCRIPT');
const el = <HTMLScriptElement>doc.createElement('SCRIPT');
el.setAttribute(attrName, attrValue);
return el;
}
createStyleElement(css: string, doc = document): HTMLStyleElement {
var style = <HTMLStyleElement>doc.createElement('style');
const style = <HTMLStyleElement>doc.createElement('style');
this.appendChild(style, this.createTextNode(css));
return style;
}
@ -230,77 +198,63 @@ export class BrowserDomAdapter extends GenericBrowserDomAdapter {
getShadowRoot(el: HTMLElement): DocumentFragment { return (<any>el).shadowRoot; }
getHost(el: HTMLElement): HTMLElement { return (<any>el).host; }
clone(node: Node): Node { return node.cloneNode(true); }
getElementsByClassName(element: any /** TODO #9100 */, name: string): HTMLElement[] {
getElementsByClassName(element: any, name: string): HTMLElement[] {
return element.getElementsByClassName(name);
}
getElementsByTagName(element: any /** TODO #9100 */, name: string): HTMLElement[] {
getElementsByTagName(element: any, name: string): HTMLElement[] {
return element.getElementsByTagName(name);
}
classList(element: any /** TODO #9100 */): any[] {
return <any[]>Array.prototype.slice.call(element.classList, 0);
}
addClass(element: any /** TODO #9100 */, className: string) { element.classList.add(className); }
removeClass(element: any /** TODO #9100 */, className: string) {
element.classList.remove(className);
}
hasClass(element: any /** TODO #9100 */, className: string): boolean {
classList(element: any): any[] { return Array.prototype.slice.call(element.classList, 0); }
addClass(element: any, className: string) { element.classList.add(className); }
removeClass(element: any, className: string) { element.classList.remove(className); }
hasClass(element: any, className: string): boolean {
return element.classList.contains(className);
}
setStyle(element: any /** TODO #9100 */, styleName: string, styleValue: string) {
setStyle(element: any, styleName: string, styleValue: string) {
element.style[styleName] = styleValue;
}
removeStyle(element: any /** TODO #9100 */, stylename: string) {
element.style[stylename] = null;
}
getStyle(element: any /** TODO #9100 */, stylename: string): string {
return element.style[stylename];
}
hasStyle(element: any /** TODO #9100 */, styleName: string, styleValue: string = null): boolean {
var value = this.getStyle(element, styleName) || '';
removeStyle(element: any, stylename: string) { element.style[stylename] = null; }
getStyle(element: any, stylename: string): string { return element.style[stylename]; }
hasStyle(element: any, styleName: string, styleValue: string = null): boolean {
const value = this.getStyle(element, styleName) || '';
return styleValue ? value == styleValue : value.length > 0;
}
tagName(element: any /** TODO #9100 */): string { return element.tagName; }
attributeMap(element: any /** TODO #9100 */): Map<string, string> {
var res = new Map<string, string>();
var elAttrs = element.attributes;
for (var i = 0; i < elAttrs.length; i++) {
var attrib = elAttrs[i];
tagName(element: any): string { return element.tagName; }
attributeMap(element: any): Map<string, string> {
const res = new Map<string, string>();
const elAttrs = element.attributes;
for (let i = 0; i < elAttrs.length; i++) {
const attrib = elAttrs[i];
res.set(attrib.name, attrib.value);
}
return res;
}
hasAttribute(element: any /** TODO #9100 */, attribute: string): boolean {
hasAttribute(element: Element, attribute: string): boolean {
return element.hasAttribute(attribute);
}
hasAttributeNS(element: any /** TODO #9100 */, ns: string, attribute: string): boolean {
hasAttributeNS(element: Element, ns: string, attribute: string): boolean {
return element.hasAttributeNS(ns, attribute);
}
getAttribute(element: any /** TODO #9100 */, attribute: string): string {
getAttribute(element: Element, attribute: string): string {
return element.getAttribute(attribute);
}
getAttributeNS(element: any /** TODO #9100 */, ns: string, name: string): string {
getAttributeNS(element: Element, ns: string, name: string): string {
return element.getAttributeNS(ns, name);
}
setAttribute(element: any /** TODO #9100 */, name: string, value: string) {
element.setAttribute(name, value);
}
setAttributeNS(element: any /** TODO #9100 */, ns: string, name: string, value: string) {
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);
}
removeAttribute(element: any /** TODO #9100 */, attribute: string) {
element.removeAttribute(attribute);
}
removeAttributeNS(element: any /** TODO #9100 */, ns: string, name: string) {
removeAttribute(element: Element, attribute: string) { element.removeAttribute(attribute); }
removeAttributeNS(element: Element, ns: string, name: string) {
element.removeAttributeNS(ns, name);
}
templateAwareRoot(el: any /** TODO #9100 */): any {
return this.isTemplateElement(el) ? this.content(el) : el;
}
templateAwareRoot(el: Node): any { return this.isTemplateElement(el) ? this.content(el) : el; }
createHtmlDocument(): HTMLDocument {
return document.implementation.createHTMLDocument('fakeTitle');
}
defaultDoc(): HTMLDocument { return document; }
getBoundingClientRect(el: any /** TODO #9100 */): any {
getBoundingClientRect(el: Element): any {
try {
return el.getBoundingClientRect();
} catch (e) {
@ -309,45 +263,34 @@ export class BrowserDomAdapter extends GenericBrowserDomAdapter {
}
getTitle(): string { return document.title; }
setTitle(newTitle: string) { document.title = newTitle || ''; }
elementMatches(n: any /** TODO #9100 */, selector: string): boolean {
var matches = false;
elementMatches(n: any, selector: string): boolean {
if (n instanceof HTMLElement) {
if (n.matches) {
matches = n.matches(selector);
} else if (n.msMatchesSelector) {
matches = n.msMatchesSelector(selector);
} else if (n.webkitMatchesSelector) {
matches = n.webkitMatchesSelector(selector);
}
return n.matches && n.matches(selector) ||
n.msMatchesSelector && n.msMatchesSelector(selector) ||
n.webkitMatchesSelector && n.webkitMatchesSelector(selector);
}
return matches;
return false;
}
isTemplateElement(el: any): boolean {
isTemplateElement(el: Node): boolean {
return el instanceof HTMLElement && el.nodeName == 'TEMPLATE';
}
isTextNode(node: Node): boolean { return node.nodeType === Node.TEXT_NODE; }
isCommentNode(node: Node): boolean { return node.nodeType === Node.COMMENT_NODE; }
isElementNode(node: Node): boolean { return node.nodeType === Node.ELEMENT_NODE; }
hasShadowRoot(node: any /** TODO #9100 */): boolean {
hasShadowRoot(node: any): boolean {
return isPresent(node.shadowRoot) && node instanceof HTMLElement;
}
isShadowRoot(node: any /** TODO #9100 */): boolean { return node instanceof DocumentFragment; }
importIntoDoc(node: Node): any {
var toImport = node;
if (this.isTemplateElement(node)) {
toImport = this.content(node);
}
return document.importNode(toImport, true);
}
isShadowRoot(node: any): boolean { return node instanceof DocumentFragment; }
importIntoDoc(node: Node): any { return document.importNode(this.templateAwareRoot(node), true); }
adoptNode(node: Node): any { return document.adoptNode(node); }
getHref(el: Element): string { return (<any>el).href; }
getEventKey(event: any /** TODO #9100 */): string {
var key = event.key;
getEventKey(event: any): string {
let key = event.key;
if (isBlank(key)) {
key = event.keyIdentifier;
// keyIdentifier is defined in the old draft of DOM Level 3 Events implemented by Chrome and
// Safari
// cf
// Safari cf
// http://www.w3.org/TR/2007/WD-DOM-Level-3-Events-20071221/events.html#Events-KeyboardEvents-Interfaces
if (isBlank(key)) {
return 'Unidentified';
@ -358,53 +301,49 @@ export class BrowserDomAdapter extends GenericBrowserDomAdapter {
// 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 ...
key = (_chromeNumKeyPadMap as any /** TODO #9100 */)[key];
key = (_chromeNumKeyPadMap as any)[key];
}
}
}
if (_keyMap.hasOwnProperty(key)) {
key = (_keyMap as any /** TODO #9100 */)[key];
}
return key;
return _keyMap[key] || key;
}
getGlobalEventTarget(target: string): EventTarget {
if (target == 'window') {
if (target === 'window') {
return window;
} else if (target == 'document') {
}
if (target === 'document') {
return document;
} else if (target == 'body') {
}
if (target === 'body') {
return document.body;
}
}
getHistory(): History { return window.history; }
getLocation(): Location { return window.location; }
getBaseHref(): string {
var href = getBaseElementHref();
if (isBlank(href)) {
return null;
}
return relativePath(href);
const href = getBaseElementHref();
return isBlank(href) ? null : relativePath(href);
}
resetBaseElement(): void { baseElement = null; }
getUserAgent(): string { return window.navigator.userAgent; }
setData(element: any /** TODO #9100 */, name: string, value: string) {
setData(element: Element, name: string, value: string) {
this.setAttribute(element, 'data-' + name, value);
}
getData(element: any /** TODO #9100 */, name: string): string {
getData(element: Element, name: string): string {
return this.getAttribute(element, 'data-' + name);
}
getComputedStyle(element: any /** TODO #9100 */): any { return getComputedStyle(element); }
getComputedStyle(element: any): any { return getComputedStyle(element); }
// TODO(tbosch): move this into a separate environment class once we have it
setGlobalVar(path: string, value: any) { setValueOnPath(global, path, value); }
supportsWebAnimation(): boolean { return isFunction((<any>Element).prototype['animate']); }
supportsWebAnimation(): boolean {
return typeof(<any>Element).prototype['animate'] === 'function';
}
performanceNow(): number {
// performance.now() is not available in all browsers, see
// http://caniuse.com/#search=performance.now
if (isPresent(window.performance) && isPresent(window.performance.now)) {
return window.performance.now();
} else {
return DateWrapper.toMillis(DateWrapper.now());
}
return window.performance && window.performance.now ? window.performance.now() :
new Date().getTime();
}
supportsCookies(): boolean { return true; }
@ -418,12 +357,11 @@ export class BrowserDomAdapter extends GenericBrowserDomAdapter {
}
}
var baseElement: any /** TODO #9100 */ = null;
let baseElement: HTMLElement = null;
function getBaseElementHref(): string {
if (isBlank(baseElement)) {
if (!baseElement) {
baseElement = document.querySelector('base');
if (isBlank(baseElement)) {
if (!baseElement) {
return null;
}
}
@ -431,9 +369,9 @@ function getBaseElementHref(): string {
}
// based on urlUtils.js in AngularJS 1
var urlParsingNode: any /** TODO #9100 */ = null;
function relativePath(url: any /** TODO #9100 */): string {
if (isBlank(urlParsingNode)) {
let urlParsingNode: any;
function relativePath(url: any): string {
if (!urlParsingNode) {
urlParsingNode = document.createElement('a');
}
urlParsingNode.setAttribute('href', url);

View File

@ -7,8 +7,7 @@
*/
import {DomAdapter} from '../dom/dom_adapter';
import {StringMapWrapper} from '../facade/collection';
import {isFunction, isPresent} from '../facade/lang';
import {isPresent} from '../facade/lang';
@ -24,27 +23,30 @@ export abstract class GenericBrowserDomAdapter extends DomAdapter {
constructor() {
super();
try {
var element = this.createElement('div', this.defaultDoc());
const element = this.createElement('div', this.defaultDoc());
if (isPresent(this.getStyle(element, 'animationName'))) {
this._animationPrefix = '';
} else {
var domPrefixes = ['Webkit', 'Moz', 'O', 'ms'];
for (var i = 0; i < domPrefixes.length; i++) {
const domPrefixes = ['Webkit', 'Moz', 'O', 'ms'];
for (let i = 0; i < domPrefixes.length; i++) {
if (isPresent(this.getStyle(element, domPrefixes[i] + 'AnimationName'))) {
this._animationPrefix = '-' + domPrefixes[i].toLowerCase() + '-';
break;
}
}
}
var transEndEventNames: {[key: string]: string} = {
const transEndEventNames: {[key: string]: string} = {
WebkitTransition: 'webkitTransitionEnd',
MozTransition: 'transitionend',
OTransition: 'oTransitionEnd otransitionend',
transition: 'transitionend'
};
StringMapWrapper.forEach(transEndEventNames, (value: string, key: string) => {
Object.keys(transEndEventNames).forEach((key: string) => {
if (isPresent(this.getStyle(element, key))) {
this._transitionEnd = value;
this._transitionEnd = transEndEventNames[key];
}
});
} catch (e) {
@ -59,12 +61,10 @@ export abstract class GenericBrowserDomAdapter extends DomAdapter {
}
supportsDOMEvents(): boolean { return true; }
supportsNativeShadowDOM(): boolean {
return isFunction((<any>this.defaultDoc().body).createShadowRoot);
return typeof(<any>this.defaultDoc().body).createShadowRoot === 'function';
}
getAnimationPrefix(): string {
return isPresent(this._animationPrefix) ? this._animationPrefix : '';
}
getTransitionEnd(): string { return isPresent(this._transitionEnd) ? this._transitionEnd : ''; }
getAnimationPrefix(): string { return this._animationPrefix ? this._animationPrefix : ''; }
getTransitionEnd(): string { return this._transitionEnd ? this._transitionEnd : ''; }
supportsAnimation(): boolean {
return isPresent(this._animationPrefix) && isPresent(this._transitionEnd);
}

View File

@ -8,7 +8,7 @@
import {Type} from '@angular/core';
var _DOM: DomAdapter = null;
let _DOM: DomAdapter = null;
export function getDOM() {
return _DOM;