UNPKG

2.17 kBJavaScriptView Raw
1// DOM properties that should NOT have "px" added when numeric
2export const IS_NON_DIMENSIONAL = /acit|ex(?:s|g|n|p|$)|rph|ows|mnc|ntw|ine[ch]|zoo|^ord/i;
3
4export const objectKeys = Object.keys || (obj => {
5 let keys = [];
6 for (let i in obj) if (obj.hasOwnProperty(i)) keys.push(i);
7 return keys;
8});
9
10export let encodeEntities = s => String(s)
11 .replace(/&/g, '&')
12 .replace(/</g, '&lt;')
13 .replace(/>/g, '&gt;')
14 .replace(/"/g, '&quot;');
15
16export let indent = (s, char) => String(s).replace(/(\n+)/g, '$1' + (char || '\t'));
17
18export let isLargeString = (s, length, ignoreLines) => (String(s).length>(length || 40) || (!ignoreLines && String(s).indexOf('\n')!==-1) || String(s).indexOf('<')!==-1);
19
20const JS_TO_CSS = {};
21
22// Convert an Object style to a CSSText string
23export function styleObjToCss(s) {
24 let str = '';
25 for (let prop in s) {
26 let val = s[prop];
27 if (val!=null) {
28 if (str) str += ' ';
29 // str += jsToCss(prop);
30 str += JS_TO_CSS[prop] || (JS_TO_CSS[prop] = prop.replace(/([A-Z])/g,'-$1').toLowerCase());
31 str += ': ';
32 str += val;
33 if (typeof val==='number' && IS_NON_DIMENSIONAL.test(prop)===false) {
34 str += 'px';
35 }
36 str += ';';
37 }
38 }
39 return str || undefined;
40}
41
42/**
43 * Copy all properties from `props` onto `obj`.
44 * @param {object} obj Object onto which properties should be copied.
45 * @param {object} props Object from which to copy properties.
46 * @returns {object}
47 * @private
48 */
49export function assign(obj, props) {
50 for (let i in props) obj[i] = props[i];
51 return obj;
52}
53
54/**
55 * Reconstruct Component-style `props` from a VNode.
56 * Ensures default/fallback values from `defaultProps`:
57 * Own-properties of `defaultProps` not present in `vnode.attributes` are added.
58 * @param {import('preact').VNode} vnode The VNode to get props for
59 * @returns {object} The props to use for this VNode
60 */
61export function getNodeProps(vnode) {
62 let props = assign({}, vnode.attributes);
63 props.children = vnode.children;
64
65 let defaultProps = vnode.nodeName.defaultProps;
66 if (defaultProps!==undefined) {
67 for (let i in defaultProps) {
68 if (props[i]===undefined) {
69 props[i] = defaultProps[i];
70 }
71 }
72 }
73
74 return props;
75}