feat(aio): add attribute utils for code atty interpretation.

These utils support flexible, natural attribute interpretation as applied to code-example and code-pane. Then apply those utils to code-example and live-example
This commit is contained in:
Ward Bell
2017-05-02 19:17:05 -07:00
committed by Matias Niemelä
parent 8760bf7be4
commit 673d8ae583
4 changed files with 208 additions and 26 deletions

View File

@ -0,0 +1,48 @@
// Utilities for processing HTML element attributes
import { ElementRef } from '@angular/core';
interface StringMap { [index: string]: string; }
/**
* Get attribute map from element or ElementRef `attributes`.
* Attribute map keys are forced lowercase for case-insensitive lookup.
* @param el The source of the attributes
*/
export function getAttrs(el: HTMLElement | ElementRef): StringMap {
const attrs: NamedNodeMap = el instanceof ElementRef ? el.nativeElement.attributes : el.attributes;
const attrMap = {};
Object.keys(attrs).forEach(key =>
attrMap[(attrs[key] as Attr).name.toLowerCase()] = (attrs[key] as Attr).value);
return attrMap;
}
/**
* Return the attribute that matches `atty`.
* @param atty Name of the attribute or a string of candidate attribute names
*/
export function getAttrValue(attrs: StringMap, attr: string | string[] = ''): string {
return attrs[typeof attr === 'string' ? attr : attr.find(a => attrs[a] !== undefined)];
}
/**
* Return the boolean state of an attribute value (if supplied)
* @param attyValue The string value of some attribute (or undefined if attribute not present)
* @param def Default boolean value when attribute is undefined.
*/
export function boolFromValue(attrValue: string, def: boolean = false) {
// tslint:disable-next-line:triple-equals
return attrValue == undefined ? def : attrValue.trim() !== 'false';
}
/**
* Return the boolean state of attribute from an element
* @param el The source of the attributes
* @param atty Name of the attribute or a string of candidate attribute names
* @param def Default boolean value when attribute is undefined.
*/
export function getBoolFromAttribute(
el: HTMLElement | ElementRef,
attr: string | string[],
def: boolean = false): boolean {
return boolFromValue(getAttrValue(getAttrs(el), attr), def);
}