Skip to content

Commit

Permalink
test bundlers
Browse files Browse the repository at this point in the history
ganlanyuan committed Feb 8, 2017

Verified

This commit was created on GitHub.com and signed with GitHub’s verified signature. The key has expired.
1 parent 9089fba commit 034ebf5
Showing 47 changed files with 1,253 additions and 3,771 deletions.
3 changes: 3 additions & 0 deletions .babelrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"presets": ["es2015"]
}
7 changes: 7 additions & 0 deletions a.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import { multiply } from "./c";

var sum = function (a, b) {
return a + b;
};

export { sum };
5 changes: 5 additions & 0 deletions b.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import { sum } from './a';
import { multiply } from "./c";

alert(sum(1, 2));
console.log(multiply(1, 2));
16 changes: 16 additions & 0 deletions b.min.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

119 changes: 119 additions & 0 deletions bundle.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions bundle.js.map

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 5 additions & 0 deletions c.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
var multiply = function (a, b) {
return a * b;
};

export { multiply };
2,842 changes: 0 additions & 2,842 deletions dist/go-native.ie8.js

This file was deleted.

3 changes: 0 additions & 3 deletions dist/go-native.ie8.min.js

This file was deleted.

1,035 changes: 329 additions & 706 deletions dist/go-native.js

Large diffs are not rendered by default.

1 change: 1 addition & 0 deletions dist/go-native.js.map

Large diffs are not rendered by default.

2 changes: 0 additions & 2 deletions dist/go-native.min.js

This file was deleted.

1 change: 0 additions & 1 deletion dist/sourcemaps/go-native.ie8.min.js.map

This file was deleted.

1 change: 0 additions & 1 deletion dist/sourcemaps/go-native.min.js.map

This file was deleted.

6 changes: 2 additions & 4 deletions docker-compose.yml
Original file line number Diff line number Diff line change
@@ -2,15 +2,13 @@ version: '2'

