Skip to content

Commit

Permalink
feat(sifrr-dom): convert to es6 module syntax
Browse files Browse the repository at this point in the history
  • Loading branch information
aadityataparia committed Aug 7, 2019
1 parent e37654e commit 58454fa
Show file tree
Hide file tree
Showing 25 changed files with 247 additions and 263 deletions.
9 changes: 5 additions & 4 deletions packages/browser/sifrr-dom/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,9 @@
"url": "https://github.com/sifrr/sifrr/issues"
},
"homepage": "https://github.com/sifrr/sifrr",
"main": "src/sifrr.dom.js",
"module": "dist/sifrr.dom.module.js",
"browser": "dist/sifrr.dom.js",
"main": "dist/sifrr.dom.cjs.js",
"module": "src/sifrr.dom.js",
"browser": "dist/sifrr.dom.min.js",
"browserslist": [
"chrome >= 55",
"safari >= 10.1",
Expand All @@ -41,7 +41,8 @@
"devDependencies": {
"@sifrr/dev": "^0.0.26",
"cache-manager": "^2.10.0",
"loadtest": "^3.0.7"
"loadtest": "^3.0.7",
"@babel/plugin-proposal-class-properties": "^7.5.5"
},
"files": [
"bin",
Expand Down
52 changes: 24 additions & 28 deletions packages/browser/sifrr-dom/src/dom/bindings.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
const { OUTER_REGEX, STATE_REGEX } = require('./constants');
import { OUTER_REGEX, STATE_REGEX } from './constants';

function replacer(match) {
export function replacer(match) {
let f;
if (match.indexOf('return ') > -1) {
f = match;
Expand All @@ -15,7 +15,7 @@ function replacer(match) {
}
}

function evaluate(fxn, el) {
export function evaluate(fxn, el) {
try {
if (typeof fxn === 'string') return fxn;
else return fxn.call(el);
Expand All @@ -29,30 +29,26 @@ function evaluate(fxn, el) {
}
}

const Bindings = {
getBindingFxns: string => {
const splitted = string.split(OUTER_REGEX),
l = splitted.length,
ret = [];
for (let i = 0; i < l; i++) {
if (splitted[i][0] === '$' && splitted[i][1] === '{') {
ret.push(replacer(splitted[i].slice(2, -1)));
} else if (splitted[i]) ret.push(splitted[i]);
}
if (ret.length === 1) return ret[0];
return ret;
},
getStringBindingFxn: string => {
const match = string.match(STATE_REGEX);
if (match) return match[1];
return Bindings.getBindingFxns(string);
},
evaluateBindings: (fxns, element) => {
if (typeof fxns === 'function') return evaluate(fxns, element);
return fxns.map(fxn => evaluate(fxn, element)).join('');
},
evaluate: evaluate,
replacer: replacer
export const getBindingFxns = string => {
const splitted = string.split(OUTER_REGEX),
l = splitted.length,
ret = [];
for (let i = 0; i < l; i++) {
if (splitted[i][0] === '$' && splitted[i][1] === '{') {
ret.push(replacer(splitted[i].slice(2, -1)));
} else if (splitted[i]) ret.push(splitted[i]);
}
if (ret.length === 1) return ret[0];
return ret;
};

export const getStringBindingFxn = string => {
const match = string.match(STATE_REGEX);
if (match) return match[1];
return getBindingFxns(string);
};

module.exports = Bindings;
export const evaluateBindings = (fxns, element) => {
if (typeof fxns === 'function') return evaluate(fxns, element);
return fxns.map(fxn => evaluate(fxn, element)).join('');
};
5 changes: 5 additions & 0 deletions packages/browser/sifrr-dom/src/dom/config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
export default {
baseUrl: '',
useShadowRoot: true,
events: []
};
33 changes: 16 additions & 17 deletions packages/browser/sifrr-dom/src/dom/constants.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,20 +2,19 @@ const temp = window.document.createElement('template');
const script = window.document.createElement('script');
const reg = '(\\${(?:(?:[^{}$]|{(?:[^{}$])*})*)})';

module.exports = {
TEMPLATE: () => temp.cloneNode(false),
SCRIPT: () => script.cloneNode(false),
TREE_WALKER: () =>
window.document.createTreeWalker(window.document, window.NodeFilter.SHOW_ALL, null, false),
TEXT_NODE: 3,
COMMENT_NODE: 8,
ELEMENT_NODE: 1,
OUTER_REGEX: new RegExp(reg, 'g'),
STATE_REGEX: /^\$\{this\.state\.([a-zA-Z0-9_$]+)\}$/,
HTML_ATTR: 'data-sifrr-html',
REPEAT_ATTR: 'data-sifrr-repeat',
KEY_ATTR: 'data-sifrr-key',
BIND_ATTR: 'data-sifrr-bind',
DEFAULT_STATE_ATTR: 'data-sifrr-default-state',
STATE_ATTR: 'data-sifrr-state'
};
export const TEMPLATE = () => temp.cloneNode(false);
export const SCRIPT = () => script.cloneNode(false);
export const TREE_WALKER = () =>
window.document.createTreeWalker(window.document, window.NodeFilter.SHOW_ALL, null, false);

export const TEXT_NODE = 3;
export const COMMENT_NODE = 8;
export const ELEMENT_NODE = 1;
export const OUTER_REGEX = new RegExp(reg, 'g');
export const STATE_REGEX = /^\$\{this\.state\.([a-zA-Z0-9_$]+)\}$/;
export const HTML_ATTR = 'data-sifrr-html';
export const REPEAT_ATTR = 'data-sifrr-repeat';
export const KEY_ATTR = 'data-sifrr-key';
export const BIND_ATTR = 'data-sifrr-bind';
export const DEFAULT_STATE_ATTR = 'data-sifrr-default-state';
export const STATE_ATTR = 'data-sifrr-state';
12 changes: 5 additions & 7 deletions packages/browser/sifrr-dom/src/dom/creator.js
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
const { TEXT_NODE, COMMENT_NODE, ELEMENT_NODE, HTML_ATTR, REPEAT_ATTR } = require('./constants');
const repeatref = require('./repeatref');
import { TEXT_NODE, COMMENT_NODE, ELEMENT_NODE, HTML_ATTR, REPEAT_ATTR } from './constants';
import repeatref from './repeatref';
// ref types:
// 0: state
// 1: text
// 2: html
// 3: arrayToDom
const { getBindingFxns, getStringBindingFxn } = require('./bindings');
const updateAttribute = require('./updateattribute');
import { getBindingFxns, getStringBindingFxn } from './bindings';
import updateAttribute from './updateattribute';

function creator(el, defaultState) {
export default function creator(el, defaultState) {
if (el.nodeType === TEXT_NODE || el.nodeType === COMMENT_NODE) {
const x = el.data;
if (x.indexOf('${') > -1) {
Expand Down Expand Up @@ -74,5 +74,3 @@ function creator(el, defaultState) {
}
return 0;
}

module.exports = creator;
16 changes: 8 additions & 8 deletions packages/browser/sifrr-dom/src/dom/element.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
const { collect, create } = require('./ref');
const creator = require('./creator');
const update = require('./update');
const Loader = require('./loader');
const { trigger } = require('./event');
const template = require('./template');
const { BIND_ATTR, STATE_ATTR } = require('./constants');
import { collect, create } from './ref';
import creator from './creator';
import update from './update';
import Loader from './loader';
import { trigger } from './event';
import template from './template';
import { BIND_ATTR, STATE_ATTR } from './constants';

function elementClassFactory(baseClass) {
return class extends baseClass {
Expand Down Expand Up @@ -165,4 +165,4 @@ function elementClassFactory(baseClass) {
};
}

module.exports = elementClassFactory(window.HTMLElement);
export default elementClassFactory(window.HTMLElement);
87 changes: 43 additions & 44 deletions packages/browser/sifrr-dom/src/dom/event.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,25 @@ const SYNTHETIC_EVENTS = {};
const listenOpts = { capture: true, passive: true };
const customOpts = { composed: true, bubbles: true };

const getEventListener = name => {
const cssMatchEvent = (e, name, dom, target) => {
function callEach(fxns, isElement) {
fxns.forEach(fxn => {
if (!isElement || fxn.__dom === dom) fxn(e, target, dom);
});
}
for (let css in SYNTHETIC_EVENTS[name]) {
if (
(typeof dom.matches === 'function' && dom.matches(css)) ||
(dom.nodeType === 9 && css === 'document') ||
css === 'element'
)
callEach(SYNTHETIC_EVENTS[name][css], css === 'element');
}
};

export { SYNTHETIC_EVENTS as all };

export const getEventListener = name => {
return e => {
const target = e.composedPath ? e.composedPath()[0] : e.target;
let dom = target;
Expand All @@ -21,51 +39,32 @@ const getEventListener = name => {
};
};

const cssMatchEvent = (e, name, dom, target) => {
function callEach(fxns, isElement) {
fxns.forEach(fxn => {
if (!isElement || fxn.__dom === dom) fxn(e, target, dom);
});
}
for (let css in SYNTHETIC_EVENTS[name]) {
if (
(typeof dom.matches === 'function' && dom.matches(css)) ||
(dom.nodeType === 9 && css === 'document') ||
css === 'element'
)
callEach(SYNTHETIC_EVENTS[name][css], css === 'element');
export const add = name => {
if (SYNTHETIC_EVENTS[name]) return false;
const namedEL = getEventListener(name);
document.addEventListener(name, namedEL, listenOpts);
SYNTHETIC_EVENTS[name] = {};
return true;
};

export const addListener = (name, css, fxn) => {
if (!SYNTHETIC_EVENTS[name])
throw Error(`You need to call Sifrr.Dom.Event.add('${name}') before using listeners.`);
if (typeof css !== 'string') {
fxn.__dom = css;
css = 'element';
}
SYNTHETIC_EVENTS[name][css] = SYNTHETIC_EVENTS[name][css] || new Set();
SYNTHETIC_EVENTS[name][css].add(fxn);
return true;
};

const Event = {
all: SYNTHETIC_EVENTS,
add: name => {
if (SYNTHETIC_EVENTS[name]) return false;
const namedEL = getEventListener(name);
document.addEventListener(name, namedEL, listenOpts);
SYNTHETIC_EVENTS[name] = {};
return true;
},
addListener: (name, css, fxn) => {
if (!SYNTHETIC_EVENTS[name])
throw Error(`You need to call Sifrr.Dom.Event.add('${name}') before using listeners.`);
if (typeof css !== 'string') {
fxn.__dom = css;
css = 'element';
}
SYNTHETIC_EVENTS[name][css] = SYNTHETIC_EVENTS[name][css] || new Set();
SYNTHETIC_EVENTS[name][css].add(fxn);
return true;
},
removeListener: (name, css, fxn) => {
if (SYNTHETIC_EVENTS[name][css]) SYNTHETIC_EVENTS[name][css].delete(fxn);
return true;
},
trigger: (el, name, options) => {
if (typeof el === 'string') el = document.$(el);
el.dispatchEvent(new CustomEvent(name, Object.assign(customOpts, options)));
},
getEventListener
export const removeListener = (name, css, fxn) => {
if (SYNTHETIC_EVENTS[name][css]) SYNTHETIC_EVENTS[name][css].delete(fxn);
return true;
};

module.exports = Event;
export const trigger = (el, name, options) => {
if (typeof el === 'string') el = document.$(el);
el.dispatchEvent(new CustomEvent(name, Object.assign(customOpts, options)));
};
11 changes: 3 additions & 8 deletions packages/browser/sifrr-dom/src/dom/keyed.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/* eslint-disable max-lines */
const { makeEqual } = require('./makeequal');
import { makeEqual } from './makeequal';

// Inspired from https://github.com/Freak613/stage0/blob/master/reconcile.js
// This is almost straightforward implementation of reconcillation algorithm
Expand All @@ -11,7 +11,7 @@ const { makeEqual } = require('./makeequal');
// How this implementation differs from others, is that it's working with data directly,
// without maintaining nodes arrays, and manipulates dom only when required

function makeChildrenEqualKeyed(parent, newData, createFn, key) {
export function makeChildrenEqualKeyed(parent, newData, createFn, key) {
const newL = newData.length,
oldL = parent.childNodes.length;

Expand Down Expand Up @@ -188,7 +188,7 @@ function makeChildrenEqualKeyed(parent, newData, createFn, key) {
// https://github.com/adamhaile/surplus/blob/master/src/runtime/content.ts#L368

// return an array of the indices of ns that comprise the longest increasing subsequence within ns
function longestPositiveIncreasingSubsequence(ns, newStart) {
export function longestPositiveIncreasingSubsequence(ns, newStart) {
let seq = [],
is = [],
l = -1,
Expand Down Expand Up @@ -236,8 +236,3 @@ function findGreatestIndexLEQ(seq, n) {

return lo;
}

module.exports = {
makeChildrenEqualKeyed,
longestPositiveIncreasingSubsequence
};
24 changes: 9 additions & 15 deletions packages/browser/sifrr-dom/src/dom/loader.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
const template = require('./template');
import template from './template';
import config from './config';

export default class Loader {
static all = {};

class Loader {
constructor(elemName, url) {
if (!window.fetch) throw Error('Sifrr.Dom.load requires Fetch API to work.');
if (!window.fetch) throw Error('Sifrr.Dom.load requires window.fetch API to work.');
if (this.constructor.all[elemName]) return this.constructor.all[elemName];
this.elementName = elemName;
Loader.all[this.elementName] = this;
Expand All @@ -16,10 +19,8 @@ class Loader {
} else {
return (
(this._exec = this.constructor.executeJS(this.getUrl('js')).catch(e => {
window.console.error(e);
window.console.log(
`JS file for '${this.elementName}' gave error. Trying to get html file.`
);
console.error(e);
console.log(`JS file for '${this.elementName}' gave error. Trying to get html file.`);
return this.constructor.executeHTML(this.getUrl('html'), this);
})),
this._exec
Expand All @@ -29,10 +30,7 @@ class Loader {

getUrl(type = 'js') {
return (
this.url ||
`${window.Sifrr.Dom.config.baseUrl + '/'}elements/${this.elementName
.split('-')
.join('/')}.${type}`
this.url || `${config.baseUrl + '/'}elements/${this.elementName.split('-').join('/')}.${type}`
);
}

Expand Down Expand Up @@ -71,7 +69,3 @@ class Loader {
});
}
}

Loader.all = {};

module.exports = Loader;

0 comments on commit 58454fa

Please sign in to comment.