services:
web:
image: cmcdev/web
image: cmcdev/web:2.1.0
ports:
- 3000:3000
# - 3001:3001
volumes:
- .:/www/web/
working_dir: /www/web
# container_name: web
# command: sh
entrypoint: sh /www/docker-start.sh
entrypoint: sh /www/start.sh
stdin_open: true
tty: true
115 changes: 60 additions & 55 deletions gulpfile.js
Original file line number Diff line number Diff line change
@@ -1,14 +1,18 @@
var config = {
sassLang: 'libsass',
const gulp = require('gulp');
const babel = require("gulp-babel");
const sourcemaps = require('gulp-sourcemaps');
const concat = require('gulp-concat');
const uglify = require('gulp-uglify');
const jshint = require('gulp-jshint');
const stylish = require('jshint-stylish');
const path = require('path');
const inject = require('gulp-inject');
const browserSync = require('browser-sync').create();
const rename = require('gulp-rename');
const mergeStream = require('merge-stream');

let config = {
sourcemaps: 'sourcemaps',
browserSync: {
server: {
baseDir: './'
},
port: '3000',
open: true,
notify: false
},

watch: {
js: 'tests/js/*.js',
@@ -52,73 +56,74 @@ var config = {
},
};

var gulp = require('gulp');
var php = require('gulp-connect-php');
var libsass = require('gulp-sass');
var rubysass = require('gulp-ruby-sass');
var sourcemaps = require('gulp-sourcemaps');
var modernizr = require('gulp-modernizr');
var concat = require('gulp-concat');
var uglify = require('gulp-uglify');
var jshint = require('gulp-jshint');
var stylish = require('jshint-stylish');
var imagemin = require('gulp-imagemin');
var svgstore = require('gulp-svgstore');
var path = require('path');
var svgmin = require('gulp-svgmin');
var svg2png = require('gulp-svg2png');
var inject = require('gulp-inject');
var browserSync = require('browser-sync').create();
var rename = require('gulp-rename');
var mergeStream = require('merge-stream');

function errorlog (error) {
console.error.bind(error);
this.emit('end');
}

// browser-sync
gulp.task('sync', function() {
browserSync.init(config.browserSync);
gulp.task('browserSync', function() {
browserSync.init({
server: {
baseDir: './'
},
port: '3000',
open: false,
notify: false
});
});

// Watch
gulp.task('watch', function () {
gulp.watch(config.js.src, ['js']);
gulp.watch('src/**/*.js', ['js']).on('change', browserSync.reload);
gulp.watch(config.watch.js).on('change', browserSync.reload);
gulp.watch(config.watch.html).on('change', browserSync.reload);
});

// JS Task
gulp.task('js', function () {
var tasks = [],
srcs = config.js.src,
names = config.js.name;
gulp.task('js', function () {
return gulp.src('src/**/*.js')
.pipe(sourcemaps.init())
.pipe(babel({
presets: ['es2015']
}))
// .pipe(concat('all.js'))
// .pipe(gulp.dest('dist'))
// .pipe(rename())
// .pipe(uglify(config.js.options[i]))
// .pipe(sourcemaps.write(config.sourcemaps))
.pipe(gulp.dest('dist'));
});
// gulp.task('js', function () {
// let tasks = [],
// srcs = config.js.src,
// names = config.js.name;

for (var i = 0; i < srcs.length; i++) {
tasks.push(
gulp.src(srcs[i])
.pipe(sourcemaps.init())
.pipe(jshint())
.pipe(jshint.reporter(stylish))
.pipe(concat(names[i]))
.on('error', errorlog)
.pipe(gulp.dest(config.js.dest))
.pipe(rename(names[i].replace('.js', '.min.js')))
.pipe(uglify(config.js.options[i]))
.pipe(sourcemaps.write(config.sourcemaps))
.pipe(gulp.dest(config.js.dest))
);
}
// for (let i = 0; i < srcs.length; i++) {
// tasks.push(
// gulp.src(srcs[i])
// .pipe(sourcemaps.init())
// .pipe(jshint())
// .pipe(jshint.reporter(stylish))
// .pipe(concat(names[i]))
// .on('error', errorlog)
// .pipe(gulp.dest(config.js.dest))
// .pipe(rename(names[i].replace('.js', '.min.js')))
// .pipe(uglify(config.js.options[i]))
// .pipe(sourcemaps.write(config.sourcemaps))
// .pipe(gulp.dest(config.js.dest))
// );
// }

return mergeStream(tasks)
.pipe(browserSync.stream());
});
// return mergeStream(tasks)
// .pipe(browserSync.stream());
// });

// Default Task
gulp.task('default', [
// 'js_min',
'js',
'sync',
'browserSync',
'watch',
]);
7 changes: 7 additions & 0 deletions rollup.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
export default {
entry: 'src/go-native.js',
dest: 'dist/go-native.js',
format: 'iife',
sourceMap: 'true',
moduleName: 'gn',
};
11 changes: 4 additions & 7 deletions src/gn/DOM.ready.js
Original file line number Diff line number Diff line change
@@ -1,16 +1,13 @@
// DOM ready
// @require "/src/gn/base.js"

gn.ready = function ( fn ) {
export var ready = function ( fn ) {

// Sanity check
if ( typeof fn !== 'function' ) { return; }
if ( typeof fn !== "function" ) { return; }

// If document is already loaded, run method
if ( document.readyState === 'complete' ) {
if ( document.readyState === "complete" ) {
return fn();
}

// Otherwise, wait until document is loaded
document.addEventListener( 'DOMContentLoaded', fn, false );
document.addEventListener( "DOMContentLoaded", fn, false );
};
11 changes: 3 additions & 8 deletions src/gn/append.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,4 @@
// append
// @require "/src/gn/base.js"
// @require "/src/gn/isNodeList.js"

gn.append = function(els, data) {
export var append = function(els, data) {
var els_new = (gn.isNodeList(els)) ? els : [els], i;

if (typeof data.nodeType !== "undefined" && data.nodeType === 1) {
@@ -11,7 +7,7 @@ gn.append = function(els, data) {
}
} else if (typeof data === "string") {
for (i = els_new.length; i--;) {
els_new[i].insertAdjacentHTML('beforeend', data);
els_new[i].insertAdjacentHTML("beforeend", data);
}
} else if (gn.isNodeList(data)) {
var fragment = document.createDocumentFragment();
@@ -22,5 +18,4 @@ gn.append = function(els, data) {
els_new[j].appendChild(fragment);
}
}
};

};
5 changes: 1 addition & 4 deletions src/gn/base.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,3 @@
// *** gn *** //
var gn = (function (g) {

// return gn
export var gn = (function (g) {
return g;
})(window.gn || {});
17 changes: 7 additions & 10 deletions src/gn/createElement.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,4 @@
// createElement
// @require "/src/gn/base.js"

gn.createElement = function(obj) {
export var createElement = function(obj) {
if (!obj || !obj.tagName) {
throw { message : "Invalid argument" };
}
@@ -34,14 +31,14 @@ gn.createElement = function(obj) {
};

// var el = gn.createElement({
// tagName: 'div',
// id: 'foo',
// className: 'foo',
// tagName: "div",
// id: "foo",
// className: "foo",
// children: [{
// tagName: 'div',
// html: '<b>Hello, creatElement</b>',
// tagName: "div",
// html: "<b>Hello, creatElement</b>",
// attributes: {
// 'am-button': 'primary'
// "am-button": "primary"
// }
// }]
// });
5 changes: 1 addition & 4 deletions src/gn/extend.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,4 @@
// extend
// @require "/src/gn/base.js"

gn.extend = function () {
export var extend = function () {
var obj, name, copy,
target = arguments[0] || {},
i = 1,
20 changes: 9 additions & 11 deletions src/gn/getClosest.js
Original file line number Diff line number Diff line change
@@ -1,30 +1,28 @@
// getClosest
// @require "/src/gn/base.js"
// @require "./bower_components/domtokenlist/src/token-list.js"
import { token_list } from "../vendors/token-list.js";

gn.getClosest = function (elem, selector) {
export var getClosest = function (elem, selector) {

var firstChar = selector.charAt(0);

// Get closest match
for ( ; elem && elem !== document; elem = elem.parentNode ) {

// If selector is a class
if ( firstChar === '.' ) {
if ( firstChar === "." ) {
if ( elem.classList.contains( selector.substr(1) ) ) {
return elem;
}
}

// If selector is an ID
if ( firstChar === '#' ) {
if ( firstChar === "#" ) {
if ( elem.id === selector.substr(1) ) {
return elem;
}
}

// If selector is a data attribute
if ( firstChar === '[' ) {
if ( firstChar === "[" ) {
if ( elem.hasAttribute( selector.substr(1, selector.length - 2) ) ) {
return elem;
}
@@ -41,7 +39,7 @@ gn.getClosest = function (elem, selector) {

};

// var elem = document.querySelector('#some-element');
// var closest = getClosest(elem, '.some-class');
// var closestLink = getClosest(elem, 'a');
// var closestExcludingElement = getClosest(elem.parentNode, '.some-class');
// var elem = document.querySelector("#some-element");
// var closest = getClosest(elem, ".some-class");
// var closestLink = getClosest(elem, "a");
// var closestExcludingElement = getClosest(elem.parentNode, ".some-class");
32 changes: 14 additions & 18 deletions src/gn/getHeight.js
Original file line number Diff line number Diff line change
@@ -1,25 +1,21 @@
// getHeight
// @require "/src/gn/base.js"
// @require "/bower_components/Units/Length.js"
// 1. outer size: content + padding + border + margin //

// 2. offset size: content + padding + border //
// el.offsetWidth
// el.offsetHeight

// 3. client size: content + padding
// el.clientWidth
// el.clientHeight
import { Length } from "../vendors/Length.js";

// 4. size: content

gn.getHeight = function (el) {
export var getHeight = function (el) {
var pattern = /\d/, // check if value contains digital number
height = el.clientHeight,
style = el.currentStyle || getComputedStyle(el),
paddingTop = (pattern.exec(style.paddingTop) === null) ? '0px' : style.paddingTop,
paddingBottom = (pattern.exec(style.paddingBottom) === null) ? '0px' : style.paddingBottom;
paddingTop = (pattern.exec(style.paddingTop) === null) ? "0px" : style.paddingTop,
paddingBottom = (pattern.exec(style.paddingBottom) === null) ? "0px" : style.paddingBottom;

height -= (parseInt(Length.toPx(el, paddingTop)) + parseInt(Length.toPx(el, paddingBottom)));
return height;
};
};

// 1. outer size: content + padding + border + margin //
// 2. offset size: content + padding + border //
// el.offsetWidth
// el.offsetHeight
// 3. client size: content + padding
// el.clientWidth
// el.clientHeight
// 4. size: content
5 changes: 1 addition & 4 deletions src/gn/getOffsetLeft.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,4 @@
// getOffsetLeft
// @require "/src/gn/base.js"

gn.getOffsetLeft = function (el) {
export var getOffsetLeft = function (el) {
var rect = el.getBoundingClientRect(),
left = rect.left + document.body.scrollLeft;
return Math.round(left);
5 changes: 1 addition & 4 deletions src/gn/getOffsetTop.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,4 @@
// getOffsetTop
// @require "/src/gn/base.js"

gn.getOffsetTop = function (el) {
export var getOffsetTop = function (el) {
var rect = el.getBoundingClientRect(),
top = rect.top + document.body.scrollTop;
return Math.round(top);
7 changes: 3 additions & 4 deletions src/gn/getOuterHeight.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
// getOuterHeight
// @require "/src/gn/base.js"
// @require "/bower_components/Units/Length.js"
import { Length } from "../vendors/Length.js";

gn.getOuterHeight = function (el) {
export var getOuterHeight = function (el) {
var pattern = /\d/, // check if value contains digital number
height = el.offsetHeight,
style = el.currentStyle || getComputedStyle(el),
@@ -13,6 +11,7 @@ gn.getOuterHeight = function (el) {
return height;
};

// 1. outer size: content + padding + border + margin //
// 2. offset size: content + padding + border //
// el.offsetWidth
// el.offsetHeight
9 changes: 3 additions & 6 deletions src/gn/getOuterWidth.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,6 @@
// getOuterWidth
// @require "/src/gn/base.js"
// @require "/bower_components/Units/Length.js"
// 1. outer size: content + padding + border + margin //
import { Length } from "../vendors/Length.js";

gn.getOuterWidth = function (el) {
export var getOuterWidth = function (el) {
var pattern = /\d/, // check if value contains digital number
width = el.offsetWidth,
style = el.currentStyle || getComputedStyle(el),
@@ -14,10 +11,10 @@ gn.getOuterWidth = function (el) {
return width;
};

// 1. outer size: content + padding + border + margin //
// 2. offset size: content + padding + border //
// el.offsetWidth
// el.offsetHeight

// 3. client size: content + padding
// el.clientWidth
// el.clientHeight
6 changes: 2 additions & 4 deletions src/gn/getParents.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
// getParents
// @require "/src/gn/base.js"
// @require "./bower_components/domtokenlist/src/token-list.js"
import { token_list } from "../vendors/token-list.js";

gn.getParents = function (elem, selector) {
export var getParents = function (elem, selector) {

var parents = [];
if ( selector ) {
6 changes: 2 additions & 4 deletions src/gn/getParentsUntil.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
// getParentsUntil
// @require "/src/gn/base.js"
// @require "./bower_components/domtokenlist/src/token-list.js"
import { token_list } from "../vendors/token-list.js";

gn.getParentsUntil = function (elem, parent, selector) {
export var getParentsUntil = function (elem, parent, selector) {

var parents = [];
if ( parent ) {
9 changes: 2 additions & 7 deletions src/gn/getSiblings.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,4 @@
// getSiblings
// @require "/src/gn/base.js"

gn.getSiblings = function (elem) {
export var getSiblings = function (elem) {
var siblings = [];
var sibling = elem.parentNode.firstChild;
for ( ; sibling; sibling = sibling.nextSibling ) {
@@ -13,6 +10,4 @@ gn.getSiblings = function (elem) {
};

// var elem = document.querySelector('#some-element');
// var siblings = getSiblings(elem);


// var siblings = getSiblings(elem);
5 changes: 1 addition & 4 deletions src/gn/getSupportedProp.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,4 @@
// get supported property
// @require "/src/gn/base.js"

gn.getSupportedProp = function (proparray){
export var getSupportedProp = function (proparray){
var root = document.documentElement;
for (var i=0; i<proparray.length; i++){
if (proparray[i] in root.style){
29 changes: 13 additions & 16 deletions src/gn/getWidth.js
Original file line number Diff line number Diff line change
@@ -1,19 +1,6 @@
// getWidth
// @require "/src/gn/base.js"
// @require "/bower_components/Units/Length.js"
// 1. outer size: content + padding + border + margin //
import { Length } from "../vendors/Length.js";

// 2. offset size: content + padding + border //
// el.offsetWidth
// el.offsetHeight

// 3. client size: content + padding
// el.clientWidth
// el.clientHeight

// 4. size: content

gn.getWidth = function (el) {
export var getWidth = function (el) {
var pattern = /\d/, // check if value contains digital number
width = el.clientWidth,
style = el.currentStyle || getComputedStyle(el),
@@ -22,4 +9,14 @@ gn.getWidth = function (el) {

width -= (parseInt(Length.toPx(el, paddingLeft)) + parseInt(Length.toPx(el, paddingRight)));
return width;
};
};

// 1. outer size: content + padding + border + margin
// 2. offset size: content + padding + border
// el.offsetWidth
// el.offsetHeight

// 3. client size: content + padding
// el.clientWidth
// el.clientHeight
// 4. size: content
5 changes: 1 addition & 4 deletions src/gn/indexOf.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,4 @@
// indexOf
// @require "/src/gn/base.js"

gn.indexOf = function (array, item) {
export var indexOf = function (array, item) {
for (var i = 0; i < array.length; i++) {
if (array[i] === item) { return i; }
}
5 changes: 1 addition & 4 deletions src/gn/isInViewport.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,4 @@
// isInViewport
// @require "/src/gn/base.js"

gn.isInViewport = function ( elem ) {
export var isInViewport = function ( elem ) {
var rect = elem.getBoundingClientRect();
return (
rect.bottom > 0 &&
9 changes: 3 additions & 6 deletions src/gn/isNodeList.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,4 @@
// isNodeList
// @require "/src/gn/base.js"

gn.isNodeList = function (el) {
export var isNodeList = function (el) {
// Only NodeList has the "item()" function
return typeof el.item !== 'undefined';
};
return typeof el.item !== "undefined";
};
9 changes: 4 additions & 5 deletions src/gn/optimizedResize.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
// optimizedResize
// https://developer.mozilla.org/en-US/docs/Web/Events/resize#requestAnimationFrame
// @require "/src/gn/base.js"
// @require "/src/es5/arrays/forEach.js"
// @require "/src/ie8/addEventListener.js"

gn.optimizedResize = (function() {
import "../es5/array/forEach.js";
import "../ie8/addEventListener.js";

export var optimizedResize = (function() {

var callbacks = [],
running = false;
6 changes: 1 addition & 5 deletions src/gn/prepend.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,4 @@
// prepend
// @require "/src/gn/base.js"
// @require "/src/gn/isNodeList.js"

gn.prepend = function(els, data) {
export var prepend = function(els, data) {
var els_new = (gn.isNodeList(els)) ? els : [els], i;

if (typeof data.nodeType !== "undefined" && data.nodeType === 1) {
6 changes: 1 addition & 5 deletions src/gn/unwrap.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,4 @@
// unwrap
// @require "/src/gn/base.js"
// @require "/src/gn/isNodeList.js"

gn.unwrap = function (els) {
export var unwrap = function (els) {
var elsNew = (gn.isNodeList(els)) ? els : [els];
for (var i = elsNew.length; i--;) {
var el = elsNew[i];
9 changes: 2 additions & 7 deletions src/gn/wrap.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,4 @@
// wrap
// @require "/src/gn/base.js"
// @require "/src/gn/isNodeList.js"

gn.wrap = function (els, obj) {
export var wrap = function (els, obj) {
var elsNew = (gn.isNodeList(els)) ? els : [els];
// Loops backwards to prevent having to clone the wrapper on the
// first element (see `wrapper` below).
@@ -26,5 +22,4 @@ gn.wrap = function (els, obj) {
parent.appendChild(wrapper);
}
}
};

};
8 changes: 2 additions & 6 deletions src/gn/wrapAll.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,4 @@
// wrapAll
// @require "/src/gn/base.js"

gn.wrapAll = function (els, wrapper) {
export var wrapAll = function (els, wrapper) {
// Cache the current parent and sibling of the first element.
var el = els.length ? els[0] : els,
parent = el.parentNode,
@@ -22,5 +19,4 @@ gn.wrapAll = function (els, wrapper) {
} else {
parent.appendChild(wrapper);
}
};

};
Empty file added src/go-native.ie8.js
Empty file.
51 changes: 51 additions & 0 deletions src/go-native.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import { isNodeList } from "./gn/isNodeList";
import { append } from "./gn/append";
import { createElement } from "./gn/createElement";
import { ready } from "./gn/dom.ready";
import { extend } from "./gn/extend";
import { getClosest } from "./gn/getClosest";
import { getHeight } from "./gn/getHeight";
import { getOffsetLeft } from "./gn/getOffsetLeft";
import { getOffsetTop } from "./gn/getOffsetTop";
import { getOuterHeight } from "./gn/getOuterHeight";
import { getOuterWidth } from "./gn/getOuterWidth";
import { getParents } from "./gn/getParents";
import { getParentsUntil } from "./gn/getParentsUntil";
import { getSiblings } from "./gn/getSiblings";
import { getSupportedProp } from "./gn/getSupportedProp";
import { getWidth } from "./gn/getWidth";
import { indexOf } from "./gn/indexOf";
import { isInViewport } from "./gn/isInViewport";
import { optimizedResize } from "./gn/optimizedResize";
import { prepend } from "./gn/prepend";
import { unwrap } from "./gn/unwrap";
import { wrap } from "./gn/wrap";
import { wrapAll } from "./gn/wrapAll";

export var gn = (function (g) {
g.isNodeList = isNodeList;
g.append = append;
g.createElement = createElement;
g.ready = ready;
g.extend = extend;
g.getClosest = getClosest;
g.getHeight = getHeight;
g.getOffsetLeft = getOffsetLeft;
g.getOffsetTop = getOffsetTop;
g.getOuterHeight = getOuterHeight;
g.getOuterWidth = getOuterWidth;
g.getParents = getParents;
g.getParentsUntil = getParentsUntil;
g.getSiblings = getSiblings;
g.getSupportedProp = getSupportedProp;
g.getWidth = getWidth;
g.indexOf = indexOf;
g.isInViewport = isInViewport;
g.optimizedResize = optimizedResize;
g.prepend = prepend;
g.unwrap = unwrap;
g.wrap = wrap;
g.wrapAll = wrapAll;

return g;
})(window.gn || {});
143 changes: 143 additions & 0 deletions src/vendors/Length.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,143 @@
// create a test element
var testElem = document.createElement('test'),
docElement = document.documentElement,
defaultView = document.defaultView,
getComputedStyle = defaultView && defaultView.getComputedStyle,
computedValueBug,
runit = /^(-?[\d+\.\-]+)([a-z]+|%)$/i,
convert = {},
conversions = [1 / 25.4, 1 / 2.54, 1 / 72, 1 / 6],
units = ['mm', 'cm', 'pt', 'pc', 'in', 'mozmm'],
i = 6; // units.length

// add the test element to the dom
docElement.appendChild(testElem);

// test for the WebKit getComputedStyle bug
// @see http://bugs.jquery.com/ticket/10639
if (getComputedStyle) {
// add a percentage margin and measure it
testElem.style.marginTop = '1%';
computedValueBug = getComputedStyle(testElem).marginTop === '1%';
}

// pre-calculate absolute unit conversions
while (i--) {
convert[units[i] + "toPx"] = conversions[i] ? conversions[i] * convert.inToPx : toPx(testElem, '1' + units[i]);
}

// remove the test element from the DOM and delete it
docElement.removeChild(testElem);
testElem = undefined;

// convert a value to pixels
function toPx(elem, value, prop, force) {
// use width as the default property, or specify your own
prop = prop || 'width';

var style,
inlineValue,
ret,
unit = (value.match(runit) || [])[2],
conversion = unit === 'px' ? 1 : convert[unit + 'toPx'],
rem = /r?em/i;

if (conversion || rem.test(unit) && !force) {
// calculate known conversions immediately
// find the correct element for absolute units or rem or fontSize + em or em
elem = conversion ? elem : unit === 'rem' ? docElement : prop === 'fontSize' ? elem.parentNode || elem : elem;

// use the pre-calculated conversion or fontSize of the element for rem and em
conversion = conversion || parseFloat(curCSS(elem, 'fontSize'));

// multiply the value by the conversion
ret = parseFloat(value) * conversion;
} else {
// begin "the awesome hack by Dean Edwards"
// @see http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291

// remember the current style
style = elem.style;
inlineValue = style[prop];

// set the style on the target element
try {
style[prop] = value;
} catch (e) {
// IE 8 and below throw an exception when setting unsupported units
return 0;
}

// read the computed value
// if style is nothing we probably set an unsupported unit
ret = !style[prop] ? 0 : parseFloat(curCSS(elem, prop));

// reset the style back to what it was or blank it out
style[prop] = inlineValue !== undefined ? inlineValue : null;
}

// return a number
return ret;
}

// return the computed value of a CSS property
function curCSS(elem, prop) {
var value,
pixel,
unit,
rvpos = /^top|bottom/,
outerProp = ["paddingTop", "paddingBottom", "borderTop", "borderBottom"],
innerHeight,
parent,
i = 4; // outerProp.length

if (getComputedStyle) {
// FireFox, Chrome/Safari, Opera and IE9+
value = getComputedStyle(elem)[prop];
} else if (pixel = elem.style['pixel' + prop.charAt(0).toUpperCase() + prop.slice(1)]) {
// IE and Opera support pixel shortcuts for top, bottom, left, right, height, width
// WebKit supports pixel shortcuts only when an absolute unit is used
value = pixel + 'px';
} else if (prop === 'fontSize') {
// correct IE issues with font-size
// @see http://bugs.jquery.com/ticket/760
value = toPx(elem, '1em', 'left', 1) + 'px';
} else {
// IE 8 and below return the specified style
value = elem.currentStyle[prop];
}

// check the unit
unit = (value.match(runit) || [])[2];
if (unit === '%' && computedValueBug) {
// WebKit won't convert percentages for top, bottom, left, right, margin and text-indent
if (rvpos.test(prop)) {
// Top and bottom require measuring the innerHeight of the parent.
innerHeight = (parent = elem.parentNode || elem).offsetHeight;
while (i--) {
innerHeight -= parseFloat(curCSS(parent, outerProp[i]));
}
value = parseFloat(value) / 100 * innerHeight + 'px';
} else {
// This fixes margin, left, right and text-indent
// @see https://bugs.webkit.org/show_bug.cgi?id=29084
// @see http://bugs.jquery.com/ticket/10639
value = toPx(elem, value);
}
} else if ((value === 'auto' || (unit && unit !== 'px')) && getComputedStyle) {
// WebKit and Opera will return auto in some cases
// Firefox will pass back an unaltered value when it can't be set, like top on a static element
value = 0;
} else if (unit && unit !== 'px' && !getComputedStyle) {
// IE 8 and below won't convert units for us
// try to convert using a prop that will return pixels
// this will be accurate for everything (except font-size and some percentages)
value = toPx(elem, value) + 'px';
}
return value;
}

// expose the conversion function to the window object
export var Length = {
toPx: toPx
};
26 changes: 26 additions & 0 deletions src/vendors/requestAnimationFrame.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
'use strict';

if (!Date.now) {
Date.now = function() { return new Date().getTime(); };
}


var vendors = ['webkit', 'moz'];
for (var i = 0; i < vendors.length && !window.requestAnimationFrame; ++i) {
var vp = vendors[i];
window.requestAnimationFrame = window[vp+'RequestAnimationFrame'];
window.cancelAnimationFrame = (window[vp+'CancelAnimationFrame']
|| window[vp+'CancelRequestAnimationFrame']);
}
if (/iP(ad|hone|od).*OS 6/.test(window.navigator.userAgent) // iOS6 is buggy
|| !window.requestAnimationFrame || !window.cancelAnimationFrame) {
var lastTime = 0;
window.requestAnimationFrame = function(callback) {
var now = Date.now();
var nextTime = Math.max(lastTime + 16, now);
return setTimeout(function() { callback(lastTime = nextTime); }, nextTime - now);
};
window.cancelAnimationFrame = clearTimeout;
}
// (function() {
// }());
352 changes: 352 additions & 0 deletions src/vendors/token-list.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,352 @@
export function token_list(){
"use strict";

/*<*/
var UNDEF,
WIN = window,
DOC = document,
OBJ = Object,
NULL = null,
TRUE = true,
FALSE = false,
/*>*/

/** Munge the hell out of our string literals. Saves a tonne of space after compression. */
SPACE = " ",
ELEMENT = "Element",
CREATE_ELEMENT = "create"+ELEMENT,
DOM_TOKEN_LIST = "DOMTokenList",
DEFINE_GETTER = "__defineGetter__",
DEFINE_PROPERTY = "defineProperty",
CLASS_ = "class",
LIST = "List",
CLASS_LIST = CLASS_+LIST,
REL = "rel",
REL_LIST = REL+LIST,
DIV = "div",
LENGTH = "length",
CONTAINS = "contains",
APPLY = "apply",
HTML_ = "HTML",
METHODS = ("item "+CONTAINS+" add remove toggle toString toLocaleString").split(SPACE),
ADD = METHODS[2],
REMOVE = METHODS[3],
TOGGLE = METHODS[4],
PROTOTYPE = "prototype",



/** Ascertain browser support for Object.defineProperty */
dpSupport = DEFINE_PROPERTY in OBJ || DEFINE_GETTER in OBJ[ PROTOTYPE ] || NULL,


/** Wrapper for Object.defineProperty that falls back to using the legacy __defineGetter__ method if available. */
defineGetter = function(object, name, fn, configurable){
if(OBJ[ DEFINE_PROPERTY ])
OBJ[ DEFINE_PROPERTY ](object, name, {
configurable: FALSE === dpSupport ? TRUE : !!configurable,
get: fn
});

else object[ DEFINE_GETTER ](name, fn);
},




/** DOMTokenList interface replacement */
DOMTokenList = function(el, prop){
var THIS = this,

/** Private variables */
tokens = [],
tokenMap = {},
length = 0,
maxLength = 0,


reindex = function(){

/** Define getter functions for array-like access to the tokenList's contents. */
if(length >= maxLength)
for(; maxLength < length; ++maxLength) (function(i){

defineGetter(THIS, i, function(){
preop();
return tokens[i];
}, FALSE);

})(maxLength);
},



/** Helper function called at the start of each class method. Internal use only. */
preop = function(){
var error, i,
args = arguments,
rSpace = /\s+/;

/** Validate the token/s passed to an instance method, if any. */
if(args[ LENGTH ])
for(i = 0; i < args[ LENGTH ]; ++i)
if(rSpace.test(args[i])){
error = new SyntaxError('String "' + args[i] + '" ' + CONTAINS + ' an invalid character');
error.code = 5;
error.name = "InvalidCharacterError";
throw error;
}


/** Split the new value apart by whitespace*/
tokens = ("" + el[prop]).replace(/^\s+|\s+$/g, "").split(rSpace);

/** Avoid treating blank strings as single-item token lists */
if("" === tokens[0]) tokens = [];

/** Repopulate the internal token lists */
tokenMap = {};
for(i = 0; i < tokens[ LENGTH ]; ++i)
tokenMap[tokens[i]] = TRUE;
length = tokens[ LENGTH ];
reindex();
};



/** Populate our internal token list if the targeted attribute of the subject element isn't empty. */
preop();



/** Return the number of tokens in the underlying string. Read-only. */
defineGetter(THIS, LENGTH, function(){
preop();
return length;
});


/** Override the default toString/toLocaleString methods to return a space-delimited list of tokens when typecast. */
THIS[ METHODS[6] /** toLocaleString */ ] =
THIS[ METHODS[5] /** toString */ ] = function(){
preop();
return tokens.join(SPACE);
};



/** Return an item in the list by its index (or undefined if the number is greater than or equal to the length of the list) */
THIS.item = function(idx){
preop();
return tokens[idx];
};


/** Return TRUE if the underlying string contains `token`; otherwise, FALSE. */
THIS[ CONTAINS ] = function(token){
preop();
return !!tokenMap[token];
};



/** Add one or more tokens to the underlying string. */
THIS[ADD] = function(){
preop[APPLY](THIS, args = arguments);

for(var args, token, i = 0, l = args[ LENGTH ]; i < l; ++i){
token = args[i];
if(!tokenMap[token]){
tokens.push(token);
tokenMap[token] = TRUE;
}
}

/** Update the targeted attribute of the attached element if the token list's changed. */
if(length !== tokens[ LENGTH ]){
length = tokens[ LENGTH ] >>> 0;
el[prop] = tokens.join(SPACE);
reindex();
}
};



/** Remove one or more tokens from the underlying string. */
THIS[ REMOVE ] = function(){
preop[APPLY](THIS, args = arguments);

/** Build a hash of token names to compare against when recollecting our token list. */
for(var args, ignore = {}, i = 0, t = []; i < args[ LENGTH ]; ++i){
ignore[args[i]] = TRUE;
delete tokenMap[args[i]];
}

/** Run through our tokens list and reassign only those that aren't defined in the hash declared above. */
for(i = 0; i < tokens[ LENGTH ]; ++i)
if(!ignore[tokens[i]]) t.push(tokens[i]);

tokens = t;
length = t[ LENGTH ] >>> 0;

/** Update the targeted attribute of the attached element. */
el[prop] = tokens.join(SPACE);
reindex();
};



/** Add or remove a token depending on whether it's already contained within the token list. */
THIS[TOGGLE] = function(token, force){
preop[APPLY](THIS, [token]);

/** Token state's being forced. */
if(UNDEF !== force){
if(force) { THIS[ADD](token); return TRUE; }
else { THIS[REMOVE](token); return FALSE; }
}

/** Token already exists in tokenList. Remove it, and return FALSE. */
if(tokenMap[token]){
THIS[ REMOVE ](token);
return FALSE;
}

/** Otherwise, add the token and return TRUE. */
THIS[ADD](token);
return TRUE;
};


/** Mark our newly-assigned methods as non-enumerable. */
(function(o, defineProperty){
if(defineProperty)
for(var i = 0; i < 7; ++i)
defineProperty(o, METHODS[i], {enumerable: FALSE});
}(THIS, OBJ[ DEFINE_PROPERTY ]));

return THIS;
},



/** Polyfills a property with a DOMTokenList */
addProp = function(o, name, attr){

defineGetter(o[PROTOTYPE], name, function(){
var tokenList,
THIS = this,

/** Prevent this from firing twice for some reason. What the hell, IE. */
gibberishProperty = DEFINE_GETTER + DEFINE_PROPERTY + name;
if(THIS[gibberishProperty]) return tokenList;
THIS[gibberishProperty] = TRUE;


/**
* IE8 can't define properties on native JavaScript objects, so we'll use a dumb hack instead.
*
* What this is doing is creating a dummy element ("reflection") inside a detached phantom node ("mirror")
* that serves as the target of Object.defineProperty instead. While we could simply use the subject HTML
* element instead, this would conflict with element types which use indexed properties (such as forms and
* select lists).
*/
if(FALSE === dpSupport){

var visage,
mirror = addProp.mirror = addProp.mirror || DOC[ CREATE_ELEMENT ](DIV),
reflections = mirror.childNodes,

/** Iterator variables */
l = reflections[ LENGTH ],
i = 0;

for(; i < l; ++i)
if(reflections[i]._R === THIS){
visage = reflections[i];
break;
}

/** Couldn't find an element's reflection inside the mirror. Materialise one. */
visage || (visage = mirror.appendChild(DOC[ CREATE_ELEMENT ](DIV)));

tokenList = DOMTokenList.call(visage, THIS, attr);
}

else tokenList = new DOMTokenList(THIS, attr);


defineGetter(THIS, name, function(){ return tokenList; });
delete THIS[gibberishProperty];

return tokenList;
}, TRUE);
},

/** Variables used for patching native methods that're partially implemented (IE doesn't support adding/removing multiple tokens, for instance). */
testList,
nativeAdd,
nativeRemove;




/** No discernible DOMTokenList support whatsoever. Time to remedy that. */
if(!WIN[ DOM_TOKEN_LIST ]){

/** Ensure the browser allows Object.defineProperty to be used on native JavaScript objects. */
if(dpSupport)
try{ defineGetter({}, "support"); }
catch(e){ dpSupport = FALSE; }


DOMTokenList.polyfill = TRUE;
WIN[ DOM_TOKEN_LIST ] = DOMTokenList;

addProp( WIN[ ELEMENT ], CLASS_LIST, CLASS_ + "Name"); /* Element.classList */
addProp( WIN[ HTML_+ "Link" + ELEMENT ], REL_LIST, REL); /* HTMLLinkElement.relList */
addProp( WIN[ HTML_+ "Anchor" + ELEMENT ], REL_LIST, REL); /* HTMLAnchorElement.relList */
addProp( WIN[ HTML_+ "Area" + ELEMENT ], REL_LIST, REL); /* HTMLAreaElement.relList */
}


/**
* Possible support, but let's check for bugs.
*
* Where arbitrary values are needed for performing a test, previous variables
* are recycled to save space in the minified file.
*/
else{
testList = DOC[ CREATE_ELEMENT ](DIV)[CLASS_LIST];

/** We'll replace a "string constant" to hold a reference to DOMTokenList.prototype (filesize optimisation, yaddah-yaddah...) */
PROTOTYPE = WIN[DOM_TOKEN_LIST][PROTOTYPE];


/** Check if we can pass multiple arguments to add/remove. To save space, we'll just recycle a previous array of strings. */
testList[ADD][APPLY](testList, METHODS);
if(2 > testList[LENGTH]){
nativeAdd = PROTOTYPE[ADD];
nativeRemove = PROTOTYPE[REMOVE];

PROTOTYPE[ADD] = function(){
for(var i = 0, args = arguments; i < args[LENGTH]; ++i)
nativeAdd.call(this, args[i]);
};

PROTOTYPE[REMOVE] = function(){
for(var i = 0, args = arguments; i < args[LENGTH]; ++i)
nativeRemove.call(this, args[i]);
};
}


/** Check if the "force" option of .toggle is supported. */
if(testList[TOGGLE](LIST, FALSE))
PROTOTYPE[TOGGLE] = function(token, force){
var THIS = this;
THIS[(force = UNDEF === force ? !THIS[CONTAINS](token) : force) ? ADD : REMOVE](token);
return !!force;
};
}
};
44 changes: 44 additions & 0 deletions webpack.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
const path = require('path');
const webpack = require('webpack');
// const ExtractTextPlugin = require('extract-text-webpack-plugin');

const PATHS = {
src: path.join(__dirname, 'src'),
dist: path.join(__dirname, 'dist')
};

module.exports = {
devtool: 'source-map',
entry: ['./src/go-native.js'],
output: {
path: PATHS.dist,
filename: 'go-native.js'
},

module: {
rules: [
{
test: /\.js$/,
include: path.join(__dirname, 'src'),
exclude: /node_modules/,
loader: 'babel-loader',
query: {
presets: ['es2015']
}
}
]
},

// postcss: [
// require('autoprefixer')
// ],

plugins: [
new webpack.optimize.OccurrenceOrderPlugin(),
// new webpack.optimize.UglifyJsPlugin(),
// new ExtractTextPlugin({
// filename: '/css/[name].css',
// allChunks: true,
// })
]
};

0 comments on commit 034ebf5

Please sign in to comment.