code stringlengths 2 1.05M |
|---|
function switchid(id){
hideallids();
showdiv(id);
}
function hideallids(){
//loop through the array and hide each element by id
for (var i=0;i<ids.length;i++){
hidediv(ids[i]);
}
}
function hidediv(id) {
//safe function to hide an element with a specified id
document.getElementById(id).style.display = 'none';
}
function showdiv(id) {
//safe function to show an element with a specified id
document.getElementById(id).style.display = 'block';
}
function printMarkdownSource() {
hidediv("source");
var view = document.getElementById("view");
var source = document.getElementById("source");
view.innerHTML = markdown.toHTML(source.innerHTML);
console.log(source.innerHTML);
}
if (window.addEventListener) {
window.addEventListener("load", printMarkdownSource, false);
} else if (window.attachEvent) {
window.attachEvent("onload", printMarkdownSource);
} else {
window.onload = printMarkdownSource;
}
|
function Ball() {
// ball id
this.ballId = 'B_'+Math.floor(Math.random() * 100000000);
// at first - we pick the direction randomlly -
// there are 4 possible directions (1,2,3,4)
// 1: up left, 2: up right, 3: down right, 4: down left
this.direction = Math.floor(Math.random() * 2) + 1;
// ball speed
this.ballSpeed = 1;
// ball size
this.ballSize = 15; // in px
// ball interval
this.ballInterval = undefined;
// ball class name
this.ballClass = 'ball';
// init the ball
this.init();
}
Ball.prototype.init = function() {
this.appendBall();
}
Ball.prototype.getBall = function() {
return document.getElementById(this.ballId);
}
Ball.prototype.appendBall = function() {
var b = document.createElement('div');
b.setAttribute('id',this.ballId);
b.setAttribute('class',this.ballClass);
document.body.appendChild(b);
}
Ball.prototype.move = function() {
var that = this;
that.ballInterval = setInterval(function() {
switch (that.direction) {
case 1:
that.getBall().style.left = that.getBall().offsetLeft - that.ballSpeed + 'px';
that.getBall().style.top = that.getBall().offsetTop - that.ballSpeed + 'px';
break;
case 2:
that.getBall().style.left = that.getBall().offsetLeft + that.ballSpeed + 'px';
that.getBall().style.top = that.getBall().offsetTop - that.ballSpeed + 'px';
break;
case 3:
that.getBall().style.left = that.getBall().offsetLeft + that.ballSpeed + 'px';
that.getBall().style.top = that.getBall().offsetTop + that.ballSpeed + 'px';
break;
case 4:
that.getBall().style.left = that.getBall().offsetLeft - that.ballSpeed + 'px';
that.getBall().style.top = that.getBall().offsetTop + that.ballSpeed + 'px';
break;
}
},1);
}
Ball.prototype.stop = function() {
clearInterval(this.ballInterval);
} |
"use babel";
export default class MrBookmarkView {
constructor() {
this.element = document.createElement("div");
this.element.classList.add("mr-bookmark-panel");
this.link = document.createElement("a");
this.link.classList.add("add-button");
const lineH = document.createElement("span");
const lineV = document.createElement("span");
lineH.classList.add("line-hor");
lineV.classList.add("line-ver");
this.link.appendChild(lineH);
this.link.appendChild(lineV);
this.element.appendChild(this.link);
this.fileContainer = document.createElement("div");
this.element.appendChild(this.fileContainer);
}
getFileContainer() {
return this.fileContainer;
}
destroy() {
this.element.remove();
}
getAddButton() {
return this.link;
}
getElement() {
return this.element;
}
}
|
/**
* Copyright (c) 2014,Egret-Labs.org
* All rights reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the Egret-Labs.org nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY EGRET-LABS.ORG AND CONTRIBUTORS "AS IS" AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL EGRET-LABS.ORG AND CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
var __extends = this.__extends || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
__.prototype = b.prototype;
d.prototype = new __();
};
var egret;
(function (egret) {
var gui;
(function (gui) {
/**
* @class egret.gui.SkinnableContainer
* @classdesc
* 可设置外观的容器的基类
* @extends egret.gui.SkinnableComponent
* @implements egret.gui.IVisualElementContainer
*/
var SkinnableContainer = (function (_super) {
__extends(SkinnableContainer, _super);
/**
* @method egret.gui.SkinnableContainer#constructor
*/
function SkinnableContainer() {
_super.call(this);
/**
* contentGroup发生改变时传递的参数
*/
this.contentGroupProperties = {};
}
/**
* 获取当前的实体容器
*/
SkinnableContainer.prototype._getCurrentContentGroup = function () {
if (this.contentGroup == null) {
if (this._placeHolderGroup == null) {
this._placeHolderGroup = new gui.Group();
this._placeHolderGroup.visible = false;
this._addToDisplayList(this._placeHolderGroup);
}
this._placeHolderGroup.addEventListener(gui.ElementExistenceEvent.ELEMENT_ADD, this._contentGroup_elementAddedHandler, this);
this._placeHolderGroup.addEventListener(gui.ElementExistenceEvent.ELEMENT_REMOVE, this._contentGroup_elementRemovedHandler, this);
return this._placeHolderGroup;
}
else {
return this.contentGroup;
}
};
Object.defineProperty(SkinnableContainer.prototype, "elementsContent", {
/**
* 设置容器子对象数组 。数组包含要添加到容器的子项列表,之前的已存在于容器中的子项列表被全部移除后添加列表里的每一项到容器。
* 设置该属性时会对您输入的数组进行一次浅复制操作,所以您之后对该数组的操作不会影响到添加到容器的子项列表数量。
*/
set: function (value) {
this._getCurrentContentGroup().elementsContent = value;
},
enumerable: true,
configurable: true
});
Object.defineProperty(SkinnableContainer.prototype, "numElements", {
/**
*/
get: function () {
return this._getCurrentContentGroup().numElements;
},
enumerable: true,
configurable: true
});
/**
* @param index {number}
* @returns {IVisualElement}
*/
SkinnableContainer.prototype.getElementAt = function (index) {
return this._getCurrentContentGroup().getElementAt(index);
};
/**
* @param element {IVisualElement}
* @returns {IVisualElement}
*/
SkinnableContainer.prototype.addElement = function (element) {
return this._getCurrentContentGroup().addElement(element);
};
/**
* @param element {IVisualElement}
* @param index {number}
* @returns {IVisualElement}
*/
SkinnableContainer.prototype.addElementAt = function (element, index) {
return this._getCurrentContentGroup().addElementAt(element, index);
};
/**
* @param element {IVisualElement}
* @returns {IVisualElement}
*/
SkinnableContainer.prototype.removeElement = function (element) {
return this._getCurrentContentGroup().removeElement(element);
};
/**
* @param index {number}
* @returns {IVisualElement}
*/
SkinnableContainer.prototype.removeElementAt = function (index) {
return this._getCurrentContentGroup().removeElementAt(index);
};
/**
*/
SkinnableContainer.prototype.removeAllElements = function () {
this._getCurrentContentGroup().removeAllElements();
};
/**
* @param element {IVisualElement}
* @returns {number}
*/
SkinnableContainer.prototype.getElementIndex = function (element) {
return this._getCurrentContentGroup().getElementIndex(element);
};
/**
* @param element {IVisualElement}
* @param index {number}
*/
SkinnableContainer.prototype.setElementIndex = function (element, index) {
this._getCurrentContentGroup().setElementIndex(element, index);
};
/**
* @param element1 {IVisualElement}
* @param element2 {IVisualElement}
*/
SkinnableContainer.prototype.swapElements = function (element1, element2) {
this._getCurrentContentGroup().swapElements(element1, element2);
};
/**
* @param index1 {number}
* @param index2 {number}
*/
SkinnableContainer.prototype.swapElementsAt = function (index1, index2) {
this._getCurrentContentGroup().swapElementsAt(index1, index2);
};
Object.defineProperty(SkinnableContainer.prototype, "layout", {
/**
* 此容器的布局对象
* @member egret.gui.SkinnableContainer#layout
*/
get: function () {
return this.contentGroup != null ? this.contentGroup.layout : this.contentGroupProperties.layout;
},
set: function (value) {
if (this.contentGroup != null) {
this.contentGroup.layout = value;
}
else {
this.contentGroupProperties.layout = value;
}
},
enumerable: true,
configurable: true
});
/**
* @param partName {string}
* @param instance {any}
*/
SkinnableContainer.prototype.partAdded = function (partName, instance) {
_super.prototype.partAdded.call(this, partName, instance);
if (instance == this.contentGroup) {
if (this.contentGroupProperties.layout !== undefined) {
this.contentGroup.layout = this.contentGroupProperties.layout;
this.contentGroupProperties = {};
}
if (this._placeHolderGroup) {
this._placeHolderGroup.removeEventListener(gui.ElementExistenceEvent.ELEMENT_ADD, this._contentGroup_elementAddedHandler, this);
this._placeHolderGroup.removeEventListener(gui.ElementExistenceEvent.ELEMENT_REMOVE, this._contentGroup_elementRemovedHandler, this);
var sourceContent = this._placeHolderGroup._getElementsContent().concat();
for (var i = this._placeHolderGroup.numElements; i > 0; i--) {
var element = this._placeHolderGroup.removeElementAt(0);
element.ownerChanged(null);
}
this._removeFromDisplayList(this._placeHolderGroup);
this.contentGroup.elementsContent = sourceContent;
for (i = sourceContent.length - 1; i >= 0; i--) {
element = sourceContent[i];
element.ownerChanged(this);
}
this._placeHolderGroup = null;
}
this.contentGroup.addEventListener(gui.ElementExistenceEvent.ELEMENT_ADD, this._contentGroup_elementAddedHandler, this);
this.contentGroup.addEventListener(gui.ElementExistenceEvent.ELEMENT_REMOVE, this._contentGroup_elementRemovedHandler, this);
}
};
/**
* @param partName {string}
* @param instance {any}
*/
SkinnableContainer.prototype.partRemoved = function (partName, instance) {
_super.prototype.partRemoved.call(this, partName, instance);
if (instance == this.contentGroup) {
this.contentGroup.removeEventListener(gui.ElementExistenceEvent.ELEMENT_ADD, this._contentGroup_elementAddedHandler, this);
this.contentGroup.removeEventListener(gui.ElementExistenceEvent.ELEMENT_REMOVE, this._contentGroup_elementRemovedHandler, this);
this.contentGroupProperties.layout = this.contentGroup.layout;
this.contentGroup.layout = null;
if (this.contentGroup.numElements > 0) {
this._placeHolderGroup = new gui.Group;
while (this.contentGroup.numElements > 0) {
this._placeHolderGroup.addElement(this.contentGroup.getElementAt(0));
}
this._placeHolderGroup.addEventListener(gui.ElementExistenceEvent.ELEMENT_ADD, this._contentGroup_elementAddedHandler, this);
this._placeHolderGroup.addEventListener(gui.ElementExistenceEvent.ELEMENT_REMOVE, this._contentGroup_elementRemovedHandler, this);
}
}
};
/**
* 容器添加元素事件
*/
SkinnableContainer.prototype._contentGroup_elementAddedHandler = function (event) {
event.element.ownerChanged(this);
this.dispatchEvent(event);
};
/**
* 容器移除元素事件
*/
SkinnableContainer.prototype._contentGroup_elementRemovedHandler = function (event) {
event.element.ownerChanged(null);
this.dispatchEvent(event);
};
return SkinnableContainer;
})(gui.SkinnableComponent);
gui.SkinnableContainer = SkinnableContainer;
SkinnableContainer.prototype.__class__ = "egret.gui.SkinnableContainer";
})(gui = egret.gui || (egret.gui = {}));
})(egret || (egret = {}));
|
"use strict"
import mongoose from 'mongoose';
import util from 'util';
// config should be imported before importing any other file
import config from './config/config';
import app from './config/express';
const debug = require('debug')('express-mongoose-es6-rest-api:index');
// make bluebird default Promise
Promise = require('bluebird'); // eslint-disable-line no-global-assign
// plugin bluebird promise in mongoose
mongoose.Promise = Promise;
// connect to mongo db
const mongoUri = `${config.mongo.host}:${config.mongo.port}`;
mongoose.connect(mongoUri, { server: { socketOptions: { keepAlive: 1 } } });
mongoose.connection.on('error', () => {
throw new Error(`unable to connect to database: ${config.db}`);
});
// print mongoose logs in dev env
if (config.MONGOOSE_DEBUG) {
mongoose.set('debug', (collectionName, method, query, doc) => {
debug(`${collectionName}.${method}`, util.inspect(query, false, 20), doc);
});
}
// module.parent check is required to support mocha watch
// src: https://github.com/mochajs/mocha/issues/1912
if (!module.parent) {
// listen on port config.port
app.listen(config.port, () => {
debug(`server started on port ${config.port} (${config.env})`);
});
}
export default app;
|
import {
simpleHandlerBuilder,
transformFilter, handlerBundle
} from '../lib/export.js'
import chai from 'chai'
import chaiAsPromised from 'chai-as-promised'
chai.use(chaiAsPromised)
const should = chai.should()
describe('bundle component test', () => {
const bundle = handlerBundle(
config => {
let count = config.initial || 0
const getCount = args => ''+count
const increment = args => ++count
const decrement = args => --count
return { getCount, increment, decrement }
})
.simpleHandler('getCount', 'void', 'text')
.simpleHandler('increment', 'void', 'void')
.simpleHandler('decrement', 'void', 'void')
const {
getCount, increment, decrement
} = bundle.toHandlerComponents()
it('basic test', async function() {
const config = { }
const getCountHandler = await getCount.loadHandler(config)
const incrementHandler = await increment.loadHandler(config)
const decrementHandler = await decrement.loadHandler(config)
await getCountHandler({}).should.eventually.equal('0')
await incrementHandler({})
await getCountHandler({}).should.eventually.equal('1')
await incrementHandler({})
await getCountHandler({}).should.eventually.equal('2')
await decrementHandler({})
await getCountHandler({}).should.eventually.equal('1')
await decrementHandler({})
await getCountHandler({}).should.eventually.equal('0')
})
it('initialize test', async function() {
const config = {
initial: 2
}
const incrementHandler = await increment.loadHandler(config)
config.initial = 4
const getCountHandler = await getCount.loadHandler(config)
await getCountHandler({}).should.eventually.equal('2')
})
it('bundle fork test', async function() {
const bundle2 = bundle.fork()
const {
getCount: getCount2,
increment: increment2
} = bundle2.toHandlerComponents()
const config = { }
const getCountHandler = await getCount.loadHandler(config)
const incrementHandler = await increment.loadHandler(config)
const getCountHandler2 = await getCount2.loadHandler(config)
const incrementHandler2 = await increment2.loadHandler(config)
await getCountHandler({}).should.eventually.equal('0')
await getCountHandler2({}).should.eventually.equal('0')
await incrementHandler({})
await getCountHandler({}).should.eventually.equal('1')
await getCountHandler2({}).should.eventually.equal('0')
await incrementHandler({})
await getCountHandler({}).should.eventually.equal('2')
await getCountHandler2({}).should.eventually.equal('0')
await incrementHandler2({})
await getCountHandler({}).should.eventually.equal('2')
await getCountHandler2({}).should.eventually.equal('1')
})
it('privatized test', async function() {
const forkTable = { }
const getCount2 = getCount.fork(forkTable)
const increment2 = increment.fork(forkTable)
const config = { }
const getCountHandler = await getCount.loadHandler(config)
const incrementHandler = await increment.loadHandler(config)
const getCountHandler2 = await getCount2.loadHandler(config)
const incrementHandler2 = await increment2.loadHandler(config)
await getCountHandler({}).should.eventually.equal('0')
await getCountHandler2({}).should.eventually.equal('0')
await incrementHandler({})
await getCountHandler({}).should.eventually.equal('1')
await getCountHandler2({}).should.eventually.equal('0')
await incrementHandler({})
await getCountHandler({}).should.eventually.equal('2')
await getCountHandler2({}).should.eventually.equal('0')
await incrementHandler2({})
await getCountHandler({}).should.eventually.equal('2')
await getCountHandler2({}).should.eventually.equal('1')
})
it('forked middleware test', async function() {
const prefixer = simpleHandlerBuilder(config => {
const prefix = config.prefix || ''
return (args, text) => prefix + '-' + text
}, 'text', 'text')
const prefixFilter = transformFilter(prefixer, 'out')
const bundle2 = bundle.fork()
const {
getCount: getCount2,
increment: increment2
} = bundle2.toHandlerComponents()
getCount2.addMiddleware(prefixFilter)
const forkTable = {}
const getCount3 = getCount2.fork(forkTable)
const increment3 = increment2.fork(forkTable)
const config = {
prefix: 'foo'
}
const getCountHandler2 = await getCount2.loadHandler(config)
const incrementHandler2 = await increment2.loadHandler(config)
config.prefix = 'bar'
const getCountHandler3 = await getCount3.loadHandler(config)
const incrementHandler3 = await increment3.loadHandler(config)
await getCountHandler2({}).should.eventually.equal('foo-0')
await getCountHandler3({}).should.eventually.equal('bar-0')
await incrementHandler2({})
await getCountHandler2({}).should.eventually.equal('foo-1')
await getCountHandler3({}).should.eventually.equal('bar-0')
await incrementHandler2({})
await getCountHandler2({}).should.eventually.equal('foo-2')
await getCountHandler3({}).should.eventually.equal('bar-0')
await incrementHandler3({})
await getCountHandler2({}).should.eventually.equal('foo-2')
await getCountHandler3({}).should.eventually.equal('bar-1')
})
})
|
import { h, resolveComponent, openBlock, createBlock, normalizeStyle, withKeys, withCtx, createElementBlock, withDirectives, createElementVNode, withModifiers, vModelText, createCommentVNode, Fragment, renderList, toDisplayString, normalizeClass, renderSlot } from 'vue';
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign#Polyfill
function assign(target, varArgs) {
var arguments$1 = arguments;
if (target === null || target === undefined) {
throw new TypeError('Cannot convert undefined or null to object')
}
var to = Object(target);
for (var index = 1; index < arguments.length; index++) {
var nextSource = arguments$1[index];
if (nextSource !== null && nextSource !== undefined) {
for (var nextKey in nextSource) {
// Avoid bugs when hasOwnProperty is shadowed
/* istanbul ignore else */
if (Object.prototype.hasOwnProperty.call(nextSource, nextKey)) {
to[nextKey] = nextSource[nextKey];
}
}
}
}
return to
}
function isExist(obj) {
return typeof obj !== 'undefined' && obj !== null
}
function isBoolean(obj) {
return typeof obj === 'boolean'
}
var defaultLang = {
uiv: {
datePicker: {
clear: 'Clear',
today: 'Today',
month: 'Month',
month1: 'January',
month2: 'February',
month3: 'March',
month4: 'April',
month5: 'May',
month6: 'June',
month7: 'July',
month8: 'August',
month9: 'September',
month10: 'October',
month11: 'November',
month12: 'December',
year: 'Year',
week1: 'Mon',
week2: 'Tue',
week3: 'Wed',
week4: 'Thu',
week5: 'Fri',
week6: 'Sat',
week7: 'Sun',
},
timePicker: {
am: 'AM',
pm: 'PM',
},
modal: {
cancel: 'Cancel',
ok: 'OK',
},
multiSelect: {
placeholder: 'Select...',
filterPlaceholder: 'Search...',
},
},
};
var lang = defaultLang;
var i18nHandler = function () {
if ('$t' in this) {
return this.$t.apply(this, arguments)
}
return null
};
var t = function (path, options) {
options = options || {};
var value;
try {
value = i18nHandler.apply(this, arguments);
/* istanbul ignore next */
if (isExist(value) && !options.$$locale) {
return value
}
} catch (e) {
// ignore
}
var array = path.split('.');
var current = options.$$locale || lang;
for (var i = 0, j = array.length; i < j; i++) {
var property = array[i];
value = current[property];
if (i === j - 1) { return value }
if (!value) { return '' }
current = value;
}
/* istanbul ignore next */
return ''
};
var Local = {
methods: {
t: function t$1() {
var arguments$1 = arguments;
var args = [];
for (var i = 0; i < arguments.length; ++i) {
args.push(arguments$1[i]);
}
args[1] = assign({}, { $$locale: this.locale }, args[1]);
return t.apply(this, args)
},
},
props: {
locale: Object,
},
};
function onlyUnique(value, index, self) {
return self.indexOf(value) === index
}
var EVENTS = {
MOUSE_ENTER: 'mouseenter',
MOUSE_LEAVE: 'mouseleave',
MOUSE_DOWN: 'mousedown',
MOUSE_UP: 'mouseup',
FOCUS: 'focus',
BLUR: 'blur',
CLICK: 'click',
INPUT: 'input',
KEY_DOWN: 'keydown',
KEY_UP: 'keyup',
KEY_PRESS: 'keypress',
RESIZE: 'resize',
SCROLL: 'scroll',
TOUCH_START: 'touchstart',
TOUCH_END: 'touchend',
};
function on(element, event, handler) {
/* istanbul ignore next */
element.addEventListener(event, handler);
}
function off(element, event, handler) {
/* istanbul ignore next */
element.removeEventListener(event, handler);
}
function isElement(el) {
return el && el.nodeType === Node.ELEMENT_NODE
}
function setDropdownPosition(dropdown, trigger, options) {
if ( options === void 0 ) options = {};
var doc = document.documentElement;
var containerScrollLeft =
(window.pageXOffset || doc.scrollLeft) - (doc.clientLeft || 0);
var containerScrollTop =
(window.pageYOffset || doc.scrollTop) - (doc.clientTop || 0);
var rect = trigger.getBoundingClientRect();
var dropdownRect = dropdown.getBoundingClientRect();
dropdown.style.right = 'auto';
dropdown.style.bottom = 'auto';
if (options.menuRight) {
dropdown.style.left =
containerScrollLeft + rect.left + rect.width - dropdownRect.width + 'px';
} else {
dropdown.style.left = containerScrollLeft + rect.left + 'px';
}
if (options.dropup) {
dropdown.style.top =
containerScrollTop + rect.top - dropdownRect.height - 4 + 'px';
} else {
dropdown.style.top = containerScrollTop + rect.top + rect.height + 'px';
}
}
function focus(el) {
if (!isElement(el)) {
return
}
el.getAttribute('tabindex') ? null : el.setAttribute('tabindex', '-1');
el.focus();
}
var DEFAULT_TAG = 'div';
var script$1 = {
props: {
tag: {
type: String,
default: DEFAULT_TAG,
},
appendToBody: {
type: Boolean,
default: false,
},
modelValue: Boolean,
dropup: {
type: Boolean,
default: false,
},
menuRight: {
type: Boolean,
default: false,
},
disabled: {
type: Boolean,
default: false,
},
notCloseElements: { type: Array, default: function () { return []; } },
positionElement: { type: null, default: undefined },
},
emits: ['update:modelValue'],
data: function data() {
return {
show: false,
triggerEl: undefined,
}
},
watch: {
modelValue: function modelValue(v) {
this.toggle(v);
},
},
mounted: function mounted() {
this.initTrigger();
if (this.triggerEl) {
on(this.triggerEl, EVENTS.CLICK, this.toggle);
on(this.triggerEl, EVENTS.KEY_DOWN, this.onKeyPress);
}
on(this.$refs.dropdown, EVENTS.KEY_DOWN, this.onKeyPress);
on(window, EVENTS.CLICK, this.windowClicked);
on(window, EVENTS.TOUCH_END, this.windowClicked);
if (this.modelValue) {
this.toggle(true);
}
},
beforeUnmount: function beforeUnmount() {
this.removeDropdownFromBody();
if (this.triggerEl) {
off(this.triggerEl, EVENTS.CLICK, this.toggle);
off(this.triggerEl, EVENTS.KEY_DOWN, this.onKeyPress);
}
off(this.$refs.dropdown, EVENTS.KEY_DOWN, this.onKeyPress);
off(window, EVENTS.CLICK, this.windowClicked);
off(window, EVENTS.TOUCH_END, this.windowClicked);
},
methods: {
getFocusItem: function getFocusItem() {
var dropdownEl = this.$refs.dropdown;
return dropdownEl.querySelector('li > a:focus')
},
onKeyPress: function onKeyPress(event) {
if (this.show) {
var dropdownEl = this.$refs.dropdown;
var keyCode = event.keyCode;
if (keyCode === 27) {
// esc
this.toggle(false);
this.triggerEl && this.triggerEl.focus();
} else if (keyCode === 13) {
// enter
var currentFocus = this.getFocusItem();
currentFocus && currentFocus.click();
} else if (keyCode === 38 || keyCode === 40) {
// up || down
event.preventDefault();
event.stopPropagation();
var currentFocus$1 = this.getFocusItem();
var items = dropdownEl.querySelectorAll('li:not(.disabled) > a');
if (!currentFocus$1) {
focus(items[0]);
} else {
for (var i = 0; i < items.length; i++) {
if (currentFocus$1 === items[i]) {
if (keyCode === 38 && i < items.length > 0) {
focus(items[i - 1]);
} else if (keyCode === 40 && i < items.length - 1) {
focus(items[i + 1]);
}
break
}
}
}
}
}
},
initTrigger: function initTrigger() {
var trigger =
this.$el.querySelector('[data-role="trigger"]') ||
this.$el.querySelector('.dropdown-toggle') ||
this.$el.firstChild;
this.triggerEl =
trigger && trigger !== this.$refs.dropdown ? trigger : null;
},
toggle: function toggle(show) {
if (this.disabled) {
return
}
if (isBoolean(show)) {
this.show = show;
} else {
this.show = !this.show;
}
if (this.appendToBody) {
this.show ? this.appendDropdownToBody() : this.removeDropdownFromBody();
}
this.$emit('update:modelValue', this.show);
},
windowClicked: function windowClicked(event) {
var target = event.target;
if (this.show && target) {
var targetInNotCloseElements = false;
if (this.notCloseElements) {
for (var i = 0, l = this.notCloseElements.length; i < l; i++) {
var isTargetInElement = this.notCloseElements[i].contains(target);
var shouldBreak = isTargetInElement;
/* istanbul ignore else */
if (this.appendToBody) {
var isTargetInDropdown = this.$refs.dropdown.contains(target);
var isElInElements =
this.notCloseElements.indexOf(this.$el) >= 0;
shouldBreak =
isTargetInElement || (isTargetInDropdown && isElInElements);
}
if (shouldBreak) {
targetInNotCloseElements = true;
break
}
}
}
var targetInDropdownBody = this.$refs.dropdown.contains(target);
var targetInTrigger =
this.$el.contains(target) && !targetInDropdownBody;
// normally, a dropdown select event is handled by @click that trigger after @touchend
// then @touchend event have to be ignore in this case
var targetInDropdownAndIsTouchEvent =
targetInDropdownBody && event.type === 'touchend';
if (
!targetInTrigger &&
!targetInNotCloseElements &&
!targetInDropdownAndIsTouchEvent
) {
this.toggle(false);
}
}
},
appendDropdownToBody: function appendDropdownToBody() {
try {
var el = this.$refs.dropdown;
el.style.display = 'block';
document.body.appendChild(el);
var positionElement = this.positionElement || this.$el;
setDropdownPosition(el, positionElement, this);
} catch (e) {
// Silent
}
},
removeDropdownFromBody: function removeDropdownFromBody() {
try {
var el = this.$refs.dropdown;
el.removeAttribute('style');
this.$el.appendChild(el);
} catch (e) {
// Silent
}
},
},
render: function render() {
return h(
this.tag,
{
class: {
'btn-group': this.tag === DEFAULT_TAG,
dropdown: !this.dropup,
dropup: this.dropup,
open: this.show,
},
},
[
this.$slots.default && this.$slots.default(),
h(
'ul',
{
class: {
'dropdown-menu': true,
'dropdown-menu-right': this.menuRight,
},
ref: 'dropdown',
},
[this.$slots.dropdown && this.$slots.dropdown()]
) ]
)
},
};
script$1.__file = "src/components/dropdown/Dropdown.vue";
var script = {
components: { Dropdown: script$1 },
mixins: [Local],
props: {
modelValue: {
type: Array,
required: true,
},
options: {
type: Array,
required: true,
},
labelKey: {
type: String,
default: 'label',
},
valueKey: {
type: String,
default: 'value',
},
limit: {
type: Number,
default: 0,
},
size: { type: String, default: undefined },
placeholder: { type: String, default: undefined },
split: {
type: String,
default: ', ',
},
disabled: {
type: Boolean,
default: false,
},
appendToBody: {
type: Boolean,
default: false,
},
block: {
type: Boolean,
default: false,
},
collapseSelected: {
type: Boolean,
default: false,
},
filterable: {
type: Boolean,
default: false,
},
filterAutoFocus: {
type: Boolean,
default: true,
},
filterFunction: { type: Function, default: undefined },
filterPlaceholder: { type: String, default: undefined },
selectedIcon: {
type: String,
default: 'glyphicon glyphicon-ok',
},
itemSelectedClass: { type: String, default: undefined },
},
emits: [
'focus',
'blur',
'visible-change',
'update:modelValue',
'change',
'limit-exceed',
'search' ],
data: function data() {
return {
showDropdown: false,
els: [],
filterInput: '',
currentActive: -1,
}
},
computed: {
containerStyles: function containerStyles() {
return {
width: this.block ? '100%' : '',
}
},
filteredOptions: function filteredOptions() {
var this$1$1 = this;
if (this.filterable && this.filterInput) {
if (this.filterFunction) {
return this.filterFunction(this.filterInput)
} else {
var filterInput = this.filterInput.toLowerCase();
return this.options.filter(
function (v) { return v[this$1$1.valueKey].toString().toLowerCase().indexOf(filterInput) >=
0 ||
v[this$1$1.labelKey].toString().toLowerCase().indexOf(filterInput) >=
0; }
)
}
} else {
return this.options
}
},
groupedOptions: function groupedOptions() {
var this$1$1 = this;
return this.filteredOptions
.map(function (v) { return v.group; })
.filter(onlyUnique)
.map(function (v) { return ({
options: this$1$1.filteredOptions.filter(function (option) { return option.group === v; }),
$group: v,
}); })
},
flattenGroupedOptions: function flattenGroupedOptions() {
var ref;
return (ref = []).concat.apply(ref, this.groupedOptions.map(function (v) { return v.options; }))
},
selectClasses: function selectClasses() {
var obj;
return ( obj = {}, obj[("input-" + (this.size))] = this.size, obj )
},
selectedIconClasses: function selectedIconClasses() {
var obj;
return ( obj = {}, obj[this.selectedIcon] = true, obj['pull-right'] = true, obj )
},
selectTextClasses: function selectTextClasses() {
return {
'text-muted': this.modelValue.length === 0,
}
},
labelValue: function labelValue() {
var this$1$1 = this;
var optionsByValue = this.options.map(function (v) { return v[this$1$1.valueKey]; });
return this.modelValue.map(function (v) {
var index = optionsByValue.indexOf(v);
return index >= 0 ? this$1$1.options[index][this$1$1.labelKey] : v
})
},
selectedText: function selectedText() {
if (this.modelValue.length) {
var labelValue = this.labelValue;
if (this.collapseSelected) {
var str = labelValue[0];
str +=
labelValue.length > 1
? ((this.split) + "+" + (labelValue.length - 1))
: '';
return str
} else {
return labelValue.join(this.split)
}
} else {
return this.placeholder || this.t('uiv.multiSelect.placeholder')
}
},
customOptionsVisible: function customOptionsVisible() {
return !!this.$slots.option || !!this.$slots.option
},
},
watch: {
showDropdown: function showDropdown(v) {
var this$1$1 = this;
// clear filter input when dropdown toggles
this.filterInput = '';
this.currentActive = -1;
this.$emit('visible-change', v);
if (v && this.filterable && this.filterAutoFocus) {
this.$nextTick(function () {
this$1$1.$refs.filterInput.focus();
});
}
},
},
mounted: function mounted() {
this.els = [this.$el];
},
methods: {
goPrevOption: function goPrevOption() {
if (!this.showDropdown) {
return
}
this.currentActive > 0
? this.currentActive--
: (this.currentActive = this.flattenGroupedOptions.length - 1);
},
goNextOption: function goNextOption() {
if (!this.showDropdown) {
return
}
this.currentActive < this.flattenGroupedOptions.length - 1
? this.currentActive++
: (this.currentActive = 0);
},
selectOption: function selectOption() {
var index = this.currentActive;
var options = this.flattenGroupedOptions;
if (!this.showDropdown) {
this.showDropdown = true;
} else if (index >= 0 && index < options.length) {
this.toggle(options[index]);
}
},
itemClasses: function itemClasses(item) {
var result = {
disabled: item.disabled,
active: this.currentActive === this.flattenGroupedOptions.indexOf(item),
};
if (this.itemSelectedClass) {
result[this.itemSelectedClass] = this.isItemSelected(item);
}
return result
},
isItemSelected: function isItemSelected(item) {
return this.modelValue.indexOf(item[this.valueKey]) >= 0
},
toggle: function toggle(item) {
if (item.disabled) {
return
}
var value = item[this.valueKey];
var index = this.modelValue.indexOf(value);
if (this.limit === 1) {
var newValue = index >= 0 ? [] : [value];
this.$emit('update:modelValue', newValue);
this.$emit('change', newValue);
} else {
if (index >= 0) {
var newVal = this.modelValue.slice();
newVal.splice(index, 1);
this.$emit('update:modelValue', newVal);
this.$emit('change', newVal);
} else if (this.limit === 0 || this.modelValue.length < this.limit) {
var newVal$1 = this.modelValue.slice();
newVal$1.push(value);
this.$emit('update:modelValue', newVal$1);
this.$emit('change', newVal$1);
} else {
this.$emit('limit-exceed');
}
}
},
searchClicked: function searchClicked() {
this.$emit('search', this.filterInput);
},
},
};
var _hoisted_1 = ["disabled"];
var _hoisted_2 = /*#__PURE__*/createElementVNode("div", {
class: "pull-right",
style: {"display":"inline-block","vertical-align":"middle"}
}, [
/*#__PURE__*/createElementVNode("span", null, " "),
/*#__PURE__*/createElementVNode("span", { class: "caret" })
], -1 /* HOISTED */);
var _hoisted_3 = ["textContent"];
var _hoisted_4 = {
key: 0,
style: {"padding":"4px 8px"}
};
var _hoisted_5 = ["placeholder"];
var _hoisted_6 = ["textContent"];
var _hoisted_7 = ["onClick"];
var _hoisted_8 = {
key: 0,
role: "button",
style: {"outline":"0"}
};
var _hoisted_9 = {
key: 1,
role: "button",
style: {"outline":"0"}
};
var _hoisted_10 = {
key: 2,
role: "button",
style: {"outline":"0"}
};
function render(_ctx, _cache, $props, $setup, $data, $options) {
var _component_dropdown = resolveComponent("dropdown");
return (openBlock(), createBlock(_component_dropdown, {
ref: "dropdown",
modelValue: $data.showDropdown,
"onUpdate:modelValue": _cache[14] || (_cache[14] = function ($event) { return (($data.showDropdown) = $event); }),
"not-close-elements": $data.els,
"append-to-body": $props.appendToBody,
disabled: $props.disabled,
style: normalizeStyle($options.containerStyles),
onKeydown: _cache[15] || (_cache[15] = withKeys(function ($event) { return ($data.showDropdown = false); }, ["esc"]))
}, {
dropdown: withCtx(function () { return [
($props.filterable)
? (openBlock(), createElementBlock("li", _hoisted_4, [
withDirectives(createElementVNode("input", {
ref: "filterInput",
"onUpdate:modelValue": _cache[5] || (_cache[5] = function ($event) { return (($data.filterInput) = $event); }),
"aria-label": "Filter...",
class: "form-control input-sm",
type: "text",
placeholder:
$props.filterPlaceholder || _ctx.t('uiv.multiSelect.filterPlaceholder')
,
onKeyup: _cache[6] || (_cache[6] = withKeys(function () {
var args = [], len = arguments.length;
while ( len-- ) args[ len ] = arguments[ len ];
return ($options.searchClicked && $options.searchClicked.apply($options, args));
}, ["enter"])),
onKeydown: [
_cache[7] || (_cache[7] = withKeys(withModifiers(function () {
var args = [], len = arguments.length;
while ( len-- ) args[ len ] = arguments[ len ];
return ($options.goNextOption && $options.goNextOption.apply($options, args));
}, ["prevent","stop"]), ["down"])),
_cache[8] || (_cache[8] = withKeys(withModifiers(function () {
var args = [], len = arguments.length;
while ( len-- ) args[ len ] = arguments[ len ];
return ($options.goPrevOption && $options.goPrevOption.apply($options, args));
}, ["prevent","stop"]), ["up"])),
_cache[9] || (_cache[9] = withKeys(withModifiers(function () {
var args = [], len = arguments.length;
while ( len-- ) args[ len ] = arguments[ len ];
return ($options.selectOption && $options.selectOption.apply($options, args));
}, ["prevent","stop"]), ["enter"]))
]
}, null, 40 /* PROPS, HYDRATE_EVENTS */, _hoisted_5), [
[vModelText, $data.filterInput]
])
]))
: createCommentVNode("v-if", true),
(openBlock(true), createElementBlock(Fragment, null, renderList($options.groupedOptions, function (item, i) {
return (openBlock(), createElementBlock(Fragment, null, [
(item.$group)
? (openBlock(), createElementBlock("li", {
key: i,
class: "dropdown-header",
textContent: toDisplayString(item.$group)
}, null, 8 /* PROPS */, _hoisted_6))
: createCommentVNode("v-if", true),
(openBlock(true), createElementBlock(Fragment, null, renderList(item.options, function (_item, j) {
return (openBlock(), createElementBlock("li", {
key: (i + "_" + j),
class: normalizeClass($options.itemClasses(_item)),
style: {"outline":"0"},
onKeydown: [
_cache[10] || (_cache[10] = withKeys(withModifiers(function () {
var args = [], len = arguments.length;
while ( len-- ) args[ len ] = arguments[ len ];
return ($options.goNextOption && $options.goNextOption.apply($options, args));
}, ["prevent","stop"]), ["down"])),
_cache[11] || (_cache[11] = withKeys(withModifiers(function () {
var args = [], len = arguments.length;
while ( len-- ) args[ len ] = arguments[ len ];
return ($options.goPrevOption && $options.goPrevOption.apply($options, args));
}, ["prevent","stop"]), ["up"])),
_cache[12] || (_cache[12] = withKeys(withModifiers(function () {
var args = [], len = arguments.length;
while ( len-- ) args[ len ] = arguments[ len ];
return ($options.selectOption && $options.selectOption.apply($options, args));
}, ["prevent","stop"]), ["enter"]))
],
onClick: withModifiers(function ($event) { return ($options.toggle(_item, $event)); }, ["stop"]),
onMouseenter: _cache[13] || (_cache[13] = function ($event) { return ($data.currentActive = -1); })
}, [
($options.customOptionsVisible)
? (openBlock(), createElementBlock("a", _hoisted_8, [
renderSlot(_ctx.$slots, "option", { item: _item }),
($props.selectedIcon && $options.isItemSelected(_item))
? (openBlock(), createElementBlock("span", {
key: 0,
class: normalizeClass($options.selectedIconClasses)
}, null, 2 /* CLASS */))
: createCommentVNode("v-if", true)
]))
: ($options.isItemSelected(_item))
? (openBlock(), createElementBlock("a", _hoisted_9, [
createElementVNode("b", null, toDisplayString(_item[$props.labelKey]), 1 /* TEXT */),
($props.selectedIcon)
? (openBlock(), createElementBlock("span", {
key: 0,
class: normalizeClass($options.selectedIconClasses)
}, null, 2 /* CLASS */))
: createCommentVNode("v-if", true)
]))
: (openBlock(), createElementBlock("a", _hoisted_10, [
createElementVNode("span", null, toDisplayString(_item[$props.labelKey]), 1 /* TEXT */)
]))
], 42 /* CLASS, PROPS, HYDRATE_EVENTS */, _hoisted_7))
}), 128 /* KEYED_FRAGMENT */))
], 64 /* STABLE_FRAGMENT */))
}), 256 /* UNKEYED_FRAGMENT */))
]; }),
default: withCtx(function () { return [
createElementVNode("div", {
class: normalizeClass(["form-control dropdown-toggle clearfix", $options.selectClasses]),
disabled: $props.disabled ? true : undefined,
tabindex: "0",
"data-role": "trigger",
onFocus: _cache[0] || (_cache[0] = function ($event) { return (_ctx.$emit('focus', $event)); }),
onBlur: _cache[1] || (_cache[1] = function ($event) { return (_ctx.$emit('blur', $event)); }),
onKeydown: [
_cache[2] || (_cache[2] = withKeys(withModifiers(function () {
var args = [], len = arguments.length;
while ( len-- ) args[ len ] = arguments[ len ];
return ($options.goNextOption && $options.goNextOption.apply($options, args));
}, ["prevent","stop"]), ["down"])),
_cache[3] || (_cache[3] = withKeys(withModifiers(function () {
var args = [], len = arguments.length;
while ( len-- ) args[ len ] = arguments[ len ];
return ($options.goPrevOption && $options.goPrevOption.apply($options, args));
}, ["prevent","stop"]), ["up"])),
_cache[4] || (_cache[4] = withKeys(withModifiers(function () {
var args = [], len = arguments.length;
while ( len-- ) args[ len ] = arguments[ len ];
return ($options.selectOption && $options.selectOption.apply($options, args));
}, ["prevent","stop"]), ["enter"]))
]
}, [
_hoisted_2,
createElementVNode("div", {
class: normalizeClass($options.selectTextClasses),
style: {"overflow-x":"hidden","text-overflow":"ellipsis","white-space":"nowrap"},
textContent: toDisplayString($options.selectedText)
}, null, 10 /* CLASS, PROPS */, _hoisted_3)
], 42 /* CLASS, PROPS, HYDRATE_EVENTS */, _hoisted_1)
]; }),
_: 3 /* FORWARDED */
}, 8 /* PROPS */, ["modelValue", "not-close-elements", "append-to-body", "disabled", "style"]))
}
script.render = render;
script.__file = "src/components/select/MultiSelect.vue";
export { script as default };
//# sourceMappingURL=MultiSelect.js.map
|
/*
Copyright (c) 2015 NAVER Corp.
name: @egjs/infinitegrid
license: MIT
author: NAVER Corp.
repository: https://github.com/naver/egjs-infinitegrid
version: 4.0.0-beta.2
*/
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
typeof define === 'function' && define.amd ? define(factory) :
(global = global || self, global.InfiniteGrid = factory());
}(this, (function () { 'use strict';
/*! *****************************************************************************
Copyright (c) Microsoft Corporation.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */
/* global Reflect, Promise */
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf || {
__proto__: []
} instanceof Array && function (d, b) {
d.__proto__ = b;
} || function (d, b) {
for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p];
};
return extendStatics(d, b);
};
function __extends(d, b) {
if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
extendStatics(d, b);
function __() {
this.constructor = d;
}
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
}
var __assign = function () {
__assign = Object.assign || function __assign(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
function __rest(s, e) {
var t = {};
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p];
if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]];
}
return t;
}
function __decorate(decorators, target, key, desc) {
var c = arguments.length,
r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc,
d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
}
/** @deprecated */
function __spreadArrays() {
for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
for (var r = Array(s), k = 0, i = 0; i < il; i++) for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) r[k] = a[j];
return r;
}
/*
Copyright (c) NAVER Corp.
name: @egjs/component
license: MIT
author: NAVER Corp.
repository: https://github.com/naver/egjs-component
version: 3.0.1
*/
/*! *****************************************************************************
Copyright (c) Microsoft Corporation.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */
function __values(o) {
var s = typeof Symbol === "function" && Symbol.iterator,
m = s && o[s],
i = 0;
if (m) return m.call(o);
if (o && typeof o.length === "number") return {
next: function () {
if (o && i >= o.length) o = void 0;
return {
value: o && o[i++],
done: !o
};
}
};
throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
}
function __read(o, n) {
var m = typeof Symbol === "function" && o[Symbol.iterator];
if (!m) return o;
var i = m.call(o),
r,
ar = [],
e;
try {
while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
} catch (error) {
e = {
error: error
};
} finally {
try {
if (r && !r.done && (m = i["return"])) m.call(i);
} finally {
if (e) throw e.error;
}
}
return ar;
}
function __spread() {
for (var ar = [], i = 0; i < arguments.length; i++) ar = ar.concat(__read(arguments[i]));
return ar;
}
/*
* Copyright (c) 2015 NAVER Corp.
* egjs projects are licensed under the MIT license
*/
var isUndefined = function (value) {
return typeof value === "undefined";
};
/**
* Event class to provide additional properties
* @ko Component에서 추가적인 프로퍼티를 제공하는 이벤트 클래스
*/
var ComponentEvent =
/*#__PURE__*/
function () {
/**
* Create a new instance of ComponentEvent.
* @ko ComponentEvent의 새로운 인스턴스를 생성한다.
* @param eventType The name of the event.<ko>이벤트 이름.</ko>
* @param props An object that contains additional event properties.<ko>추가적인 이벤트 프로퍼티 오브젝트.</ko>
*/
function ComponentEvent(eventType, props) {
var e_1, _a;
this.eventType = eventType;
this._canceled = false;
if (!props) return;
try {
for (var _b = __values(Object.keys(props)), _c = _b.next(); !_c.done; _c = _b.next()) {
var key = _c.value; // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
this[key] = props[key];
}
} catch (e_1_1) {
e_1 = {
error: e_1_1
};
} finally {
try {
if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
} finally {
if (e_1) throw e_1.error;
}
}
}
/**
* Stop the event. {@link ComponentEvent#isCanceled} will return `true` after.
* @ko 이벤트를 중단한다. 이후 {@link ComponentEvent#isCanceled}가 `true`를 반환한다.
*/
var __proto = ComponentEvent.prototype;
__proto.stop = function () {
this._canceled = true;
};
/**
* Returns a boolean value that indicates whether {@link ComponentEvent#stop} is called before.
* @ko {@link ComponentEvent#stop}이 호출되었는지 여부를 반환한다.
* @return {boolean} A boolean value that indicates whether {@link ComponentEvent#stop} is called before.<ko>이전에 {@link ComponentEvent#stop}이 불려졌는지 여부를 반환한다.</ko>
*/
__proto.isCanceled = function () {
return this._canceled;
};
return ComponentEvent;
}();
/**
* A class used to manage events in a component
* @ko 컴포넌트의 이벤트을 관리할 수 있게 하는 클래스
*/
var Component =
/*#__PURE__*/
function () {
/**
* @support {"ie": "7+", "ch" : "latest", "ff" : "latest", "sf" : "latest", "edge" : "latest", "ios" : "7+", "an" : "2.1+ (except 3.x)"}
*/
function Component() {
this._eventHandler = {};
}
/**
* Trigger a custom event.
* @ko 커스텀 이벤트를 발생시킨다
* @param {string | ComponentEvent} event The name of the custom event to be triggered or an instance of the ComponentEvent<ko>발생할 커스텀 이벤트의 이름 또는 ComponentEvent의 인스턴스</ko>
* @param {any[]} params Event data to be sent when triggering a custom event <ko>커스텀 이벤트가 발생할 때 전달할 데이터</ko>
* @return An instance of the component itself<ko>컴포넌트 자신의 인스턴스</ko>
* @example
* ```ts
* import Component, { ComponentEvent } from "@egjs/component";
*
* class Some extends Component<{
* beforeHi: ComponentEvent<{ foo: number; bar: string }>;
* hi: { foo: { a: number; b: boolean } };
* someEvent: (foo: number, bar: string) => void;
* someOtherEvent: void; // When there's no event argument
* }> {
* some(){
* if(this.trigger("beforeHi")){ // When event call to stop return false.
* this.trigger("hi");// fire hi event.
* }
* }
* }
*
* const some = new Some();
* some.on("beforeHi", e => {
* if(condition){
* e.stop(); // When event call to stop, `hi` event not call.
* }
* // `currentTarget` is component instance.
* console.log(some === e.currentTarget); // true
*
* typeof e.foo; // number
* typeof e.bar; // string
* });
* some.on("hi", e => {
* typeof e.foo.b; // boolean
* });
* // If you want to more know event design. You can see article.
* // https://github.com/naver/egjs-component/wiki/How-to-make-Component-event-design%3F
* ```
*/
var __proto = Component.prototype;
__proto.trigger = function (event) {
var params = [];
for (var _i = 1; _i < arguments.length; _i++) {
params[_i - 1] = arguments[_i];
}
var eventName = event instanceof ComponentEvent ? event.eventType : event;
var handlers = __spread(this._eventHandler[eventName] || []);
if (handlers.length <= 0) {
return this;
}
if (event instanceof ComponentEvent) {
event.currentTarget = this;
handlers.forEach(function (handler) {
handler(event);
});
} else {
handlers.forEach(function (handler) {
// eslint-disable-next-line @typescript-eslint/no-unsafe-call
handler.apply(void 0, __spread(params));
});
}
return this;
};
/**
* Executed event just one time.
* @ko 이벤트가 한번만 실행된다.
* @param {string} eventName The name of the event to be attached or an event name - event handler mapped object.<ko>등록할 이벤트의 이름 또는 이벤트 이름-핸들러 오브젝트</ko>
* @param {function} handlerToAttach The handler function of the event to be attached <ko>등록할 이벤트의 핸들러 함수</ko>
* @return An instance of the component itself<ko>컴포넌트 자신의 인스턴스</ko>
* @example
* ```ts
* import Component, { ComponentEvent } from "@egjs/component";
*
* class Some extends Component<{
* hi: ComponentEvent;
* }> {
* hi() {
* alert("hi");
* }
* thing() {
* this.once("hi", this.hi);
* }
* }
*
* var some = new Some();
* some.thing();
* some.trigger(new ComponentEvent("hi"));
* // fire alert("hi");
* some.trigger(new ComponentEvent("hi"));
* // Nothing happens
* ```
*/
__proto.once = function (eventName, handlerToAttach) {
var _this = this;
if (typeof eventName === "object" && isUndefined(handlerToAttach)) {
var eventHash = eventName;
for (var key in eventHash) {
this.once(key, eventHash[key]);
}
return this;
} else if (typeof eventName === "string" && typeof handlerToAttach === "function") {
var listener_1 = function () {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
} // eslint-disable-next-line @typescript-eslint/no-unsafe-call
handlerToAttach.apply(void 0, __spread(args));
_this.off(eventName, listener_1);
};
this.on(eventName, listener_1);
}
return this;
};
/**
* Checks whether an event has been attached to a component.
* @ko 컴포넌트에 이벤트가 등록됐는지 확인한다.
* @param {string} eventName The name of the event to be attached <ko>등록 여부를 확인할 이벤트의 이름</ko>
* @return {boolean} Indicates whether the event is attached. <ko>이벤트 등록 여부</ko>
* @example
* ```ts
* import Component from "@egjs/component";
*
* class Some extends Component<{
* hi: void;
* }> {
* some() {
* this.hasOn("hi");// check hi event.
* }
* }
* ```
*/
__proto.hasOn = function (eventName) {
return !!this._eventHandler[eventName];
};
/**
* Attaches an event to a component.
* @ko 컴포넌트에 이벤트를 등록한다.
* @param {string} eventName The name of the event to be attached or an event name - event handler mapped object.<ko>등록할 이벤트의 이름 또는 이벤트 이름-핸들러 오브젝트</ko>
* @param {function} handlerToAttach The handler function of the event to be attached <ko>등록할 이벤트의 핸들러 함수</ko>
* @return An instance of a component itself<ko>컴포넌트 자신의 인스턴스</ko>
* @example
* ```ts
* import Component, { ComponentEvent } from "@egjs/component";
*
* class Some extends Component<{
* hi: void;
* }> {
* hi() {
* console.log("hi");
* }
* some() {
* this.on("hi",this.hi); //attach event
* }
* }
* ```
*/
__proto.on = function (eventName, handlerToAttach) {
if (typeof eventName === "object" && isUndefined(handlerToAttach)) {
var eventHash = eventName;
for (var name in eventHash) {
this.on(name, eventHash[name]);
}
return this;
} else if (typeof eventName === "string" && typeof handlerToAttach === "function") {
var handlerList = this._eventHandler[eventName];
if (isUndefined(handlerList)) {
this._eventHandler[eventName] = [];
handlerList = this._eventHandler[eventName];
}
handlerList.push(handlerToAttach);
}
return this;
};
/**
* Detaches an event from the component.<br/>If the `eventName` is not given this will detach all event handlers attached.<br/>If the `handlerToDetach` is not given, this will detach all event handlers for `eventName`.
* @ko 컴포넌트에 등록된 이벤트를 해제한다.<br/>`eventName`이 주어지지 않았을 경우 모든 이벤트 핸들러를 제거한다.<br/>`handlerToAttach`가 주어지지 않았을 경우 `eventName`에 해당하는 모든 이벤트 핸들러를 제거한다.
* @param {string?} eventName The name of the event to be detached <ko>해제할 이벤트의 이름</ko>
* @param {function?} handlerToDetach The handler function of the event to be detached <ko>해제할 이벤트의 핸들러 함수</ko>
* @return An instance of a component itself <ko>컴포넌트 자신의 인스턴스</ko>
* @example
* ```ts
* import Component, { ComponentEvent } from "@egjs/component";
*
* class Some extends Component<{
* hi: void;
* }> {
* hi() {
* console.log("hi");
* }
* some() {
* this.off("hi",this.hi); //detach event
* }
* }
* ```
*/
__proto.off = function (eventName, handlerToDetach) {
var e_1, _a; // Detach all event handlers.
if (isUndefined(eventName)) {
this._eventHandler = {};
return this;
} // Detach all handlers for eventname or detach event handlers by object.
if (isUndefined(handlerToDetach)) {
if (typeof eventName === "string") {
delete this._eventHandler[eventName];
return this;
} else {
var eventHash = eventName;
for (var name in eventHash) {
this.off(name, eventHash[name]);
}
return this;
}
} // Detach single event handler
var handlerList = this._eventHandler[eventName];
if (handlerList) {
var idx = 0;
try {
for (var handlerList_1 = __values(handlerList), handlerList_1_1 = handlerList_1.next(); !handlerList_1_1.done; handlerList_1_1 = handlerList_1.next()) {
var handlerFunction = handlerList_1_1.value;
if (handlerFunction === handlerToDetach) {
handlerList.splice(idx, 1);
if (handlerList.length <= 0) {
delete this._eventHandler[eventName];
}
break;
}
idx++;
}
} catch (e_1_1) {
e_1 = {
error: e_1_1
};
} finally {
try {
if (handlerList_1_1 && !handlerList_1_1.done && (_a = handlerList_1.return)) _a.call(handlerList_1);
} finally {
if (e_1) throw e_1.error;
}
}
}
return this;
};
/**
* Version info string
* @ko 버전정보 문자열
* @name VERSION
* @static
* @example
* Component.VERSION; // ex) 3.0.0
* @memberof Component
*/
Component.VERSION = "3.0.1";
return Component;
}();
/*
* Copyright (c) 2015 NAVER Corp.
* egjs projects are licensed under the MIT license
*/
var ComponentEvent$1 = ComponentEvent;
/*
Copyright (c) NAVER Corp.
name: @egjs/component
license: MIT
author: NAVER Corp.
repository: https://github.com/naver/egjs-component
version: 2.2.2
*/
/*! *****************************************************************************
Copyright (c) Microsoft Corporation.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */
function __values$1(o) {
var s = typeof Symbol === "function" && Symbol.iterator,
m = s && o[s],
i = 0;
if (m) return m.call(o);
if (o && typeof o.length === "number") return {
next: function () {
if (o && i >= o.length) o = void 0;
return {
value: o && o[i++],
done: !o
};
}
};
throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
}
/*
* Copyright (c) 2015 NAVER Corp.
* egjs projects are licensed under the MIT license
*/
function isUndefined$1(value) {
return typeof value === "undefined";
}
/**
* A class used to manage events in a component
* @ko 컴포넌트의 이벤트을 관리할 수 있게 하는 클래스
* @alias eg.Component
*/
var Component$1 =
/*#__PURE__*/
function () {
/**
* @support {"ie": "7+", "ch" : "latest", "ff" : "latest", "sf" : "latest", "edge" : "latest", "ios" : "7+", "an" : "2.1+ (except 3.x)"}
*/
function Component() {
/**
* @deprecated
* @private
*/
this.options = {};
this._eventHandler = {};
}
/**
* Triggers a custom event.
* @ko 커스텀 이벤트를 발생시킨다
* @param {string} eventName The name of the custom event to be triggered <ko>발생할 커스텀 이벤트의 이름</ko>
* @param {object} customEvent Event data to be sent when triggering a custom event <ko>커스텀 이벤트가 발생할 때 전달할 데이터</ko>
* @param {any[]} restParam Additional parameters when triggering a custom event <ko>커스텀 이벤트가 발생할 때 필요시 추가적으로 전달할 데이터</ko>
* @return Indicates whether the event has occurred. If the stop() method is called by a custom event handler, it will return false and prevent the event from occurring. <a href="https://github.com/naver/egjs-component/wiki/How-to-make-Component-event-design%3F">Ref</a> <ko>이벤트 발생 여부. 커스텀 이벤트 핸들러에서 stop() 메서드를 호출하면 'false'를 반환하고 이벤트 발생을 중단한다. <a href="https://github.com/naver/egjs-component/wiki/How-to-make-Component-event-design%3F">참고</a></ko>
* @example
* ```
* class Some extends eg.Component {
* some(){
* if(this.trigger("beforeHi")){ // When event call to stop return false.
* this.trigger("hi");// fire hi event.
* }
* }
* }
*
* const some = new Some();
* some.on("beforeHi", (e) => {
* if(condition){
* e.stop(); // When event call to stop, `hi` event not call.
* }
* });
* some.on("hi", (e) => {
* // `currentTarget` is component instance.
* console.log(some === e.currentTarget); // true
* });
* // If you want to more know event design. You can see article.
* // https://github.com/naver/egjs-component/wiki/How-to-make-Component-event-design%3F
* ```
*/
var __proto = Component.prototype;
__proto.trigger = function (eventName) {
var _this = this;
var params = [];
for (var _i = 1; _i < arguments.length; _i++) {
params[_i - 1] = arguments[_i];
}
var handlerList = this._eventHandler[eventName] || [];
var hasHandlerList = handlerList.length > 0;
if (!hasHandlerList) {
return true;
}
var customEvent = params[0] || {};
var restParams = params.slice(1); // If detach method call in handler in first time then handler list calls.
handlerList = handlerList.concat();
var isCanceled = false; // This should be done like this to pass previous tests
customEvent.eventType = eventName;
customEvent.stop = function () {
isCanceled = true;
};
customEvent.currentTarget = this;
var arg = [customEvent];
if (restParams.length >= 1) {
arg = arg.concat(restParams);
}
handlerList.forEach(function (handler) {
handler.apply(_this, arg);
});
return !isCanceled;
};
/**
* Executed event just one time.
* @ko 이벤트가 한번만 실행된다.
* @param {string} eventName The name of the event to be attached <ko>등록할 이벤트의 이름</ko>
* @param {function} handlerToAttach The handler function of the event to be attached <ko>등록할 이벤트의 핸들러 함수</ko>
* @return An instance of a component itself<ko>컴포넌트 자신의 인스턴스</ko>
* @example
* ```
* class Some extends eg.Component {
* hi() {
* alert("hi");
* }
* thing() {
* this.once("hi", this.hi);
* }
*
* var some = new Some();
* some.thing();
* some.trigger("hi");
* // fire alert("hi");
* some.trigger("hi");
* // Nothing happens
* ```
*/
__proto.once = function (eventName, handlerToAttach) {
var _this = this;
if (typeof eventName === "object" && isUndefined$1(handlerToAttach)) {
var eventHash = eventName;
for (var key in eventHash) {
this.once(key, eventHash[key]);
}
return this;
} else if (typeof eventName === "string" && typeof handlerToAttach === "function") {
var listener_1 = function () {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
handlerToAttach.apply(_this, args);
_this.off(eventName, listener_1);
};
this.on(eventName, listener_1);
}
return this;
};
/**
* Checks whether an event has been attached to a component.
* @ko 컴포넌트에 이벤트가 등록됐는지 확인한다.
* @param {string} eventName The name of the event to be attached <ko>등록 여부를 확인할 이벤트의 이름</ko>
* @return {boolean} Indicates whether the event is attached. <ko>이벤트 등록 여부</ko>
* @example
* ```
* class Some extends eg.Component {
* some() {
* this.hasOn("hi");// check hi event.
* }
* }
* ```
*/
__proto.hasOn = function (eventName) {
return !!this._eventHandler[eventName];
};
/**
* Attaches an event to a component.
* @ko 컴포넌트에 이벤트를 등록한다.
* @param {string} eventName The name of the event to be attached <ko>등록할 이벤트의 이름</ko>
* @param {function} handlerToAttach The handler function of the event to be attached <ko>등록할 이벤트의 핸들러 함수</ko>
* @return An instance of a component itself<ko>컴포넌트 자신의 인스턴스</ko>
* @example
* ```
* class Some extends eg.Component {
* hi() {
* console.log("hi");
* }
* some() {
* this.on("hi",this.hi); //attach event
* }
* }
* ```
*/
__proto.on = function (eventName, handlerToAttach) {
if (typeof eventName === "object" && isUndefined$1(handlerToAttach)) {
var eventHash = eventName;
for (var name in eventHash) {
this.on(name, eventHash[name]);
}
return this;
} else if (typeof eventName === "string" && typeof handlerToAttach === "function") {
var handlerList = this._eventHandler[eventName];
if (isUndefined$1(handlerList)) {
this._eventHandler[eventName] = [];
handlerList = this._eventHandler[eventName];
}
handlerList.push(handlerToAttach);
}
return this;
};
/**
* Detaches an event from the component.
* @ko 컴포넌트에 등록된 이벤트를 해제한다
* @param {string} eventName The name of the event to be detached <ko>해제할 이벤트의 이름</ko>
* @param {function} handlerToDetach The handler function of the event to be detached <ko>해제할 이벤트의 핸들러 함수</ko>
* @return An instance of a component itself <ko>컴포넌트 자신의 인스턴스</ko>
* @example
* ```
* class Some extends eg.Component {
* hi() {
* console.log("hi");
* }
* some() {
* this.off("hi",this.hi); //detach event
* }
* }
* ```
*/
__proto.off = function (eventName, handlerToDetach) {
var e_1, _a; // Detach all event handlers.
if (isUndefined$1(eventName)) {
this._eventHandler = {};
return this;
} // Detach all handlers for eventname or detach event handlers by object.
if (isUndefined$1(handlerToDetach)) {
if (typeof eventName === "string") {
delete this._eventHandler[eventName];
return this;
} else {
var eventHash = eventName;
for (var name in eventHash) {
this.off(name, eventHash[name]);
}
return this;
}
} // Detach single event handler
var handlerList = this._eventHandler[eventName];
if (handlerList) {
var idx = 0;
try {
for (var handlerList_1 = __values$1(handlerList), handlerList_1_1 = handlerList_1.next(); !handlerList_1_1.done; handlerList_1_1 = handlerList_1.next()) {
var handlerFunction = handlerList_1_1.value;
if (handlerFunction === handlerToDetach) {
handlerList.splice(idx, 1);
break;
}
idx++;
}
} catch (e_1_1) {
e_1 = {
error: e_1_1
};
} finally {
try {
if (handlerList_1_1 && !handlerList_1_1.done && (_a = handlerList_1.return)) _a.call(handlerList_1);
} finally {
if (e_1) throw e_1.error;
}
}
}
return this;
};
/**
* Version info string
* @ko 버전정보 문자열
* @name VERSION
* @static
* @example
* eg.Component.VERSION; // ex) 2.0.0
* @memberof eg.Component
*/
Component.VERSION = "2.2.2";
return Component;
}();
/*
Copyright (c) 2020-present NAVER Corp.
name: @egjs/imready
license: MIT
author: NAVER Corp.
repository: https://github.com/naver/egjs-imready
version: 1.1.3
*/
/*! *****************************************************************************
Copyright (c) Microsoft Corporation.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */
/* global Reflect, Promise */
var extendStatics$1 = function (d, b) {
extendStatics$1 = Object.setPrototypeOf || {
__proto__: []
} instanceof Array && function (d, b) {
d.__proto__ = b;
} || function (d, b) {
for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p];
};
return extendStatics$1(d, b);
};
function __extends$1(d, b) {
extendStatics$1(d, b);
function __() {
this.constructor = d;
}
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
}
var __assign$1 = function () {
__assign$1 = Object.assign || function __assign(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
}
return t;
};
return __assign$1.apply(this, arguments);
};
function __spreadArrays$1() {
for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
for (var r = Array(s), k = 0, i = 0; i < il; i++) for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) r[k] = a[j];
return r;
}
/*
egjs-imready
Copyright (c) 2020-present NAVER Corp.
MIT license
*/
var isWindow = typeof window !== "undefined";
var ua = isWindow ? window.navigator.userAgent : "";
var SUPPORT_COMPUTEDSTYLE = isWindow ? !!("getComputedStyle" in window) : false;
var IS_IE = /MSIE|Trident|Windows Phone|Edge/.test(ua);
var SUPPORT_ADDEVENTLISTENER = isWindow ? !!("addEventListener" in document) : false;
var WIDTH = "width";
var HEIGHT = "height";
function getAttribute(el, name) {
return el.getAttribute(name) || "";
}
function toArray(arr) {
return [].slice.call(arr);
}
function hasSizeAttribute(target, prefix) {
if (prefix === void 0) {
prefix = "data-";
}
return !!target.getAttribute(prefix + "width");
}
function hasLoadingAttribute(target) {
return "loading" in target && target.getAttribute("loading") === "lazy";
}
function hasSkipAttribute(target, prefix) {
if (prefix === void 0) {
prefix = "data-";
}
return !!target.getAttribute(prefix + "skip");
}
function addEvent(element, type, handler) {
if (SUPPORT_ADDEVENTLISTENER) {
element.addEventListener(type, handler, false);
} else if (element.attachEvent) {
element.attachEvent("on" + type, handler);
} else {
element["on" + type] = handler;
}
}
function removeEvent(element, type, handler) {
if (element.removeEventListener) {
element.removeEventListener(type, handler, false);
} else if (element.detachEvent) {
element.detachEvent("on" + type, handler);
} else {
element["on" + type] = null;
}
}
function innerWidth(el) {
return getSize(el, "Width");
}
function innerHeight(el) {
return getSize(el, "Height");
}
function getStyles(el) {
return (SUPPORT_COMPUTEDSTYLE ? window.getComputedStyle(el) : el.currentStyle) || {};
}
function getSize(el, name) {
var size = el["client" + name] || el["offset" + name];
return parseFloat(size || getStyles(el)[name.toLowerCase()]) || 0;
}
function getContentElements(element, tags, prefix) {
var skipElements = toArray(element.querySelectorAll(__spreadArrays$1(["[" + prefix + "skip] [" + prefix + "width]"], tags.map(function (tag) {
return ["[" + prefix + "skip] " + tag, tag + "[" + prefix + "skip]", "[" + prefix + "width] " + tag].join(", ");
})).join(", ")));
return toArray(element.querySelectorAll("[" + prefix + "width], " + tags.join(", "))).filter(function (el) {
return skipElements.indexOf(el) === -1;
});
}
/*
egjs-imready
Copyright (c) 2020-present NAVER Corp.
MIT license
*/
var elements = [];
function addAutoSizer(element, prefix) {
!elements.length && addEvent(window, "resize", resizeAllAutoSizers);
element.__PREFIX__ = prefix;
elements.push(element);
resize(element);
}
function removeAutoSizer(element, prefix) {
var index = elements.indexOf(element);
if (index < 0) {
return;
}
var fixed = getAttribute(element, prefix + "fixed");
delete element.__PREFIX__;
element.style[fixed === HEIGHT ? WIDTH : HEIGHT] = "";
elements.splice(index, 1);
!elements.length && removeEvent(window, "resize", resizeAllAutoSizers);
}
function resize(element, prefix) {
if (prefix === void 0) {
prefix = "data-";
}
var elementPrefix = element.__PREFIX__ || prefix;
var dataWidth = parseInt(getAttribute(element, "" + elementPrefix + WIDTH), 10) || 0;
var dataHeight = parseInt(getAttribute(element, "" + elementPrefix + HEIGHT), 10) || 0;
var fixed = getAttribute(element, elementPrefix + "fixed");
if (fixed === HEIGHT) {
var size = innerHeight(element) || dataHeight;
element.style[WIDTH] = dataWidth / dataHeight * size + "px";
} else {
var size = innerWidth(element) || dataWidth;
element.style[HEIGHT] = dataHeight / dataWidth * size + "px";
}
}
function resizeAllAutoSizers() {
elements.forEach(function (element) {
resize(element);
});
}
var Loader =
/*#__PURE__*/
function (_super) {
__extends$1(Loader, _super);
function Loader(element, options) {
if (options === void 0) {
options = {};
}
var _this = _super.call(this) || this;
_this.isReady = false;
_this.isPreReady = false;
_this.hasDataSize = false;
_this.hasLoading = false;
_this.isSkip = false;
_this.onCheck = function (e) {
_this.clear();
if (e && e.type === "error") {
_this.onError(_this.element);
} // I'm pre-ready and ready!
var withPreReady = !_this.hasDataSize && !_this.hasLoading;
_this.onReady(withPreReady);
};
_this.options = __assign$1({
prefix: "data-"
}, options);
_this.element = element;
_this.hasDataSize = hasSizeAttribute(element, _this.options.prefix);
_this.hasLoading = hasLoadingAttribute(element);
_this.isSkip = hasSkipAttribute(_this.element);
return _this;
}
var __proto = Loader.prototype;
__proto.check = function () {
if (this.isSkip || !this.checkElement()) {
// I'm Ready
this.onAlreadyReady(true);
return false;
}
if (this.hasDataSize) {
addAutoSizer(this.element, this.options.prefix);
}
if (this.hasDataSize || this.hasLoading) {
// I'm Pre Ready
this.onAlreadyPreReady();
} // Wati Pre Ready, Ready
return true;
};
__proto.addEvents = function () {
var _this = this;
var element = this.element;
this.constructor.EVENTS.forEach(function (name) {
addEvent(element, name, _this.onCheck);
});
};
__proto.clear = function () {
var _this = this;
var element = this.element;
this.constructor.EVENTS.forEach(function (name) {
removeEvent(element, name, _this.onCheck);
});
this.removeAutoSizer();
};
__proto.destroy = function () {
this.clear();
this.off();
};
__proto.removeAutoSizer = function () {
if (this.hasDataSize) {
// I'm already ready.
var prefix = this.options.prefix;
removeAutoSizer(this.element, prefix);
}
};
__proto.onError = function (target) {
this.trigger("error", {
element: this.element,
target: target
});
};
__proto.onPreReady = function () {
if (this.isPreReady) {
return;
}
this.isPreReady = true;
this.trigger("preReady", {
element: this.element,
hasLoading: this.hasLoading,
isSkip: this.isSkip
});
};
__proto.onReady = function (withPreReady) {
if (this.isReady) {
return;
}
withPreReady = !this.isPreReady && withPreReady;
if (withPreReady) {
this.isPreReady = true;
}
this.removeAutoSizer();
this.isReady = true;
this.trigger("ready", {
element: this.element,
withPreReady: withPreReady,
hasLoading: this.hasLoading,
isSkip: this.isSkip
});
};
__proto.onAlreadyError = function (target) {
var _this = this;
setTimeout(function () {
_this.onError(target);
});
};
__proto.onAlreadyPreReady = function () {
var _this = this;
setTimeout(function () {
_this.onPreReady();
});
};
__proto.onAlreadyReady = function (withPreReady) {
var _this = this;
setTimeout(function () {
_this.onReady(withPreReady);
});
};
Loader.EVENTS = [];
return Loader;
}(Component$1);
var ElementLoader =
/*#__PURE__*/
function (_super) {
__extends$1(ElementLoader, _super);
function ElementLoader() {
return _super !== null && _super.apply(this, arguments) || this;
}
var __proto = ElementLoader.prototype;
__proto.setHasLoading = function (hasLoading) {
this.hasLoading = hasLoading;
};
__proto.check = function () {
if (this.isSkip) {
// I'm Ready
this.onAlreadyReady(true);
return false;
}
if (this.hasDataSize) {
addAutoSizer(this.element, this.options.prefix);
this.onAlreadyPreReady();
} else {
// has not data size
this.trigger("requestChildren");
}
return true;
};
__proto.checkElement = function () {
return true;
};
__proto.destroy = function () {
this.clear();
this.trigger("requestDestroy");
this.off();
};
__proto.onAlreadyPreReady = function () {
// has data size
_super.prototype.onAlreadyPreReady.call(this);
this.trigger("reqeustReadyChildren");
};
ElementLoader.EVENTS = [];
return ElementLoader;
}(Loader);
/**
* @alias eg.ImReady
* @extends eg.Component
*/
var ImReadyManager =
/*#__PURE__*/
function (_super) {
__extends$1(ImReadyManager, _super);
/**
* @param - ImReady's options
*/
function ImReadyManager(options) {
if (options === void 0) {
options = {};
}
var _this = _super.call(this) || this;
_this.readyCount = 0;
_this.preReadyCount = 0;
_this.totalCount = 0;
_this.totalErrorCount = 0;
_this.isPreReadyOver = true;
_this.elementInfos = [];
_this.options = __assign$1({
loaders: {},
prefix: "data-"
}, options);
return _this;
}
/**
* Checks whether elements are in the ready state.
* @ko 엘리먼트가 준비 상태인지 체크한다.
* @elements - Elements to check ready status. <ko> 준비 상태를 체크할 엘리먼트들.</ko>
* @example
* ```html
* <div>
* <img src="./1.jpg" data-width="1280" data-height="853" style="width:100%"/>
* <img src="./2.jpg" data-width="1280" data-height="853"/>
* <img src="ERR" data-width="1280" data-height="853"/>
* </div>
* ```
* ## Javascript
* ```js
* import ImReady from "@egjs/imready";
*
* const im = new ImReady(); // umd: eg.ImReady
* im.check(document.querySelectorAll("img")).on({
* preReadyElement: e => {
* // 1, 3
* // 2, 3
* // 3, 3
* console.log(e.preReadyCount, e.totalCount),
* },
* });
* ```
*/
var __proto = ImReadyManager.prototype;
__proto.check = function (elements) {
var _this = this;
var prefix = this.options.prefix;
this.clear();
this.elementInfos = toArray(elements).map(function (element, index) {
var loader = _this.getLoader(element, {
prefix: prefix
});
loader.check();
loader.on("error", function (e) {
_this.onError(index, e.target);
}).on("preReady", function (e) {
var info = _this.elementInfos[index];
info.hasLoading = e.hasLoading;
info.isSkip = e.isSkip;
var isPreReady = _this.checkPreReady(index);
_this.onPreReadyElement(index);
isPreReady && _this.onPreReady();
}).on("ready", function (_a) {
var withPreReady = _a.withPreReady,
hasLoading = _a.hasLoading,
isSkip = _a.isSkip;
var info = _this.elementInfos[index];
info.hasLoading = hasLoading;
info.isSkip = isSkip;
var isPreReady = withPreReady && _this.checkPreReady(index);
var isReady = _this.checkReady(index); // Pre-ready and ready occur simultaneously
withPreReady && _this.onPreReadyElement(index);
_this.onReadyElement(index);
isPreReady && _this.onPreReady();
isReady && _this.onReady();
});
return {
loader: loader,
element: element,
hasLoading: false,
hasError: false,
isPreReady: false,
isReady: false,
isSkip: false
};
});
var length = this.elementInfos.length;
this.totalCount = length;
if (!length) {
setTimeout(function () {
_this.onPreReady();
_this.onReady();
});
}
return this;
};
/**
* Gets the total count of elements to be checked.
* @ko 체크하는 element의 총 개수를 가져온다.
*/
__proto.getTotalCount = function () {
return this.totalCount;
};
/**
* Whether the elements are all pre-ready. (all sizes are known)
* @ko 엘리먼트들이 모두 사전 준비가 됐는지 (사이즈를 전부 알 수 있는지) 여부.
*/
__proto.isPreReady = function () {
return this.elementInfos.every(function (info) {
return info.isPreReady;
});
};
/**
* Whether the elements are all ready.
* @ko 엘리먼트들이 모두 준비가 됐는지 여부.
*/
__proto.isReady = function () {
return this.elementInfos.every(function (info) {
return info.isReady;
});
};
/**
* Whether an error has occurred in the elements in the current state.
* @ko 현재 상태에서 엘리먼트들이 에러가 발생했는지 여부.
*/
__proto.hasError = function () {
return this.totalErrorCount > 0;
};
/**
* Clears events of elements being checked.
* @ko 체크 중인 엘리먼트들의 이벤트를 해제 한다.
*/
__proto.clear = function () {
this.isPreReadyOver = false;
this.totalCount = 0;
this.preReadyCount = 0;
this.readyCount = 0;
this.totalErrorCount = 0;
this.elementInfos.forEach(function (info) {
if (!info.isReady && info.loader) {
info.loader.destroy();
}
});
this.elementInfos = [];
};
/**
* Destory all events.
* @ko 모든 이벤트를 해제 한다.
*/
__proto.destroy = function () {
this.clear();
this.off();
};
__proto.getLoader = function (element, options) {
var _this = this;
var tagName = element.tagName.toLowerCase();
var loaders = this.options.loaders;
var tags = Object.keys(loaders);
if (loaders[tagName]) {
return new loaders[tagName](element, options);
}
var loader = new ElementLoader(element, options);
var children = toArray(element.querySelectorAll(tags.join(", ")));
loader.setHasLoading(children.some(function (el) {
return hasLoadingAttribute(el);
}));
var withPreReady = false;
var childrenImReady = this.clone().on("error", function (e) {
loader.onError(e.target);
}).on("ready", function () {
loader.onReady(withPreReady);
});
loader.on("requestChildren", function () {
// has not data size
var contentElements = getContentElements(element, tags, _this.options.prefix);
childrenImReady.check(contentElements).on("preReady", function (e) {
withPreReady = e.isReady;
if (!withPreReady) {
loader.onPreReady();
}
});
}).on("reqeustReadyChildren", function () {
// has data size
// loader call preReady
// check only video, image elements
childrenImReady.check(children);
}).on("requestDestroy", function () {
childrenImReady.destroy();
});
return loader;
};
__proto.clone = function () {
return new ImReadyManager(__assign$1({}, this.options));
};
__proto.checkPreReady = function (index) {
this.elementInfos[index].isPreReady = true;
++this.preReadyCount;
if (this.preReadyCount < this.totalCount) {
return false;
}
return true;
};
__proto.checkReady = function (index) {
this.elementInfos[index].isReady = true;
++this.readyCount;
if (this.readyCount < this.totalCount) {
return false;
}
return true;
};
__proto.onError = function (index, target) {
var info = this.elementInfos[index];
info.hasError = true;
/**
* An event occurs if the image, video fails to load.
* @ko 이미지, 비디오가 로딩에 실패하면 이벤트가 발생한다.
* @event eg.ImReady#error
* @param {eg.ImReady.OnError} e - The object of data to be sent to an event <ko>이벤트에 전달되는 데이터 객체</ko>
* @param {HTMLElement} [e.element] - The element with error images.<ko>오류난 이미지가 있는 엘리먼트</ko>
* @param {number} [e.index] - The item's index with error images. <ko>오류난 이미지가 있는 엘리먼트의 인덱스</ko>
* @param {HTMLElement} [e.target] - Error image target in element <ko>엘리먼트의 오류난 이미지 타겟</ko>
* @param {number} [e.errorCount] - The number of elements with errors <ko>에러가 있는 엘리먼트들의 개수</ko>
* @param {number} [e.totalErrorCount] - The total number of targets with errors <ko>에러가 있는 타겟들의 총 개수</ko>
* @example
* ```html
* <div>
* <img src="./1.jpg" data-width="1280" data-height="853" style="width:100%"/>
* <img src="./2.jpg"/>
* <img src="ERR"/>
* </div>
* ```
* ## Javascript
* ```js
* import ImReady from "@egjs/imready";
*
* const im = new ImReady(); // umd: eg.ImReady
* im.check([document.querySelector("div")]).on({
* error: e => {
* // <div>...</div>, 0, <img src="ERR"/>
* console.log(e.element, e.index, e.target),
* },
* });
* ```
*/
this.trigger("error", {
element: info.element,
index: index,
target: target,
errorCount: this.getErrorCount(),
totalErrorCount: ++this.totalErrorCount
});
};
__proto.onPreReadyElement = function (index) {
var info = this.elementInfos[index];
/**
* An event occurs when the element is pre-ready (when the loading attribute is applied or the size is known)
* @ko 해당 엘리먼트가 사전 준비되었을 때(loading 속성이 적용되었거나 사이즈를 알 수 있을 때) 이벤트가 발생한다.
* @event eg.ImReady#preReadyElement
* @param {eg.ImReady.OnPreReadyElement} e - The object of data to be sent to an event <ko>이벤트에 전달되는 데이터 객체</ko>
* @param {HTMLElement} [e.element] - The pre-ready element.<ko>사전 준비된 엘리먼트</ko>
* @param {number} [e.index] - The index of the pre-ready element. <ko>사전 준비된 엘리먼트의 인덱스</ko>
* @param {number} [e.preReadyCount] - Number of elements pre-ready <ko>사전 준비된 엘리먼트들의 개수</ko>
* @param {number} [e.readyCount] - Number of elements ready <ko>준비된 엘리먼트들의 개수</ko>
* @param {number} [e.totalCount] - Total number of elements <ko>엘리먼트들의 총 개수</ko>
* @param {boolean} [e.isPreReady] - Whether all elements are pre-ready <ko>모든 엘리먼트가 사전 준비가 끝났는지 여부</ko>
* @param {boolean} [e.isReady] - Whether all elements are ready <ko>모든 엘리먼트가 준비가 끝났는지 여부</ko>
* @param {boolean} [e.hasLoading] - Whether the loading attribute has been applied <ko>loading 속성이 적용되었는지 여부</ko>
* @param {boolean} [e.isSkip] - Whether the check is omitted due to skip attribute <ko>skip 속성으로 인하여 체크가 생략됐는지 여부</ko>
* @example
* ```html
* <div>
* <img src="./1.jpg" data-width="1280" data-height="853" style="width:100%"/>
* <img src="./2.jpg" data-width="1280" data-height="853"/>
* <img src="ERR" data-width="1280" data-height="853"/>
* </div>
* ```
* ## Javascript
* ```js
* import ImReady from "@egjs/imready";
*
* const im = new ImReady(); // umd: eg.ImReady
* im.check(document.querySelectorAll("img")).on({
* preReadyElement: e => {
* // 1, 3
* // 2, 3
* // 3, 3
* console.log(e.preReadyCount, e.totalCount),
* },
* });
* ```
*/
this.trigger("preReadyElement", {
element: info.element,
index: index,
preReadyCount: this.preReadyCount,
readyCount: this.readyCount,
totalCount: this.totalCount,
isPreReady: this.isPreReady(),
isReady: this.isReady(),
hasLoading: info.hasLoading,
isSkip: info.isSkip
});
};
__proto.onPreReady = function () {
this.isPreReadyOver = true;
/**
* An event occurs when all element are pre-ready (When all elements have the loading attribute applied or the size is known)
* @ko 모든 엘리먼트들이 사전 준비된 경우 (모든 엘리먼트들이 loading 속성이 적용되었거나 사이즈를 알 수 있는 경우) 이벤트가 발생한다.
* @event eg.ImReady#preReady
* @param {eg.ImReady.OnPreReady} e - The object of data to be sent to an event <ko>이벤트에 전달되는 데이터 객체</ko>
* @param {number} [e.readyCount] - Number of elements ready <ko>준비된 엘리먼트들의 개수</ko>
* @param {number} [e.totalCount] - Total number of elements <ko>엘리먼트들의 총 개수</ko>
* @param {boolean} [e.isReady] - Whether all elements are ready <ko>모든 엘리먼트가 준비가 끝났는지 여부</ko>
* @param {boolean} [e.hasLoading] - Whether the loading attribute has been applied <ko>loading 속성이 적용되었는지 여부</ko>
* @example
* ```html
* <div>
* <img src="./1.jpg" data-width="1280" data-height="853" style="width:100%"/>
* <img src="./2.jpg" data-width="1280" data-height="853"/>
* <img src="ERR" data-width="1280" data-height="853"/>
* </div>
* ```
* ## Javascript
* ```js
* import ImReady from "@egjs/imready";
*
* const im = new ImReady(); // umd: eg.ImReady
* im.check(document.querySelectorAll("img")).on({
* preReady: e => {
* // 0, 3
* console.log(e.readyCount, e.totalCount),
* },
* });
* ```
*/
this.trigger("preReady", {
readyCount: this.readyCount,
totalCount: this.totalCount,
isReady: this.isReady(),
hasLoading: this.hasLoading()
});
};
__proto.onReadyElement = function (index) {
var info = this.elementInfos[index];
/**
* An event occurs when the element is ready
* @ko 해당 엘리먼트가 준비가 되었을 때 이벤트가 발생한다.
* @event eg.ImReady#readyElement
* @param {eg.ImReady.OnReadyElement} e - The object of data to be sent to an event <ko>이벤트에 전달되는 데이터 객체</ko>
* @param {HTMLElement} [e.element] - The ready element.<ko>준비된 엘리먼트</ko>
* @param {number} [e.index] - The index of the ready element. <ko>준비된 엘리먼트의 인덱스</ko>
* @param {boolean} [e.hasError] - Whether there is an error in the element <ko>해당 엘리먼트에 에러가 있는지 여부</ko>
* @param {number} [e.errorCount] - The number of elements with errors <ko>에러가 있는 엘리먼트들의 개수</ko>
* @param {number} [e.totalErrorCount] - The total number of targets with errors <ko>에러가 있는 타겟들의 총 개수</ko>
* @param {number} [e.preReadyCount] - Number of elements pre-ready <ko>사전 준비된 엘리먼트들의 개수</ko>
* @param {number} [e.readyCount] - Number of elements ready <ko>준비된 엘리먼트들의 개수</ko>
* @param {number} [e.totalCount] - Total number of elements <ko>엘리먼트들의 총 개수</ko>
* @param {boolean} [e.isPreReady] - Whether all elements are pre-ready <ko>모든 엘리먼트가 사전 준비가 끝났는지 여부</ko>
* @param {boolean} [e.isReady] - Whether all elements are ready <ko>모든 엘리먼트가 준비가 끝났는지 여부</ko>
* @param {boolean} [e.hasLoading] - Whether the loading attribute has been applied <ko>loading 속성이 적용되었는지 여부</ko>
* @param {boolean} [e.isPreReadyOver] - Whether pre-ready is over <ko>사전 준비가 끝났는지 여부</ko>
* @param {boolean} [e.isSkip] - Whether the check is omitted due to skip attribute <ko>skip 속성으로 인하여 체크가 생략됐는지 여부</ko>
* @example
* ```html
* <div>
* <img src="./1.jpg" data-width="1280" data-height="853" style="width:100%"/>
* <img src="./2.jpg" data-width="1280" data-height="853"/>
* <img src="ERR" data-width="1280" data-height="853"/>
* </div>
* ```
* ## Javascript
* ```js
* import ImReady from "@egjs/imready";
*
* const im = new ImReady(); // umd: eg.ImReady
* im.check(document.querySelectorAll("img")).on({
* readyElement: e => {
* // 1, 0, false, 3
* // 2, 1, false, 3
* // 3, 2, true, 3
* console.log(e.readyCount, e.index, e.hasError, e.totalCount),
* },
* });
* ```
*/
this.trigger("readyElement", {
index: index,
element: info.element,
hasError: info.hasError,
errorCount: this.getErrorCount(),
totalErrorCount: this.totalErrorCount,
preReadyCount: this.preReadyCount,
readyCount: this.readyCount,
totalCount: this.totalCount,
isPreReady: this.isPreReady(),
isReady: this.isReady(),
hasLoading: info.hasLoading,
isPreReadyOver: this.isPreReadyOver,
isSkip: info.isSkip
});
};
__proto.onReady = function () {
/**
* An event occurs when all element are ready
* @ko 모든 엘리먼트들이 준비된 경우 이벤트가 발생한다.
* @event eg.ImReady#ready
* @param {eg.ImReady.OnReady} e - The object of data to be sent to an event <ko>이벤트에 전달되는 데이터 객체</ko>
* @param {number} [e.errorCount] - The number of elements with errors <ko>에러가 있는 엘리먼트들의 개수</ko>
* @param {number} [e.totalErrorCount] - The total number of targets with errors <ko>에러가 있는 타겟들의 총 개수</ko>
* @param {number} [e.totalCount] - Total number of elements <ko>엘리먼트들의 총 개수</ko>
* @example
* ```html
* <div>
* <img src="./1.jpg" data-width="1280" data-height="853" style="width:100%"/>
* <img src="./2.jpg" data-width="1280" data-height="853"/>
* <img src="ERR" data-width="1280" data-height="853"/>
* </div>
* ```
* ## Javascript
* ```js
* import ImReady from "@egjs/imready";
*
* const im = new ImReady(); // umd: eg.ImReady
* im.check(document.querySelectorAll("img")).on({
* preReady: e => {
* // 0, 3
* console.log(e.readyCount, e.totalCount),
* },
* ready: e => {
* // 1, 3
* console.log(e.errorCount, e.totalCount),
* },
* });
* ```
*/
this.trigger("ready", {
errorCount: this.getErrorCount(),
totalErrorCount: this.totalErrorCount,
totalCount: this.totalCount
});
};
__proto.getErrorCount = function () {
return this.elementInfos.filter(function (info) {
return info.hasError;
}).length;
};
__proto.hasLoading = function () {
return this.elementInfos.some(function (info) {
return info.hasLoading;
});
};
return ImReadyManager;
}(Component$1);
var ImageLoader =
/*#__PURE__*/
function (_super) {
__extends$1(ImageLoader, _super);
function ImageLoader() {
return _super !== null && _super.apply(this, arguments) || this;
}
var __proto = ImageLoader.prototype;
__proto.checkElement = function () {
var element = this.element;
var src = element.getAttribute("src");
if (element.complete) {
if (src) {
// complete
if (!element.naturalWidth) {
this.onAlreadyError(element);
}
return false;
} else {
// Using an external lazy loading module
this.onAlreadyPreReady();
}
}
this.addEvents();
IS_IE && element.setAttribute("src", src);
return true;
};
ImageLoader.EVENTS = ["load", "error"];
return ImageLoader;
}(Loader);
var VideoLoader =
/*#__PURE__*/
function (_super) {
__extends$1(VideoLoader, _super);
function VideoLoader() {
return _super !== null && _super.apply(this, arguments) || this;
}
var __proto = VideoLoader.prototype;
__proto.checkElement = function () {
var element = this.element; // HAVE_NOTHING: 0, no information whether or not the audio/video is ready
// HAVE_METADATA: 1, HAVE_METADATA - metadata for the audio/video is ready
// HAVE_CURRENT_DATA: 2, data for the current playback position is available, but not enough data to play next frame/millisecond
// HAVE_FUTURE_DATA: 3, data for the current and at least the next frame is available
// HAVE_ENOUGH_DATA: 4, enough data available to start playing
if (element.readyState >= 1) {
return false;
}
if (element.error) {
this.onAlreadyError(element);
return false;
}
this.addEvents();
return true;
};
VideoLoader.EVENTS = ["loadedmetadata", "error"];
return VideoLoader;
}(Loader);
var ImReady =
/*#__PURE__*/
function (_super) {
__extends$1(ImReady, _super);
function ImReady(options) {
if (options === void 0) {
options = {};
}
return _super.call(this, __assign$1({
loaders: {
img: ImageLoader,
video: VideoLoader
}
}, options)) || this;
}
return ImReady;
}(ImReadyManager);
/*
Copyright (c) 2019-present NAVER Corp.
name: @egjs/list-differ
license: MIT
author: NAVER Corp.
repository: https://github.com/naver/egjs-list-differ
version: 1.0.0
*/
/*
egjs-list-differ
Copyright (c) 2019-present NAVER Corp.
MIT license
*/
var PolyMap =
/*#__PURE__*/
function () {
function PolyMap() {
this.keys = [];
this.values = [];
}
var __proto = PolyMap.prototype;
__proto.get = function (key) {
return this.values[this.keys.indexOf(key)];
};
__proto.set = function (key, value) {
var keys = this.keys;
var values = this.values;
var prevIndex = keys.indexOf(key);
var index = prevIndex === -1 ? keys.length : prevIndex;
keys[index] = key;
values[index] = value;
};
return PolyMap;
}();
/*
egjs-list-differ
Copyright (c) 2019-present NAVER Corp.
MIT license
*/
var HashMap =
/*#__PURE__*/
function () {
function HashMap() {
this.object = {};
}
var __proto = HashMap.prototype;
__proto.get = function (key) {
return this.object[key];
};
__proto.set = function (key, value) {
this.object[key] = value;
};
return HashMap;
}();
/*
egjs-list-differ
Copyright (c) 2019-present NAVER Corp.
MIT license
*/
var SUPPORT_MAP = typeof Map === "function";
/*
egjs-list-differ
Copyright (c) 2019-present NAVER Corp.
MIT license
*/
var Link =
/*#__PURE__*/
function () {
function Link() {}
var __proto = Link.prototype;
__proto.connect = function (prevLink, nextLink) {
this.prev = prevLink;
this.next = nextLink;
prevLink && (prevLink.next = this);
nextLink && (nextLink.prev = this);
};
__proto.disconnect = function () {
// In double linked list, diconnect the interconnected relationship.
var prevLink = this.prev;
var nextLink = this.next;
prevLink && (prevLink.next = nextLink);
nextLink && (nextLink.prev = prevLink);
};
__proto.getIndex = function () {
var link = this;
var index = -1;
while (link) {
link = link.prev;
++index;
}
return index;
};
return Link;
}();
/*
egjs-list-differ
Copyright (c) 2019-present NAVER Corp.
MIT license
*/
function orderChanged(changed, fixed) {
// It is roughly in the order of these examples.
// 4, 6, 0, 2, 1, 3, 5, 7
var fromLinks = []; // 0, 1, 2, 3, 4, 5, 6, 7
var toLinks = [];
changed.forEach(function (_a) {
var from = _a[0],
to = _a[1];
var link = new Link();
fromLinks[from] = link;
toLinks[to] = link;
}); // `fromLinks` are connected to each other by double linked list.
fromLinks.forEach(function (link, i) {
link.connect(fromLinks[i - 1]);
});
return changed.filter(function (_, i) {
return !fixed[i];
}).map(function (_a, i) {
var from = _a[0],
to = _a[1];
if (from === to) {
return [0, 0];
}
var fromLink = fromLinks[from];
var toLink = toLinks[to - 1];
var fromIndex = fromLink.getIndex(); // Disconnect the link connected to `fromLink`.
fromLink.disconnect(); // Connect `fromLink` to the right of `toLink`.
if (!toLink) {
fromLink.connect(undefined, fromLinks[0]);
} else {
fromLink.connect(toLink, toLink.next);
}
var toIndex = fromLink.getIndex();
return [fromIndex, toIndex];
});
}
var Result =
/*#__PURE__*/
function () {
function Result(prevList, list, added, removed, changed, maintained, changedBeforeAdded, fixed) {
this.prevList = prevList;
this.list = list;
this.added = added;
this.removed = removed;
this.changed = changed;
this.maintained = maintained;
this.changedBeforeAdded = changedBeforeAdded;
this.fixed = fixed;
}
var __proto = Result.prototype;
Object.defineProperty(__proto, "ordered", {
get: function () {
if (!this.cacheOrdered) {
this.caculateOrdered();
}
return this.cacheOrdered;
},
enumerable: true,
configurable: true
});
Object.defineProperty(__proto, "pureChanged", {
get: function () {
if (!this.cachePureChanged) {
this.caculateOrdered();
}
return this.cachePureChanged;
},
enumerable: true,
configurable: true
});
__proto.caculateOrdered = function () {
var ordered = orderChanged(this.changedBeforeAdded, this.fixed);
var changed = this.changed;
var pureChanged = [];
this.cacheOrdered = ordered.filter(function (_a, i) {
var from = _a[0],
to = _a[1];
var _b = changed[i],
fromBefore = _b[0],
toBefore = _b[1];
if (from !== to) {
pureChanged.push([fromBefore, toBefore]);
return true;
}
});
this.cachePureChanged = pureChanged;
};
return Result;
}();
/**
*
* @memberof eg.ListDiffer
* @static
* @function
* @param - Previous List <ko> 이전 목록 </ko>
* @param - List to Update <ko> 업데이트 할 목록 </ko>
* @param - This callback function returns the key of the item. <ko> 아이템의 키를 반환하는 콜백 함수입니다.</ko>
* @return - Returns the diff between `prevList` and `list` <ko> `prevList`와 `list`의 다른 점을 반환한다.</ko>
* @example
* import { diff } from "@egjs/list-differ";
* // script => eg.ListDiffer.diff
* const result = diff([0, 1, 2, 3, 4, 5], [7, 8, 0, 4, 3, 6, 2, 1], e => e);
* // List before update
* // [1, 2, 3, 4, 5]
* console.log(result.prevList);
* // Updated list
* // [4, 3, 6, 2, 1]
* console.log(result.list);
* // Index array of values added to `list`
* // [0, 1, 5]
* console.log(result.added);
* // Index array of values removed in `prevList`
* // [5]
* console.log(result.removed);
* // An array of index pairs of `prevList` and `list` with different indexes from `prevList` and `list`
* // [[0, 2], [4, 3], [3, 4], [2, 6], [1, 7]]
* console.log(result.changed);
* // The subset of `changed` and an array of index pairs that moved data directly. Indicate an array of absolute index pairs of `ordered`.(Formatted by: Array<[index of prevList, index of list]>)
* // [[4, 3], [3, 4], [2, 6]]
* console.log(result.pureChanged);
* // An array of index pairs to be `ordered` that can synchronize `list` before adding data. (Formatted by: Array<[prevIndex, nextIndex]>)
* // [[4, 1], [4, 2], [4, 3]]
* console.log(result.ordered);
* // An array of index pairs of `prevList` and `list` that have not been added/removed so data is preserved
* // [[0, 2], [4, 3], [3, 4], [2, 6], [1, 7]]
* console.log(result.maintained);
*/
function diff(prevList, list, findKeyCallback) {
var mapClass = SUPPORT_MAP ? Map : findKeyCallback ? HashMap : PolyMap;
var callback = findKeyCallback || function (e) {
return e;
};
var added = [];
var removed = [];
var maintained = [];
var prevKeys = prevList.map(callback);
var keys = list.map(callback);
var prevKeyMap = new mapClass();
var keyMap = new mapClass();
var changedBeforeAdded = [];
var fixed = [];
var removedMap = {};
var changed = [];
var addedCount = 0;
var removedCount = 0; // Add prevKeys and keys to the hashmap.
prevKeys.forEach(function (key, prevListIndex) {
prevKeyMap.set(key, prevListIndex);
});
keys.forEach(function (key, listIndex) {
keyMap.set(key, listIndex);
}); // Compare `prevKeys` and `keys` and add them to `removed` if they are not in `keys`.
prevKeys.forEach(function (key, prevListIndex) {
var listIndex = keyMap.get(key); // In prevList, but not in list, it is removed.
if (typeof listIndex === "undefined") {
++removedCount;
removed.push(prevListIndex);
} else {
removedMap[listIndex] = removedCount;
}
}); // Compare `prevKeys` and `keys` and add them to `added` if they are not in `prevKeys`.
keys.forEach(function (key, listIndex) {
var prevListIndex = prevKeyMap.get(key); // In list, but not in prevList, it is added.
if (typeof prevListIndex === "undefined") {
added.push(listIndex);
++addedCount;
} else {
maintained.push([prevListIndex, listIndex]);
removedCount = removedMap[listIndex] || 0;
changedBeforeAdded.push([prevListIndex - removedCount, listIndex - addedCount]);
fixed.push(listIndex === prevListIndex);
if (prevListIndex !== listIndex) {
changed.push([prevListIndex, listIndex]);
}
}
}); // Sort by ascending order of 'to(list's index).
removed.reverse();
return new Result(prevList, list, added, removed, changed, maintained, changedBeforeAdded, fixed);
}
/*
Copyright (c) 2019-present NAVER Corp.
name: @egjs/children-differ
license: MIT
author: NAVER Corp.
repository: https://github.com/naver/egjs-children-differ
version: 1.0.1
*/
/*
egjs-children-differ
Copyright (c) 2019-present NAVER Corp.
MIT license
*/
var findKeyCallback = typeof Map === "function" ? undefined : function () {
var childrenCount = 0;
return function (el) {
return el.__DIFF_KEY__ || (el.__DIFF_KEY__ = ++childrenCount);
};
}();
/*
egjs-children-differ
Copyright (c) 2019-present NAVER Corp.
MIT license
*/
/**
*
* @memberof eg.ChildrenDiffer
* @static
* @function
* @param - Previous List <ko> 이전 목록 </ko>
* @param - List to Update <ko> 업데이트 할 목록 </ko>
* @return - Returns the diff between `prevList` and `list` <ko> `prevList`와 `list`의 다른 점을 반환한다.</ko>
* @example
* import { diff } from "@egjs/children-differ";
* // script => eg.ChildrenDiffer.diff
* const result = diff([0, 1, 2, 3, 4, 5], [7, 8, 0, 4, 3, 6, 2, 1]);
* // List before update
* // [1, 2, 3, 4, 5]
* console.log(result.prevList);
* // Updated list
* // [4, 3, 6, 2, 1]
* console.log(result.list);
* // Index array of values added to `list`
* // [0, 1, 5]
* console.log(result.added);
* // Index array of values removed in `prevList`
* // [5]
* console.log(result.removed);
* // An array of index pairs of `prevList` and `list` with different indexes from `prevList` and `list`
* // [[0, 2], [4, 3], [3, 4], [2, 6], [1, 7]]
* console.log(result.changed);
* // The subset of `changed` and an array of index pairs that moved data directly. Indicate an array of absolute index pairs of `ordered`.(Formatted by: Array<[index of prevList, index of list]>)
* // [[4, 3], [3, 4], [2, 6]]
* console.log(result.pureChanged);
* // An array of index pairs to be `ordered` that can synchronize `list` before adding data. (Formatted by: Array<[prevIndex, nextIndex]>)
* // [[4, 1], [4, 2], [4, 3]]
* console.log(result.ordered);
* // An array of index pairs of `prevList` and `list` that have not been added/removed so data is preserved
* // [[0, 2], [4, 3], [3, 4], [2, 6], [1, 7]]
* console.log(result.maintained);
*/
function diff$1(prevList, list) {
return diff(prevList, list, findKeyCallback);
}
/*
Copyright (c) 2021-present NAVER Corp.
name: @egjs/grid
license: MIT
author: NAVER Corp.
repository: https://github.com/naver/egjs-grid
version: 1.5.0-beta.0
*/
/*! *****************************************************************************
Copyright (c) Microsoft Corporation.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */
/* global Reflect, Promise */
var extendStatics$2 = function (d, b) {
extendStatics$2 = Object.setPrototypeOf || {
__proto__: []
} instanceof Array && function (d, b) {
d.__proto__ = b;
} || function (d, b) {
for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p];
};
return extendStatics$2(d, b);
};
function __extends$2(d, b) {
if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
extendStatics$2(d, b);
function __() {
this.constructor = d;
}
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
}
var __assign$2 = function () {
__assign$2 = Object.assign || function __assign(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
}
return t;
};
return __assign$2.apply(this, arguments);
};
function __decorate$1(decorators, target, key, desc) {
var c = arguments.length,
r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc,
d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
}
/** @deprecated */
function __spreadArrays$2() {
for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
for (var r = Array(s), k = 0, i = 0; i < il; i++) for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) r[k] = a[j];
return r;
}
var DEFAULT_GRID_OPTIONS = {
horizontal: false,
useTransform: false,
percentage: false,
isEqualSize: false,
isConstantSize: false,
gap: 0,
attributePrefix: "data-grid-",
resizeDebounce: 100,
maxResizeDebounce: 0,
autoResize: true,
preserveUIOnDestroy: false,
defaultDirection: "end",
externalContainerManager: null,
externalItemRenderer: null,
renderOnPropertyChange: true,
useFit: true
};
var PROPERTY_TYPE;
(function (PROPERTY_TYPE) {
PROPERTY_TYPE[PROPERTY_TYPE["PROPERTY"] = 1] = "PROPERTY";
PROPERTY_TYPE[PROPERTY_TYPE["RENDER_PROPERTY"] = 2] = "RENDER_PROPERTY";
})(PROPERTY_TYPE || (PROPERTY_TYPE = {}));
var MOUNT_STATE;
(function (MOUNT_STATE) {
MOUNT_STATE[MOUNT_STATE["UNCHECKED"] = 1] = "UNCHECKED";
MOUNT_STATE[MOUNT_STATE["UNMOUNTED"] = 2] = "UNMOUNTED";
MOUNT_STATE[MOUNT_STATE["MOUNTED"] = 3] = "MOUNTED";
})(MOUNT_STATE || (MOUNT_STATE = {}));
var UPDATE_STATE;
(function (UPDATE_STATE) {
UPDATE_STATE[UPDATE_STATE["NEED_UPDATE"] = 1] = "NEED_UPDATE";
UPDATE_STATE[UPDATE_STATE["WAIT_LOADING"] = 2] = "WAIT_LOADING";
UPDATE_STATE[UPDATE_STATE["UPDATED"] = 3] = "UPDATED";
})(UPDATE_STATE || (UPDATE_STATE = {}));
var GRID_PROPERTY_TYPES = {
gap: PROPERTY_TYPE.RENDER_PROPERTY,
defaultDirection: PROPERTY_TYPE.PROPERTY,
renderOnPropertyChange: PROPERTY_TYPE.PROPERTY,
preserveUIOnDestroy: PROPERTY_TYPE.PROPERTY,
useFit: PROPERTY_TYPE.PROPERTY
};
var RECT_NAMES = {
horizontal: {
inlinePos: "top",
contentPos: "left",
inlineSize: "height",
contentSize: "width"
},
vertical: {
inlinePos: "left",
contentPos: "top",
inlineSize: "width",
contentSize: "height"
}
};
var ContainerManager =
/*#__PURE__*/
function (_super) {
__extends$2(ContainerManager, _super);
function ContainerManager(container, options) {
var _this = _super.call(this) || this;
_this.container = container;
_this._resizeTimer = 0;
_this._maxResizeDebounceTimer = 0;
_this._onResize = function () {
clearTimeout(_this._resizeTimer);
clearTimeout(_this._maxResizeDebounceTimer);
_this._maxResizeDebounceTimer = 0;
_this._resizeTimer = 0;
_this.trigger("resize");
};
_this._scheduleResize = function () {
var _a = _this.options,
resizeDebounce = _a.resizeDebounce,
maxResizeDebounce = _a.maxResizeDebounce;
if (!_this._maxResizeDebounceTimer && maxResizeDebounce >= resizeDebounce) {
_this._maxResizeDebounceTimer = window.setTimeout(_this._onResize, maxResizeDebounce);
}
if (_this._resizeTimer) {
clearTimeout(_this._resizeTimer);
_this._resizeTimer = 0;
}
_this._resizeTimer = window.setTimeout(_this._onResize, resizeDebounce);
};
_this.options = __assign$2({
horizontal: DEFAULT_GRID_OPTIONS.horizontal,
autoResize: DEFAULT_GRID_OPTIONS.autoResize,
resizeDebounce: DEFAULT_GRID_OPTIONS.resizeDebounce,
maxResizeDebounce: DEFAULT_GRID_OPTIONS.maxResizeDebounce
}, options);
_this._init();
return _this;
}
var __proto = ContainerManager.prototype;
__proto.resize = function () {
var container = this.container;
this.setRect({
width: container.clientWidth,
height: container.clientHeight
});
};
__proto.getRect = function () {
return this.rect;
};
__proto.setRect = function (rect) {
this.rect = __assign$2({}, rect);
};
__proto.getInlineSize = function () {
return this.rect[this.options.horizontal ? "height" : "width"];
};
__proto.getContentSize = function () {
return this.rect[this.options.horizontal ? "width" : "height"];
};
__proto.getStatus = function () {
return {
rect: __assign$2({}, this.rect)
};
};
__proto.setStatus = function (status) {
this.rect = __assign$2({}, status.rect);
this.setContentSize(this.getContentSize());
};
__proto.setContentSize = function (size) {
var sizeName = this.options.horizontal ? "width" : "height";
this.rect[sizeName] = size;
this.container.style[sizeName] = size + "px";
};
__proto.destroy = function (options) {
if (options === void 0) {
options = {};
}
window.removeEventListener("resize", this._scheduleResize);
if (!options.preserveUI) {
this.container.style.cssText = this.orgCSSText;
}
};
__proto._init = function () {
var container = this.container;
var style = window.getComputedStyle(container);
this.orgCSSText = container.style.cssText;
if (style.position === "static") {
container.style.position = "relative";
}
if (this.options.autoResize) {
window.addEventListener("resize", this._scheduleResize);
}
};
return ContainerManager;
}(Component);
function getKeys(obj) {
return Object.keys(obj);
}
function isString(val) {
return typeof val === "string";
}
function isObject(val) {
return typeof val === "object";
}
function isNumber(val) {
return typeof val === "number";
}
function camelize(str) {
return str.replace(/[\s-_]([a-z])/g, function (all, letter) {
return letter.toUpperCase();
});
}
function getDataAttributes(element, attributePrefix) {
var dataAttributes = {};
var attributes = element.attributes;
var length = attributes.length;
for (var i = 0; i < length; ++i) {
var attribute = attributes[i];
var name = attribute.name,
value = attribute.value;
if (name.indexOf(attributePrefix) === -1) {
continue;
}
dataAttributes[camelize(name.replace(attributePrefix, ""))] = value;
}
return dataAttributes;
}
/* Class Decorator */
function GetterSetter(component) {
var prototype = component.prototype,
propertyTypes = component.propertyTypes;
var _loop_1 = function (name) {
var shouldRender = propertyTypes[name] === PROPERTY_TYPE.RENDER_PROPERTY;
var descriptor = Object.getOwnPropertyDescriptor(prototype, name) || {};
var getter = descriptor.get || function get() {
return this.options[name];
};
var setter = descriptor.set || function set(value) {
var options = this.options;
var prevValue = options[name];
if (prevValue === value) {
return;
}
options[name] = value;
if (shouldRender && options.renderOnPropertyChange) {
this.scheduleRender();
}
};
var attributes = {
enumerable: true,
configurable: true,
get: getter,
set: setter
};
Object.defineProperty(prototype, name, attributes);
};
for (var name in propertyTypes) {
_loop_1(name);
}
}
function withMethods(methods) {
return function (prototype, memberName) {
methods.forEach(function (name) {
if (name in prototype) {
return;
}
prototype[name] = function () {
var _a;
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
var result = (_a = this[memberName])[name].apply(_a, args); // fix `this` type to return your own `class` instance to the instance using the decorator.
if (result === this[memberName]) {
return this;
} else {
return result;
}
};
});
};
}
function range(length) {
var arr = [];
for (var i = 0; i < length; ++i) {
arr.push(i);
}
return arr;
}
function getRangeCost(value, valueRange) {
return Math.max(value - valueRange[1], valueRange[0] - value, 0) + 1;
}
var ItemRenderer =
/*#__PURE__*/
function () {
function ItemRenderer(options) {
this.initialRect = null;
this.sizePercetage = false;
this.posPercetage = false;
this.options = __assign$2({
attributePrefix: DEFAULT_GRID_OPTIONS.attributePrefix,
useTransform: DEFAULT_GRID_OPTIONS.useTransform,
horizontal: DEFAULT_GRID_OPTIONS.horizontal,
percentage: DEFAULT_GRID_OPTIONS.percentage,
isEqualSize: DEFAULT_GRID_OPTIONS.isEqualSize,
isConstantSize: DEFAULT_GRID_OPTIONS.isConstantSize
}, options);
this._init();
}
var __proto = ItemRenderer.prototype;
__proto.resize = function () {
this.initialRect = null;
};
__proto.renderItems = function (items) {
var _this = this;
items.forEach(function (item) {
_this._renderItem(item);
});
};
__proto.getInlineSize = function () {
return this.containerRect[this.options.horizontal ? "height" : "width"];
};
__proto.setContainerRect = function (rect) {
this.containerRect = rect;
};
__proto.updateItems = function (items) {
var _this = this;
items.forEach(function (item) {
_this._updateItem(item);
});
};
__proto.getStatus = function () {
return {
initialRect: this.initialRect
};
};
__proto.setStatus = function (status) {
this.initialRect = status.initialRect;
};
__proto._init = function () {
var percentage = this.options.percentage;
var sizePercentage = false;
var posPercentage = false;
if (percentage === true) {
sizePercentage = true;
posPercentage = true;
} else if (percentage) {
if (percentage.indexOf("position") > -1) {
posPercentage = true;
}
if (percentage.indexOf("size") > -1) {
sizePercentage = true;
}
}
this.posPercetage = posPercentage;
this.sizePercetage = sizePercentage;
};
__proto._updateItem = function (item) {
var _a = this.options,
isEqualSize = _a.isEqualSize,
isConstantSize = _a.isConstantSize;
var initialRect = this.initialRect;
var orgRect = item.orgRect,
element = item.element;
var isLoading = item.updateState === UPDATE_STATE.WAIT_LOADING;
var hasOrgSize = orgRect && orgRect.width && orgRect.height;
var rect;
if (isEqualSize && initialRect) {
rect = initialRect;
} else if (isConstantSize && hasOrgSize && !isLoading) {
rect = orgRect;
} else if (!element) {
return;
} else {
rect = {
left: element.offsetLeft,
top: element.offsetTop,
width: element.offsetWidth,
height: element.offsetHeight
};
}
if (!item.isFirstUpdate) {
item.orgRect = __assign$2({}, rect);
}
item.rect = __assign$2({}, rect);
if (item.element) {
item.mountState = MOUNT_STATE.MOUNTED;
}
if (item.updateState === UPDATE_STATE.NEED_UPDATE) {
item.updateState = UPDATE_STATE.UPDATED;
item.isFirstUpdate = true;
}
item.attributes = element ? getDataAttributes(element, this.options.attributePrefix) : {};
if (!isLoading) {
this.initialRect = __assign$2({}, rect);
}
return rect;
};
__proto._renderItem = function (item) {
var element = item.element;
var cssRect = item.cssRect;
if (!element || !cssRect) {
return;
}
var _a = this.options,
horizontal = _a.horizontal,
useTransform = _a.useTransform;
var posPercentage = this.posPercetage;
var sizePercentage = this.sizePercetage;
var cssTexts = ["position: absolute;"];
var _b = RECT_NAMES[horizontal ? "horizontal" : "vertical"],
sizeName = _b.inlineSize,
posName = _b.inlinePos;
var inlineSize = this.getInlineSize();
var keys = getKeys(cssRect);
if (useTransform) {
keys = keys.filter(function (key) {
return key !== "top" && key !== "left";
});
cssTexts.push("transform: " + ("translate(" + (cssRect.left || 0) + "px, " + (cssRect.top || 0) + "px);"));
}
cssTexts.push.apply(cssTexts, keys.map(function (name) {
var value = cssRect[name];
if (name === sizeName && sizePercentage || name === posName && posPercentage) {
return name + ": " + value / inlineSize * 100 + "%;";
}
return name + ": " + value + "px;";
}));
element.style.cssText += cssTexts.join("");
};
return ItemRenderer;
}();
/**
* @memberof Grid
* @implements Grid.GridItem.GridItemStatus
*/
var GridItem =
/*#__PURE__*/
function () {
/**
* @constructor
* @param horizontal - Direction of the scroll movement. (true: horizontal, false: vertical) <ko>스크롤 이동 방향. (true: 가로방향, false: 세로방향)</ko>
* @param itemStatus - Default status object of GridItem module. <ko>GridItem 모듈의 기본 status 객체.</ko>
*/
function GridItem(horizontal, itemStatus) {
if (itemStatus === void 0) {
itemStatus = {};
}
var _a;
this.horizontal = horizontal;
var element = itemStatus.element;
var status = __assign$2({
key: "",
orgRect: {
left: 0,
top: 0,
width: 0,
height: 0
},
rect: {
left: 0,
top: 0,
width: 0,
height: 0
},
cssRect: {},
attributes: {},
data: {},
isFirstUpdate: false,
mountState: MOUNT_STATE.UNCHECKED,
updateState: UPDATE_STATE.NEED_UPDATE,
element: element || null,
orgCSSText: (_a = element === null || element === void 0 ? void 0 : element.style.cssText) !== null && _a !== void 0 ? _a : "",
gridData: {}
}, itemStatus);
for (var name in status) {
this[name] = status[name];
}
}
var __proto = GridItem.prototype;
Object.defineProperty(__proto, "orgInlineSize", {
/**
* The size in inline direction before first rendering. "width" if horizontal is false, "height" otherwise.
* @ko 첫 렌더링 되기 전의 inline 방향의 사이즈. horizontal이 false면 "width", 아니면 "height".
* @member Grid.GridItem#orgInlineSize
*/
get: function () {
var orgRect = this.orgRect || this.rect;
return this.horizontal ? orgRect.height : orgRect.width;
},
enumerable: false,
configurable: true
});
Object.defineProperty(__proto, "orgContentSize", {
/**
* The size in content direction before first rendering. "height" if horizontal is false, "width" otherwise.
* @ko 첫 렌더링 되기 전의 content 방향의 사이즈. horizontal이 false면 "height", 아니면 "width".
* @member Grid.GridItem#orgContentSize
*/
get: function () {
var orgRect = this.orgRect || this.rect;
return this.horizontal ? orgRect.width : orgRect.height;
},
enumerable: false,
configurable: true
});
Object.defineProperty(__proto, "inlineSize", {
/**
* The size in inline direction. "width" if horizontal is false, "height" otherwise.
* @ko inline 방향의 사이즈. horizontal이 false면 "width", 아니면 "height".
* @member Grid.GridItem#inlineSize
*/
get: function () {
var rect = this.rect;
return this.horizontal ? rect.height : rect.width;
},
enumerable: false,
configurable: true
});
Object.defineProperty(__proto, "contentSize", {
/**
* The size in content direction. "height" if horizontal is false, "width" otherwise.
* @ko content 방향의 사이즈. horizontal이 false면 "height", 아니면 "width".
* @member Grid.GridItem#contentSize
*/
get: function () {
var rect = this.rect;
return this.horizontal ? rect.width : rect.height;
},
enumerable: false,
configurable: true
});
Object.defineProperty(__proto, "cssInlineSize", {
/**
* The CSS size in inline direction applied to the Grid. "width" if horizontal is false, "height" otherwise.
* @ko Grid에 적용된 inline 방향의 CSS 사이즈. horizontal이 false면 "width", 아니면 "height".
* @member Grid.GridItem#cssInlineSize
*/
get: function () {
var cssRect = this.cssRect;
return this.horizontal ? cssRect.height : cssRect.width;
},
set: function (inlineSize) {
var cssRect = this.cssRect;
cssRect[this.horizontal ? "height" : "width"] = inlineSize;
},
enumerable: false,
configurable: true
});
Object.defineProperty(__proto, "cssContentSize", {
/**
* The CSS size in content direction applied to the Grid. "height" if horizontal is false, "width" otherwise.
* @ko Grid에 적용된 content 방향의 CSS 사이즈. horizontal이 false면 "height", 아니면 "width".
* @member Grid.GridItem#cssContentSize
*/
get: function () {
var cssRect = this.cssRect;
return this.horizontal ? cssRect.width : cssRect.height;
},
set: function (contentSize) {
var cssRect = this.cssRect;
cssRect[this.horizontal ? "width" : "height"] = contentSize;
},
enumerable: false,
configurable: true
});
Object.defineProperty(__proto, "cssInlinePos", {
/**
* The CSS pos in inline direction applied to the Grid. "left" if horizontal is false, "top" otherwise.
* @ko Grid에 적용된 inline 방향의 CSS 포지션. horizontal이 false면 "left", 아니면 "top".
* @member Grid.GridItem#cssInlinePos
*/
get: function () {
var cssRect = this.cssRect;
return this.horizontal ? cssRect.top : cssRect.left;
},
set: function (inlinePos) {
var cssRect = this.cssRect;
cssRect[this.horizontal ? "top" : "left"] = inlinePos;
},
enumerable: false,
configurable: true
});
Object.defineProperty(__proto, "cssContentPos", {
/**
* The CSS pos in content direction applied to the Grid. "top" if horizontal is false, "left" otherwise.
* @ko Grid에 적용된 content 방향의 CSS 포지션. horizontal이 false면 "top", 아니면 "left".
* @member Grid.GridItem#cssContentPos
*/
get: function () {
var cssRect = this.cssRect;
return this.horizontal ? cssRect.left : cssRect.top;
},
set: function (contentPos) {
var cssRect = this.cssRect;
cssRect[this.horizontal ? "left" : "top"] = contentPos;
},
enumerable: false,
configurable: true
});
/**
* Set CSS Rect through GridRect.
* @ko GridRect을 통해 CSS Rect를 설정한다.
* @param - The style for setting CSS rect. <ko>CSS rect를 설정하기 위한 스타일.</ko>
*/
__proto.setCSSGridRect = function (gridRect) {
var names = RECT_NAMES[this.horizontal ? "horizontal" : "vertical"];
var rect = {};
for (var name in gridRect) {
rect[names[name]] = gridRect[name];
}
this.cssRect = rect;
};
/**
* Returns the status of the item.
* @ko 아이템의 상태를 반환한다.
*/
__proto.getStatus = function () {
return {
mountState: this.mountState,
updateState: this.updateState,
attributes: this.attributes,
orgCSSText: this.orgCSSText,
isFirstUpdate: this.isFirstUpdate,
element: null,
key: this.key,
orgRect: this.orgRect,
rect: this.rect,
cssRect: this.cssRect,
gridData: this.gridData,
data: this.data
};
};
/**
* Returns minimized status of the item.
* @ko 아이템의 간소화된 상태를 반환한다.
*/
__proto.getMinimizedStatus = function () {
var status = {
orgRect: this.orgRect,
rect: this.rect,
cssRect: this.cssRect,
attributes: this.attributes,
gridData: this.gridData
};
if (typeof this.key !== "undefined") {
status.key = this.key;
}
if (this.mountState !== MOUNT_STATE.UNCHECKED) {
status.mountState = this.mountState;
}
if (this.updateState !== UPDATE_STATE.NEED_UPDATE) {
status.updateState = this.updateState;
}
if (this.isFirstUpdate) {
status.isFirstUpdate = true;
}
if (this.orgCSSText) {
status.orgCSSText = this.orgCSSText;
}
return status;
};
return GridItem;
}();
/**
* @extends eg.Component
*/
var Grid =
/*#__PURE__*/
function (_super) {
__extends$2(Grid, _super);
/**
* @param - A base element for a module <ko>모듈을 적용할 기준 엘리먼트</ko>
* @param - The option object of the Grid module <ko>Grid 모듈의 옵션 객체</ko>
*/
function Grid(containerElement, options) {
if (options === void 0) {
options = {};
}
var _this = _super.call(this) || this;
_this.items = [];
_this.outlines = {
start: [],
end: []
};
_this._renderTimer = 0;
_this._onResize = function () {
_this.renderItems({
useResize: true
});
};
_this.options = __assign$2(__assign$2({}, _this.constructor.defaultOptions), options);
_this.containerElement = isString(containerElement) ? document.querySelector(containerElement) : containerElement;
var _a = _this.options,
isEqualSize = _a.isEqualSize,
isConstantSize = _a.isConstantSize,
useTransform = _a.useTransform,
horizontal = _a.horizontal,
percentage = _a.percentage,
externalContainerManager = _a.externalContainerManager,
externalItemRenderer = _a.externalItemRenderer,
resizeDebounce = _a.resizeDebounce,
maxResizeDebounce = _a.maxResizeDebounce,
autoResize = _a.autoResize; // TODO: 테스트용 설정
_this.containerManager = externalContainerManager || new ContainerManager(_this.containerElement, {
horizontal: horizontal,
resizeDebounce: resizeDebounce,
maxResizeDebounce: maxResizeDebounce,
autoResize: autoResize
}).on("resize", _this._onResize);
_this.itemRenderer = externalItemRenderer || new ItemRenderer({
useTransform: useTransform,
isEqualSize: isEqualSize,
isConstantSize: isConstantSize,
percentage: percentage
});
_this._init();
return _this;
}
var __proto = Grid.prototype;
Grid_1 = Grid;
/**
* Return Container Element.
* @ko 컨테이너 엘리먼트를 반환한다.
*/
__proto.getContainerElement = function () {
return this.containerElement;
};
/**
* Return items.
* @ko 아이템들을 반환한다.
*/
__proto.getItems = function () {
return this.items;
};
/**
* Returns the children of the container element.
* @ko 컨테이너 엘리먼트의 children을 반환한다.
*/
__proto.getChildren = function () {
return [].slice.call(this.containerElement.children);
};
/**
* Set items.
* @ko 아이템들을 설정한다.
* @param items - The items to set. <ko>설정할 아이템들</ko>
*/
__proto.setItems = function (items) {
this.items = items;
return this;
};
/**
* Gets the container's inline size. ("width" if horizontal is false, otherwise "height")
* @ko container의 inline 사이즈를 가져온다. (horizontal이 false면 "width", 아니면 "height")
*/
__proto.getContainerInlineSize = function () {
return this.containerManager.getInlineSize();
};
/**
* Returns the outlines of the start and end of the Grid.
* @ko Grid의 처음과 끝의 outline을 반환한다.
*/
__proto.getOutlines = function () {
return this.outlines;
};
/**
* Set outlines.
* @ko 아웃라인을 설정한다.
* @param outlines - The outlines to set. <ko>설정할 아웃라인.</ko>
*/
__proto.setOutlines = function (outlines) {
this.outlines = outlines;
return this;
};
/**
* When elements change, it synchronizes and renders items.
* @ko elements가 바뀐 경우 동기화를 하고 렌더링을 한다.
* @param - Options for rendering. <ko>렌더링을 하기 위한 옵션.</ko>
*/
__proto.syncElements = function (options) {
if (options === void 0) {
options = {};
}
var items = this.items;
var horizontal = this.options.horizontal;
var elements = this.getChildren();
var _a = diff$1(this.items.map(function (item) {
return item.element;
}), elements),
added = _a.added,
maintained = _a.maintained,
changed = _a.changed,
removed = _a.removed;
var nextItems = [];
maintained.forEach(function (_a) {
var beforeIndex = _a[0],
afterIndex = _a[1];
nextItems[afterIndex] = items[beforeIndex];
});
added.forEach(function (index) {
nextItems[index] = new GridItem(horizontal, {
element: elements[index]
});
});
this.setItems(nextItems);
if (added.length || removed.length || changed.length) {
this.renderItems(options);
}
return this;
};
/**
* Update the size of the items and render them.
* @ko 아이템들의 사이즈를 업데이트하고 렌더링을 한다.
* @param - Items to be updated. <ko>업데이트할 아이템들.</ko>
* @param - Options for rendering. <ko>렌더링을 하기 위한 옵션.</ko>
*/
__proto.updateItems = function (items, options) {
if (items === void 0) {
items = this.items;
}
if (options === void 0) {
options = {};
}
items.forEach(function (item) {
item.updateState = UPDATE_STATE.NEED_UPDATE;
});
this.checkReady(options);
return this;
};
/**
* Rearrange items to fit the grid and render them. When rearrange is complete, the `renderComplete` event is fired.
* @ko grid에 맞게 아이템을 재배치하고 렌더링을 한다. 배치가 완료되면 `renderComplete` 이벤트가 발생한다.
* @param - Options for rendering. <ko>렌더링을 하기 위한 옵션.</ko>
* @example
* import { MasonryGrid } from "@egjs/grid";
* const grid = new MasonryGrid();
*
* grid.on("renderComplete", e => {
* console.log(e);
* });
* grid.renderItems();
*/
__proto.renderItems = function (options) {
if (options === void 0) {
options = {};
}
this._clearRenderTimer();
if (!this.getItems().length && this.getChildren().length) {
this.syncElements(options);
} else if (options.useResize) {
// Resize container and Update all items
this._resizeContainer();
this.updateItems(this.items, options);
} else {
// Update only items that need to be updated.
this.checkReady(options);
}
return this;
};
/**
* Returns current status such as item's position, size. The returned status can be restored with the setStatus() method.
* @ko 아이템의 위치, 사이즈 등 현재 상태를 반환한다. 반환한 상태는 setStatus() 메서드로 복원할 수 있다.
* @param - Whether to minimize the status of the item. (default: false) <ko>item의 status를 최소화할지 여부. (default: false)</ko>
*/
__proto.getStatus = function (isMinimize) {
return {
outlines: this.outlines,
items: this.items.map(function (item) {
return isMinimize ? item.getMinimizedStatus() : item.getStatus();
}),
containerManager: this.containerManager.getStatus(),
itemRenderer: this.itemRenderer.getStatus()
};
};
/**
* Set status of the Grid module with the status returned through a call to the getStatus() method.
* @ko getStatus() 메서드에 대한 호출을 통해 반환된 상태로 Grid 모듈의 상태를 설정한다.
*/
__proto.setStatus = function (status) {
var _this = this;
var horizontal = this.options.horizontal;
var containerManager = this.containerManager;
var prevInlineSize = containerManager.getInlineSize();
var children = this.getChildren();
this.itemRenderer.setStatus(status.itemRenderer);
containerManager.setStatus(status.containerManager);
this.outlines = status.outlines;
this.items = status.items.map(function (item, i) {
return new GridItem(horizontal, __assign$2(__assign$2({}, item), {
element: children[i]
}));
});
this.itemRenderer.renderItems(this.items);
if (prevInlineSize !== containerManager.getInlineSize()) {
this.renderItems({
useResize: true
});
} else {
window.setTimeout(function () {
_this._renderComplete({
direction: _this.defaultDirection,
mounted: _this.items,
updated: [],
isResize: false
});
});
}
return this;
};
/**
* Releases the instnace and events and returns the CSS of the container and elements.
* @ko 인스턴스와 이벤트를 해제하고 컨테이너와 엘리먼트들의 CSS를 되돌린다.
* @param Options for destroy. <ko>destory()를 위한 옵션</ko>
*/
__proto.destroy = function (options) {
var _a;
if (options === void 0) {
options = {};
}
var _b = options.preserveUI,
preserveUI = _b === void 0 ? this.options.preserveUIOnDestroy : _b;
this.containerManager.destroy({
preserveUI: preserveUI
});
if (!preserveUI) {
this.items.forEach(function (_a) {
var element = _a.element,
orgCSSText = _a.orgCSSText;
if (element) {
element.style.cssText = orgCSSText;
}
});
}
(_a = this._im) === null || _a === void 0 ? void 0 : _a.destroy();
};
__proto.checkReady = function (options) {
var _this = this;
var _a;
if (options === void 0) {
options = {};
} // Grid: renderItems => checkReady => readyItems => applyGrid
var items = this.items;
var updated = items.filter(function (item) {
return item.element && item.updateState !== UPDATE_STATE.UPDATED;
});
var mounted = updated.filter(function (item) {
return item.mountState !== MOUNT_STATE.MOUNTED;
});
var moreUpdated = [];
(_a = this._im) === null || _a === void 0 ? void 0 : _a.destroy();
this._im = new ImReady({
prefix: this.options.attributePrefix
}).on("preReadyElement", function (e) {
updated[e.index].updateState = UPDATE_STATE.WAIT_LOADING;
}).on("preReady", function () {
_this.itemRenderer.updateItems(updated);
_this.readyItems(mounted, updated, options);
}).on("readyElement", function (e) {
var item = updated[e.index];
item.updateState = UPDATE_STATE.NEED_UPDATE; // after preReady
if (e.isPreReadyOver) {
item.element.style.cssText = item.orgCSSText;
_this.itemRenderer.updateItems([item]);
_this.readyItems([], [item], options);
}
}).on("error", function (e) {
var item = items[e.index];
/**
* This event is fired when an error occurs in the content.
* @ko 콘텐츠 로드에 에러가 날 때 발생하는 이벤트.
* @event Grid#contentError
* @param {Grid.OnContentError} e - The object of data to be sent to an event <ko>이벤트에 전달되는 데이터 객체</ko>
* @example
grid.on("contentError", e => {
e.update();
});
*/
_this.trigger("contentError", {
element: e.element,
target: e.target,
item: item,
update: function () {
moreUpdated.push(item);
}
});
}).on("ready", function () {
if (moreUpdated.length) {
_this.updateItems(moreUpdated);
}
}).check(updated.map(function (item) {
return item.element;
}));
};
__proto.scheduleRender = function () {
var _this = this;
this._clearRenderTimer();
this._renderTimer = window.setTimeout(function () {
_this.renderItems();
});
};
__proto.fitOutlines = function (useFit) {
if (useFit === void 0) {
useFit = this.useFit;
}
var outlines = this.outlines;
var startOutline = outlines.start;
var endOutline = outlines.end;
var outlineOffset = startOutline.length ? Math.min.apply(Math, startOutline) : 0; // If the outline is less than 0, a fit occurs forcibly.
if (!useFit && outlineOffset > 0) {
return;
}
outlines.start = startOutline.map(function (point) {
return point - outlineOffset;
});
outlines.end = endOutline.map(function (point) {
return point - outlineOffset;
});
this.items.forEach(function (item) {
var contentPos = item.cssContentPos;
if (!isNumber(contentPos)) {
return;
}
item.cssContentPos = contentPos - outlineOffset;
});
};
__proto.readyItems = function (mounted, updated, options) {
var prevOutlines = this.outlines;
var direction = options.direction || this.options.defaultDirection;
var prevOutline = options.outline || prevOutlines[direction === "end" ? "start" : "end"];
var items = this.items;
var nextOutlines = {
start: __spreadArrays$2(prevOutline),
end: __spreadArrays$2(prevOutline)
};
if (items.length) {
nextOutlines = this.applyGrid(this.items, direction, prevOutline);
}
this.setOutlines(nextOutlines);
this.fitOutlines();
this.itemRenderer.renderItems(this.items);
this._refreshContainerContentSize();
this._renderComplete({
direction: direction,
mounted: mounted,
updated: updated,
isResize: !!options.useResize
});
};
__proto._renderComplete = function (e) {
/**
* This event is fired when the Grid has completed rendering.
* @ko Grid가 렌더링이 완료됐을 때 발생하는 이벤트이다.
* @event Grid#renderComplete
* @param {Grid.OnRenderComplete} e - The object of data to be sent to an event <ko>이벤트에 전달되는 데이터 객체</ko>
* @example
grid.on("renderComplete", e => {
console.log(e.mounted, e.updated, e.useResize);
});
*/
this.trigger("renderComplete", e);
};
__proto._clearRenderTimer = function () {
clearTimeout(this._renderTimer);
this._renderTimer = 0;
};
__proto._refreshContainerContentSize = function () {
var _a = this.outlines,
startOutline = _a.start,
endOutline = _a.end;
var gap = this.options.gap;
var endPoint = endOutline.length ? Math.max.apply(Math, endOutline) : 0;
var startPoint = startOutline.length ? Math.max.apply(Math, startOutline) : 0;
var contentSize = Math.max(startPoint, endPoint - gap);
this.containerManager.setContentSize(contentSize);
};
__proto._resizeContainer = function () {
this.containerManager.resize();
this.itemRenderer.setContainerRect(this.containerManager.getRect());
};
__proto._init = function () {
this._resizeContainer();
};
var Grid_1;
Grid.defaultOptions = DEFAULT_GRID_OPTIONS;
Grid.propertyTypes = GRID_PROPERTY_TYPES;
Grid = Grid_1 = __decorate$1([GetterSetter], Grid);
return Grid;
}(Component);
/**
* Gap used to create space around items.
* @ko 아이템들 사이의 공간.
* @name Grid#gap
* @type {$ts:Grid.GridOptions["gap"]}
* @example
* import { MasonryGrid } from "@egjs/grid";
*
* const grid = new MasonryGrid(container, {
* gap: 0,
* });
*
* grid.gap = 5;
*/
/**
* The default direction value when direction is not set in the render option.
* @ko render옵션에서 direction을 미설정시의 기본 방향값.
* @name Grid#defaultDirection
* @type {$ts:Grid.GridOptions["defaultDirection"]}
* @example
* import { MasonryGrid } from "@egjs/grid";
*
* const grid = new MasonryGrid(container, {
* defaultDirection: "end",
* });
*
* grid.defaultDirection = "start";
*/
/**
* Whether to move the outline to 0 when the top is empty when rendering. However, if it overflows above the top, the outline is forced to 0. (default: true)
* @ko 렌더링시 상단이 비어있을 때 아웃라인을 0으로 이동시킬지 여부. 하지만 상단보다 넘치는 경우 아웃라인을 0으로 강제 이동한다. (default: true)
* @name Grid#useFit
* @type {$ts:Grid.GridOptions["useFit"]}
* @example
* import { MasonryGrid } from "@egjs/grid";
*
* const grid = new MasonryGrid(container, {
* useFit: true,
* });
*
* grid.useFit = false;
/**
* Whether to preserve the UI of the existing container or item when destroying.
* @ko destroy 시 기존 컨테이너, 아이템의 UI를 보존할지 여부.
* @name Grid#preserveUIOnDestroy
* @type {$ts:Grid.GridOptions["preserveUIOnDestroy"]}
* @example
* import { MasonryGrid } from "@egjs/grid";
*
* const grid = new MasonryGrid(container, {
* preserveUIOnDestroy: false,
* });
*
* grid.preserveUIOnDestroy = true;
*/
function getColumnPoint(outline, columnIndex, columnCount, pointCaculationName) {
return Math[pointCaculationName].apply(Math, outline.slice(columnIndex, columnIndex + columnCount));
}
function getColumnIndex(outline, columnCount, nearestCalculationName) {
var length = outline.length - columnCount + 1;
var pointCaculationName = nearestCalculationName === "max" ? "min" : "max";
var indexCaculationName = nearestCalculationName === "max" ? "lastIndexOf" : "indexOf";
var points = range(length).map(function (index) {
return getColumnPoint(outline, index, columnCount, pointCaculationName);
});
return points[indexCaculationName](Math[nearestCalculationName].apply(Math, points));
}
/**
* MasonryGrid is a grid that stacks items with the same width as a stack of bricks. Adjust the width of all images to the same size, find the lowest height column, and insert a new item.
*
* @ko MasonryGrid는 벽돌을 쌓아 올린 모양처럼 동일한 너비를 가진 아이템를 쌓는 레이아웃이다. 모든 이미지의 너비를 동일한 크기로 조정하고, 가장 높이가 낮은 열을 찾아 새로운 이미지를 삽입한다. 따라서 배치된 아이템 사이에 빈 공간이 생기지는 않지만 배치된 레이아웃의 아래쪽은 울퉁불퉁해진다.
* @memberof Grid
* @param {HTMLElement | string} container - A base element for a module <ko>모듈을 적용할 기준 엘리먼트</ko>
* @param {Grid.MasonryGrid.MasonryGridOptions} options - The option object of the MasonryGrid module <ko>MasonryGrid 모듈의 옵션 객체</ko>
*/
var MasonryGrid =
/*#__PURE__*/
function (_super) {
__extends$2(MasonryGrid, _super);
function MasonryGrid() {
var _this = _super !== null && _super.apply(this, arguments) || this;
_this._columnSize = 0;
_this._column = 1;
return _this;
}
var __proto = MasonryGrid.prototype;
__proto.applyGrid = function (items, direction, outline) {
this._calculateColumnSize(items);
this._calculateColumn(items);
var column = this._column;
var columnSize = this._columnSize;
var _a = this.options,
gap = _a.gap,
align = _a.align,
columnSizeRatio = _a.columnSizeRatio,
columnSizeOption = _a.columnSize;
var outlineLength = outline.length;
var itemsLength = items.length;
var alignPoses = this._getAlignPoses();
var isEndDirection = direction === "end";
var nearestCalculationName = isEndDirection ? "min" : "max";
var pointCalculationName = isEndDirection ? "max" : "min";
var startOutline = [0];
if (outlineLength === column) {
startOutline = outline.slice();
} else {
var point_1 = outlineLength ? Math[pointCalculationName].apply(Math, outline) : 0;
startOutline = range(column).map(function () {
return point_1;
});
}
var endOutline = startOutline.slice();
var columnDist = column > 1 ? alignPoses[1] - alignPoses[0] : 0;
var isStretch = align === "stretch";
var _loop_1 = function (i) {
var item = items[isEndDirection ? i : itemsLength - 1 - i];
var columnAttribute = parseInt(item.attributes.column || "1", 10);
var maxColumnAttribute = parseInt(item.attributes.maxColumn || "1", 10);
var inlineSize = item.inlineSize;
var contentSize = item.contentSize;
var columnCount = Math.min(column, columnAttribute || Math.max(1, Math.ceil((inlineSize + gap) / columnDist)));
var maxColumnCount = Math.min(column, Math.max(columnCount, maxColumnAttribute));
var columnIndex = getColumnIndex(endOutline, columnCount, nearestCalculationName);
var contentPos = getColumnPoint(endOutline, columnIndex, columnCount, pointCalculationName);
while (columnCount < maxColumnCount) {
var nextEndColumnIndex = columnIndex + columnCount;
var nextColumnIndex = columnIndex - 1;
if (isEndDirection && (nextEndColumnIndex >= column || endOutline[nextEndColumnIndex] > contentPos)) {
break;
}
if (!isEndDirection && (nextColumnIndex < 0 || endOutline[nextColumnIndex]) < contentPos) {
break;
}
if (!isEndDirection) {
--columnIndex;
}
++columnCount;
}
columnIndex = Math.max(0, columnIndex);
columnCount = Math.min(column - columnIndex, columnCount);
if (columnAttribute > 0 && (columnCount > 1 || isStretch || columnSizeOption)) {
inlineSize = (columnCount - 1) * columnDist + columnSize;
item.cssInlineSize = inlineSize;
}
if (columnSizeRatio > 0) {
contentSize = inlineSize / columnSizeRatio;
item.cssContentSize = contentSize;
}
var inlinePos = alignPoses[columnIndex];
contentPos = isEndDirection ? contentPos : contentPos - gap - contentSize;
item.cssInlinePos = inlinePos;
item.cssContentPos = contentPos;
var nextOutlinePoint = isEndDirection ? contentPos + contentSize + gap : contentPos;
range(columnCount).forEach(function (indexOffset) {
endOutline[columnIndex + indexOffset] = nextOutlinePoint;
});
};
for (var i = 0; i < itemsLength; ++i) {
_loop_1(i);
} // if end items, startOutline is low, endOutline is high
// if start items, startOutline is high, endOutline is low
return {
start: isEndDirection ? startOutline : endOutline,
end: isEndDirection ? endOutline : startOutline
};
};
__proto._calculateColumnSize = function (items) {
var _a = this.options,
columnSizeOption = _a.columnSize,
gap = _a.gap,
align = _a.align;
if (align === "stretch") {
var column = this.column;
if (columnSizeOption) {
column = Math.max(1, Math.floor((this.getContainerInlineSize() + gap) / (columnSizeOption + gap)));
}
this._columnSize = (this.getContainerInlineSize() + gap) / (column || 1) - gap;
} else if (columnSizeOption) {
this._columnSize = columnSizeOption;
} else if (items.length) {
var checkedItem = items[0];
for (var _i = 0, items_1 = items; _i < items_1.length; _i++) {
var item = items_1[_i];
var attributes = item.attributes;
if (item.updateState !== UPDATE_STATE.UPDATED || !item.inlineSize || attributes.column || attributes.maxColumnCount) {
continue;
}
checkedItem = item;
break;
}
var inlineSize = checkedItem.inlineSize || 0;
this._columnSize = inlineSize;
return inlineSize;
}
this._columnSize = this._columnSize || 0;
return this._columnSize;
};
__proto._calculateColumn = function (items) {
var _a = this.options,
gap = _a.gap,
columnOption = _a.column;
var columnSize = this._columnSize;
var column = 1;
if (columnOption) {
column = columnOption;
} else if (!columnSize) {
column = 1;
} else {
column = Math.min(items.length, Math.max(1, Math.floor((this.getContainerInlineSize() + gap) / (columnSize + gap))));
}
this._column = column;
return column;
};
__proto._getAlignPoses = function () {
var columnSize = this._columnSize;
var column = this._column;
var _a = this.options,
align = _a.align,
gap = _a.gap;
var containerSize = this.getContainerInlineSize();
var indexes = range(column);
var offset = 0;
var dist = 0;
if (align === "justify" || align === "stretch") {
var countDist = column - 1;
dist = countDist ? Math.max((containerSize - columnSize) / countDist, columnSize + gap) : 0;
offset = Math.min(0, containerSize / 2 - (countDist * dist + columnSize) / 2);
} else {
dist = columnSize + gap;
var totalColumnSize = (column - 1) * dist + columnSize;
if (align === "center") {
offset = (containerSize - totalColumnSize) / 2;
} else if (align === "end") {
offset = containerSize - totalColumnSize;
}
}
return indexes.map(function (i) {
return offset + i * dist;
});
};
MasonryGrid.propertyTypes = __assign$2(__assign$2({}, Grid.propertyTypes), {
column: PROPERTY_TYPE.RENDER_PROPERTY,
columnSize: PROPERTY_TYPE.RENDER_PROPERTY,
columnSizeRatio: PROPERTY_TYPE.RENDER_PROPERTY,
align: PROPERTY_TYPE.RENDER_PROPERTY
});
MasonryGrid.defaultOptions = __assign$2(__assign$2({}, Grid.defaultOptions), {
align: "justify",
column: 0,
columnSize: 0,
columnSizeRatio: 0
});
MasonryGrid = __decorate$1([GetterSetter], MasonryGrid);
return MasonryGrid;
}(Grid);
/**
* Align of the position of the items. If you want to use `stretch`, be sure to set `column` or `columnSize` option. ("start", "center", "end", "justify", "stretch") (default: "justify")
* @ko 아이템들의 위치의 정렬. `stretch`를 사용하고 싶다면 `column` 또는 `columnSize` 옵션을 설정해라. ("start", "center", "end", "justify", "stretch") (default: "justify")
* @name Grid.MasonryGrid#align
* @type {$ts:Grid.MasonryGrid.MasonryGridOptions["align"]}
* @example
* import { MasonryGrid } from "@egjs/grid";
*
* const grid = new MasonryGrid(container, {
* align: "start",
* });
*
* grid.align = "justify";
*/
/**
* The number of columns. If the number of columns is 0, it is automatically calculated according to the size of the container.
* @ko 열의 개수. 열의 개수가 0이라면, 컨테이너의 사이즈에 의해 계산이 된다. (default: 0)
* @name Grid.MasonryGrid#column
* @type {$ts:Grid.MasonryGrid.MasonryGridOptions["column"]}
* @example
* import { MasonryGrid } from "@egjs/grid";
*
* const grid = new MasonryGrid(container, {
* column: 0,
* });
*
* grid.column = 4;
*/
/**
* The size of the columns. If it is 0, it is calculated as the size of the first item in items. (default: 0)
* @ko 열의 사이즈. 만약 열의 사이즈가 0이면, 아이템들의 첫번째 아이템의 사이즈로 계산이 된다. (default: 0)
* @name Grid.MasonryGrid#columnSize
* @type {$ts:Grid.MasonryGrid.MasonryGridOptions["columnSize"]}
* @example
* import { MasonryGrid } from "@egjs/grid";
*
* const grid = new MasonryGrid(container, {
* columnSize: 0,
* });
*
* grid.columnSize = 200;
*/
/**
* The size ratio(inlineSize / contentSize) of the columns. 0 is not set. (default: 0)
* @ko 열의 사이즈 비율(inlineSize / contentSize). 0은 미설정이다.
* @name Grid.MasonryGrid#columnSizeRatio
* @type {$ts:Grid.MasonryGrid.MasonryGridOptions["columnSizeRatio"]}
* @example
* import { MasonryGrid } from "@egjs/grid";
*
* const grid = new MasonryGrid(container, {
* columnSizeRatio: 0,
* });
*
* grid.columnSizeRatio = 0.5;
*/
/* eslint-disable */
/******************************************************************************
* Created 2008-08-19.
*
* Dijkstra path-finding functions. Adapted from the Dijkstar Python project.
*
* Copyright (C) 2008
* Wyatt Baldwin <self@wyattbaldwin.com>
* All rights reserved
*
* Licensed under the MIT license.
*
* http://www.opensource.org/licenses/mit-license.php
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*****************************************************************************/
function single_source_shortest_paths(graph, s, d) {
// Predecessor map for each node that has been encountered.
// node ID => predecessor node ID
var predecessors = {}; // Costs of shortest paths from s to all nodes encountered.
// node ID => cost
var costs = {};
costs[s] = 0; // Costs of shortest paths from s to all nodes encountered; differs from
// `costs` in that it provides easy access to the node that currently has
// the known shortest path from s.
// XXX: Do we actually need both `costs` and `open`?
var open = new BinaryHeap(function (x) {
return x.cost;
});
open.push({
value: s,
cost: 0
});
var closest;
var u;
var cost_of_s_to_u;
var adjacent_nodes;
var cost_of_e;
var cost_of_s_to_u_plus_cost_of_e;
var cost_of_s_to_v;
var first_visit;
while (open.size()) {
// In the nodes remaining in graph that have a known cost from s,
// find the node, u, that currently has the shortest path from s.
closest = open.pop();
u = closest.value;
cost_of_s_to_u = closest.cost; // Get nodes adjacent to u...
adjacent_nodes = graph(u) || {}; // ...and explore the edges that connect u to those nodes, updating
// the cost of the shortest paths to any or all of those nodes as
// necessary. v is the node across the current edge from u.
for (var v in adjacent_nodes) {
// Get the cost of the edge running from u to v.
cost_of_e = adjacent_nodes[v]; // Cost of s to u plus the cost of u to v across e--this is *a*
// cost from s to v that may or may not be less than the current
// known cost to v.
cost_of_s_to_u_plus_cost_of_e = cost_of_s_to_u + cost_of_e; // If we haven't visited v yet OR if the current known cost from s to
// v is greater than the new cost we just found (cost of s to u plus
// cost of u to v across e), update v's cost in the cost list and
// update v's predecessor in the predecessor list (it's now u).
cost_of_s_to_v = costs[v];
first_visit = typeof costs[v] === "undefined";
if (first_visit || cost_of_s_to_v > cost_of_s_to_u_plus_cost_of_e) {
costs[v] = cost_of_s_to_u_plus_cost_of_e;
open.push({
value: v,
cost: cost_of_s_to_u_plus_cost_of_e
});
predecessors[v] = u;
}
}
}
if (typeof costs[d] === "undefined") {
var msg = ["Could not find a path from ", s, " to ", d, "."].join("");
throw new Error(msg);
}
return predecessors;
}
function extract_shortest_path_from_predecessor_list(predecessors, d) {
var nodes = [];
var u = d;
while (u) {
nodes.push(u);
u = predecessors[u];
}
nodes.reverse();
return nodes;
}
function find_path(graph, s, d) {
var predecessors = single_source_shortest_paths(graph, s, d);
return extract_shortest_path_from_predecessor_list(predecessors, d);
}
var BinaryHeap =
/*#__PURE__*/
function () {
function BinaryHeap(scoreFunction) {
this.content = [];
this.scoreFunction = scoreFunction;
}
var __proto = BinaryHeap.prototype;
__proto.push = function (element) {
// Add the new element to the end of the array.
this.content.push(element); // Allow it to bubble up.
this.bubbleUp(this.content.length - 1);
};
__proto.pop = function () {
// Store the first element so we can return it later.
var result = this.content[0]; // Get the element at the end of the array.
var end = this.content.pop(); // If there are any elements left, put the end element at the
// start, and let it sink down.
if (this.content.length > 0) {
this.content[0] = end;
this.sinkDown(0);
}
return result;
};
__proto.size = function () {
return this.content.length;
};
__proto.bubbleUp = function (_n) {
var n = _n; // Fetch the element that has to be moved.
var element = this.content[n]; // When at 0, an element can not go up any further.
while (n > 0) {
// Compute the parent element's index, and fetch it.
var parentN = Math.floor((n + 1) / 2) - 1;
var parent = this.content[parentN]; // Swap the elements if the parent is greater.
if (this.scoreFunction(element) < this.scoreFunction(parent)) {
this.content[parentN] = element;
this.content[n] = parent; // Update 'n' to continue at the new position.
n = parentN;
} else {
// Found a parent that is less, no need to move it further.
break;
}
}
};
__proto.sinkDown = function (n) {
// Look up the target element and its score.
var length = this.content.length;
var element = this.content[n];
var elemScore = this.scoreFunction(element);
var child1Score;
while (true) {
// Compute the indices of the child elements.
var child2N = (n + 1) * 2;
var child1N = child2N - 1; // This is used to store the new position of the element,
// if any.
var swap = null; // If the first child exists (is inside the array)...
if (child1N < length) {
// Look it up and compute its score.
var child1 = this.content[child1N];
child1Score = this.scoreFunction(child1); // If the score is less than our element's, we need to swap.
if (child1Score < elemScore) {
swap = child1N;
}
} // Do the same checks for the other child.
if (child2N < length) {
var child2 = this.content[child2N];
var child2Score = this.scoreFunction(child2);
if (child2Score < (swap == null ? elemScore : child1Score)) {
swap = child2N;
}
} // If the element needs to be moved, swap it, and continue.
if (swap !== null) {
this.content[n] = this.content[swap];
this.content[swap] = element;
n = swap;
} else {
// Otherwise, we are done.
break;
}
}
};
return BinaryHeap;
}();
function splitItems(items, path) {
var length = path.length;
var groups = [];
for (var i = 0; i < length - 1; ++i) {
var path1 = parseInt(path[i], 10);
var path2 = parseInt(path[i + 1], 10);
groups.push(items.slice(path1, path2));
}
return groups;
}
function getExpectedColumnSize(item, rowSize) {
var inlineSize = item.orgInlineSize;
var contentSize = item.orgContentSize;
if (!inlineSize || !contentSize) {
return 0;
}
var inlineOffset = parseFloat(item.gridData.inlineOffset) || 0;
var contentOffset = parseFloat(item.gridData.contentOffset) || 0;
return (inlineSize - inlineOffset) / (contentSize - contentOffset) * (rowSize - contentOffset) + inlineOffset;
}
/**
* 'justified' is a printing term with the meaning that 'it fits in one row wide'. JustifiedGrid is a grid that the item is filled up on the basis of a line given a size.
* If 'data-grid-inline-offset' or 'data-grid-content-offset' are set for item element, the ratio is maintained except for the offset value.
* If 'data-grid-maintained-target' is set for an element whose ratio is to be maintained, the item is rendered while maintaining the ratio of the element.
* @ko 'justified'는 '1행의 너비에 맞게 꼭 들어찬'이라는 의미를 가진 인쇄 용어다. JustifiedGrid는 용어의 의미대로 너비가 주어진 사이즈를 기준으로 아이템가 가득 차도록 배치하는 Grid다.
* 아이템 엘리먼트에 'data-grid-inline-offset' 또는 'data-grid-content-offset'를 설정하면 offset 값을 제외하고 비율을 유지한다.
* 비율을 유지하고 싶은 엘리먼트에 'data-grid-maintained-target'을 설정한다면 해당 엘리먼트의 비율을 유지하면서 아이템이 렌더링이 된다.
* @memberof Grid
* @param {HTMLElement | string} container - A base element for a module <ko>모듈을 적용할 기준 엘리먼트</ko>
* @param {Grid.JustifiedGrid.JustifiedGridOptions} options - The option object of the JustifiedGrid module <ko>JustifiedGrid 모듈의 옵션 객체</ko>
*/
var JustifiedGrid =
/*#__PURE__*/
function (_super) {
__extends$2(JustifiedGrid, _super);
function JustifiedGrid() {
return _super !== null && _super.apply(this, arguments) || this;
}
var __proto = JustifiedGrid.prototype;
__proto.applyGrid = function (items, direction, outline) {
var rowRange = this.options.rowRange;
var path = [];
if (items.length) {
path = rowRange ? this._getRowPath(items) : this._getPath(items);
}
return this._setStyle(items, path, outline, direction === "end");
};
__proto.readyItems = function (mounted, updated, options) {
var _a = this.options,
attributePrefix = _a.attributePrefix,
horizontal = _a.horizontal;
updated.forEach(function (item) {
var element = item.element;
var attributes = item.attributes;
var gridData = item.gridData;
var inlineOffset = parseFloat(attributes.inlineOffset) || gridData.inlineOffset || 0;
var contentOffset = parseFloat(attributes.contentOffset) || gridData.contentOffset | 0;
if (element && !("inlineOffset" in attributes) && !("contentOffset" in attributes) && item.mountState === MOUNT_STATE.MOUNTED) {
var maintainedTarget = element.querySelector("[" + attributePrefix + "maintained-target]");
if (maintainedTarget) {
var widthOffset = element.offsetWidth - element.clientWidth + element.scrollWidth - maintainedTarget.clientWidth;
var heightOffset = element.offsetHeight - element.clientHeight + element.scrollHeight - maintainedTarget.clientHeight;
if (horizontal) {
inlineOffset = heightOffset;
contentOffset = widthOffset;
} else {
inlineOffset = widthOffset;
contentOffset = heightOffset;
}
}
}
gridData.inlineOffset = inlineOffset;
gridData.contentOffset = contentOffset;
});
_super.prototype.readyItems.call(this, mounted, updated, options);
};
__proto._getRowPath = function (items) {
var _a;
var columnRange = this._getColumnRange();
var rowRange = this._getRowRange();
var pathLink = this._getRowLink(items, {
path: [0],
cost: 0,
length: 0,
currentNode: 0
}, columnRange, rowRange);
return (_a = pathLink === null || pathLink === void 0 ? void 0 : pathLink.path.map(function (node) {
return "" + node;
})) !== null && _a !== void 0 ? _a : [];
};
__proto._getRowLink = function (items, currentLink, columnRange, rowRange) {
var minColumn = columnRange[0];
var minRow = rowRange[0],
maxRow = rowRange[1];
var lastNode = items.length;
var path = currentLink.path,
pathLength = currentLink.length,
cost = currentLink.cost,
currentNode = currentLink.currentNode; // not reached lastNode but path is exceed or the number of remaining nodes is less than minColumn.
if (currentNode < lastNode && (maxRow <= pathLength || currentNode + minColumn > lastNode)) {
var rangeCost = getRangeCost(lastNode - currentNode, columnRange);
var lastCost = rangeCost * Math.abs(this._getCost(items, currentNode, lastNode));
return __assign$2(__assign$2({}, currentLink), {
length: pathLength + 1,
path: __spreadArrays$2(path, [lastNode]),
currentNode: lastNode,
cost: cost + lastCost,
isOver: true
});
} else if (currentNode >= lastNode) {
return __assign$2(__assign$2({}, currentLink), {
currentNode: lastNode,
isOver: minRow > pathLength || maxRow < pathLength
});
} else {
return this._searchRowLink(items, currentLink, lastNode, columnRange, rowRange);
}
};
__proto._searchRowLink = function (items, currentLink, lastNode, columnRange, rowRange) {
var minColumn = columnRange[0],
maxColumn = columnRange[1];
var currentNode = currentLink.currentNode,
path = currentLink.path,
pathLength = currentLink.length,
cost = currentLink.cost;
var length = Math.min(lastNode, currentNode + maxColumn);
var links = [];
for (var nextNode = currentNode + minColumn; nextNode <= length; ++nextNode) {
if (nextNode === currentNode) {
continue;
}
var nextCost = Math.abs(this._getCost(items, currentNode, nextNode));
var nextLink = this._getRowLink(items, {
path: __spreadArrays$2(path, [nextNode]),
length: pathLength + 1,
cost: cost + nextCost,
currentNode: nextNode
}, columnRange, rowRange);
if (nextLink) {
links.push(nextLink);
}
}
links.sort(function (a, b) {
var aIsOver = a.isOver;
var bIsOver = b.isOver;
if (aIsOver !== bIsOver) {
// If it is over, the cost is high.
return aIsOver ? 1 : -1;
}
var aRangeCost = getRangeCost(a.length, rowRange);
var bRangeCost = getRangeCost(b.length, rowRange);
return aRangeCost - bRangeCost || a.cost - b.cost;
}); // It returns the lowest cost link.
return links[0];
};
__proto._getExpectedRowSize = function (items) {
var gap = this.options.gap;
var containerInlineSize = this.getContainerInlineSize() - gap * (items.length - 1);
var ratioSum = 0;
var inlineSum = 0;
items.forEach(function (item) {
var inlineSize = item.orgInlineSize;
var contentSize = item.orgContentSize;
if (!inlineSize || !contentSize) {
return;
} // sum((expect - offset) * ratio) = container inline size
var inlineOffset = parseFloat(item.gridData.inlineOffset) || 0;
var contentOffset = parseFloat(item.gridData.contentOffset) || 0;
var maintainedRatio = (inlineSize - inlineOffset) / (contentSize - contentOffset);
ratioSum += maintainedRatio;
inlineSum += contentOffset * maintainedRatio;
containerInlineSize -= inlineOffset;
});
return ratioSum ? (containerInlineSize + inlineSum) / ratioSum : 0;
};
__proto._getExpectedInlineSize = function (items, rowSize) {
var gap = this.options.gap;
var size = items.reduce(function (sum, item) {
return sum + getExpectedColumnSize(item, rowSize);
}, 0);
return size ? size + gap * (items.length - 1) : 0;
};
__proto._getCost = function (items, i, j) {
var lineItems = items.slice(i, j);
var rowSize = this._getExpectedRowSize(lineItems);
var _a = this._getSizeRange(),
minSize = _a[0],
maxSize = _a[1];
if (this.isCroppedSize) {
if (minSize <= rowSize && rowSize <= maxSize) {
return 0;
}
var expectedInlineSize = this._getExpectedInlineSize(lineItems, rowSize < minSize ? minSize : maxSize);
return Math.pow(expectedInlineSize - this.getContainerInlineSize(), 2);
}
if (isFinite(maxSize)) {
// if this size is not in range, the cost increases sharply.
if (rowSize < minSize) {
return Math.pow(rowSize - minSize, 2) + Math.pow(maxSize, 2);
} else if (rowSize > maxSize) {
return Math.pow(rowSize - maxSize, 2) + Math.pow(maxSize, 2);
}
} else if (rowSize < minSize) {
return Math.max(Math.pow(minSize, 2), Math.pow(rowSize, 2)) + Math.pow(maxSize, 2);
} // if this size in range, the cost is row
return rowSize - minSize;
};
__proto._getPath = function (items) {
var _this = this;
var lastNode = items.length;
var columnRangeOption = this.options.columnRange;
var _a = isObject(columnRangeOption) ? columnRangeOption : [columnRangeOption, columnRangeOption],
minColumn = _a[0],
maxColumn = _a[1];
var graph = function (nodeKey) {
var results = {};
var currentNode = parseInt(nodeKey, 10);
for (var nextNode = Math.min(currentNode + minColumn, lastNode); nextNode <= lastNode; ++nextNode) {
if (nextNode - currentNode > maxColumn) {
break;
}
var cost = _this._getCost(items, currentNode, nextNode);
if (cost < 0 && nextNode === lastNode) {
cost = 0;
}
results["" + nextNode] = Math.pow(cost, 2);
}
return results;
}; // shortest path for items' total height.
return find_path(graph, "0", "" + lastNode);
};
__proto._setStyle = function (items, path, outline, isEndDirection) {
var _this = this;
if (outline === void 0) {
outline = [];
}
var _a = this.options,
gap = _a.gap,
isCroppedSize = _a.isCroppedSize,
displayedRow = _a.displayedRow;
var sizeRange = this._getSizeRange();
var startPoint = outline[0] || 0;
var containerInlineSize = this.getContainerInlineSize();
var groups = splitItems(items, path);
var contentPos = startPoint;
var displayedSize = 0;
groups.forEach(function (groupItems, rowIndex) {
var length = groupItems.length;
var rowSize = _this._getExpectedRowSize(groupItems);
if (isCroppedSize) {
rowSize = Math.max(sizeRange[0], Math.min(rowSize, sizeRange[1]));
}
var expectedInlineSize = _this._getExpectedInlineSize(groupItems, rowSize);
var allGap = gap * (length - 1);
var scale = (containerInlineSize - allGap) / (expectedInlineSize - allGap);
groupItems.forEach(function (item, i) {
var columnSize = getExpectedColumnSize(item, rowSize);
var prevItem = groupItems[i - 1];
var inlinePos = prevItem ? prevItem.cssInlinePos + prevItem.cssInlineSize + gap : 0;
if (isCroppedSize) {
columnSize *= scale;
}
item.setCSSGridRect({
inlinePos: inlinePos,
contentPos: contentPos,
inlineSize: columnSize,
contentSize: rowSize
});
});
contentPos += gap + rowSize;
if (displayedRow < 0 || rowIndex < displayedRow) {
displayedSize = contentPos;
}
});
if (isEndDirection) {
// previous group's end outline is current group's start outline
return {
start: [startPoint],
end: [displayedSize]
};
} // always start is lower than end.
// contentPos is endPoinnt
var height = contentPos - startPoint;
items.forEach(function (item) {
item.cssContentPos -= height;
});
return {
start: [startPoint - height],
end: [startPoint]
};
};
__proto._getRowRange = function () {
var rowRange = this.rowRange;
return isObject(rowRange) ? rowRange : [rowRange, rowRange];
};
__proto._getColumnRange = function () {
var columnRange = this.columnRange;
return isObject(columnRange) ? columnRange : [columnRange, columnRange];
};
__proto._getSizeRange = function () {
var sizeRange = this.sizeRange;
return isObject(sizeRange) ? sizeRange : [sizeRange, sizeRange];
};
JustifiedGrid.propertyTypes = __assign$2(__assign$2({}, Grid.propertyTypes), {
columnRange: PROPERTY_TYPE.RENDER_PROPERTY,
rowRange: PROPERTY_TYPE.RENDER_PROPERTY,
sizeRange: PROPERTY_TYPE.RENDER_PROPERTY,
isCroppedSize: PROPERTY_TYPE.RENDER_PROPERTY,
displayedRow: PROPERTY_TYPE.RENDER_PROPERTY
});
JustifiedGrid.defaultOptions = __assign$2(__assign$2({}, Grid.defaultOptions), {
columnRange: [1, 8],
rowRange: 0,
sizeRange: [0, Infinity],
displayedRow: -1,
isCroppedSize: false
});
JustifiedGrid = __decorate$1([GetterSetter], JustifiedGrid);
return JustifiedGrid;
}(Grid);
/**
* The minimum and maximum number of items per line. (default: [1, 8])
* @ko 한 줄에 들어가는 아이템의 최소, 최대 개수. (default: [1, 8])
* @name Grid.JustifiedGrid#columnRange
* @type {$ts:Grid.JustifiedGrid.JustifiedGridOptions["columnRange"]}
* @example
* import { JustifiedGrid } from "@egjs/grid";
*
* const grid = new JustifiedGrid(container, {
* columnRange: [1, 8],
* });
*
* grid.columnRange = [3, 6];
*/
/**
* The minimum and maximum number of rows in a group, 0 is not set. (default: 0)
* @ko 한 그룹에 들어가는 행의 최소, 최대 개수, 0은 미설정이다. (default: 0)
* @name Grid.JustifiedGrid#rowRange
* @type {$ts:Grid.JustifiedGrid.JustifiedGridOptions["rowRange"]}
* @example
* import { JustifiedGrid } from "@egjs/grid";
*
* const grid = new JustifiedGrid(container, {
* rowRange: 0,
* });
*
* grid.rowRange = [3, 4];
*/
/**
* The minimum and maximum size by which the item is adjusted. If it is not calculated, it may deviate from the minimum and maximum sizes. (default: [0, Infinity])
* @ko 아이템이 조정되는 최소, 최대 사이즈. 계산이 되지 않는 경우 최소, 최대 사이즈를 벗어날 수 있다. (default: [0, Infinity])
* @name Grid.JustifiedGrid#sizeRange
* @type {$ts:Grid.JustifiedGrid.JustifiedGridOptions["sizeRange"]}
* @example
* import { JustifiedGrid } from "@egjs/grid";
*
* const grid = new JustifiedGrid(container, {
* sizeRange: [0, Infinity],
* });
*
* grid.sizeRange = [200, 800];
*/
/**
* Maximum number of rows to be counted for container size. You can hide it on the screen by setting overflow: hidden. -1 is not set. (default: -1)
* @ko - 컨테이너 크기에 계산될 최대 row 개수. overflow: hidden을 설정하면 화면에 가릴 수 있다. -1은 미설정이다. (default: -1)
* @name Grid.JustifiedGrid#displayedRow
* @type {$ts:Grid.JustifiedGrid.JustifiedGridOptions["displayedRow"]}
* @example
* import { JustifiedGrid } from "@egjs/grid";
*
* const grid = new JustifiedGrid(container, {
* displayedRow: -1,
* });
*
* grid.displayedRow = 3;
*/
/**
* Whether to crop when the row size is out of sizeRange. If set to true, this ratio can be broken. (default: false)
* @ko - row 사이즈가 sizeRange에 벗어나면 크롭할지 여부. true로 설정하면 비율이 깨질 수 있다. (default: false)
* @name Grid.JustifiedGrid#isCroppedSize
* @type {$ts:Grid.JustifiedGrid.JustifiedGridOptions["isCroppedSize"]}
* @example
* import { JustifiedGrid } from "@egjs/grid";
*
* const grid = new JustifiedGrid(container, {
* sizeRange: [200, 250],
* isCroppedSize: false,
* });
*
* grid.isCroppedSize = true;
*/
function getMaxPoint(outline) {
var maxPoint = -Infinity;
outline.forEach(function (point) {
if (isFinite(point)) {
maxPoint = Math.max(maxPoint, point);
}
});
return isFinite(maxPoint) ? maxPoint : 0;
}
function getMinPoint(outline) {
var minPoint = Infinity;
outline.forEach(function (point) {
if (isFinite(point)) {
minPoint = Math.min(minPoint, point);
}
});
return isFinite(minPoint) ? minPoint : 0;
}
function getOutlinePoint(startOutline, frameOutline, useFrameFill) {
return getMaxPoint(startOutline) + getOutlineDist(startOutline, frameOutline, useFrameFill);
}
function getOutlineDist(startOutline, endOutline, useFrameFill) {
var length = startOutline.length;
if (!length) {
return 0;
}
var minEndPoint = getMinPoint(endOutline);
var maxStartPoint = getMaxPoint(startOutline);
var frameDist = 0;
if (!useFrameFill) {
return 0;
}
for (var outlineIndex = 0; outlineIndex < length; ++outlineIndex) {
var startPoint = startOutline[outlineIndex];
var endPoint = endOutline[outlineIndex];
if (!isFinite(startPoint) || !isFinite(endPoint)) {
continue;
}
var startPos = startPoint - maxStartPoint;
var endPos = endPoint - minEndPoint; // Fill empty block.
frameDist = outlineIndex ? Math.max(frameDist, frameDist + startPos - endPos) : startPos - endPos;
}
return frameDist;
}
function fillOutlines(startOutline, endOutline, rect) {
var inlinePos = rect.inlinePos,
inlineSize = rect.inlineSize,
contentPos = rect.contentPos,
contentSize = rect.contentSize;
for (var outlineIndex = inlinePos; outlineIndex < inlinePos + inlineSize; ++outlineIndex) {
startOutline[outlineIndex] = Math.min(startOutline[outlineIndex], contentPos);
endOutline[outlineIndex] = Math.max(endOutline[outlineIndex], contentPos + contentSize);
}
}
/**
* 'Frame' is a printing term with the meaning that 'it fits in one row wide'. FrameGrid is a grid that the item is filled up on the basis of a line given a size.
* @ko 'Frame'는 '1행의 너비에 맞게 꼭 들어찬'이라는 의미를 가진 인쇄 용어다. FrameGrid는 용어의 의미대로 너비가 주어진 사이즈를 기준으로 아이템이 가득 차도록 배치하는 Grid다.
* @memberof Grid
* @param {HTMLElement | string} container - A base element for a module <ko>모듈을 적용할 기준 엘리먼트</ko>
* @param {Grid.FrameGrid.FrameGridOptions} options - The option object of the FrameGrid module <ko>FrameGrid 모듈의 옵션 객체</ko>
*/
var FrameGrid =
/*#__PURE__*/
function (_super) {
__extends$2(FrameGrid, _super);
function FrameGrid() {
return _super !== null && _super.apply(this, arguments) || this;
}
var __proto = FrameGrid.prototype;
__proto.applyGrid = function (items, direction, outline) {
var frame = this._getFrame();
var frameInlineSize = frame.inlineSize,
frameContentSize = frame.contentSize,
frameRects = frame.rects;
var _a = this.options,
gap = _a.gap,
useFrameFill = _a.useFrameFill;
var _b = this.getRectSize(frameInlineSize),
rectInlineSize = _b.inlineSize,
rectContentSize = _b.contentSize;
var itemsLength = items.length;
if (!itemsLength || !frameInlineSize || !frameContentSize) {
return {
start: outline,
end: outline
};
}
var rectsLength = frameRects.length;
var startOutline = range(frameInlineSize).map(function () {
return Infinity;
});
var endOutline = range(frameInlineSize).map(function () {
return -Infinity;
});
var frameOutline = frame.outline.map(function (point) {
return point * (rectContentSize + gap);
});
for (var startIndex = 0; startIndex < itemsLength; startIndex += rectsLength) {
// Compare group's startOutline and startOutline of rect
var startPoint = getOutlinePoint(endOutline, frameOutline, useFrameFill);
for (var rectIndex = 0; rectIndex < rectsLength && startIndex + rectIndex < itemsLength; ++rectIndex) {
var item = items[startIndex + rectIndex];
var _c = frameRects[rectIndex],
frameRectContentPos = _c.contentPos,
frameRectInlinePos = _c.inlinePos,
frameRectContentSize = _c.contentSize,
frameRectInlineSize = _c.inlineSize;
var contentPos = startPoint + frameRectContentPos * (rectContentSize + gap);
var inlinePos = frameRectInlinePos * (rectInlineSize + gap);
var contentSize = frameRectContentSize * (rectContentSize + gap) - gap;
var inlineSize = frameRectInlineSize * (rectInlineSize + gap) - gap;
fillOutlines(startOutline, endOutline, {
inlinePos: frameRectInlinePos,
inlineSize: frameRectInlineSize,
contentPos: contentPos,
contentSize: contentSize + gap
});
item.setCSSGridRect({
inlinePos: inlinePos,
contentPos: contentPos,
inlineSize: inlineSize,
contentSize: contentSize
});
}
}
var isDirectionEnd = direction === "end";
var gridOutline = outline;
if (gridOutline.length !== frameInlineSize) {
var point_1 = isDirectionEnd ? Math.max.apply(Math, gridOutline) : Math.min.apply(Math, gridOutline);
gridOutline = range(frameInlineSize).map(function () {
return point_1;
});
}
startOutline = startOutline.map(function (point) {
return isFinite(point) ? point : 0;
});
endOutline = endOutline.map(function (point) {
return isFinite(point) ? point : 0;
});
var outlineDist = isDirectionEnd ? getOutlineDist(startOutline, gridOutline, useFrameFill) : getOutlineDist(gridOutline, endOutline, useFrameFill);
items.forEach(function (item) {
item.cssContentPos += outlineDist;
});
return {
start: startOutline.map(function (point) {
return point + outlineDist;
}),
end: endOutline.map(function (point) {
return point + outlineDist;
})
};
};
__proto.getRectSize = function (frameInlineSize) {
var _a = this.options,
gap = _a.gap,
rectSizeOption = _a.rectSize;
if (typeof rectSizeOption === "object") {
return rectSizeOption;
}
var rectSizeValue = rectSizeOption ? rectSizeOption : (this.getContainerInlineSize() + gap) / frameInlineSize - gap;
return {
inlineSize: rectSizeValue,
contentSize: rectSizeValue
};
};
__proto._getFrame = function () {
var frame = this.options.frame;
var frameContentSize = frame.length;
var frameInlineSize = frameContentSize ? frame[0].length : 0;
var rects = [];
var passMap = {};
var startOutline = range(frameInlineSize).map(function () {
return Infinity;
});
var endOutline = range(frameInlineSize).map(function () {
return -Infinity;
});
for (var y1 = 0; y1 < frameContentSize; ++y1) {
for (var x1 = 0; x1 < frameInlineSize; ++x1) {
var type = frame[y1][x1];
if (!type) {
continue;
}
if (passMap[y1 + "," + x1]) {
continue;
}
var rect = this._findRect(passMap, type, y1, x1, frameInlineSize, frameContentSize);
fillOutlines(startOutline, endOutline, rect);
rects.push(rect);
}
}
rects.sort(function (a, b) {
return a.type < b.type ? -1 : 1;
});
return {
rects: rects,
inlineSize: frameInlineSize,
contentSize: frameContentSize,
outline: startOutline
};
};
__proto._findRect = function (passMap, type, y1, x1, frameInlineSize, frameContentSize) {
var frame = this.options.frame;
var contentSize = 1;
var inlineSize = 1; // find rect
for (var x2 = x1; x2 < frameInlineSize; ++x2) {
if (frame[y1][x2] === type) {
inlineSize = x2 - x1 + 1;
continue;
}
break;
}
for (var y2 = y1; y2 < frameContentSize; ++y2) {
if (frame[y2][x1] === type) {
contentSize = y2 - y1 + 1;
continue;
}
break;
} // pass rect
for (var y = y1; y < y1 + contentSize; ++y) {
for (var x = x1; x < x1 + inlineSize; ++x) {
passMap[y + "," + x] = true;
}
}
var rect = {
type: type,
inlinePos: x1,
contentPos: y1,
inlineSize: inlineSize,
contentSize: contentSize
};
return rect;
};
FrameGrid.propertyTypes = __assign$2(__assign$2({}, Grid.propertyTypes), {
frame: PROPERTY_TYPE.RENDER_PROPERTY,
useFrameFill: PROPERTY_TYPE.RENDER_PROPERTY,
rectSize: PROPERTY_TYPE.RENDER_PROPERTY
});
FrameGrid.defaultOptions = __assign$2(__assign$2({}, Grid.defaultOptions), {
frame: [],
rectSize: 0,
useFrameFill: true
});
FrameGrid = __decorate$1([GetterSetter], FrameGrid);
return FrameGrid;
}(Grid);
/**
* The shape of the grid. You can set the shape and order of items with a 2d array ([contentPos][inlinePos]). You can place items as many times as you fill the array with numbers, and zeros and spaces are empty spaces. The order of the items is arranged in ascending order of the numeric values that fill the array. (default: [])
* @ko Grid의 모양. 2d 배열([contentPos][inlinePos])로 아이템의 모양과 순서를 설정할 수 있다. 숫자로 배열을 채운만큼 아이템을 배치할 수 있으며 0과 공백은 빈 공간이다. 아이템들의 순서는 배열을 채운 숫자값의 오름차순대로 배치가 된다. (default: [])
* @name Grid.FrameGrid#frame
* @type {$ts:Grid.FrameGrid.FrameGridOptions["frame"]}
* @example
* import { FrameGrid } from "@egjs/grid";
*
* // Item 1 : 2 x 2
* // Item 2 : 1 x 1
* // Item 3 : 1 x 2
* // Item 4 : 1 x 1
* // Item 5 : 2 x 1
* const grid = new FrameGrid(container, {
* frame: [
* [1, 1, 0, 0, 2, 3],
* [1, 1, 0, 4, 5, 5],
* ],
* });
*
* // Item 1 : 2 x 2
* // Item 2 : 2 x 2
* grid.frame = [
* [1, 1, 0, 0, 2, 2],
* [1, 1, 0, 0, 2, 2],
* ];
*/
/**
* Make sure that the frame can be attached after the previous frame. (default: true)
* @ko 다음 프레임이 전 프레임에 이어 붙일 수 있는지 있는지 확인한다. (default: true)
* @name Grid.FrameGrid#useFrameFill
* @type {$ts:Grid.FrameGrid.FrameGridOptions["useFrameFill"]}
* @example
* import { FrameGrid } from "@egjs/grid";
*
* const grid = new FrameGrid(container, {
* useFrameFill: true,
* });
*
* grid.useFrameFill = false;
*/
/**
* 1x1 rect size. If it is 0, it is determined by the number of columns in the frame. (default: 0)
* @ko 1x1 직사각형 크기. 0이면 frame의 column의 개수에 의해 결정된다. (default: 0)
* @name Grid.FrameGrid#rectSize
* @type {$ts:Grid.FrameGrid.FrameGridOptions["rectSize"]}
* @example
* import { FrameGrid } from "@egjs/grid";
*
* const grid = new FrameGrid(container, {
* rectSize: 0,
* });
*
* grid.rectSize = { inlineSize: 100, contentSize: 150 };
*/
var BoxModel =
/*#__PURE__*/
function () {
function BoxModel(status) {
var boxStatus = __assign$2({
orgInlineSize: 0,
orgContentSize: 0,
inlineSize: 0,
contentSize: 0,
inlinePos: 0,
contentPos: 0,
items: []
}, status);
for (var name in boxStatus) {
this[name] = boxStatus[name];
}
}
var __proto = BoxModel.prototype;
__proto.scaleTo = function (inlineSize, contentSize) {
var scaleX = this.inlineSize ? inlineSize / this.inlineSize : 0;
var scaleY = this.contentSize ? contentSize / this.contentSize : 0;
this.items.forEach(function (item) {
if (scaleX !== 0) {
item.inlinePos *= scaleX;
item.inlineSize *= scaleX;
}
if (scaleY !== 0) {
item.contentPos *= scaleY;
item.contentSize *= scaleY;
}
});
this.inlineSize = inlineSize;
this.contentSize = contentSize;
};
__proto.push = function (item) {
this.items.push(item);
};
__proto.getOrgSizeWeight = function () {
return this.orgInlineSize * this.orgContentSize;
};
__proto.getSize = function () {
return this.inlineSize * this.contentSize;
};
__proto.getOrgRatio = function () {
return this.orgContentSize === 0 ? 0 : this.orgInlineSize / this.orgContentSize;
};
__proto.getRatio = function () {
return this.contentSize === 0 ? 0 : this.inlineSize / this.contentSize;
};
return BoxModel;
}();
function getCost(originLength, length) {
var cost = originLength / length;
if (cost < 1) {
cost = 1 / cost;
}
return cost - 1;
}
function fitArea(item, bestFitArea, itemFitSize, containerFitSize, isContentDirection) {
item.contentSize = itemFitSize.contentSize;
item.inlineSize = itemFitSize.inlineSize;
bestFitArea.contentSize = containerFitSize.contentSize;
bestFitArea.inlineSize = containerFitSize.inlineSize;
if (isContentDirection) {
item.contentPos = bestFitArea.contentPos + bestFitArea.contentSize;
item.inlinePos = bestFitArea.inlinePos;
} else {
item.inlinePos = bestFitArea.inlinePos + bestFitArea.inlineSize;
item.contentPos = bestFitArea.contentPos;
}
}
/**
* The PackingGrid is a grid that shows the important items bigger without sacrificing the weight of the items.
* Rows and columns are separated so that items are dynamically placed within the horizontal and vertical space rather than arranged in an orderly fashion.
* If `sizeWeight` is higher than `ratioWeight`, the size of items is preserved as much as possible.
* Conversely, if `ratioWeight` is higher than `sizeWeight`, the ratio of items is preserved as much as possible.
* @ko PackingGrid는 아이템의 본래 크기에 따른 비중을 해치지 않으면서 중요한 카드는 더 크게 보여 주는 레이아웃이다.
* 행과 열이 구분돼 아이템을 정돈되게 배치하는 대신 가로세로 일정 공간 내에서 동적으로 아이템을 배치한다.
* `sizeWeight`가 `ratioWeight`보다 높으면 아이템들의 size가 최대한 보존이 된다.
* 반대로 `ratioWeight`가 `sizeWeight`보다 높으면 아이템들의 비율이 최대한 보존이 된다.
* @memberof Grid
* @param {HTMLElement | string} container - A base element for a module <ko>모듈을 적용할 기준 엘리먼트</ko>
* @param {Grid.PackingGrid.PackingGridOptions} options - The option object of the PackingGrid module <ko>PackingGrid 모듈의 옵션 객체</ko>
*/
var PackingGrid =
/*#__PURE__*/
function (_super) {
__extends$2(PackingGrid, _super);
function PackingGrid() {
return _super !== null && _super.apply(this, arguments) || this;
}
var __proto = PackingGrid.prototype;
__proto.applyGrid = function (items, direction, outline) {
var _this = this;
var _a = this.options,
aspectRatio = _a.aspectRatio,
gap = _a.gap;
var containerInlineSize = this.getContainerInlineSize();
var containerContentSize = containerInlineSize / aspectRatio;
var prevOutline = outline.length ? outline : [0];
var startPoint = direction === "end" ? Math.max.apply(Math, prevOutline) : Math.min.apply(Math, prevOutline) - containerContentSize - gap;
var endPoint = startPoint + containerContentSize + gap;
var container = new BoxModel({});
items.forEach(function (item) {
var model = new BoxModel({
inlineSize: item.orgInlineSize,
contentSize: item.orgContentSize,
orgInlineSize: item.orgInlineSize,
orgContentSize: item.orgContentSize
});
_this._findBestFitArea(container, model);
container.push(model);
container.scaleTo(containerInlineSize + gap, containerContentSize + gap);
});
items.forEach(function (item, i) {
var boxItem = container.items[i];
var inlineSize = boxItem.inlineSize - gap;
var contentSize = boxItem.contentSize - gap;
var contentPos = startPoint + boxItem.contentPos;
var inlinePos = boxItem.inlinePos;
item.setCSSGridRect({
inlinePos: inlinePos,
contentPos: contentPos,
inlineSize: inlineSize,
contentSize: contentSize
});
});
return {
start: [startPoint],
end: [endPoint]
};
};
__proto._findBestFitArea = function (container, item) {
if (container.getRatio() === 0) {
// 아이템 최초 삽입시 전체영역 지정
container.orgInlineSize = item.inlineSize;
container.orgContentSize = item.contentSize;
container.inlineSize = item.inlineSize;
container.contentSize = item.contentSize;
return;
}
var bestFitArea;
var minCost = Infinity;
var isContentDirection = false;
var itemFitSize = {
inlineSize: 0,
contentSize: 0
};
var containerFitSize = {
inlineSize: 0,
contentSize: 0
};
var sizeWeight = this._getWeight("size");
var ratioWeight = this._getWeight("ratio");
container.items.forEach(function (child) {
var containerSizeCost = getCost(child.getOrgSizeWeight(), child.getSize()) * sizeWeight;
var containerRatioCost = getCost(child.getOrgRatio(), child.getRatio()) * ratioWeight;
var inlineSize = child.inlineSize;
var contentSize = child.contentSize;
for (var i = 0; i < 2; ++i) {
var itemInlineSize = void 0;
var itemContentSize = void 0;
var containerInlineSize = void 0;
var containerContentSize = void 0;
if (i === 0) {
// add item to content pos (top, bottom)
itemInlineSize = inlineSize;
itemContentSize = contentSize * (item.contentSize / (child.orgContentSize + item.contentSize));
containerInlineSize = inlineSize;
containerContentSize = contentSize - itemContentSize;
} else {
// add item to inline pos (left, right)
itemContentSize = contentSize;
itemInlineSize = inlineSize * (item.inlineSize / (child.orgInlineSize + item.inlineSize));
containerContentSize = contentSize;
containerInlineSize = inlineSize - itemInlineSize;
}
var itemSize = itemInlineSize * itemContentSize;
var itemRatio = itemInlineSize / itemContentSize;
var containerSize = containerInlineSize * containerContentSize;
var containerRatio = containerContentSize / containerContentSize;
var cost = getCost(item.getSize(), itemSize) * sizeWeight;
cost += getCost(item.getRatio(), itemRatio) * ratioWeight;
cost += getCost(child.getOrgSizeWeight(), containerSize) * sizeWeight - containerSizeCost;
cost += getCost(child.getOrgRatio(), containerRatio) * ratioWeight - containerRatioCost;
if (cost === Math.min(cost, minCost)) {
minCost = cost;
bestFitArea = child;
isContentDirection = i === 0;
itemFitSize.inlineSize = itemInlineSize;
itemFitSize.contentSize = itemContentSize;
containerFitSize.inlineSize = containerInlineSize;
containerFitSize.contentSize = containerContentSize;
}
}
});
fitArea(item, bestFitArea, itemFitSize, containerFitSize, isContentDirection);
};
__proto._getWeight = function (type) {
var options = this.options;
var weightPriority = options.weightPriority;
if (weightPriority === type) {
return 100;
} else if (weightPriority === "custom") {
return options[type + "Weight"];
}
return 1;
};
PackingGrid.propertyTypes = __assign$2(__assign$2({}, Grid.propertyTypes), {
aspectRatio: PROPERTY_TYPE.RENDER_PROPERTY,
sizeWeight: PROPERTY_TYPE.RENDER_PROPERTY,
ratioWeight: PROPERTY_TYPE.RENDER_PROPERTY,
weightPriority: PROPERTY_TYPE.RENDER_PROPERTY
});
PackingGrid.defaultOptions = __assign$2(__assign$2({}, Grid.defaultOptions), {
aspectRatio: 1,
sizeWeight: 1,
ratioWeight: 1,
weightPriority: "custom"
});
PackingGrid = __decorate$1([GetterSetter], PackingGrid);
return PackingGrid;
}(Grid);
var ua$1 = typeof window !== "undefined" ? window.navigator.userAgent : "";
var IS_IOS = /iPhone|iPad/.test(ua$1);
var CONTAINER_CLASS_NAME = "infinitegrid-container";
var IGNORE_PROPERITES_MAP = {
renderOnPropertyChange: true,
useFit: true,
autoResize: true
};
var INFINITEGRID_PROPERTY_TYPES = __assign({}, GRID_PROPERTY_TYPES);
var INFINITEGRID_EVENTS = {
SCROLL: "scroll",
REQUEST_APPEND: "requestAppend",
REQUEST_PREPEND: "requestPrepend",
RENDER_COMPLETE: "renderComplete",
CONTENT_ERROR: "contentError"
}; // type?: ITEM_TYPE;
// groupKey?: string | number;
// key?: string | number;
// element?: HTMLElement | null;
// html?: string;
// data?: Record<string, any>;
var ITEM_INFO_PROPERTIES = {
type: true,
groupKey: true,
key: true,
element: true,
html: true,
data: true
};
var INFINITEGRID_METHODS = ["updateItems", "getItems", "getVisibleItems", "getGroups", "getVisibleGroups", "renderItems", "getContainerElement", "getScrollContainerElement", "getWrapperElement", "setStatus", "getStatus", "removePlaceholders", "prependPlaceholders", "appendPlaceholders", "getStartCursor", "getEndCursor", "setCursors"];
var GROUP_TYPE;
(function (GROUP_TYPE) {
GROUP_TYPE[GROUP_TYPE["NORMAL"] = 1] = "NORMAL";
GROUP_TYPE[GROUP_TYPE["VIRTUAL"] = 2] = "VIRTUAL";
GROUP_TYPE[GROUP_TYPE["LOADING"] = 3] = "LOADING";
})(GROUP_TYPE || (GROUP_TYPE = {}));
var ITEM_TYPE;
(function (ITEM_TYPE) {
ITEM_TYPE[ITEM_TYPE["NORMAL"] = 1] = "NORMAL";
ITEM_TYPE[ITEM_TYPE["VIRTUAL"] = 2] = "VIRTUAL";
ITEM_TYPE[ITEM_TYPE["LOADING"] = 3] = "LOADING";
})(ITEM_TYPE || (ITEM_TYPE = {}));
var STATUS_TYPE;
(function (STATUS_TYPE) {
// does not remove anything.
STATUS_TYPE[STATUS_TYPE["NOT_REMOVE"] = 0] = "NOT_REMOVE"; // Minimize information on invisible items
STATUS_TYPE[STATUS_TYPE["MINIMIZE_INVISIBLE_ITEMS"] = 1] = "MINIMIZE_INVISIBLE_ITEMS"; // Minimize information on invisible groups
STATUS_TYPE[STATUS_TYPE["MINIMIZE_INVISIBLE_GROUPS"] = 2] = "MINIMIZE_INVISIBLE_GROUPS"; // remove invisible groups
STATUS_TYPE[STATUS_TYPE["REMOVE_INVISIBLE_GROUPS"] = 3] = "REMOVE_INVISIBLE_GROUPS";
})(STATUS_TYPE || (STATUS_TYPE = {}));
var INVISIBLE_POS = -9999;
var InfiniteGridItem =
/*#__PURE__*/
function (_super) {
__extends(InfiniteGridItem, _super);
function InfiniteGridItem(horizontal, itemStatus) {
var _this = _super.call(this, horizontal, __assign({
html: "",
type: ITEM_TYPE.NORMAL,
cssRect: {
top: INVISIBLE_POS,
left: INVISIBLE_POS
}
}, itemStatus)) || this;
if (_this.type === ITEM_TYPE.VIRTUAL) {
if (_this.rect.width || _this.rect.height) {
_this.mountState = MOUNT_STATE.UNMOUNTED;
}
var orgRect = _this.orgRect;
var rect = _this.rect;
var cssRect = _this.cssRect;
if (cssRect.width) {
rect.width = cssRect.width;
} else if (orgRect.width) {
rect.width = orgRect.width;
}
if (cssRect.height) {
rect.height = cssRect.height;
} else if (orgRect.height) {
rect.height = orgRect.height;
}
}
return _this;
}
var __proto = InfiniteGridItem.prototype;
__proto.getVirtualStatus = function () {
return {
type: ITEM_TYPE.VIRTUAL,
groupKey: this.groupKey,
key: this.key,
orgRect: this.orgRect,
rect: this.rect,
cssRect: this.cssRect,
attributes: this.attributes
};
};
__proto.getMinimizedStatus = function () {
var status = __assign(__assign({}, _super.prototype.getStatus.call(this)), {
type: ITEM_TYPE.NORMAL,
groupKey: this.groupKey
});
if (this.html) {
status.html = this.html;
}
return status;
};
return InfiniteGridItem;
}(GridItem);
var LOADING_GROUP_KEY = "__INFINITEGRID__LOADING_GRID";
var LOADING_ITEM_KEY = "__INFINITEGRID__LOADING_ITEM";
var LoadingGrid =
/*#__PURE__*/
function (_super) {
__extends(LoadingGrid, _super);
function LoadingGrid() {
var _this = _super !== null && _super.apply(this, arguments) || this;
_this.type = "";
return _this;
}
var __proto = LoadingGrid.prototype;
__proto.getLoadingItem = function () {
return this.items[0] || null;
};
__proto.setLoadingItem = function (item) {
if (item) {
var loadingItem = this.getLoadingItem();
if (!loadingItem) {
this.items = [new InfiniteGridItem(this.options.horizontal, __assign(__assign({}, item), {
type: ITEM_TYPE.LOADING,
key: LOADING_ITEM_KEY
}))];
} else {
for (var name in item) {
loadingItem[name] = item[name];
}
}
} else {
this.items = [];
}
};
__proto.applyGrid = function (items, direction, outline) {
if (!items.length) {
return {
start: outline,
end: outline
};
}
var nextOutline = outline.length ? __spreadArrays(outline) : [0];
var item = items[0];
var offset = item.contentSize + this.gap;
item.cssInlinePos = this.getContainerInlineSize() / 2 - item.inlineSize / 2;
if (direction === "end") {
var maxPos = Math.max.apply(Math, nextOutline);
item.cssContentPos = maxPos;
return {
start: nextOutline,
end: nextOutline.map(function (pos) {
return pos + offset;
})
};
} else {
var minPos = Math.min.apply(Math, nextOutline);
item.cssContentPos = minPos - offset;
return {
start: nextOutline.map(function (pos) {
return pos - offset;
}),
end: nextOutline
};
}
};
return LoadingGrid;
}(Grid);
function isWindow$1(el) {
return el === window;
}
function isNumber$1(val) {
return typeof val === "number";
}
function isString$1(val) {
return typeof val === "string";
}
function isObject$1(val) {
return typeof val === "object";
}
function flat(arr) {
return arr.reduce(function (prev, cur) {
return __spreadArrays(prev, cur);
}, []);
}
function splitOptions(options) {
var gridOptions = options.gridOptions,
otherOptions = __rest(options, ["gridOptions"]);
return __assign(__assign({}, splitGridOptions(gridOptions)), otherOptions);
}
function splitGridOptions(options) {
var nextOptions = {};
var gridOptions = {};
var defaultOptions = Grid.defaultOptions;
for (var name in options) {
var value = options[name];
if (!(name in IGNORE_PROPERITES_MAP)) {
gridOptions[name] = value;
}
if (name in defaultOptions) {
nextOptions[name] = value;
}
}
return __assign(__assign({}, nextOptions), {
gridOptions: gridOptions
});
}
function categorize(items) {
var groups = [];
var groupKeys = {};
var registeredGroupKeys = {};
items.filter(function (item) {
return item.groupKey != null;
}).forEach(function (_a) {
var groupKey = _a.groupKey;
registeredGroupKeys[groupKey] = true;
});
var generatedGroupKey;
var isContinuousGroupKey = false;
items.forEach(function (item) {
if (item.groupKey != null) {
isContinuousGroupKey = false;
} else {
if (!isContinuousGroupKey) {
generatedGroupKey = makeKey(registeredGroupKeys);
isContinuousGroupKey = true;
registeredGroupKeys[generatedGroupKey] = true;
}
item.groupKey = generatedGroupKey;
}
var groupKey = item.groupKey;
var group = groupKeys[groupKey];
if (!group) {
group = {
groupKey: groupKey,
items: []
};
groupKeys[groupKey] = group;
groups.push(group);
}
group.items.push(item);
});
return groups;
}
function getNextCursors(prevKeys, nextKeys, prevStartCursor, prevEndCursor) {
var result = diff(prevKeys, nextKeys, function (key) {
return key;
});
var nextStartCursor = -1;
var nextEndCursor = -1; // sync cursors
result.maintained.forEach(function (_a) {
var prevIndex = _a[0],
nextIndex = _a[1];
if (prevStartCursor <= prevIndex && prevIndex <= prevEndCursor) {
if (nextStartCursor === -1) {
nextStartCursor = nextIndex;
nextEndCursor = nextIndex;
} else {
nextStartCursor = Math.min(nextStartCursor, nextIndex);
nextEndCursor = Math.max(nextEndCursor, nextIndex);
}
}
});
return {
startCursor: nextStartCursor,
endCursor: nextEndCursor
};
}
function splitVirtualGroups(groups, direction, nextGroups) {
var virtualGroups = [];
if (direction === "start") {
var index = findIndex(groups, function (group) {
return group.type === GROUP_TYPE.NORMAL;
});
if (index === -1) {
return [];
}
virtualGroups = groups.slice(0, index);
} else {
var index = findLastIndex(groups, function (group) {
return group.type === GROUP_TYPE.NORMAL;
});
if (index === -1) {
return [];
}
virtualGroups = groups.slice(index + 1);
}
var nextVirtualGroups = diff(virtualGroups, nextGroups, function (_a) {
var groupKey = _a.groupKey;
return groupKey;
}).removed.map(function (index) {
return virtualGroups[index];
}).reverse();
return nextVirtualGroups;
}
function getFirstRenderingItems(nextItems, horizontal) {
var groups = categorize(nextItems);
if (!groups[0]) {
return [];
}
return groups[0].items.map(function (item) {
return new InfiniteGridItem(horizontal, __assign({}, item));
});
}
function getRenderingItemsByStatus(groupManagerStatus, nextItems, usePlaceholder, horizontal) {
var prevGroups = groupManagerStatus.groups;
var groups = categorize(nextItems);
var startVirtualGroups = splitVirtualGroups(prevGroups, "start", groups);
var endVirtualGroups = splitVirtualGroups(prevGroups, "end", groups);
var nextGroups = __spreadArrays(startVirtualGroups, groups, endVirtualGroups);
var _a = getNextCursors(prevGroups.map(function (group) {
return group.groupKey;
}), nextGroups.map(function (group) {
return group.groupKey;
}), groupManagerStatus.cursors[0], groupManagerStatus.cursors[1]),
startCursor = _a.startCursor,
endCursor = _a.endCursor;
var nextVisibleItems = flat(nextGroups.slice(startCursor, endCursor + 1).map(function (group) {
return group.items.map(function (item) {
return new InfiniteGridItem(horizontal, __assign({}, item));
});
}));
if (!usePlaceholder) {
nextVisibleItems = nextVisibleItems.filter(function (item) {
return item.type !== ITEM_TYPE.VIRTUAL;
});
}
return nextVisibleItems;
}
/* Class Decorator */
function InfiniteGridGetterSetter(component) {
var prototype = component.prototype,
propertyTypes = component.propertyTypes;
var _loop_1 = function (name) {
var attributes = {
enumerable: true,
configurable: true,
get: function () {
var options = this.groupManager.options;
if (name in options) {
return options[name];
} else {
return options.gridOptions[name];
}
},
set: function (value) {
var prevValue = this.groupManager[name];
if (prevValue === value) {
return;
}
this.groupManager[name] = value;
}
};
Object.defineProperty(prototype, name, attributes);
};
for (var name in propertyTypes) {
_loop_1(name);
}
}
function makeKey(registeredKeys) {
// eslint-disable-next-line no-constant-condition
while (true) {
var key = new Date().getTime() + Math.floor(Math.random() * 1000);
if (!(key in registeredKeys)) {
return key;
}
}
}
function convertHTMLtoElement(html) {
var dummy = document.createElement("div");
dummy.innerHTML = html;
return toArray$1(dummy.children);
}
function convertInsertedItems(items, groupKey) {
var insertedItems;
if (isString$1(items)) {
insertedItems = convertHTMLtoElement(items);
} else {
insertedItems = items;
}
return insertedItems.map(function (item) {
var element;
var html = "";
var key;
if (isString$1(item)) {
html = item;
} else if ("parentNode" in item) {
element = item;
html = item.outerHTML;
} else {
return __assign({
groupKey: groupKey
}, item);
}
return {
key: key,
groupKey: groupKey,
html: html,
element: element
};
});
}
function toArray$1(nodes) {
var array = [];
if (nodes) {
var length = nodes.length;
for (var i = 0; i < length; i++) {
array.push(nodes[i]);
}
}
return array;
}
function findIndex(arr, callback) {
var length = arr.length;
for (var i = 0; i < length; ++i) {
if (callback(arr[i], i)) {
return i;
}
}
return -1;
}
function findLastIndex(arr, callback) {
var length = arr.length;
for (var i = length - 1; i >= 0; --i) {
if (callback(arr[i], i)) {
return i;
}
}
return -1;
}
function getItemInfo(info) {
var nextInfo = {};
for (var name in info) {
if (name in ITEM_INFO_PROPERTIES) {
nextInfo[name] = info[name];
}
}
return nextInfo;
}
function setPlaceholder(item, info) {
for (var name in info) {
var value = info[name];
if (isObject$1(value)) {
item[name] = __assign(__assign({}, item[name]), value);
} else {
item[name] = info[name];
}
}
}
function isFlatOutline(start, end) {
return start.length === end.length && start.every(function (pos, i) {
return end[i] === pos;
});
}
function range$1(length) {
var arr = [];
for (var i = 0; i < length; ++i) {
arr.push(i);
}
return arr;
}
function flatGroups(groups) {
return flat(groups.map(function (_a) {
var grid = _a.grid;
return grid.getItems();
}));
}
function filterVirtuals(items, includePlaceholders) {
if (includePlaceholders) {
return items;
} else {
return items.filter(function (item) {
return item.type !== ITEM_TYPE.VIRTUAL;
});
}
}
/**
* Decorator that makes the method of InfiniteGrid available in the framework.
* @ko 프레임워크에서 InfiniteGrid의 메소드를 사용할 수 있게 하는 데코레이터.
* @memberof InfiniteGrid
* @private
* @example
* ```js
* import { withInfiniteGridMethods } from "@egjs/infinitegrid";
*
* class Grid extends React.Component<Partial<InfiniteGridProps & InfiniteGridOptions>> {
* @withInfiniteGridMethods
* private grid: NativeGrid;
* }
* ```
*/
var withInfiniteGridMethods = withMethods(INFINITEGRID_METHODS);
var GroupManager =
/*#__PURE__*/
function (_super) {
__extends(GroupManager, _super);
function GroupManager(container, options) {
var _this = _super.call(this, container, splitOptions(options)) || this;
_this.groupItems = [];
_this.groups = [];
_this.itemKeys = {};
_this.groupKeys = {};
_this.startCursor = 0;
_this.endCursor = 0;
_this._placeholder = null;
_this._loadingGrid = new LoadingGrid(container, {
externalContainerManager: _this.containerManager,
useFit: false,
autoResize: false,
renderOnPropertyChange: false,
gap: _this.gap
});
return _this;
}
var __proto = GroupManager.prototype;
Object.defineProperty(__proto, "gridOptions", {
set: function (options) {
var _a = splitGridOptions(options),
gridOptions = _a.gridOptions,
otherOptions = __rest(_a, ["gridOptions"]);
var shouldRender = this._checkShouldRender(options);
this.options.gridOptions = gridOptions;
this.groups.forEach(function (_a) {
var grid = _a.grid;
for (var name in options) {
grid[name] = options[name];
}
});
for (var name in otherOptions) {
this[name] = otherOptions[name];
}
this._loadingGrid.gap = this.gap;
if (shouldRender) {
this.scheduleRender();
}
},
enumerable: false,
configurable: true
});
__proto.getItemByKey = function (key) {
return this.itemKeys[key] || null;
};
__proto.getGroupItems = function (includePlaceholders) {
return filterVirtuals(this.groupItems, includePlaceholders);
};
__proto.getVisibleItems = function (includePlaceholders) {
return filterVirtuals(this.items, includePlaceholders);
};
__proto.getRenderingItems = function () {
if (this.hasPlaceholder()) {
return this.items;
} else {
return this.items.filter(function (item) {
return item.type !== ITEM_TYPE.VIRTUAL;
});
}
};
__proto.getGroups = function (includePlaceholders) {
return filterVirtuals(this.groups, includePlaceholders);
};
__proto.hasVisibleVirtualGroups = function () {
return this.getVisibleGroups(true).some(function (group) {
return group.type === GROUP_TYPE.VIRTUAL;
});
};
__proto.hasPlaceholder = function () {
return !!this._placeholder;
};
__proto.hasLoadingItem = function () {
return !!this._getLoadingItem();
};
__proto.setPlaceholder = function (placeholder) {
this._placeholder = placeholder;
this._updatePlaceholder();
};
__proto.getLoadingType = function () {
return this._loadingGrid.type;
};
__proto.startLoading = function (type) {
this._loadingGrid.type = type;
this.items = this._getRenderingItems();
return true;
};
__proto.endLoading = function () {
var prevType = this._loadingGrid.type;
this._loadingGrid.type = "";
this.items = this._getRenderingItems();
return !!prevType;
};
__proto.setLoading = function (loading) {
this._loadingGrid.setLoadingItem(loading);
this.items = this._getRenderingItems();
};
__proto.getVisibleGroups = function (includePlaceholders) {
var groups = this.groups.slice(this.startCursor, this.endCursor + 1);
return filterVirtuals(groups, includePlaceholders);
};
__proto.applyGrid = function (items, direction, outline) {
var _this = this;
items.forEach(function (item) {
item.mountState = MOUNT_STATE.MOUNTED;
});
var renderingGroups = this.groups.slice();
if (!renderingGroups.length) {
return {
start: [],
end: []
};
}
var loadingGrid = this._loadingGrid;
if (loadingGrid.getLoadingItem()) {
if (loadingGrid.type === "start") {
renderingGroups.unshift(this._getLoadingGroup());
} else if (loadingGrid.type === "end") {
renderingGroups.push(this._getLoadingGroup());
}
}
var groups = renderingGroups.slice();
var nextOutline = outline;
if (direction === "start") {
groups.reverse();
}
groups.forEach(function (group) {
var grid = group.grid;
var gridItems = grid.getItems();
var isVirtual = group.type === GROUP_TYPE.VIRTUAL && !gridItems[0];
var appliedItems = gridItems.filter(function (item) {
return item.mountState !== MOUNT_STATE.UNCHECKED && item.rect.width;
});
var gridOutlines;
if (isVirtual) {
gridOutlines = _this._applyVirtualGrid(grid, direction, nextOutline);
} else if (appliedItems.length) {
gridOutlines = grid.applyGrid(appliedItems, direction, nextOutline);
} else {
gridOutlines = {
start: __spreadArrays(nextOutline),
end: __spreadArrays(nextOutline)
};
}
grid.setOutlines(gridOutlines);
nextOutline = gridOutlines[direction];
});
return {
start: renderingGroups[0].grid.getOutlines().start,
end: renderingGroups[renderingGroups.length - 1].grid.getOutlines().end
};
};
__proto.syncItems = function (nextItemInfos) {
var _this = this;
var prevItemKeys = this.itemKeys;
this.itemKeys = {};
var nextItems = this._syncItemInfos(nextItemInfos.map(function (info) {
return getItemInfo(info);
}), prevItemKeys);
var prevGroupKeys = this.groupKeys;
var nextManagerGroups = categorize(nextItems);
var startVirtualGroups = this._splitVirtualGroups("start", nextManagerGroups);
var endVirtualGroups = this._splitVirtualGroups("end", nextManagerGroups);
nextManagerGroups = __spreadArrays(startVirtualGroups, this._mergeVirtualGroups(nextManagerGroups), endVirtualGroups);
var nextGroups = nextManagerGroups.map(function (_a) {
var _b, _c;
var groupKey = _a.groupKey,
items = _a.items;
var isVirtual = !items[0] || items[0].type === ITEM_TYPE.VIRTUAL;
var grid = (_c = (_b = prevGroupKeys[groupKey]) === null || _b === void 0 ? void 0 : _b.grid) !== null && _c !== void 0 ? _c : _this._makeGrid();
var gridItems = isVirtual ? items : items.filter(function (_a) {
var type = _a.type;
return type === ITEM_TYPE.NORMAL;
});
grid.setItems(gridItems);
return {
type: isVirtual ? GROUP_TYPE.VIRTUAL : GROUP_TYPE.NORMAL,
groupKey: groupKey,
grid: grid,
items: gridItems,
renderItems: items
};
});
this._registerGroups(nextGroups);
};
__proto.renderItems = function (options) {
if (options === void 0) {
options = {};
}
if (options.useResize) {
this.groupItems.forEach(function (item) {
item.updateState = UPDATE_STATE.NEED_UPDATE;
});
var loadingItem = this._getLoadingItem();
if (loadingItem) {
loadingItem.updateState = UPDATE_STATE.NEED_UPDATE;
}
}
return _super.prototype.renderItems.call(this, options);
};
__proto.setCursors = function (startCursor, endCursor) {
this.startCursor = startCursor;
this.endCursor = endCursor;
this.items = this._getRenderingItems();
};
__proto.getStartCursor = function () {
return this.startCursor;
};
__proto.getEndCursor = function () {
return this.endCursor;
};
__proto.getGroupStatus = function (type) {
var orgStartCursor = this.startCursor;
var orgEndCursor = this.endCursor;
var orgGroups = this.groups;
var startCursor = orgStartCursor;
var endCursor = orgEndCursor;
var isMinimizeItems = type === STATUS_TYPE.MINIMIZE_INVISIBLE_ITEMS;
var isMinimizeGroups = type === STATUS_TYPE.MINIMIZE_INVISIBLE_GROUPS;
var groups;
if (type === STATUS_TYPE.REMOVE_INVISIBLE_GROUPS) {
groups = this.getVisibleGroups();
endCursor -= startCursor;
startCursor = 0;
} else {
groups = this.getGroups();
}
var groupStatus = groups.map(function (_a, i) {
var grid = _a.grid,
groupKey = _a.groupKey;
var isOutsideCursor = i < startCursor || endCursor < i;
var isVirtualItems = isMinimizeItems && isOutsideCursor;
var isVirtualGroup = isMinimizeGroups && isOutsideCursor;
var gridItems = grid.getItems();
var items = isVirtualGroup ? [] : gridItems.map(function (item) {
return isVirtualItems ? item.getVirtualStatus() : item.getMinimizedStatus();
});
return {
type: isVirtualGroup || isVirtualItems ? GROUP_TYPE.VIRTUAL : GROUP_TYPE.NORMAL,
groupKey: groupKey,
outlines: grid.getOutlines(),
items: items
};
});
var startGroup = orgGroups[orgStartCursor];
var endGroup = orgGroups[orgEndCursor];
var totalItems = this.getGroupItems();
var itemStartCursor = totalItems.indexOf(startGroup === null || startGroup === void 0 ? void 0 : startGroup.items[0]);
var itemEndCursor = totalItems.indexOf(endGroup === null || endGroup === void 0 ? void 0 : endGroup.items.slice().reverse()[0]);
return {
cursors: [startCursor, endCursor],
orgCursors: [orgStartCursor, orgEndCursor],
itemCursors: [itemStartCursor, itemEndCursor],
startGroupKey: startGroup === null || startGroup === void 0 ? void 0 : startGroup.groupKey,
endGroupKey: endGroup === null || endGroup === void 0 ? void 0 : endGroup.groupKey,
groups: groupStatus,
outlines: this.outlines
};
};
__proto.setGroupStatus = function (status) {
var _this = this;
this.itemKeys = {};
this.groupItems = [];
this.items = [];
var prevGroupKeys = this.groupKeys;
var nextGroups = status.groups.map(function (_a) {
var _b, _c;
var type = _a.type,
groupKey = _a.groupKey,
items = _a.items,
outlines = _a.outlines;
var nextItems = _this._syncItemInfos(items);
var grid = (_c = (_b = prevGroupKeys[groupKey]) === null || _b === void 0 ? void 0 : _b.grid) !== null && _c !== void 0 ? _c : _this._makeGrid();
grid.setOutlines(outlines);
grid.setItems(nextItems);
return {
type: type,
groupKey: groupKey,
grid: grid,
items: nextItems,
renderItems: nextItems
};
});
this.setOutlines(status.outlines);
this._registerGroups(nextGroups);
this._updatePlaceholder();
this.setCursors(status.cursors[0], status.cursors[1]);
};
__proto.appendPlaceholders = function (items, groupKey) {
return this.insertPlaceholders("end", items, groupKey);
};
__proto.prependPlaceholders = function (items, groupKey) {
return this.insertPlaceholders("start", items, groupKey);
};
__proto.removePlaceholders = function (type) {
var groups = this.groups;
var length = groups.length;
if (type === "start") {
var index = findIndex(groups, function (group) {
return group.type === GROUP_TYPE.NORMAL;
});
groups.splice(0, index);
} else if (type === "end") {
var index = findLastIndex(groups, function (group) {
return group.type === GROUP_TYPE.NORMAL;
});
groups.splice(index + 1, length - index - 1);
} else {
var groupKey_1 = type.groupKey;
var index = findIndex(groups, function (group) {
return group.groupKey === groupKey_1;
});
if (index > -1) {
groups.splice(index, 1);
}
}
this.syncItems(flatGroups(this.getGroups()));
};
__proto.insertPlaceholders = function (direction, items, groupKey) {
var _a, _b;
if (groupKey === void 0) {
groupKey = makeKey(this.groupKeys);
}
var infos = [];
if (isNumber$1(items)) {
infos = range$1(items).map(function () {
return {
type: ITEM_TYPE.VIRTUAL,
groupKey: groupKey
};
});
} else if (Array.isArray(items)) {
infos = items.map(function (status) {
return __assign(__assign({
groupKey: groupKey
}, status), {
type: ITEM_TYPE.VIRTUAL
});
});
}
var grid = this._makeGrid();
var nextItems = this._syncItemInfos(infos, this.itemKeys);
this._updatePlaceholder(nextItems);
grid.setItems(nextItems);
var group = {
type: GROUP_TYPE.VIRTUAL,
groupKey: groupKey,
grid: grid,
items: nextItems,
renderItems: nextItems
};
if (direction === "end") {
this.groups.push(group);
(_a = this.groupItems).push.apply(_a, nextItems);
} else {
this.groups.splice(0, 0, group);
(_b = this.groupItems).splice.apply(_b, __spreadArrays([0, 0], nextItems));
if (this.startCursor > -1) {
++this.startCursor;
++this.endCursor;
}
}
return {
group: group,
items: nextItems
};
};
__proto.checkRerenderItems = function () {
var isRerender = false;
this.getVisibleGroups().forEach(function (group) {
var items = group.items;
if (items.length === group.renderItems.length || items.every(function (item) {
return item.mountState === MOUNT_STATE.UNCHECKED;
})) {
return;
}
isRerender = true;
group.renderItems = __spreadArrays(items);
});
return isRerender;
};
__proto._getGroupItems = function () {
return flatGroups(this.getGroups(true));
};
__proto._getRenderingItems = function () {
var items = flat(this.getVisibleGroups(true).map(function (item) {
return item.renderItems;
}));
var loadingGrid = this._loadingGrid;
var loadingItem = loadingGrid.getLoadingItem();
if (loadingItem) {
if (loadingGrid.type === "end") {
items.push(loadingItem);
} else if (loadingGrid.type === "start") {
items.unshift(loadingItem);
}
}
return items;
};
__proto._checkShouldRender = function (options) {
var GridConstructor = this.options.gridConstructor;
var prevOptions = this.gridOptions;
var propertyTypes = GridConstructor.propertyTypes;
for (var name in prevOptions) {
if (!(name in options) && propertyTypes[name] === PROPERTY_TYPE.RENDER_PROPERTY) {
return true;
}
}
for (var name in options) {
if (prevOptions[name] !== options[name] && propertyTypes[name] === PROPERTY_TYPE.RENDER_PROPERTY) {
return true;
}
}
return false;
};
__proto._applyVirtualGrid = function (grid, direction, outline) {
var startOutline = outline.length ? __spreadArrays(outline) : [0];
var prevOutlines = grid.getOutlines();
var prevOutline = prevOutlines[direction === "end" ? "start" : "end"];
if (prevOutline.length !== startOutline.length || prevOutline.some(function (value, i) {
return value !== startOutline[i];
})) {
return {
start: __spreadArrays(startOutline),
end: __spreadArrays(startOutline)
};
}
return prevOutlines;
};
__proto._syncItemInfos = function (nextItemInfos, prevItemKeys) {
if (prevItemKeys === void 0) {
prevItemKeys = {};
}
var horizontal = this.options.horizontal;
var nextItemKeys = this.itemKeys;
nextItemInfos.filter(function (info) {
return info.key != null;
}).forEach(function (info) {
var key = info.key;
var prevItem = prevItemKeys[key];
if (!prevItem) {
nextItemKeys[key] = new InfiniteGridItem(horizontal, __assign({}, info));
} else if (prevItem.type === ITEM_TYPE.VIRTUAL && info.type !== ITEM_TYPE.VIRTUAL) {
nextItemKeys[key] = new InfiniteGridItem(horizontal, __assign({
orgRect: prevItem.orgRect,
rect: prevItem.rect
}, info));
} else {
if (info.data) {
prevItem.data = info.data;
}
nextItemKeys[key] = prevItem;
}
});
var nextItems = nextItemInfos.map(function (info) {
var key = info.key;
if (info.key == null) {
key = makeKey(nextItemKeys);
nextItemKeys[key] = new InfiniteGridItem(horizontal, __assign(__assign({}, info), {
key: key
}));
}
return nextItemKeys[key];
});
return nextItems;
};
__proto._registerGroups = function (groups) {
var nextGroupKeys = {};
groups.forEach(function (group) {
nextGroupKeys[group.groupKey] = group;
});
this.groups = groups;
this.groupKeys = nextGroupKeys;
this.groupItems = this._getGroupItems();
};
__proto._splitVirtualGroups = function (direction, nextGroups) {
var groups = splitVirtualGroups(this.groups, direction, nextGroups);
var itemKeys = this.itemKeys;
groups.forEach(function (_a) {
var renderItems = _a.renderItems;
renderItems.forEach(function (item) {
itemKeys[item.key] = item;
});
});
return groups;
};
__proto._mergeVirtualGroups = function (groups) {
var itemKeys = this.itemKeys;
var groupKeys = this.groupKeys;
groups.forEach(function (group) {
var prevGroup = groupKeys[group.groupKey];
if (!prevGroup) {
return;
}
var items = group.items;
if (items.every(function (item) {
return item.mountState === MOUNT_STATE.UNCHECKED;
})) {
prevGroup.renderItems.forEach(function (item) {
if (item.type === ITEM_TYPE.VIRTUAL && !itemKeys[item.key]) {
items.push(item);
itemKeys[item.key] = item;
}
});
}
});
return groups;
};
__proto._updatePlaceholder = function (items) {
if (items === void 0) {
items = this.groupItems;
}
var placeholder = this._placeholder;
if (!placeholder) {
return;
}
items.filter(function (item) {
return item.type === ITEM_TYPE.VIRTUAL;
}).forEach(function (item) {
setPlaceholder(item, placeholder);
});
};
__proto._makeGrid = function () {
var GridConstructor = this.options.gridConstructor;
var gridOptions = this.gridOptions;
var container = this.containerElement;
return new GridConstructor(container, __assign(__assign({}, gridOptions), {
useFit: false,
autoResize: false,
renderOnPropertyChange: false,
externalContainerManager: this.containerManager,
externalItemRenderer: this.itemRenderer
}));
};
__proto._getLoadingGroup = function () {
var loadingGrid = this._loadingGrid;
var items = loadingGrid.getItems();
return {
groupKey: LOADING_GROUP_KEY,
type: GROUP_TYPE.NORMAL,
grid: loadingGrid,
items: items,
renderItems: items
};
};
__proto._getLoadingItem = function () {
return this._loadingGrid.getLoadingItem();
};
GroupManager.defaultOptions = __assign(__assign({}, Grid.defaultOptions), {
gridConstructor: null,
gridOptions: {}
});
GroupManager.propertyTypes = __assign(__assign({}, Grid.propertyTypes), {
gridConstructor: PROPERTY_TYPE.PROPERTY,
gridOptions: PROPERTY_TYPE.PROPERTY
});
GroupManager = __decorate([GetterSetter], GroupManager);
return GroupManager;
}(Grid);
var Infinite =
/*#__PURE__*/
function (_super) {
__extends(Infinite, _super);
function Infinite(options) {
var _this = _super.call(this) || this;
_this.startCursor = -1;
_this.endCursor = -1;
_this.size = 0;
_this.items = [];
_this.itemKeys = {};
_this.options = __assign({
threshold: 0,
useRecycle: true,
defaultDirection: "end"
}, options);
return _this;
}
var __proto = Infinite.prototype;
__proto.scroll = function (scrollPos) {
var prevStartCursor = this.startCursor;
var prevEndCursor = this.endCursor;
var items = this.items;
var length = items.length;
var size = this.size;
var _a = this.options,
defaultDirection = _a.defaultDirection,
threshold = _a.threshold,
useRecycle = _a.useRecycle;
var isDirectionEnd = defaultDirection === "end";
if (!length) {
this.trigger(isDirectionEnd ? "requestAppend" : "requestPrepend", {
key: undefined,
isVirtual: false
});
return;
} else if (prevStartCursor === -1 || prevEndCursor === -1) {
var nextCursor = isDirectionEnd ? 0 : length - 1;
this.trigger("change", {
prevStartCursor: prevStartCursor,
prevEndCursor: prevEndCursor,
nextStartCursor: nextCursor,
nextEndCursor: nextCursor
});
return;
}
var endScrollPos = scrollPos + size;
var startEdgePos = Math.max.apply(Math, items[prevStartCursor].startOutline);
var endEdgePos = Math.min.apply(Math, items[prevEndCursor].endOutline);
var visibles = items.map(function (item) {
var startOutline = item.startOutline,
endOutline = item.endOutline;
if (!startOutline.length || !endOutline.length) {
return false;
}
var startPos = Math.min.apply(Math, startOutline);
var endPos = Math.max.apply(Math, endOutline);
if (startPos - threshold <= endScrollPos && scrollPos <= endPos + threshold) {
return true;
}
return false;
});
var hasStartItems = 0 < prevStartCursor;
var hasEndItems = prevEndCursor < length - 1;
var isStart = scrollPos <= startEdgePos + threshold;
var isEnd = endScrollPos >= endEdgePos - threshold;
var nextStartCursor = visibles.indexOf(true);
var nextEndCursor = visibles.lastIndexOf(true);
if (nextStartCursor === -1) {
nextStartCursor = prevStartCursor;
nextEndCursor = prevEndCursor;
}
if (!useRecycle) {
nextStartCursor = Math.min(nextStartCursor, prevStartCursor);
nextEndCursor = Math.max(nextEndCursor, prevEndCursor);
}
if (nextStartCursor === prevStartCursor && hasStartItems && isStart) {
nextStartCursor -= 1;
}
if (nextEndCursor === prevEndCursor && hasEndItems && isEnd) {
nextEndCursor += 1;
}
if (prevStartCursor !== nextStartCursor || prevEndCursor !== nextEndCursor) {
this.trigger("change", {
prevStartCursor: prevStartCursor,
prevEndCursor: prevEndCursor,
nextStartCursor: nextStartCursor,
nextEndCursor: nextEndCursor
});
return;
} else if (this._requestVirtualItems()) {
return;
} else if ((!isDirectionEnd || !isEnd) && isStart) {
this.trigger("requestPrepend", {
key: items[prevStartCursor].key,
isVirtual: false
});
} else if ((isDirectionEnd || !isStart) && isEnd) {
this.trigger("requestAppend", {
key: items[prevEndCursor].key,
isVirtual: false
});
}
};
/**
* @private
* Call the requestAppend or requestPrepend event to fill the virtual items.
* @ko virtual item을 채우기 위해 requestAppend 또는 requestPrepend 이벤트를 호출합니다.
* @return - Whether the event is called. <ko>이벤트를 호출했는지 여부.</ko>
*/
__proto._requestVirtualItems = function () {
var isDirectionEnd = this.options.defaultDirection === "end";
var items = this.items;
var totalVisibleItems = this.getVisibleItems();
var visibleItems = totalVisibleItems.filter(function (item) {
return !item.isVirtual;
});
var totalVisibleLength = totalVisibleItems.length;
var visibleLength = visibleItems.length;
var startCursor = this.getStartCursor();
var endCursor = this.getEndCursor();
if (visibleLength === totalVisibleLength) {
return false;
} else if (visibleLength) {
var startKey_1 = visibleItems[0].key;
var endKey_1 = visibleItems[visibleLength - 1].key;
var startIndex = findIndex(items, function (item) {
return item.key === startKey_1;
}) - 1;
var endIndex = findIndex(items, function (item) {
return item.key === endKey_1;
}) + 1;
var isEnd = endIndex <= endCursor;
var isStart = startIndex >= startCursor; // Fill the placeholder with the original item.
if ((isDirectionEnd || !isStart) && isEnd) {
this.trigger("requestAppend", {
key: endKey_1,
nextKey: items[endIndex].key,
isVirtual: true
});
return true;
} else if ((!isDirectionEnd || !isEnd) && isStart) {
this.trigger("requestPrepend", {
key: startKey_1,
nextKey: items[startIndex].key,
isVirtual: true
});
return true;
}
} else if (totalVisibleLength) {
var lastItem = totalVisibleItems[totalVisibleLength - 1];
if (isDirectionEnd) {
this.trigger("requestAppend", {
nextKey: totalVisibleItems[0].key,
isVirtual: true
});
} else {
this.trigger("requestPrepend", {
nextKey: lastItem.key,
isVirtual: true
});
}
return true;
}
return false;
};
__proto.setCursors = function (startCursor, endCursor) {
this.startCursor = startCursor;
this.endCursor = endCursor;
};
__proto.setSize = function (size) {
this.size = size;
};
__proto.getStartCursor = function () {
return this.startCursor;
};
__proto.getEndCursor = function () {
return this.endCursor;
};
__proto.isLoading = function (direction) {
var startCursor = this.startCursor;
var endCursor = this.endCursor;
var items = this.items;
var firstItem = items[startCursor];
var lastItem = items[endCursor];
var length = items.length;
if (direction === "end" && endCursor < length - 1 && !lastItem.isVirtual && !isFlatOutline(lastItem.startOutline, lastItem.endOutline)) {
return false;
}
if (direction === "start" && startCursor > 0 && !firstItem.isVirtual && !isFlatOutline(firstItem.startOutline, firstItem.endOutline)) {
return false;
}
return true;
};
__proto.setItems = function (nextItems) {
this.items = nextItems;
var itemKeys = {};
nextItems.forEach(function (item) {
itemKeys[item.key] = item;
});
this.itemKeys = itemKeys;
};
__proto.syncItems = function (nextItems) {
var prevItems = this.items;
var prevStartCursor = this.startCursor;
var prevEndCursor = this.endCursor;
var _a = getNextCursors(this.items.map(function (item) {
return item.key;
}), nextItems.map(function (item) {
return item.key;
}), prevStartCursor, prevEndCursor),
nextStartCursor = _a.startCursor,
nextEndCursor = _a.endCursor; // sync items between cursors
var isChange = nextEndCursor - nextStartCursor !== prevEndCursor - prevStartCursor || prevStartCursor === -1 || nextStartCursor === -1;
if (!isChange) {
var prevVisibleItems = prevItems.slice(prevStartCursor, prevEndCursor + 1);
var nextVisibleItems = nextItems.slice(nextStartCursor, nextEndCursor + 1);
var visibleResult = diff(prevVisibleItems, nextVisibleItems, function (item) {
return item.key;
});
isChange = visibleResult.added.length > 0 || visibleResult.removed.length > 0 || visibleResult.changed.length > 0;
}
this.setItems(nextItems);
this.setCursors(nextStartCursor, nextEndCursor);
return isChange;
};
__proto.getItems = function () {
return this.items;
};
__proto.getVisibleItems = function () {
var startCursor = this.startCursor;
var endCursor = this.endCursor;
if (startCursor === -1) {
return [];
}
return this.items.slice(startCursor, endCursor + 1);
};
__proto.getItemByKey = function (key) {
return this.itemKeys[key];
};
__proto.getRenderedVisibleItems = function () {
var items = this.getVisibleItems();
var rendered = items.map(function (_a) {
var startOutline = _a.startOutline,
endOutline = _a.endOutline;
var length = startOutline.length;
if (length === 0 || length !== endOutline.length) {
return false;
}
return startOutline.some(function (pos, i) {
return endOutline[i] !== pos;
});
});
var startIndex = rendered.indexOf(true);
var endIndex = rendered.lastIndexOf(true);
return endIndex === -1 ? [] : items.slice(startIndex, endIndex + 1);
};
__proto.destroy = function () {
this.off();
this.startCursor = -1;
this.endCursor = -1;
this.items = [];
this.size = 0;
};
return Infinite;
}(Component);
var Renderer =
/*#__PURE__*/
function (_super) {
__extends(Renderer, _super);
function Renderer() {
var _this = _super !== null && _super.apply(this, arguments) || this;
_this.items = [];
_this.container = null;
_this.rendererKey = 0;
_this._updateTimer = 0;
_this._state = {};
return _this;
}
var __proto = Renderer.prototype;
__proto.updateKey = function () {
this.rendererKey = Date.now();
};
__proto.getItems = function () {
return this.items;
};
__proto.setContainer = function (container) {
this.container = container;
};
__proto.setItems = function (items) {
var rendererKey = this.rendererKey;
this.items = items.map(function (item) {
return __assign(__assign({}, item), {
renderKey: rendererKey + "_" + item.key
});
});
};
__proto.render = function (nextItems, state) {
if (state) {
this._state = state;
}
return this.syncItems(nextItems);
};
__proto.update = function (state) {
var _this = this;
if (state === void 0) {
state = {};
}
this._state = state;
this.trigger("update", {
state: state
});
clearTimeout(this._updateTimer);
this._updateTimer = window.setTimeout(function () {
_this.trigger("requestUpdate", {
state: state
});
});
};
__proto.updated = function (nextElements) {
var items = this.items;
var diffResult = this._diffResult;
var isChanged = !!(diffResult.added.length || diffResult.removed.length || diffResult.changed.length);
var state = this._state;
this._state = {};
items.forEach(function (item, i) {
item.element = nextElements[i];
});
this.trigger("updated", {
items: items,
elements: toArray$1(nextElements),
diffResult: this._diffResult,
state: state,
isChanged: isChanged
});
return isChanged;
};
__proto.destroy = function () {
this.off();
};
__proto.syncItems = function (nextItems) {
var prevItems = this.items;
this.setItems(nextItems);
var result = diff(prevItems, this.items, function (item) {
return item.renderKey;
});
this._diffResult = result;
return result;
};
return Renderer;
}(Component);
var VanillaRenderer =
/*#__PURE__*/
function (_super) {
__extends(VanillaRenderer, _super);
function VanillaRenderer() {
return _super !== null && _super.apply(this, arguments) || this;
}
var __proto = VanillaRenderer.prototype;
__proto.render = function (nextItems, state) {
var container = this.container;
var result = _super.prototype.render.call(this, nextItems, state);
var prevList = result.prevList,
removed = result.removed,
ordered = result.ordered,
added = result.added,
list = result.list;
var diffList = __spreadArrays(prevList);
removed.forEach(function (index) {
diffList.splice(index, 1);
container.removeChild(prevList[index].element);
});
ordered.forEach(function (_a) {
var _b, _c;
var prevIndex = _a[0],
nextIndex = _a[1];
var item = diffList.splice(prevIndex, 1)[0];
diffList.splice(nextIndex, 0, item);
container.insertBefore(item.element, (_c = (_b = diffList[nextIndex + 1]) === null || _b === void 0 ? void 0 : _b.element) !== null && _c !== void 0 ? _c : null);
});
added.forEach(function (index) {
var _a, _b;
var item = list[index];
diffList.splice(index, 0, item);
container.insertBefore(item.element, (_b = (_a = diffList[index + 1]) === null || _a === void 0 ? void 0 : _a.element) !== null && _b !== void 0 ? _b : null);
});
this.updated(container.children);
return result;
};
return VanillaRenderer;
}(Renderer);
var VanillaGridRenderer =
/*#__PURE__*/
function (_super) {
__extends(VanillaGridRenderer, _super);
function VanillaGridRenderer() {
return _super !== null && _super.apply(this, arguments) || this;
}
var __proto = VanillaGridRenderer.prototype;
__proto.syncItems = function (nextItems) {
var result = _super.prototype.syncItems.call(this, nextItems);
var added = result.added,
list = result.list;
added.forEach(function (index) {
var orgItem = nextItems[index].orgItem;
if (orgItem.html && !orgItem.element) {
orgItem.element = convertHTMLtoElement(orgItem.html)[0];
}
list[index].element = orgItem.element;
});
return result;
};
return VanillaGridRenderer;
}(VanillaRenderer);
var ScrollManager =
/*#__PURE__*/
function (_super) {
__extends(ScrollManager, _super);
function ScrollManager(wrapper, options) {
var _this = _super.call(this) || this;
_this.wrapper = wrapper;
_this.prevScrollPos = null;
_this.scrollOffset = 0;
_this.contentSize = 0;
_this._isScrollIssue = IS_IOS;
_this._onCheck = function () {
var prevScrollPos = _this.getScrollPos();
var nextScrollPos = _this.getOrgScrollPos();
_this.setScrollPos(nextScrollPos);
if (prevScrollPos === null || _this._isScrollIssue && nextScrollPos === 0 || prevScrollPos === nextScrollPos) {
nextScrollPos && (_this._isScrollIssue = false);
return;
}
_this._isScrollIssue = false;
_this.trigger(new ComponentEvent$1("scroll", {
direction: prevScrollPos < nextScrollPos ? "end" : "start",
scrollPos: nextScrollPos,
relativeScrollPos: _this.getRelativeScrollPos()
}));
};
_this.options = __assign({
container: false,
containerTag: "div",
horizontal: false
}, options);
_this._init();
return _this;
}
var __proto = ScrollManager.prototype;
__proto.getWrapper = function () {
return this.wrapper;
};
__proto.getContainer = function () {
return this.container;
};
__proto.getScrollContainer = function () {
return this.scrollContainer;
};
__proto.getScrollOffset = function () {
return this.scrollOffset;
};
__proto.getContentSize = function () {
return this.contentSize;
};
__proto.getRelativeScrollPos = function () {
return (this.prevScrollPos || 0) - this.scrollOffset;
};
__proto.getScrollPos = function () {
return this.prevScrollPos;
};
__proto.setScrollPos = function (pos) {
this.prevScrollPos = pos;
};
__proto.getOrgScrollPos = function () {
var eventTarget = this.eventTarget;
var horizontal = this.options.horizontal;
var prop = "scroll" + (horizontal ? "Left" : "Top");
if (isWindow$1(eventTarget)) {
return window[horizontal ? "pageXOffset" : "pageYOffset"] || document.documentElement[prop] || document.body[prop];
} else {
return eventTarget[prop];
}
};
__proto.setStatus = function (status) {
this.contentSize = status.contentSize;
this.scrollOffset = status.scrollOffset;
this.prevScrollPos = status.prevScrollPos;
this.scrollTo(this.prevScrollPos);
};
__proto.getStatus = function () {
return {
contentSize: this.contentSize,
scrollOffset: this.scrollOffset,
prevScrollPos: this.prevScrollPos
};
};
__proto.scrollTo = function (pos) {
var eventTarget = this.eventTarget;
var horizontal = this.options.horizontal;
var _a = horizontal ? [pos, 0] : [0, pos],
x = _a[0],
y = _a[1];
if (isWindow$1(eventTarget)) {
eventTarget.scroll(x, y);
} else {
eventTarget.scrollLeft = x;
eventTarget.scrollTop = y;
}
};
__proto.scrollBy = function (pos) {
if (!pos) {
return;
}
var eventTarget = this.eventTarget;
var horizontal = this.options.horizontal;
var _a = horizontal ? [pos, 0] : [0, pos],
x = _a[0],
y = _a[1];
this.prevScrollPos += pos;
if (isWindow$1(eventTarget)) {
eventTarget.scrollBy(x, y);
} else {
eventTarget.scrollLeft += x;
eventTarget.scrollTop += y;
}
};
__proto.resize = function () {
var scrollContainer = this.scrollContainer;
var horizontal = this.options.horizontal;
var scrollContainerRect = scrollContainer === document.body ? {
top: 0,
left: 0
} : scrollContainer.getBoundingClientRect();
var containerRect = this.container.getBoundingClientRect();
this.scrollOffset = (this.prevScrollPos || 0) + (horizontal ? containerRect.left - scrollContainerRect.left : containerRect.top - scrollContainerRect.top);
this.contentSize = horizontal ? scrollContainer.offsetWidth : scrollContainer.offsetHeight;
};
__proto.destroy = function () {
var container = this.container;
this.eventTarget.removeEventListener("scroll", this._onCheck);
if (this._isCreateElement) {
var scrollContainer = this.scrollContainer;
var fragment_1 = document.createDocumentFragment();
var childNodes = toArray$1(container.childNodes);
scrollContainer.removeChild(container);
childNodes.forEach(function (childNode) {
fragment_1.appendChild(childNode);
});
scrollContainer.appendChild(fragment_1);
} else if (this.options.container) {
container.style.cssText = this._orgCSSText;
}
};
__proto._init = function () {
var _a;
var _b = this.options,
containerOption = _b.container,
containerTag = _b.containerTag,
horizontal = _b.horizontal;
var wrapper = this.wrapper;
var scrollContainer = wrapper;
var container = wrapper;
if (!containerOption) {
scrollContainer = document.body;
} else {
if (containerOption instanceof HTMLElement) {
// Container that already exists
container = containerOption;
} else if (containerOption === true) {
// Create Container
container = document.createElement(containerTag);
container.style.position = "relative";
container.className = CONTAINER_CLASS_NAME;
var childNodes = toArray$1(scrollContainer.childNodes);
childNodes.forEach(function (childNode) {
container.appendChild(childNode);
});
scrollContainer.appendChild(container);
this._isCreateElement = true;
} else {
// Find Container by Selector
container = scrollContainer.querySelector(containerOption);
}
var style = scrollContainer.style;
_a = horizontal ? ["scroll", "hidden"] : ["hidden", "scroll"], style.overflowX = _a[0], style.overflowY = _a[1];
}
var eventTarget = scrollContainer === document.body ? window : scrollContainer;
eventTarget.addEventListener("scroll", this._onCheck);
this._orgCSSText = container.style.cssText;
this.container = container;
this.scrollContainer = scrollContainer;
this.eventTarget = eventTarget;
this.resize();
this.setScrollPos(this.getOrgScrollPos());
};
return ScrollManager;
}(Component);
/**
* A module used to arrange items including content infinitely according to layout type. With this module, you can implement various layouts composed of different items whose sizes vary. It guarantees performance by maintaining the number of DOMs the module is handling under any circumstance
* @ko 콘텐츠가 있는 아이템을 레이아웃 타입에 따라 무한으로 배치하는 모듈. 다양한 크기의 아이템을 다양한 레이아웃으로 배치할 수 있다. 아이템의 개수가 계속 늘어나도 모듈이 처리하는 DOM의 개수를 일정하게 유지해 최적의 성능을 보장한다
* @extends Component
* @support {"ie": "9+(with polyfill)", "ch" : "latest", "ff" : "latest", "sf" : "latest", "edge" : "latest", "ios" : "7+", "an" : "4.X+"}
* @example
```html
<ul id="grid">
<li class="card">
<div>test1</div>
</li>
<li class="card">
<div>test2</div>
</li>
<li class="card">
<div>test3</div>
</li>
<li class="card">
<div>test4</div>
</li>
<li class="card">
<div>test5</div>
</li>
<li class="card">
<div>test6</div>
</li>
</ul>
<script>
import { MasonryGrid } from "@egjs/infinitegrid";
var some = new MasonryGrid("#grid").on("renderComplete", function(e) {
// ...
});
// If you already have items in the container, call "layout" method.
some.renderItems();
</script>
```
*/
var InfiniteGrid =
/*#__PURE__*/
function (_super) {
__extends(InfiniteGrid, _super);
/**
* @param - A base element for a module <ko>모듈을 적용할 기준 엘리먼트</ko>
* @param - The option object of the InfiniteGrid module <ko>eg.InfiniteGrid 모듈의 옵션 객체</ko>
*/
function InfiniteGrid(wrapper, options) {
var _this = _super.call(this) || this;
_this._waitType = "";
_this._onScroll = function (_a) {
var direction = _a.direction,
scrollPos = _a.scrollPos,
relativeScrollPos = _a.relativeScrollPos;
_this._scroll();
_this.trigger(new ComponentEvent$1(INFINITEGRID_EVENTS.SCROLL, {
direction: direction,
scrollPos: scrollPos,
relativeScrollPos: relativeScrollPos
}));
};
_this._onChange = function (e) {
// console.log(e.prevStartCursor, e.prevEndCursor, e.nextStartCursor, e.nextEndCursor);
_this.setCursors(e.nextStartCursor, e.nextEndCursor);
};
_this._onRendererUpdated = function (e) {
if (!e.isChanged) {
_this._checkEndLoading();
_this._scroll();
return;
}
var renderedItems = e.items;
var _a = e.diffResult,
added = _a.added,
removed = _a.removed,
prevList = _a.prevList,
list = _a.list;
removed.forEach(function (index) {
var orgItem = prevList[index].orgItem;
if (orgItem.mountState !== MOUNT_STATE.UNCHECKED) {
orgItem.mountState = MOUNT_STATE.UNMOUNTED;
}
});
renderedItems.forEach(function (item) {
// set grid element
var gridItem = item.orgItem;
gridItem.element = item.element;
return gridItem;
});
var horizontal = _this.options.horizontal;
var addedItems = added.map(function (index) {
var gridItem = list[index].orgItem;
var element = gridItem.element;
if (gridItem.type === ITEM_TYPE.VIRTUAL) {
var cssRect = __assign({}, gridItem.cssRect);
var rect = gridItem.rect;
if (!cssRect.width && rect.width) {
cssRect.width = rect.width;
}
if (!cssRect.height && rect.height) {
cssRect.height = rect.height;
} // virtual item
return new GridItem(horizontal, {
element: element,
cssRect: cssRect
});
}
return gridItem;
});
var _b = e.state,
isRestore = _b.isRestore,
isResize = _b.isResize;
_this.itemRenderer.renderItems(addedItems);
if (isRestore) {
_this._onRenderComplete({
mounted: added.map(function (index) {
return list[index].orgItem;
}),
updated: [],
isResize: false,
direction: _this.defaultDirection
});
if (isResize) {
_this.groupManager.renderItems();
}
} else {
_this.groupManager.renderItems();
}
};
_this._onResize = function () {
_this.renderItems({
useResize: true
});
};
_this._onRequestAppend = function (e) {
_this._onRequestInsert("end", INFINITEGRID_EVENTS.REQUEST_APPEND, e);
};
_this._onRequestPrepend = function (e) {
_this._onRequestInsert("start", INFINITEGRID_EVENTS.REQUEST_PREPEND, e);
};
_this._onContentError = function (_a) {
var element = _a.element,
target = _a.target,
item = _a.item,
update = _a.update;
_this.trigger(new ComponentEvent$1(INFINITEGRID_EVENTS.CONTENT_ERROR, {
element: element,
target: target,
item: item,
update: update,
remove: function () {
_this.removeByKey(item.key);
}
}));
};
_this._onRenderComplete = function (_a) {
var isResize = _a.isResize,
mounted = _a.mounted,
updated = _a.updated,
direction = _a.direction;
var infinite = _this.infinite;
var prevRenderedGroups = infinite.getRenderedVisibleItems();
var length = prevRenderedGroups.length;
var isDirectionEnd = direction === "end";
_this._syncInfinite();
if (length) {
var prevStandardGroup = prevRenderedGroups[isDirectionEnd ? 0 : length - 1];
var nextStandardGroup = infinite.getItemByKey(prevStandardGroup.key);
var offset = isDirectionEnd ? Math.min.apply(Math, nextStandardGroup.startOutline) - Math.min.apply(Math, prevStandardGroup.startOutline) : Math.max.apply(Math, nextStandardGroup.endOutline) - Math.max.apply(Math, prevStandardGroup.endOutline);
if (offset) {
console.log(offset, prevRenderedGroups, infinite.getRenderedVisibleItems());
}
_this.scrollManager.scrollBy(offset);
}
_this.trigger(new ComponentEvent$1(INFINITEGRID_EVENTS.RENDER_COMPLETE, {
isResize: isResize,
direction: direction,
mounted: mounted.filter(function (item) {
return item.type !== ITEM_TYPE.LOADING;
}),
updated: updated.filter(function (item) {
return item.type !== ITEM_TYPE.LOADING;
}),
startCursor: _this.getStartCursor(),
endCursor: _this.getEndCursor(),
items: _this.getVisibleItems(true),
groups: _this.getVisibleGroups(true)
}));
if (_this.groupManager.checkRerenderItems()) {
_this._update();
} else {
_this._checkEndLoading();
_this._scroll();
}
};
_this.options = __assign(__assign(__assign({}, _this.constructor.defaultOptions), {
renderer: new VanillaGridRenderer().on("requestUpdate", function () {
return _this._render();
})
}), options);
var _a = _this.options,
gridConstructor = _a.gridConstructor,
containerTag = _a.containerTag,
container = _a.container,
renderer = _a.renderer,
threshold = _a.threshold,
useRecycle = _a.useRecycle,
gridOptions = __rest(_a, ["gridConstructor", "containerTag", "container", "renderer", "threshold", "useRecycle"]); // options.container === false, wrapper = container, scrollContainer = document.body
// options.container === true, wrapper = scrollContainer, container = wrapper's child
// options.container === string,
var horizontal = gridOptions.horizontal,
attributePrefix = gridOptions.attributePrefix,
useTransform = gridOptions.useTransform,
percentage = gridOptions.percentage,
isConstantSize = gridOptions.isConstantSize,
isEqualSize = gridOptions.isEqualSize;
var wrapperElement = isString$1(wrapper) ? document.querySelector(wrapper) : wrapper;
var scrollManager = new ScrollManager(wrapperElement, {
container: container,
containerTag: containerTag,
horizontal: horizontal
}).on({
scroll: _this._onScroll
});
var containerElement = scrollManager.getContainer();
var containerManager = new ContainerManager(containerElement, {
horizontal: horizontal
}).on("resize", _this._onResize);
var itemRenderer = new ItemRenderer({
attributePrefix: attributePrefix,
horizontal: horizontal,
useTransform: useTransform,
percentage: percentage,
isEqualSize: isEqualSize,
isConstantSize: isConstantSize
});
var infinite = new Infinite({
useRecycle: useRecycle,
threshold: threshold
}).on({
"change": _this._onChange,
"requestAppend": _this._onRequestAppend,
"requestPrepend": _this._onRequestPrepend
});
infinite.setSize(scrollManager.getContentSize());
var groupManager = new GroupManager(containerElement, {
gridConstructor: gridConstructor,
externalItemRenderer: itemRenderer,
externalContainerManager: containerManager,
gridOptions: gridOptions
});
groupManager.on({
"renderComplete": _this._onRenderComplete,
"contentError": _this._onContentError
});
renderer.setContainer(containerElement);
renderer.on("updated", _this._onRendererUpdated);
_this.itemRenderer = itemRenderer;
_this.groupManager = groupManager;
_this.wrapperElement = wrapperElement;
_this.scrollManager = scrollManager;
_this.containerManager = containerManager;
_this.infinite = infinite;
_this.containerManager.resize();
return _this;
}
var __proto = InfiniteGrid.prototype;
InfiniteGrid_1 = InfiniteGrid;
/**
* Rearrange items to fit the grid and render them. When rearrange is complete, the `renderComplete` event is fired.
* @ko grid에 맞게 아이템을 재배치하고 렌더링을 한다. 배치가 완료되면 `renderComplete` 이벤트가 발생한다.
* @param - Options for rendering. <ko>렌더링을 하기 위한 옵션.</ko>
* @example
* import { MasonryGrid } from "@egjs/infinitegrid";
* const grid = new MasonryGrid();
*
* grid.on("renderComplete", e => {
* console.log(e);
* });
* grid.renderItems();
*/
__proto.renderItems = function (options) {
if (options === void 0) {
options = {};
}
if (options.useResize) {
this.containerManager.resize();
}
this._resizeScroll();
if (!this.getItems(true).length) {
var children = toArray$1(this.getContainerElement().children);
if (children.length > 0) {
this.append(children);
} else {
this.infinite.scroll(0);
return this;
}
}
if (!this.getVisibleGroups(true).length) {
this.setCursors(0, 0);
} else {
this.groupManager.renderItems(options);
}
return this;
};
/**
* Returns the wrapper element specified by the user.
* @ko 컨테이너 엘리먼트를 반환한다.
*/
__proto.getWrapperElement = function () {
return this.scrollManager.getWrapper();
};
/**
* Returns the container element corresponding to the scroll area.
* @ko 스크롤 영역에 해당하는 컨테이너 엘리먼트를 반환한다.
*/
__proto.getScrollContainerElement = function () {
return this.scrollManager.getScrollContainer();
};
/**
* Returns the container element containing item elements.
* @ko 아이템 엘리먼트들을 담긴 컨테이너 엘리먼트를 반환한다.
*/
__proto.getContainerElement = function () {
return this.scrollManager.getContainer();
};
/**
* When items change, it synchronizes and renders items.
* @ko items가 바뀐 경우 동기화를 하고 렌더링을 한다.
* @param - Options for rendering. <ko>렌더링을 하기 위한 옵션.</ko>
*/
__proto.syncItems = function (items) {
this.groupManager.syncItems(items);
this._syncGroups();
return this;
};
/**
* Change the currently visible groups.
* @ko 현재 보이는 그룹들을 바꾼다.
* @param - first index of visible groups. <ko>보이는 그룹의 첫번째 index.</ko>
* @param - last index of visible groups. <ko>보이는 그룹의 마지막 index.</ko>
*/
__proto.setCursors = function (startCursor, endCursor, useFirstRender) {
this.groupManager.setCursors(startCursor, endCursor);
this.infinite.setCursors(startCursor, endCursor);
if (useFirstRender) {
this._render();
} else {
this._update();
this._checkEndLoading();
}
return this;
};
/**
* Returns the first index of visible groups.
* @ko 보이는 그룹들의 첫번째 index를 반환한다.
*/
__proto.getStartCursor = function () {
return this.infinite.getStartCursor();
};
/**
* Returns the last index of visible groups.
* @ko 보이는 그룹들의 마지막 index를 반환한다.
*/
__proto.getEndCursor = function () {
return this.infinite.getEndCursor();
};
/**
* Add items at the bottom(right) of the grid.
* @ko 아이템들을 grid 아래(오른쪽)에 추가한다.
* @param - items to be added <ko>추가할 아이템들</ko>
* @param - The group key to be configured in items. It is automatically generated by default.
* <ko>추가할 아이템에 설정할 그룹 키. 생략하면 값이 자동으로 생성된다.</ko>
* @return - An instance of a module itself<ko>모듈 자신의 인스턴스</ko>
* @example
* ig.append("<div class='item'>test1</div><div class='item'>test2</div>");
* ig.append(["<div class='item'>test1</div>", "<div class='item'>test2</div>"]);
* ig.append([HTMLElement1, HTMLElement2]);
*/
__proto.append = function (items, groupKey) {
return this.insert(-1, items, groupKey);
};
/**
* Add items at the top(left) of the grid.
* @ko 아이템들을 grid 위(왼쪽)에 추가한다.
* @param - items to be added <ko>추가할 아이템들</ko>
* @param - The group key to be configured in items. It is automatically generated by default.
* <ko>추가할 아이템에 설정할 그룹 키. 생략하면 값이 자동으로 생성된다.</ko>
* @return - An instance of a module itself<ko>모듈 자신의 인스턴스</ko>
* @example
* ig.prepend("<div class='item'>test1</div><div class='item'>test2</div>");
* ig.prepend(["<div class='item'>test1</div>", "<div class='item'>test2</div>"]);
* ig.prepend([HTMLElement1, HTMLElement2]);
*/
__proto.prepend = function (items, groupKey) {
return this.insert(0, items, groupKey);
};
/**
* Add items to a specific index.
* @ko 아이템들을 특정 index에 추가한다.
* @param - index to add <ko>추가하기 위한 index</ko>
* @param - items to be added <ko>추가할 아이템들</ko>
* @param - The group key to be configured in items. It is automatically generated by default.
* <ko>추가할 아이템에 설정할 그룹 키. 생략하면 값이 자동으로 생성된다.</ko>
* @return - An instance of a module itself<ko>모듈 자신의 인스턴스</ko>
* @example
* ig.insert(2, "<div class='item'>test1</div><div class='item'>test2</div>");
* ig.insert(3, ["<div class='item'>test1</div>", "<div class='item'>test2</div>"]);
* ig.insert(4, [HTMLElement1, HTMLElement2]);
*/
__proto.insert = function (index, items, groupKey) {
var nextItemInfos = this.groupManager.getGroupItems();
var itemInfos = convertInsertedItems(items, groupKey);
if (index === -1) {
nextItemInfos.push.apply(nextItemInfos, itemInfos);
} else {
nextItemInfos.splice.apply(nextItemInfos, __spreadArrays([index, 0], itemInfos));
}
return this.syncItems(nextItemInfos);
};
/**
* Returns the current state of a module such as location information. You can use the setStatus() method to restore the information returned through a call to this method.
* @ko 아이템의 위치 정보 등 모듈의 현재 상태 정보를 반환한다. 이 메서드가 반환한 정보를 저장해 두었다가 setStatus() 메서드로 복원할 수 있다
* @param - STATUS_TYPE.NOT_REMOVE = Get all information about items. STATUS_TYPE.REMOVE_INVISIBLE_ITEMS = Get information on visible items only.
* STATUS_TYPE.MINIMIZE_INVISIBLE_ITEMS = Compress invisible items. You can replace it with a placeholder. STATUS_TYPE.MINIMIZE_INVISIBLE_GROUPS = Compress invisible groups.
* <ko> STATUS_TYPE.NOT_REMOVE = 모든 아이템들의 정보를 가져온다. STATUS_TYPE.REMOVE_INVISIBLE_ITEMS = 보이는 아이템들의 정보만 가져온다.
* STATUS_TYPE.MINIMIZE_INVISIBLE_ITEMS = 안보이는 아이템들을 압축한다. placeholder로 대체가 가능하다. STATUS_TYPE.MINIMIZE_INVISIBLE_GROUPS = 안보이는 그룹을 압축한다.</ko>
*/
__proto.getStatus = function (type) {
return {
containerManager: this.containerManager.getStatus(),
itemRenderer: this.itemRenderer.getStatus(),
groupManager: this.groupManager.getGroupStatus(type),
scrollManager: this.scrollManager.getStatus()
};
};
/**
* You can set placeholders to restore status or wait for items to be added.
* @ko status 복구 또는 아이템 추가 대기를 위한 placeholder를 설정할 수 있다.
* @param - The placeholder status. <ko>placeholder의 status</ko>
*/
__proto.setPlaceholder = function (info) {
this.groupManager.setPlaceholder(info);
return this;
};
/**
* You can set placeholders to restore status or wait for items to be added.
* @ko status 복구 또는 아이템 추가 대기를 위한 placeholder를 설정할 수 있다.
* @param - The placeholder status. <ko>placeholder의 status</ko>
*/
__proto.setLoading = function (info) {
this.groupManager.setLoading(info);
return this;
};
/**
* Add the placeholder at the end.
* @ko placeholder들을 마지막에 추가한다.
* @param - Items that correspond to placeholders. If it is a number, it duplicates the number of copies. <ko>placeholder에 해당하는 아이템들. 숫자면 갯수만큼 복제를 한다.</ko>
* @param - The group key to be configured in items. It is automatically generated by default.
* <ko>추가할 아이템에 설정할 그룹 키. 생략하면 값이 자동으로 생성된다.</ko>
*/
__proto.appendPlaceholders = function (items, groupKey) {
var _this = this;
var result = this.groupManager.appendPlaceholders(items, groupKey);
this._syncGroups(true);
return __assign(__assign({}, result), {
remove: function () {
_this.removePlaceholders({
groupKey: result.group.groupKey
});
}
});
};
/**
* Add the placeholder at the start.
* @ko placeholder들을 처음에 추가한다.
* @param - Items that correspond to placeholders. If it is a number, it duplicates the number of copies. <ko>placeholder에 해당하는 아이템들. 숫자면 갯수만큼 복제를 한다.</ko>
* @param - The group key to be configured in items. It is automatically generated by default.
* <ko>추가할 아이템에 설정할 그룹 키. 생략하면 값이 자동으로 생성된다.</ko>
*/
__proto.prependPlaceholders = function (items, groupKey) {
var _this = this;
var result = this.groupManager.prependPlaceholders(items, groupKey);
this._syncGroups(true);
return __assign(__assign({}, result), {
remove: function () {
_this.removePlaceholders({
groupKey: result.group.groupKey
});
}
});
};
/**
* Remove placeholders
* @ko placeholder들을 삭제한다.
* @param type - Remove the placeholders corresponding to the groupkey. When "start" or "end", remove all placeholders in that direction. <ko>groupkey에 해당하는 placeholder들을 삭제한다. "start" 또는 "end" 일 때 해당 방향의 모든 placeholder들을 삭제한다.</ko>
*/
__proto.removePlaceholders = function (type) {
this.groupManager.removePlaceholders(type);
this._syncGroups(true);
};
/**
* Sets the status of the InfiniteGrid module with the information returned through a call to the getStatus() method.
* @ko getStatus() 메서드가 저장한 정보로 InfiniteGrid 모듈의 상태를 설정한다.
* @param - status object of the InfiniteGrid module
*/
__proto.setStatus = function (status, useFirstRender) {
this.itemRenderer.setStatus(status.itemRenderer);
this.containerManager.setStatus(status.containerManager);
this.scrollManager.setStatus(status.scrollManager);
var groupManager = this.groupManager;
var prevInlineSize = this.containerManager.getInlineSize();
groupManager.setGroupStatus(status.groupManager);
this._syncInfinite();
this.infinite.setCursors(groupManager.getStartCursor(), groupManager.getEndCursor());
this._getRenderer().updateKey();
var state = {
isReisze: this.containerManager.getInlineSize() !== prevInlineSize,
isRestore: true
};
if (useFirstRender) {
this._update(state);
} else {
this._update(state);
}
return this;
};
/**
* Removes the group corresponding to index.
* @ko index에 해당하는 그룹을 제거 한다.
*/
__proto.removeGroupByIndex = function (index) {
var nextGroups = this.groupManager.getGroups();
return this.removeGroupByKey(nextGroups[index].groupKey);
};
/**
* Removes the group corresponding to key.
* @ko key에 해당하는 그룹을 제거 한다.
*/
__proto.removeGroupByKey = function (key) {
var nextItemInfos = this.groupManager.getItems();
var firstIndex = findIndex(nextItemInfos, function (item) {
return item.groupKey === key;
});
var lastIndex = findLastIndex(nextItemInfos, function (item) {
return item.groupKey === key;
});
if (firstIndex === -1) {
return this;
}
nextItemInfos.splice(firstIndex, lastIndex - firstIndex + 1);
return this.syncItems(nextItemInfos);
};
/**
* Removes the item corresponding to index.
* @ko index에 해당하는 아이템을 제거 한다.
*/
__proto.removeByIndex = function (index) {
var nextItemInfos = this.getItems(true);
nextItemInfos.splice(index, 1);
return this.syncItems(nextItemInfos);
};
/**
* Removes the item corresponding to key.
* @ko key에 해당하는 아이템을 제거 한다.
*/
__proto.removeByKey = function (key) {
var nextItemInfos = this.getItems(true);
var index = findIndex(nextItemInfos, function (item) {
return item.key === key;
});
return this.removeByIndex(index);
};
/**
* Update the size of the items and render them.
* @ko 아이템들의 사이즈를 업데이트하고 렌더링을 한다.
* @param - Items to be updated. <ko>업데이트할 아이템들.</ko>
* @param - Options for rendering. <ko>렌더링을 하기 위한 옵션.</ko>
*/
__proto.updateItems = function (items, options) {
if (options === void 0) {
options = {};
}
this.groupManager.updateItems(items, options);
return this;
};
/**
* Return all items of InfiniteGrid.
* @ko InfiniteGrid의 모든 아이템들을 반환한다.
* @param - Whether to include items corresponding to placeholders. <ko>placeholder에 해당하는 아이템들을 포함할지 여부.</ko>
*/
__proto.getItems = function (includePlaceholders) {
return this.groupManager.getGroupItems(includePlaceholders);
};
/**
* Return visible items of InfiniteGrid.
* @ko InfiniteGrid의 보이는 아이템들을 반환한다.
* @param - Whether to include items corresponding to placeholders. <ko>placeholder에 해당하는 아이템들을 포함할지 여부.</ko>
*/
__proto.getVisibleItems = function (includePlaceholders) {
return this.groupManager.getVisibleItems(includePlaceholders);
};
/**
* Return rendering items of InfiniteGrid.
* @ko InfiniteGrid의 렌더링 아이템들을 반환한다.
*/
__proto.getRenderingItems = function () {
return this.groupManager.getRenderingItems();
};
/**
* Return all groups of InfiniteGrid.
* @ko InfiniteGrid의 모든 그룹들을 반환한다.
* @param - Whether to include groups corresponding to placeholders. <ko>placeholder에 해당하는 그룹들을 포함할지 여부.</ko>
*/
__proto.getGroups = function (includePlaceholders) {
return this.groupManager.getGroups(includePlaceholders);
};
/**
* Return visible groups of InfiniteGrid.
* @ko InfiniteGrid의 보이는 그룹들을 반환한다.
* @param - Whether to include groups corresponding to placeholders. <ko>placeholder에 해당하는 그룹들을 포함할지 여부.</ko>
*/
__proto.getVisibleGroups = function (includePlaceholders) {
return this.groupManager.getVisibleGroups(includePlaceholders);
};
__proto.wait = function (direction) {
if (direction === void 0) {
direction = "end";
}
this._waitType = direction;
this._checkStartLoading(direction);
};
__proto.ready = function () {
this._waitType = "";
};
/**
* Releases the instnace and events and returns the CSS of the container and elements.
* @ko 인스턴스와 이벤트를 해제하고 컨테이너와 엘리먼트들의 CSS를 되돌린다.
*/
__proto.destroy = function () {
this.off();
this.groupManager.destroy();
this.scrollManager.destroy();
this.infinite.destroy();
};
__proto._getRenderer = function () {
return this.options.renderer;
};
__proto._render = function (state) {
this._getRenderer().render(this.getRenderingItems().map(function (item) {
return {
element: item.element,
key: item.type + "_" + item.key,
orgItem: item
};
}), state);
};
__proto._update = function (state) {
if (state === void 0) {
state = {};
}
this._getRenderer().update(state);
};
__proto._resizeScroll = function () {
var scrollManager = this.scrollManager;
scrollManager.resize();
this.infinite.setSize(scrollManager.getContentSize());
};
__proto._syncGroups = function (isUpdate) {
var infinite = this.infinite;
this._syncInfinite();
this.groupManager.setCursors(infinite.getStartCursor(), infinite.getEndCursor());
if (isUpdate) {
this._update();
} else {
this._render();
}
};
__proto._syncInfinite = function () {
this.infinite.syncItems(this.getGroups(true).map(function (_a) {
var groupKey = _a.groupKey,
grid = _a.grid,
type = _a.type;
var outlines = grid.getOutlines();
return {
key: groupKey,
isVirtual: type === GROUP_TYPE.VIRTUAL,
startOutline: outlines.start,
endOutline: outlines.end
};
}));
};
__proto._scroll = function () {
this.infinite.scroll(this.scrollManager.getRelativeScrollPos());
};
__proto._onRequestInsert = function (direction, eventType, e) {
var _this = this;
if (this._waitType) {
this._checkStartLoading(this._waitType);
return;
}
this.trigger(new ComponentEvent$1(eventType, {
groupKey: e.key,
nextGroupKey: e.nextKey,
isVirtual: e.isVirtual,
wait: function () {
_this.wait(direction);
},
ready: function () {
_this.ready();
}
}));
};
__proto._checkStartLoading = function (direction) {
var groupManager = this.groupManager;
var infinite = this.infinite;
if (!groupManager.getLoadingType() && infinite.isLoading(direction) && groupManager.startLoading(direction) && groupManager.hasLoadingItem()) {
this._update();
}
};
__proto._checkEndLoading = function () {
var groupManager = this.groupManager;
var loadingType = this.groupManager.getLoadingType();
if (loadingType && (!this._waitType || !this.infinite.isLoading(loadingType)) && groupManager.endLoading() && groupManager.hasLoadingItem()) {
this._update();
}
};
var InfiniteGrid_1;
InfiniteGrid.defaultOptions = __assign(__assign({}, DEFAULT_GRID_OPTIONS), {
container: false,
renderer: null,
threshold: 100,
useRecycle: true
});
InfiniteGrid.propertyTypes = INFINITEGRID_PROPERTY_TYPES;
InfiniteGrid = InfiniteGrid_1 = __decorate([InfiniteGridGetterSetter], InfiniteGrid);
return InfiniteGrid;
}(Component);
/**
* MasonryInfiniteGrid is a grid that stacks items with the same width as a stack of bricks. Adjust the width of all images to the same size, find the lowest height column, and insert a new item.
*
* @ko MasonryInfiniteGrid는 벽돌을 쌓아 올린 모양처럼 동일한 너비를 가진 아이템을 쌓는 레이아웃이다. 모든 이미지의 너비를 동일한 크기로 조정하고, 가장 높이가 낮은 열을 찾아 새로운 이미지를 삽입한다. 따라서 배치된 아이템 사이에 빈 공간이 생기지는 않지만 배치된 레이아웃의 아래쪽은 울퉁불퉁해진다.
* @memberof InfiniteGrid
* @param {HTMLElement | string} container - A base element for a module <ko>모듈을 적용할 기준 엘리먼트</ko>
* @param {InfiniteGrid.MasonryInfiniteGrid.MasonryInfiniteGridOptions} options - The option object of the MasonryInfiniteGrid module <ko>MasonryInfiniteGrid 모듈의 옵션 객체</ko>
*/
var MasonryInfiniteGrid =
/*#__PURE__*/
function (_super) {
__extends(MasonryInfiniteGrid, _super);
function MasonryInfiniteGrid() {
return _super !== null && _super.apply(this, arguments) || this;
}
MasonryInfiniteGrid.propertyTypes = __assign(__assign({}, InfiniteGrid.propertyTypes), MasonryGrid.propertyTypes);
MasonryInfiniteGrid.defaultOptions = __assign(__assign(__assign({}, InfiniteGrid.defaultOptions), MasonryGrid.defaultOptions), {
gridConstructor: MasonryGrid
});
MasonryInfiniteGrid = __decorate([InfiniteGridGetterSetter], MasonryInfiniteGrid);
return MasonryInfiniteGrid;
}(InfiniteGrid);
/**
* 'justified' is a printing term with the meaning that 'it fits in one row wide'. JustifiedInfiniteGrid is a grid that the item is filled up on the basis of a line given a size.
* If 'data-grid-inline-offset' or 'data-grid-content-offset' are set for item element, the ratio is maintained except for the offset value.
* If 'data-grid-maintained-target' is set for an element whose ratio is to be maintained, the item is rendered while maintaining the ratio of the element.
* @ko 'justified'는 '1행의 너비에 맞게 꼭 들어찬'이라는 의미를 가진 인쇄 용어다. JustifiedInfiniteGrid는 용어의 의미대로 너비가 주어진 사이즈를 기준으로 아이템가 가득 차도록 배치하는 Grid다.
* 아이템 엘리먼트에 'data-grid-inline-offset' 또는 'data-grid-content-offset'를 설정하면 offset 값을 제외하고 비율을 유지한다.
* 비율을 유지하고 싶은 엘리먼트에 'data-grid-maintained-target'을 설정한다면 해당 엘리먼트의 비율을 유지하면서 아이템이 렌더링이 된다.
* @memberof InfiniteGrid
* @param {HTMLElement | string} container - A base element for a module <ko>모듈을 적용할 기준 엘리먼트</ko>
* @param {JustifiedInfiniteGrid.JustifiedInfiniteGridOptions} options - The option object of the JustifiedInfiniteGrid module <ko>JustifiedInfiniteGrid 모듈의 옵션 객체</ko>
*/
var JustifiedInfiniteGrid =
/*#__PURE__*/
function (_super) {
__extends(JustifiedInfiniteGrid, _super);
function JustifiedInfiniteGrid() {
return _super !== null && _super.apply(this, arguments) || this;
}
JustifiedInfiniteGrid.propertyTypes = __assign(__assign({}, InfiniteGrid.propertyTypes), JustifiedGrid.propertyTypes);
JustifiedInfiniteGrid.defaultOptions = __assign(__assign(__assign({}, InfiniteGrid.defaultOptions), JustifiedGrid.defaultOptions), {
gridConstructor: JustifiedGrid
});
JustifiedInfiniteGrid = __decorate([InfiniteGridGetterSetter], JustifiedInfiniteGrid);
return JustifiedInfiniteGrid;
}(InfiniteGrid);
/**
* 'Frame' is a printing term with the meaning that 'it fits in one row wide'. FrameInfiniteGrid is a grid that the item is filled up on the basis of a line given a size.
* @ko 'Frame'는 '1행의 너비에 맞게 꼭 들어찬'이라는 의미를 가진 인쇄 용어다. FrameInfiniteGrid는 용어의 의미대로 너비가 주어진 사이즈를 기준으로 아이템이 가득 차도록 배치하는 Grid다.
* @memberof InfiniteGrid
* @param {HTMLElement | string} container - A base element for a module <ko>모듈을 적용할 기준 엘리먼트</ko>
* @param {InfiniteGrid.FrameInfiniteGrid.FrameInfiniteGridOptions} options - The option object of the FrameInfiniteGrid module <ko>FrameGrid 모듈의 옵션 객체</ko>
*/
var FrameInfiniteGrid =
/*#__PURE__*/
function (_super) {
__extends(FrameInfiniteGrid, _super);
function FrameInfiniteGrid() {
return _super !== null && _super.apply(this, arguments) || this;
}
FrameInfiniteGrid.propertyTypes = __assign(__assign({}, InfiniteGrid.propertyTypes), FrameGrid.propertyTypes);
FrameInfiniteGrid.defaultOptions = __assign(__assign(__assign({}, InfiniteGrid.defaultOptions), FrameGrid.defaultOptions), {
gridConstructor: FrameGrid
});
FrameInfiniteGrid = __decorate([InfiniteGridGetterSetter], FrameInfiniteGrid);
return FrameInfiniteGrid;
}(InfiniteGrid);
/**
* The PackingInfiniteGrid is a grid that shows the important items bigger without sacrificing the weight of the items.
* Rows and columns are separated so that items are dynamically placed within the horizontal and vertical space rather than arranged in an orderly fashion.
* If `sizeWeight` is higher than `ratioWeight`, the size of items is preserved as much as possible.
* Conversely, if `ratioWeight` is higher than `sizeWeight`, the ratio of items is preserved as much as possible.
* @ko PackingInfiniteGrid는 아이템의 본래 크기에 따른 비중을 해치지 않으면서 중요한 카드는 더 크게 보여 주는 레이아웃이다.
* 행과 열이 구분돼 아이템을 정돈되게 배치하는 대신 가로세로 일정 공간 내에서 동적으로 아이템을 배치한다.
* `sizeWeight`가 `ratioWeight`보다 높으면 아이템들의 size가 최대한 보존이 된다.
* 반대로 `ratioWeight`가 `sizeWeight`보다 높으면 아이템들의 비율이 최대한 보존이 된다.
* @memberof Grid
* @param {HTMLElement | string} container - A base element for a module <ko>모듈을 적용할 기준 엘리먼트</ko>
* @param {Grid.PackingInfiniteGrid.PackingInfiniteGridOptions} options - The option object of the PackingInfiniteGrid module <ko>PackingInfiniteGrid 모듈의 옵션 객체</ko>
*/
var PackingInfiniteGrid =
/*#__PURE__*/
function (_super) {
__extends(PackingInfiniteGrid, _super);
function PackingInfiniteGrid() {
return _super !== null && _super.apply(this, arguments) || this;
}
PackingInfiniteGrid.propertyTypes = __assign(__assign({}, InfiniteGrid.propertyTypes), PackingGrid.propertyTypes);
PackingInfiniteGrid.defaultOptions = __assign(__assign(__assign({}, InfiniteGrid.defaultOptions), PackingGrid.defaultOptions), {
gridConstructor: PackingGrid
});
PackingInfiniteGrid = __decorate([InfiniteGridGetterSetter], PackingInfiniteGrid);
return PackingInfiniteGrid;
}(InfiniteGrid);
var modules = {
__proto__: null,
'default': InfiniteGrid,
withInfiniteGridMethods: withInfiniteGridMethods,
getRenderingItemsByStatus: getRenderingItemsByStatus,
getFirstRenderingItems: getFirstRenderingItems,
InfiniteGridItem: InfiniteGridItem,
MasonryInfiniteGrid: MasonryInfiniteGrid,
JustifiedInfiniteGrid: JustifiedInfiniteGrid,
FrameInfiniteGrid: FrameInfiniteGrid,
PackingInfiniteGrid: PackingInfiniteGrid,
Renderer: Renderer,
IS_IOS: IS_IOS,
CONTAINER_CLASS_NAME: CONTAINER_CLASS_NAME,
IGNORE_PROPERITES_MAP: IGNORE_PROPERITES_MAP,
INFINITEGRID_PROPERTY_TYPES: INFINITEGRID_PROPERTY_TYPES,
INFINITEGRID_EVENTS: INFINITEGRID_EVENTS,
ITEM_INFO_PROPERTIES: ITEM_INFO_PROPERTIES,
INFINITEGRID_METHODS: INFINITEGRID_METHODS,
get GROUP_TYPE () { return GROUP_TYPE; },
get ITEM_TYPE () { return ITEM_TYPE; },
get STATUS_TYPE () { return STATUS_TYPE; },
INVISIBLE_POS: INVISIBLE_POS
};
for (var name in modules) {
InfiniteGrid[name] = modules[name];
}
return InfiniteGrid;
})));
//# sourceMappingURL=infinitegrid.js.map
|
import { B as Behavior, H as isTouch, f as fixPosition } from './index-16504bb3.js';
class TooltipBehavior extends Behavior {
connected() {
const { host } = this;
const parent = this.parent = this.host.parentNode;
if (parent && parent.nuElement && !parent.hasAttribute('describedby')) {
parent.setAttribute('describedby', this.nuId);
}
let hover = false;
let focus = false;
host.hidden = true;
this.setMod('tooltip', true);
if (isTouch) return;
const showTooltip = () => {
this.use('fixate')
.then(Fixate => Fixate.start());
host.hidden = false;
parent.nuSetMod('tooltip-shown', true);
};
const hideTooltip = () => {
this.use('fixate')
.then(Fixate => Fixate.end());
host.hidden = true;
parent.nuSetMod('tooltip-shown', false);
};
const onMouseEnter = () => {
hover = true;
if (focus) return;
showTooltip();
setTimeout(() => {
fixPosition(host);
});
};
const onMouseLeave = () => {
hover = false;
focus = false;
hideTooltip();
};
const onFocus = () => {
focus = true;
if (hover) return;
showTooltip();
};
const onBlur = () => {
focus = false;
if (hover) return;
hideTooltip();
};
parent.addEventListener('mouseenter', onMouseEnter);
parent.addEventListener('mouseleave', onMouseLeave);
this.removeListeners = () => {
parent.removeEventListener('mouseenter', onMouseEnter);
parent.removeEventListener('mouseleave', onMouseLeave);
};
host.nuSetContextHook('focus', (val) => {
if (val) {
onFocus();
} else {
onBlur();
}
});
}
disconnected() {
const removeListeners = this.removeListeners;
if (removeListeners) {
removeListeners();
}
}
}
export default TooltipBehavior;
|
/*
Highcharts JS v9.1.0 (2021-05-03)
(c) 2009-2021 Torstein Honsi
License: www.highcharts.com/license
*/
(function(a){"object"===typeof module&&module.exports?(a["default"]=a,module.exports=a):"function"===typeof define&&define.amd?define("highcharts/themes/grid",["highcharts"],function(b){a(b);a.Highcharts=b;return a}):a("undefined"!==typeof Highcharts?Highcharts:void 0)})(function(a){function b(a,c,b,d){a.hasOwnProperty(c)||(a[c]=d.apply(null,b))}a=a?a._modules:{};b(a,"Extensions/Themes/Grid.js",[a["Core/Globals.js"],a["Core/Options.js"]],function(a,b){b=b.setOptions;a.theme={colors:"#058DC7 #50B432 #ED561B #DDDF00 #24CBE5 #64E572 #FF9655 #FFF263 #6AF9C4".split(" "),
chart:{backgroundColor:{linearGradient:{x1:0,y1:0,x2:1,y2:1},stops:[[0,"rgb(255, 255, 255)"],[1,"rgb(240, 240, 255)"]]},borderWidth:2,plotBackgroundColor:"rgba(255, 255, 255, .9)",plotShadow:!0,plotBorderWidth:1},title:{style:{color:"#000",font:'bold 16px "Trebuchet MS", Verdana, sans-serif'}},subtitle:{style:{color:"#666666",font:'bold 12px "Trebuchet MS", Verdana, sans-serif'}},xAxis:{gridLineWidth:1,lineColor:"#000",tickColor:"#000",labels:{style:{color:"#000",font:"11px Trebuchet MS, Verdana, sans-serif"}},
title:{style:{color:"#333",fontWeight:"bold",fontSize:"12px",fontFamily:"Trebuchet MS, Verdana, sans-serif"}}},yAxis:{minorTickInterval:"auto",lineColor:"#000",lineWidth:1,tickWidth:1,tickColor:"#000",labels:{style:{color:"#000",font:"11px Trebuchet MS, Verdana, sans-serif"}},title:{style:{color:"#333",fontWeight:"bold",fontSize:"12px",fontFamily:"Trebuchet MS, Verdana, sans-serif"}}},legend:{itemStyle:{font:"9pt Trebuchet MS, Verdana, sans-serif",color:"black"},itemHoverStyle:{color:"#039"},itemHiddenStyle:{color:"gray"}},
labels:{style:{color:"#99b"}},navigation:{buttonOptions:{theme:{stroke:"#CCCCCC"}}}};b(a.theme)});b(a,"masters/themes/grid.src.js",[],function(){})});
//# sourceMappingURL=grid.js.map |
var ydm = require('../../ydm')
, path = require('path')
, fs = require('fs')
, logger = require('winston')
module.exports = function(req, res, next) {
var filePath = path.join(ydm.dropsPath, req.params.name+'.js')
fs.writeFile(filePath, req.body, function(err) {
if (err) {
logger.error(err.stack)
res.status(500).end(res.message);
} else {
logger.info('Created '+req.params.name)
res.status(201).end('ok');
}
})
}
|
module.exports = function (app,io,jwt) {
io.on('connection', function(socket) {
socket.auth = false;
socket.on('authenticate', function(data){
var user = jwt.decode(data.token, app.get('superSecret'));
app.get('connections')[user._id] = socket;
socket.auth = true;
});
});
};
|
module.exports = {
FlatWaterRenderer: require('./FlatWaterRenderer'),
ProjectedGrid: require('./ProjectedGrid'),
ProjectedGridWaterRenderer: require('./ProjectedGridWaterRenderer')
};
if (typeof(window) !== 'undefined') {
for (var key in module.exports) {
window.goo[key] = module.exports[key];
}
} |
import * as assert from 'assert';
import {qw, qwm} from '../src/js-utils';
describe('qw', () => {
it('simple', () => {
const qwRes = qw(`
str1 123
str2 str3\nstr4\tstr5
`);
assert.deepEqual(qwRes, ['str1', '123', 'str2', 'str3', 'str4', 'str5']);
});
it('empty', () => {
const qwRes = qw(`
`);
assert.deepEqual(qwRes, []);
});
});
describe('qwm', () => {
it('simple', () => {
const qwRes = qwm(`
key1 val1 key2 val2
key3 val3
`);
assert.deepEqual(qwRes, {key1: 'val1', key2: 'val2', key3: 'val3'});
});
it('odd', () => {
assert.throws(
() => {
qwm(`
key1 val1 key2 val2
key3
`);
}
);
});
});
|
Clazz.declarePackage ("JS");
Clazz.load (null, "JS.ScriptExt", ["JU.AU"], function () {
c$ = Clazz.decorateAsClass (function () {
this.vwr = null;
this.e = null;
this.chk = false;
this.st = null;
this.slen = 0;
Clazz.instantialize (this, arguments);
}, JS, "ScriptExt");
Clazz.defineMethod (c$, "init",
function (eval) {
this.e = eval;
this.vwr = this.e.vwr;
return this;
}, "~O");
Clazz.defineMethod (c$, "atomExpressionAt",
function (i) {
return this.e.atomExpressionAt (i);
}, "~N");
Clazz.defineMethod (c$, "checkLength",
function (i) {
this.e.checkLength (i);
}, "~N");
Clazz.defineMethod (c$, "error",
function (err) {
this.e.error (err);
}, "~N");
Clazz.defineMethod (c$, "invArg",
function () {
this.e.invArg ();
});
Clazz.defineMethod (c$, "invPO",
function () {
this.error (23);
});
Clazz.defineMethod (c$, "getShapeProperty",
function (shapeType, propertyName) {
return this.e.getShapeProperty (shapeType, propertyName);
}, "~N,~S");
Clazz.defineMethod (c$, "paramAsStr",
function (i) {
return this.e.paramAsStr (i);
}, "~N");
Clazz.defineMethod (c$, "centerParameter",
function (i) {
return this.e.centerParameter (i, null);
}, "~N");
Clazz.defineMethod (c$, "floatParameter",
function (i) {
return this.e.floatParameter (i);
}, "~N");
Clazz.defineMethod (c$, "getPoint3f",
function (i, allowFractional) {
return this.e.getPoint3f (i, allowFractional);
}, "~N,~B");
Clazz.defineMethod (c$, "intParameter",
function (index) {
return this.e.intParameter (index);
}, "~N");
Clazz.defineMethod (c$, "isFloatParameter",
function (index) {
switch (this.e.tokAt (index)) {
case 2:
case 3:
return true;
}
return false;
}, "~N");
Clazz.defineMethod (c$, "setShapeProperty",
function (shapeType, propertyName, propertyValue) {
this.e.setShapeProperty (shapeType, propertyName, propertyValue);
}, "~N,~S,~O");
Clazz.defineMethod (c$, "showString",
function (s) {
this.e.showString (s);
}, "~S");
Clazz.defineMethod (c$, "stringParameter",
function (index) {
return this.e.stringParameter (index);
}, "~N");
Clazz.defineMethod (c$, "getToken",
function (i) {
return this.e.getToken (i);
}, "~N");
Clazz.defineMethod (c$, "tokAt",
function (i) {
return this.e.tokAt (i);
}, "~N");
Clazz.defineMethod (c$, "setShapeId",
function (iShape, i, idSeen) {
if (idSeen) this.invArg ();
var name = this.e.setShapeNameParameter (i).toLowerCase ();
this.setShapeProperty (iShape, "thisID", name);
return name;
}, "~N,~N,~B");
Clazz.defineMethod (c$, "getColorTrans",
function (eval, i, allowNone, ret) {
var translucentLevel = 3.4028235E38;
if (eval.theTok != 1765808134) --i;
switch (this.tokAt (i + 1)) {
case 603979967:
i++;
translucentLevel = (this.isFloatParameter (i + 1) ? eval.getTranslucentLevel (++i) : this.vwr.getFloat (570425354));
break;
case 1073742074:
i++;
translucentLevel = 0;
break;
}
if (eval.isColorParam (i + 1)) {
ret[0] = eval.getArgbParam (++i);
} else if (this.tokAt (i + 1) == 1073742333) {
ret[0] = 0;
eval.iToken = i + 1;
} else if (translucentLevel == 3.4028235E38) {
this.invArg ();
} else {
ret[0] = -2147483648;
}i = eval.iToken;
return translucentLevel;
}, "JS.ScriptEval,~N,~B,~A");
Clazz.defineMethod (c$, "finalizeObject",
function (shapeID, colorArgb, translucentLevel, intScale, doSet, data, iptDisplayProperty, bs) {
if (doSet) {
this.setShapeProperty (shapeID, "set", data);
}if (colorArgb != -2147483648) this.e.setShapePropertyBs (shapeID, "color", Integer.$valueOf (colorArgb), bs);
if (translucentLevel != 3.4028235E38) this.e.setShapeTranslucency (shapeID, "", "translucent", translucentLevel, bs);
if (intScale != 0) {
this.setShapeProperty (shapeID, "scale", Integer.$valueOf (intScale));
}if (iptDisplayProperty > 0) {
if (!this.e.setMeshDisplayProperty (shapeID, iptDisplayProperty, 0)) this.invArg ();
}}, "~N,~N,~N,~N,~B,~O,~N,JU.BS");
Clazz.defineMethod (c$, "getIntArray2",
function (i) {
var list = (this.e.getToken (i)).getList ();
var faces = JU.AU.newInt2 (list.size ());
for (var vi = faces.length; --vi >= 0; ) {
var face = list.get (vi).getList ();
if (face == null) this.invArg ();
faces[vi] = Clazz.newIntArray (face.size (), 0);
for (var vii = faces[vi].length; --vii >= 0; ) faces[vi][vii] = face.get (vii).intValue;
}
return faces;
}, "~N");
Clazz.defineMethod (c$, "getAllPoints",
function (index) {
var points = null;
var bs = null;
try {
switch (this.e.tokAt (index)) {
case 7:
points = this.e.getPointArray (index, -1, false);
break;
case 12290:
case 10:
case 1073742325:
bs = this.atomExpressionAt (index);
break;
}
if (points == null) {
if (bs == null) bs = this.vwr.getAllAtoms ();
points = new Array (bs.cardinality ());
for (var i = bs.nextSetBit (0), pt = 0; i >= 0; i = bs.nextSetBit (i + 1)) points[pt++] = this.vwr.ms.at[i];
}} catch (e) {
if (Clazz.exceptionOf (e, Exception)) {
} else {
throw e;
}
}
if (points.length < 3) this.invArg ();
return points;
}, "~N");
});
|
(function($, cornerstone, cornerstoneTools) {
'use strict';
function multiTouchDragTool(touchDragCallback, options) {
var configuration = {};
var events = 'CornerstoneToolsMultiTouchDrag';
if (options && options.fireOnTouchStart === true) {
events += ' CornerstoneToolsMultiTouchStart';
}
var toolInterface = {
activate: function(element) {
$(element).off(events, touchDragCallback);
if (options && options.eventData) {
$(element).on(events, options.eventData, touchDragCallback);
} else {
$(element).on(events, touchDragCallback);
}
if (options && options.activateCallback) {
options.activateCallback(element);
}
},
disable: function(element) {
$(element).off(events, touchDragCallback);
if (options && options.disableCallback) {
options.disableCallback(element);
}
},
enable: function(element) {
$(element).off(events, touchDragCallback);
if (options && options.enableCallback) {
options.enableCallback(element);
}
},
deactivate: function(element) {
$(element).off(events, touchDragCallback);
if (options && options.deactivateCallback) {
options.deactivateCallback(element);
}
},
getConfiguration: function() {
return configuration;
},
setConfiguration: function(config) {
configuration = config;
}
};
return toolInterface;
}
// module exports
cornerstoneTools.multiTouchDragTool = multiTouchDragTool;
})($, cornerstone, cornerstoneTools);
|
export { browserActions } from './actions';
export { browserReducer } from './reducer';
export { browserSagas } from './sagas';
export { getBrowserMedia } from './selectors';
export { infiniteScroll } from './scroll/infinite-scroll';
|
import test from 'ava';
test('test.js', t => {
t.pass();
});
|
var kunstmaanbundles = kunstmaanbundles || {};
kunstmaanbundles.mediaChooser = (function(window, undefined) {
var init, initDelBtn;
var $body = $('body');
init = function() {
// Save and update preview can be found in url-chooser.js
initDelBtn();
};
// Del btn
initDelBtn = function() {
$body.on('click', '.js-media-chooser-del-preview-btn', function(e) {
var $this = $(this),
linkedID = $this.data('linked-id'),
$widget = $('#' + linkedID + '-widget'),
$input = $('#' + linkedID);
$widget.removeClass('media-chooser--choosen');
$input.val('');
});
};
return {
init: init
};
})(window);
|
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _react = require('react');
var _react2 = _interopRequireDefault(_react);
var _reactIconBase = require('react-icon-base');
var _reactIconBase2 = _interopRequireDefault(_reactIconBase);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var MdCrop169 = function MdCrop169(props) {
return _react2.default.createElement(
_reactIconBase2.default,
_extends({ viewBox: '0 0 40 40' }, props),
_react2.default.createElement(
'g',
null,
_react2.default.createElement('path', { d: 'm31.6 26.6v-13.2h-23.2v13.2h23.2z m0-16.6q1.4 0 2.4 1t1 2.4v13.2q0 1.4-1 2.4t-2.4 1h-23.2q-1.4 0-2.4-1t-1-2.4v-13.2q0-1.4 1-2.4t2.4-1h23.2z' })
)
);
};
exports.default = MdCrop169;
module.exports = exports['default']; |
/*!
* jQuery Simulate v0.0.1 - simulate browser mouse and keyboard events
* https://github.com/jquery/jquery-simulate
*
* Copyright 2012 jQuery Foundation and other contributors
* Released under the MIT license.
* http://jquery.org/license
*
* Date: Sun Dec 9 12:15:33 2012 -0500
*/
;(function( $, undefined ) {
"use strict";
var rkeyEvent = /^key/,
rmouseEvent = /^(?:mouse|contextmenu)|click/,
rdocument = /\[object (?:HTML)?Document\]/;
function isDocument(ele) {
return rdocument.test(Object.prototype.toString.call(ele));
}
function windowOfDocument(doc) {
for (var i=0; i < window.frames.length; i+=1) {
if (window.frames[i].document === doc) {
return window.frames[i];
}
}
return window;
}
$.fn.simulate = function( type, options ) {
return this.each(function() {
new $.simulate( this, type, options );
});
};
$.simulate = function( elem, type, options ) {
var method = $.camelCase( "simulate-" + type );
this.target = elem;
this.options = options || {};
if ( this[ method ] ) {
this[ method ]();
} else {
this.simulateEvent( elem, type, this.options );
}
};
$.extend( $.simulate, {
keyCode: {
BACKSPACE: 8,
COMMA: 188,
DELETE: 46,
DOWN: 40,
END: 35,
ENTER: 13,
ESCAPE: 27,
HOME: 36,
LEFT: 37,
NUMPAD_ADD: 107,
NUMPAD_DECIMAL: 110,
NUMPAD_DIVIDE: 111,
NUMPAD_ENTER: 108,
NUMPAD_MULTIPLY: 106,
NUMPAD_SUBTRACT: 109,
PAGE_DOWN: 34,
PAGE_UP: 33,
PERIOD: 190,
RIGHT: 39,
SPACE: 32,
TAB: 9,
UP: 38
},
buttonCode: {
LEFT: 0,
MIDDLE: 1,
RIGHT: 2
}
});
$.extend( $.simulate.prototype, {
simulateEvent: function( elem, type, options ) {
var event = this.createEvent( type, options );
this.dispatchEvent( elem, type, event, options );
},
createEvent: function( type, options ) {
if ( rkeyEvent.test( type ) ) {
return this.keyEvent( type, options );
}
if ( rmouseEvent.test( type ) ) {
return this.mouseEvent( type, options );
}
},
mouseEvent: function( type, options ) {
var event,
eventDoc,
doc = isDocument(this.target)? this.target : (this.target.ownerDocument || document),
docEle,
body;
options = $.extend({
bubbles: true,
cancelable: (type !== "mousemove"),
view: windowOfDocument(doc),
detail: 0,
screenX: 0,
screenY: 0,
clientX: 1,
clientY: 1,
ctrlKey: false,
altKey: false,
shiftKey: false,
metaKey: false,
button: 0,
relatedTarget: undefined
}, options );
if ( doc.createEvent ) {
event = doc.createEvent( "MouseEvents" );
event.initMouseEvent( type, options.bubbles, options.cancelable,
options.view, options.detail,
options.screenX, options.screenY, options.clientX, options.clientY,
options.ctrlKey, options.altKey, options.shiftKey, options.metaKey,
options.button, options.relatedTarget || doc.body.parentNode );
// IE 9+ creates events with pageX and pageY set to 0.
// Trying to modify the properties throws an error,
// so we define getters to return the correct values.
if ( event.pageX === 0 && event.pageY === 0 && Object.defineProperty ) {
eventDoc = isDocument(event.relatedTarget)? event.relatedTarget : (event.relatedTarget.ownerDocument || document);
docEle = eventDoc.documentElement;
body = eventDoc.body;
Object.defineProperty( event, "pageX", {
get: function() {
return options.clientX +
( docEle && docEle.scrollLeft || body && body.scrollLeft || 0 ) -
( docEle && docEle.clientLeft || body && body.clientLeft || 0 );
}
});
Object.defineProperty( event, "pageY", {
get: function() {
return options.clientY +
( docEle && docEle.scrollTop || body && body.scrollTop || 0 ) -
( docEle && docEle.clientTop || body && body.clientTop || 0 );
}
});
}
} else if ( doc.createEventObject ) {
event = doc.createEventObject();
$.extend( event, options );
// standards event.button uses constants defined here: http://msdn.microsoft.com/en-us/library/ie/ff974877(v=vs.85).aspx
// old IE event.button uses constants defined here: http://msdn.microsoft.com/en-us/library/ie/ms533544(v=vs.85).aspx
// so we actually need to map the standard back to oldIE
event.button = {
0: 1,
1: 4,
2: 2
}[ event.button ] || event.button;
}
return event;
},
keyEvent: function( type, options ) {
var event, doc;
options = $.extend({
bubbles: true,
cancelable: true,
view: windowOfDocument(doc),
ctrlKey: false,
altKey: false,
shiftKey: false,
metaKey: false,
keyCode: 0,
charCode: undefined
}, options );
doc = isDocument(this.target)? this.target : (this.target.ownerDocument || document);
if ( doc.createEvent ) {
try {
event = doc.createEvent( "KeyEvents" );
event.initKeyEvent( type, options.bubbles, options.cancelable, options.view,
options.ctrlKey, options.altKey, options.shiftKey, options.metaKey,
options.keyCode, options.charCode );
// initKeyEvent throws an exception in WebKit
// see: http://stackoverflow.com/questions/6406784/initkeyevent-keypress-only-works-in-firefox-need-a-cross-browser-solution
// and also https://bugs.webkit.org/show_bug.cgi?id=13368
// fall back to a generic event until we decide to implement initKeyboardEvent
} catch( err ) {
event = doc.createEvent( "Events" );
event.initEvent( type, options.bubbles, options.cancelable );
$.extend( event, {
view: options.view,
ctrlKey: options.ctrlKey,
altKey: options.altKey,
shiftKey: options.shiftKey,
metaKey: options.metaKey,
keyCode: options.keyCode,
charCode: options.charCode
});
}
} else if ( doc.createEventObject ) {
event = doc.createEventObject();
$.extend( event, options );
}
if ( !!/msie [\w.]+/.exec( navigator.userAgent.toLowerCase() ) || (({}).toString.call( window.opera ) === "[object Opera]") ) {
event.keyCode = (options.charCode > 0) ? options.charCode : options.keyCode;
event.charCode = undefined;
}
return event;
},
dispatchEvent: function( elem, type, event, options ) {
if (options.jQueryTrigger === true) {
$(elem).trigger($.extend({}, event, options, {type: type}));
}
else if ( elem.dispatchEvent ) {
elem.dispatchEvent( event );
} else if ( elem.fireEvent ) {
elem.fireEvent( "on" + type, event );
}
},
simulateFocus: function() {
var focusinEvent,
triggered = false,
$element = $( this.target );
function trigger() {
triggered = true;
}
$element.bind( "focus", trigger );
$element[ 0 ].focus();
if ( !triggered ) {
focusinEvent = $.Event( "focusin" );
focusinEvent.preventDefault();
$element.trigger( focusinEvent );
$element.triggerHandler( "focus" );
}
$element.unbind( "focus", trigger );
},
simulateBlur: function() {
var focusoutEvent,
triggered = false,
$element = $( this.target );
function trigger() {
triggered = true;
}
$element.bind( "blur", trigger );
$element[ 0 ].blur();
// blur events are async in IE
setTimeout(function() {
// IE won't let the blur occur if the window is inactive
if ( $element[ 0 ].ownerDocument.activeElement === $element[ 0 ] ) {
$element[ 0 ].ownerDocument.body.focus();
}
// Firefox won't trigger events if the window is inactive
// IE doesn't trigger events if we had to manually focus the body
if ( !triggered ) {
focusoutEvent = $.Event( "focusout" );
focusoutEvent.preventDefault();
$element.trigger( focusoutEvent );
$element.triggerHandler( "blur" );
}
$element.unbind( "blur", trigger );
}, 1 );
}
});
/** complex events **/
function findCenter( elem ) {
var offset,
$document,
$elem = $( elem );
if ( isDocument($elem[0]) ) {
$document = $elem;
offset = { left: 0, top: 0 };
}
else {
$document = $( $elem[0].ownerDocument || document );
offset = $elem.offset();
}
return {
x: offset.left + $elem.outerWidth() / 2 - $document.scrollLeft(),
y: offset.top + $elem.outerHeight() / 2 - $document.scrollTop()
};
}
function findCorner( elem ) {
var offset,
$document,
$elem = $( elem );
if ( isDocument($elem[0]) ) {
$document = $elem;
offset = { left: 0, top: 0 };
}
else {
$document = $( $elem[0].ownerDocument || document );
offset = $elem.offset();
}
return {
x: offset.left - document.scrollLeft(),
y: offset.top - document.scrollTop()
};
}
$.extend( $.simulate.prototype, {
simulateDrag: function() {
var i = 0,
target = this.target,
options = this.options,
center = options.handle === "corner" ? findCorner( target ) : findCenter( target ),
x = Math.floor( center.x ),
y = Math.floor( center.y ),
coord = { clientX: x, clientY: y },
dx = options.dx || ( options.x !== undefined ? options.x - x : 0 ),
dy = options.dy || ( options.y !== undefined ? options.y - y : 0 ),
moves = options.moves || 3;
this.simulateEvent( target, "mousedown", coord );
for ( ; i < moves ; i++ ) {
x += dx / moves;
y += dy / moves;
coord = {
clientX: Math.round( x ),
clientY: Math.round( y )
};
this.simulateEvent( target.ownerDocument, "mousemove", coord );
}
if ( $.contains( document, target ) ) {
this.simulateEvent( target, "mouseup", coord );
this.simulateEvent( target, "click", coord );
} else {
this.simulateEvent( document, "mouseup", coord );
}
}
});
})( jQuery );
|
function s4() { return Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1); }
function guid() { return s4() + s4() + '-' + s4() + '-' + s4() + '-' + s4() + '-' + s4() + s4() + s4(); } |
this.define([
'scaffolding',
'strongforce',
'models/Hexagon',
'models/HexCell'
], function(S, strongforce) {
'use strict';
var Model = strongforce.Model,
selectDirection;
selectDirection = {
N: function(cellId) {
return [
cellId[0] - 2,
cellId[1]
];
},
NE: function(cellId) {
return [
cellId[0] - 1,
cellId[1] + (1 - cellId[0] % 2)
];
},
SE: function(cellId) {
return [
cellId[0] + 1,
cellId[1] + (1 - cellId[0] % 2)
];
},
S: function(cellId) {
return [
cellId[0] + 2,
cellId[1]
];
},
SW: function(cellId) {
return [
cellId[0] + 1,
cellId[1] - cellId[0] % 2
];
},
NW: function(cellId) {
return [
cellId[0] - 1,
cellId[1] - cellId[0] % 2
];
}
};
function Neighborhood(board, cellId) {
this._board = board;
this._cellId = cellId;
}
S.theClass(Neighborhood).inheritsFrom(Model);
Neighborhood.prototype.getAliveNeighbours = function () {
return this._getNeighborhood().filter(function (cell) {
return cell && cell.alive;
}).length;
};
Neighborhood.prototype._getNeighborhood = function () {
return [
this._getNeighbour('N'),
this._getNeighbour('NE'),
this._getNeighbour('SE'),
this._getNeighbour('S'),
this._getNeighbour('SW'),
this._getNeighbour('NW')
];
};
Neighborhood.prototype._getNeighbour = function (direction) {
var cellId = this._cellId,
rows = this._board.length,
cols = this._board[0].length;
direction = direction.toUpperCase();
var neighbourId = selectDirection[direction](cellId),
r = neighbourId[0], c = neighbourId[1],
isOutOfBounds = r < 0 || r >= rows || c < 0 || c >= cols;
return isOutOfBounds ? null : this._board[r][c];
};
return Neighborhood;
});
|
// req: glMatrix
T5.Registry.register('renderer', 'webgl', function(view, panFrame, container, params, baseRenderer) {
params = cog.extend({
}, params);
/* some shaders */
var DEFAULT_SHADER_FRAGMENT = [
'#ifdef GL_ES',
'precision highp float;',
'#endif',
'varying vec2 vTextureCoord;',
'uniform sampler2D uSampler;',
'void main(void) {',
'gl_FragColor = texture2D(uSampler, vec2(vTextureCoord.s, vTextureCoord.t));',
'}'
].join('\n'),
DEFAULT_SHADER_VERTEX = [
'attribute vec3 aVertexPosition;',
'attribute vec2 aTextureCoord;',
'uniform mat4 uMVMatrix;',
'uniform mat4 uPMatrix;',
'varying vec2 vTextureCoord;',
'void main(void) {',
'gl_Position = uPMatrix * uMVMatrix * vec4(aVertexPosition, 1.0);',
'vTextureCoord = aTextureCoord;',
'}'
].join('\n');
/* internals */
var TILE_SIZE = 256,
vpWidth,
vpHeight,
canvas,
gl,
shaderProgram,
mvMatrix = mat4.create(),
pMatrix = mat4.create(),
tilesToRender = [],
viewport,
drawOffsetX = 0,
drawOffsetY = 0,
transform = null,
previousStyles = {},
squareVertexTextureBuffer;
function createTileBuffer(tile) {
var texture, buffer,
x1, x2, y1, y2,
vertices;
// flag the tile as loading
tile.loading = true;
T5.getImage(tile.url, function(image) {
texture = tile.texture = gl.createTexture();
texture.image = image;
// finished loading, clear flag
tile.loading = false;
// initialise the texture
gl.bindTexture(gl.TEXTURE_2D, texture);
gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true);
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, texture.image);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
gl.bindTexture(gl.TEXTURE_2D, null);
// initialise the tile verticies
x1 = tile.x;
y1 = -tile.y;
x2 = x1 + tile.w;
y2 = y1 + tile.h;
vertices = [
x2, y2, 0,
x1, y2, 0,
x2, y1, 0,
x1, y1, 0
];
// now create the tile buffer
buffer = tile.buffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW);
buffer.itemSize = 3;
buffer.numItems = 4;
view.invalidate();
});
} // createTileBuffer
function handleDetach() {
// remove teh canvas
panFrame.removeChild(canvas);
} // handleDetach
function handlePredraw(evt, layers, viewport, tickCount, hitData) {
// update the offset x and y
drawOffsetX = viewport.x;
drawOffsetY = viewport.y;
// reset the draw buffers
tilesToRender = [];
gl.viewport(0, 0, vpWidth, vpHeight);
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
mat4.perspective(45, vpWidth / vpHeight, 0.1, 1000, pMatrix);
mat4.identity(mvMatrix);
mat4.rotate(mvMatrix, -Math.PI / 4, [1, 0, 0]);
mat4.translate(mvMatrix, [
-drawOffsetX - vpWidth / 2,
drawOffsetY + 200 / viewport.scaleFactor,
-200 / viewport.scaleFactor]
);
} // handlePredraw
function init() {
var xSeg, ySeg;
if (panFrame) {
// initialise the viewport height and width
vpWidth = view.width = panFrame.offsetWidth;
vpHeight = view.height = panFrame.offsetHeight;
// calculate the number of x segments
xSeg = (vpWidth / TILE_SIZE | 0) + 2;
ySeg = (vpHeight / TILE_SIZE | 0) + 2;
// create the canvas
canvas = T5.DOM.create('canvas', null, {
position: 'absolute',
'z-index': 1
});
canvas.width = vpWidth;
canvas.height = vpHeight;
// get the webgl context
gl = canvas.getContext('experimental-webgl');
gl.viewportWidth = vpWidth;
gl.viewportHeight = vpHeight;
// add the canvas to the panFrame
panFrame.appendChild(canvas);
// initialise the shaders
initShaders();
// initialise the buffers
initBuffers();
gl.clearColor(0.0, 0.0, 0.0, 1.0);
gl.enable(gl.DEPTH_TEST);
} // if
} // init
function initBuffers() {
var vertices = [
1.0, 1.0,
0.0, 1.0,
1.0, 0.0,
0.0, 0.0
];
squareVertexTextureBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, squareVertexTextureBuffer);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW);
squareVertexTextureBuffer.itemSize = 2;
squareVertexTextureBuffer.numItems = 4;
} // initBuffers
function initShaders() {
function createShader(type, source) {
var shader = gl.createShader(type);
gl.shaderSource(shader, source);
gl.compileShader(shader);
return shader;
} // createShader
shaderProgram = gl.createProgram();
gl.attachShader(shaderProgram,
createShader(gl.FRAGMENT_SHADER, DEFAULT_SHADER_FRAGMENT)
);
gl.attachShader(shaderProgram,
createShader(gl.VERTEX_SHADER, DEFAULT_SHADER_VERTEX)
);
gl.linkProgram(shaderProgram);
if (!gl.getProgramParameter(shaderProgram, gl.LINK_STATUS)) {
cog.log("Could not initialise shaders", 'warn');
}
gl.useProgram(shaderProgram);
shaderProgram.vertexPositionAttribute = gl.getAttribLocation(shaderProgram, "aVertexPosition");
gl.enableVertexAttribArray(shaderProgram.vertexPositionAttribute);
shaderProgram.textureCoordAttribute = gl.getAttribLocation(shaderProgram, "aTextureCoord");
gl.enableVertexAttribArray(shaderProgram.textureCoordAttribute);
shaderProgram.pMatrixUniform = gl.getUniformLocation(shaderProgram, "uPMatrix");
shaderProgram.mvMatrixUniform = gl.getUniformLocation(shaderProgram, "uMVMatrix");
shaderProgram.samplerUniform = gl.getUniformLocation(shaderProgram, "uSampler");
} // initShaders
function setMatrixUniforms() {
gl.uniformMatrix4fv(shaderProgram.pMatrixUniform, false, pMatrix);
gl.uniformMatrix4fv(shaderProgram.mvMatrixUniform, false, mvMatrix);
} // setMatrixUniforms
/* exports */
function applyStyle(styleId) {
var nextStyle = T5.Style.get(styleId);
if (nextStyle) {
} // if
} // applyStyle
function applyTransform(drawable) {
} // applyTransform
function arc(x, y, radius, startAngle, endAngle) {
} // arc
function drawTiles(viewport, tiles, okToLoad) {
var tile,
inViewport,
offsetX = transform ? transform.x : drawOffsetX,
offsetY = transform ? transform.y : drawOffsetY,
minX = offsetX - 256,
minY = offsetY - 256,
maxX = offsetX + vpWidth,
maxY = offsetY + vpHeight,
relX, relY;
for (var ii = tiles.length; ii--; ) {
tile = tiles[ii];
// calculate the image relative position
relX = tile.screenX = tile.x - offsetX;
relY = tile.screenY = tile.y - offsetY;
// show or hide the image depending on whether it is in the viewport
if ((! tile.buffer) && (! tile.loading)) {
createTileBuffer(tile);
} // if
// add the buffer to the list
if (tile.buffer) {
tilesToRender[tilesToRender.length] = tile;
} // if
} // for
} // drawTiles
function image(img, x, y, width, height) {
} // image
function render() {
// iterate through the tiles to render and render
for (var ii = tilesToRender.length; ii--; ) {
var tile = tilesToRender[ii];
// set the tile buffer
gl.bindBuffer(gl.ARRAY_BUFFER, tile.buffer);
gl.vertexAttribPointer(
shaderProgram.vertexPositionAttribute,
tile.buffer.itemSize,
gl.FLOAT,
false,
0,
0);
// set the texture buffer
gl.bindBuffer(gl.ARRAY_BUFFER, squareVertexTextureBuffer);
gl.vertexAttribPointer(
shaderProgram.textureCoordAttribute,
squareVertexTextureBuffer.itemSize,
gl.FLOAT,
false,
0,
0);
// activate the tile texture
gl.activeTexture(gl.TEXTURE0);
gl.bindTexture(gl.TEXTURE_2D, tile.texture);
gl.uniform1i(shaderProgram.samplerUniform, 0);
// draw the tile
gl.drawArrays(gl.TRIANGLE_STRIP, 0, tile.buffer.numItems);
} // for
setMatrixUniforms();
} // render
function path(points) {
} // path
/* initialization */
// initialise the panFrame
init();
var _this = cog.extend(baseRenderer, {
interactTarget: canvas,
applyStyle: applyStyle,
applyTransform: applyTransform,
arc: arc,
drawTiles: drawTiles,
image: image,
render: render,
path: path,
getContext: function() {
return context;
},
getDimensions: function() {
return {
width: vpWidth,
height: vpHeight
};
},
getViewport: function() {
return viewport;
}
});
cog.log('created webgl renderer');
// handle detach requests
_this.bind('detach', handleDetach);
_this.bind('predraw', handlePredraw);
return _this;
}); |
import Ember from 'ember';
import FilterContent from 'ember-cli-filter-component/components/filter-content';
export default FilterContent; |
$(function() {
var sidebarId = '#sidebar',
$sidebar = $(sidebarId),
$sidenav = $sidebar.children('.nav');
// Call the ScrollSpy plugin which is for automatically
// updating nav targets based on scroll position.
$('body').scrollspy({
target: sidebarId
});
/**
* Keep expanding at least one item that contains subitems
* Two states of an item:
* expanded: display all subitems
* activated: different visual appearance (bold text)
* and display all subitems if they existed
*/
function keepExpandingSidebar() {
if (
// Check the current activated item, not include the first one
// which is (by default) a built-in welcome item
$sidenav.children('li:not(:first).active').length == 0 ||
// Check if the current activated item contains any subitems
$sidenav.children('li.active').children('.nav').length == 0
) {
// Expand the first item that contains subitems
$sidenav.find('.nav:first').addClass('show');
} else {
$sidenav.find('.nav:first').removeClass('show');
}
}
// This event fires whenever a new item becomes activated by the scrollspy
$sidebar.on('activate.bs.scrollspy', function (e) {
keepExpandingSidebar();
});
keepExpandingSidebar();
// Prevent demo links from navigating
$('a[href="#"]:not([data-toggle], [rel="async"])').click(function() {
return false;
});
// Prevent demo forms from submitting
$('form:not([action])').submit(function() {
return false;
});
// HTML inspector button
var inspectorParentCls = 'js-html-inspector',
inspectorBtnCls = 'js-btn-inspector',
$inspectorDialog = $('#dialog-html-inspector'),
$inspectorBtn = $('<button class="btn btn-default btn-xs ' + inspectorBtnCls + '">' +
'<>' +
'</button>');
$inspectorBtn.click(function() {
var $parent = $(this).closest('.' + inspectorParentCls).clone();
// Replace elements
var replaceTarget = $parent.data('replace-target');
if (typeof replaceTarget !== 'undefined') {
$parent.find(replaceTarget).each(function() {
$(this).replaceWith($(this).html());
});
}
// Remove elements
var removeTargets = $parent.data('remove-target') || [];
if ( ! (removeTargets instanceof Array)) {
removeTargets = [removeTargets];
}
removeTargets.push('.' + inspectorBtnCls);
$.each(removeTargets, function(index, target) {
$parent.find(target).remove();
});
// Remove classes from elements
var removeClassesTargets = $parent.data('remove-class-target') || [];
if ( ! (removeClassesTargets instanceof Array)) {
removeClassesTargets = [removeClassesTargets];
}
$.each(removeClassesTargets, function(index, target) {
$parent.find(target).removeClass(target.split('.')[1]);
});
// Trim whitespaces
var lines = $parent.html().split('\n');
if (lines.length > 0) {
// Remove all empty lines on the top
while(lines[0].trim().length === 0) {
lines.shift();
}
// Change indentation based on the first line
var indentSize = lines[0].length - lines[0].trim().length,
re = new RegExp(' {' + indentSize + '}'),
html = [];
$.each(lines, function(index, line) {
if (line.trim().length > 0 && line.match(re)) {
html.push(line.substring(indentSize));
} else if (line.length === 0) {
// Intended empty line
html.push('');
}
});
// Copy html to dialog and launch
$inspectorDialog
.find('.modal-body code').text(html.join('\n')).end()
.modal();
}
});
// Add inspector button
$('.' + inspectorParentCls).hover(function() {
$(this).append($inspectorBtn);
});
}); |
import React from 'react'
import Icon from 'react-icon-base'
const FaComments = props => (
<Icon viewBox="0 0 40 40" {...props}>
<g><path d="m31.4 17.1q0 3.1-2.1 5.8t-5.7 4.1-7.9 1.6q-1.9 0-3.9-0.4-2.8 2-6.2 2.9-0.8 0.2-1.9 0.3h-0.1q-0.3 0-0.5-0.2t-0.2-0.4q0-0.1 0-0.2t0-0.1 0-0.1l0.1-0.2 0-0.1 0.1-0.1 0.1-0.1 0.1-0.1q0.1-0.1 0.5-0.6t0.6-0.6 0.5-0.7 0.6-0.8 0.4-1q-2.7-1.6-4.3-4t-1.6-5q0-3.1 2.1-5.7t5.7-4.2 7.9-1.5 7.9 1.5 5.7 4.2 2.1 5.7z m8.6 5.8q0 2.6-1.6 5t-4.3 3.9q0.2 0.5 0.4 1t0.6 0.8 0.5 0.7 0.6 0.7 0.5 0.5q0 0 0.1 0.1t0.1 0.1 0.1 0.1 0 0.2l0.1 0.1 0 0.1 0 0.1 0 0.2q0 0.3-0.3 0.5t-0.5 0.1q-1.1-0.1-1.9-0.3-3.4-0.9-6.2-2.9-2 0.4-3.9 0.4-6.1 0-10.6-3 1.3 0.1 2 0.1 3.6 0 6.9-1t5.9-2.9q2.8-2 4.3-4.7t1.5-5.7q0-1.7-0.5-3.4 2.9 1.6 4.5 4t1.7 5.2z"/></g>
</Icon>
)
export default FaComments
|
/*
AngularJS v1.2.24-build.438+sha.992101d
(c) 2010-2014 Google, Inc. http://angularjs.org
License: MIT
*/
(function(n,e,A){'use strict';function x(s,g,h){return{restrict:"ECA",terminal:!0,priority:400,transclude:"element",link:function(a,c,b,f,w){function y(){p&&(p.remove(),p=null);k&&(k.$destroy(),k=null);l&&(h.leave(l,function(){p=null}),p=l,l=null)}function v(){var b=s.current&&s.current.locals;if(e.isDefined(b&&b.$template)){var b=a.$new(),d=s.current;l=w(b,function(d){h.enter(d,null,l||c,function(){!e.isDefined(t)||t&&!a.$eval(t)||g()});y()});k=d.scope=b;k.$emit("$viewContentLoaded");k.$eval(u)}else y()}
var k,l,p,t=b.autoscroll,u=b.onload||"";a.$on("$routeChangeSuccess",v);v()}}}function z(e,g,h){return{restrict:"ECA",priority:-400,link:function(a,c){var b=h.current,f=b.locals;c.html(f.$template);var w=e(c.contents());b.controller&&(f.$scope=a,f=g(b.controller,f),b.controllerAs&&(a[b.controllerAs]=f),c.data("$ngControllerController",f),c.children().data("$ngControllerController",f));w(a)}}}n=e.module("ngRoute",["ng"]).provider("$route",function(){function s(a,c){return e.extend(new (e.extend(function(){},
{prototype:a})),c)}function g(a,e){var b=e.caseInsensitiveMatch,f={originalPath:a,regexp:a},h=f.keys=[];a=a.replace(/([().])/g,"\\$1").replace(/(\/)?:(\w+)([\?\*])?/g,function(a,e,b,c){a="?"===c?c:null;c="*"===c?c:null;h.push({name:b,optional:!!a});e=e||"";return""+(a?"":e)+"(?:"+(a?e:"")+(c&&"(.+?)"||"([^/]+)")+(a||"")+")"+(a||"")}).replace(/([\/$\*])/g,"\\$1");f.regexp=RegExp("^"+a+"$",b?"i":"");return f}var h={};this.when=function(a,c){h[a]=e.extend({reloadOnSearch:!0},c,a&&g(a,c));if(a){var b=
"/"==a[a.length-1]?a.substr(0,a.length-1):a+"/";h[b]=e.extend({redirectTo:a},g(b,c))}return this};this.otherwise=function(a){this.when(null,a);return this};this.$get=["$rootScope","$location","$routeParams","$q","$injector","$http","$templateCache","$sce",function(a,c,b,f,g,n,v,k){function l(){var d=p(),m=r.current;if(d&&m&&d.$$route===m.$$route&&e.equals(d.pathParams,m.pathParams)&&!d.reloadOnSearch&&!u)m.params=d.params,e.copy(m.params,b),a.$broadcast("$routeUpdate",m);else if(d||m)u=!1,a.$broadcast("$routeChangeStart",
d,m),(r.current=d)&&d.redirectTo&&(e.isString(d.redirectTo)?c.path(t(d.redirectTo,d.params)).search(d.params).replace():c.url(d.redirectTo(d.pathParams,c.path(),c.search())).replace()),f.when(d).then(function(){if(d){var a=e.extend({},d.resolve),c,b;e.forEach(a,function(d,c){a[c]=e.isString(d)?g.get(d):g.invoke(d)});e.isDefined(c=d.template)?e.isFunction(c)&&(c=c(d.params)):e.isDefined(b=d.templateUrl)&&(e.isFunction(b)&&(b=b(d.params)),b=k.getTrustedResourceUrl(b),e.isDefined(b)&&(d.loadedTemplateUrl=
b,c=n.get(b,{cache:v}).then(function(a){return a.data})));e.isDefined(c)&&(a.$template=c);return f.all(a)}}).then(function(c){d==r.current&&(d&&(d.locals=c,e.copy(d.params,b)),a.$broadcast("$routeChangeSuccess",d,m))},function(c){d==r.current&&a.$broadcast("$routeChangeError",d,m,c)})}function p(){var a,b;e.forEach(h,function(f,h){var q;if(q=!b){var g=c.path();q=f.keys;var l={};if(f.regexp)if(g=f.regexp.exec(g)){for(var k=1,p=g.length;k<p;++k){var n=q[k-1],r=g[k];n&&r&&(l[n.name]=r)}q=l}else q=null;
else q=null;q=a=q}q&&(b=s(f,{params:e.extend({},c.search(),a),pathParams:a}),b.$$route=f)});return b||h[null]&&s(h[null],{params:{},pathParams:{}})}function t(a,c){var b=[];e.forEach((a||"").split(":"),function(a,d){if(0===d)b.push(a);else{var e=a.match(/(\w+)(.*)/),f=e[1];b.push(c[f]);b.push(e[2]||"");delete c[f]}});return b.join("")}var u=!1,r={routes:h,reload:function(){u=!0;a.$evalAsync(l)}};a.$on("$locationChangeSuccess",l);return r}]});n.provider("$routeParams",function(){this.$get=function(){return{}}});
n.directive("ngView",x);n.directive("ngView",z);x.$inject=["$route","$anchorScroll","$animate"];z.$inject=["$compile","$controller","$route"]})(window,window.angular);
//# sourceMappingURL=angular-route.min.js.map
|
// Utility funcitons
module.exports = {};
|
module.exports = (gulp, plugins, utilities) => {
return () => gulp.src(utilities.paths.BUILD_FOLDER, {read: false}).pipe(plugins.clean());
};
|
function js() {
console.log("js/file.js should have tab width 8");
}
|
(function() {
"use strict";
// Place page specific javascript here
})(); |
module.exports = function (d) {
if(!d)return null;
var ds = '';
var f = function(name,o) {
for(var i in o){
var v = o[i];
if((typeof v)==='object'){
f(i,v);
}else{
ds +=(name+'.'+i+'='+(v?v:'')+'&');
}
}
}
for(var i in d){
var v = d[i];
if((typeof v)==='object'){
f(i,v);
}else{
ds += (i+'='+v+'&');
}
}
return ds;
} |
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports['default'] = {
// Options.jsx
items_per_page: '/ صفحه',
jump_to: 'برو به',
jump_to_confirm: 'تایید',
page: '',
// Pagination.jsx
prev_page: 'صفحه قبلی',
next_page: 'صفحه بعدی',
prev_5: '۵ صفحه قبلی',
next_5: '۵ صفحه بعدی',
prev_3: '۳ صفحه قبلی',
next_3: '۳ صفحه بعدی'
};
module.exports = exports['default']; |
/*
Copyright (c) 2003-2016, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'preview', 'ro', {
preview: 'Previzualizare'
} );
|
define({
"settingsHeader": "지오룩업 위젯에 대한 세부정보 설정",
"settingsDesc": "맵의 폴리곤 레이어에 대해 CSV 파일에서 위치 목록을 보강합니다. 폴리곤 레이어에서 선택한 필드가 위치에 추가됩니다.",
"settingsLoadingLayers": "레이어를 불러오는 동안 기다려 주세요.",
"settingsConfigureTitle": "레이어 필드 구성",
"layerTable": {
"colEnrich": "보강",
"colLabel": "레이어",
"colFieldSelector": "필드"
},
"fieldTable": {
"colAppend": "추가",
"colName": "이름",
"colAlias": "별칭",
"colOrder": "작업",
"label": "추가할 필드를 선택합니다. 별칭과 순서를 업데이트할 필드를 선택하세요."
},
"symbolArea": {
"symbolLabelWithin": "다음 내에서 위치에 대한 심볼 선택:",
"symbolLabelOutside": "다음 바깥에서 위치에 대한 심볼 선택:"
},
"advSettings": {
"label": "고급 설정",
"latFieldsDesc": "위도 필드에 사용할 수 있는 필드 이름입니다.",
"longFieldsDesc": "경도 필드에 사용할 수 있는 필드 이름입니다.",
"intersectFieldDesc": "조회 결과가 레이어와 교차하는 경우 값을 저장하기 위해 생성되는 필드 이름입니다.",
"intersectInDesc": "위치가 폴리곤과 교차할 때 저장되는 값입니다.",
"intersectOutDesc": "위치가 폴리곤과 교차하지 않을 때 저장되는 값입니다.",
"maxRowCount": "CSV 파일의 최대 행 수입니다.",
"cacheNumberDesc": "더 빠른 처리를 위한 포인트 군집 임계값입니다.",
"subTitle": "CSV 파일에 대한 값을 설정합니다."
},
"noPolygonLayers": "폴리곤 레이어 없음",
"errorOnOk": "구성을 저장하기 전에 모든 매개변수를 입력하세요.",
"saveFields": "필드 저장",
"cancelFields": "필드 취소",
"saveAdv": "고급 설정 저장",
"cancelAdv": "고급 설정 취소",
"advSettingsBtn": "고급 설정",
"chooseSymbol": "심볼 선택",
"okBtn": "확인",
"cancelBtn": "취소"
}); |
"use strict";
var cache = {},
fs = require('fs'),
path = require('path'),
vm = require('vm');
module.exports = function (file, mocks, context) {
var script;
mocks = mocks || {};
context = context || {};
file = path.join(path.dirname(module.parent.filename), file);
cache[file] = cache[file] || module.exports.onload(file,
fs.readFileSync(file, 'utf8'));
script = vm.createScript(cache[file], file);
context.require = function (a) {
if (mocks[a]) {
return mocks[a];
}
if (a.indexOf('.') === 0) {
a = path.join(path.dirname(file), a);
}
return require(a);
};
context.module = context.module || {};
context.module.exports = {};
context.exports = context.module.exports;
script.runInNewContext(context);
return context.module.exports;
};
module.exports.onload = function (file, content) {
if (file.match(/\.coffee$/)) {
return require('coffee-script').compile(content, {
filename : file
});
}
return content;
};
|
export const APPEND_FILES = "APPEND_FILES";
export const APPEND_OBS_CARDS = "APPEND_OBS_CARDS";
export const APPEND_TO_SELECTED_OBS_CARDS = "APPEND_TO_SELECTED_OBS_CARDS";
export const CREATE_BLANK_OBS_CARD = "CREATE_BLANK_OBS_CARD";
export const DRAG = "DRAG";
export const INSERT_CARDS_BEFORE = "INSERT_CARDS_BEFORE";
export const MERGE_OBS_CARDS = "MERGE_OBS_CARDS";
export const REMOVE_FILE = "REMOVE_FILE";
export const REMOVE_FROM_SELECTED_OBS_CARDS = "REMOVE_FROM_SELECTED_OBS_CARDS";
export const REMOVE_OBS_CARD = "REMOVE_OBS_CARD";
export const REMOVE_SELECTED = "REMOVE_SELECTED";
export const SELECT_ALL = "SELECT_ALL";
export const SELECT_OBS_CARDS = "SELECT_OBS_CARDS";
export const SET_STATE = "SET_STATE";
export const UPDATE_FILE = "UPDATE_FILE";
export const UPDATE_OBS_CARD = "UPDATE_OBS_CARD";
export const UPDATE_OBS_CARD_FILE = "UPDATE_OBS_CARD_FILE";
export const UPDATE_SELECTED_OBS_CARDS = "UPDATE_SELECTED_OBS_CARDS";
export const UPDATE_STATE = "UPDATE_STATE";
|
// Testing the main file
describe(".closest(selector)", function() {
afterEach(function(){
// A previous bug that would change the inner of the original reference
expect(base.length).to.equal(1);
});
it("should be a function", function() {
expect(typeof base.closest).to.equal('function');
});
it("can select the children of ul", function() {
expect(base.find('li').closest('ul').length).to.equal(1);
});
it("is okay with no ancestors", function() {
expect(base.closest('.nonexist').length).to.equal(0);
});
});
|
'use strict'
const {BrowserWindow, MenuItem, webContents} = require('electron')
const EventEmitter = require('events').EventEmitter
const v8Util = process.atomBinding('v8_util')
const bindings = process.atomBinding('menu')
// Automatically generated radio menu item's group id.
var nextGroupId = 0
// Search between separators to find a radio menu item and return its group id,
// otherwise generate a group id.
var generateGroupId = function (items, pos) {
var i, item, j, k, ref1, ref2, ref3
if (pos > 0) {
for (i = j = ref1 = pos - 1; ref1 <= 0 ? j <= 0 : j >= 0; i = ref1 <= 0 ? ++j : --j) {
item = items[i]
if (item.type === 'radio') {
return item.groupId
}
if (item.type === 'separator') {
break
}
}
} else if (pos < items.length) {
for (i = k = ref2 = pos, ref3 = items.length - 1; ref2 <= ref3 ? k <= ref3 : k >= ref3; i = ref2 <= ref3 ? ++k : --k) {
item = items[i]
if (item.type === 'radio') {
return item.groupId
}
if (item.type === 'separator') {
break
}
}
}
return ++nextGroupId
}
// Returns the index of item according to |id|.
var indexOfItemById = function (items, id) {
var i, item, j, len
for (i = j = 0, len = items.length; j < len; i = ++j) {
item = items[i]
if (item.id === id) {
return i
}
}
return -1
}
// Returns the index of where to insert the item according to |position|.
var indexToInsertByPosition = function (items, position) {
var insertIndex
if (!position) {
return items.length
}
const [query, id] = position.split('=')
insertIndex = indexOfItemById(items, id)
if (insertIndex === -1 && query !== 'endof') {
console.warn("Item with id '" + id + "' is not found")
return items.length
}
switch (query) {
case 'after':
insertIndex++
break
case 'endof':
// If the |id| doesn't exist, then create a new group with the |id|.
if (insertIndex === -1) {
items.push({
id: id,
type: 'separator'
})
insertIndex = items.length - 1
}
// Find the end of the group.
insertIndex++
while (insertIndex < items.length && items[insertIndex].type !== 'separator') {
insertIndex++
}
}
return insertIndex
}
const Menu = bindings.Menu
Object.setPrototypeOf(Menu.prototype, EventEmitter.prototype)
Menu.prototype._init = function () {
this.commandsMap = {}
this.groupsMap = {}
this.items = []
this.delegate = {
isCommandIdChecked: (commandId) => {
var command = this.commandsMap[commandId]
return command != null ? command.checked : undefined
},
isCommandIdEnabled: (commandId) => {
var command = this.commandsMap[commandId]
return command != null ? command.enabled : undefined
},
isCommandIdVisible: (commandId) => {
var command = this.commandsMap[commandId]
return command != null ? command.visible : undefined
},
getAcceleratorForCommandId: (commandId, useDefaultAccelerator) => {
const command = this.commandsMap[commandId]
if (command == null) return
if (command.accelerator != null) return command.accelerator
if (useDefaultAccelerator) return command.getDefaultRoleAccelerator()
},
getIconForCommandId: (commandId) => {
var command = this.commandsMap[commandId]
return command != null ? command.icon : undefined
},
executeCommand: (event, commandId) => {
const command = this.commandsMap[commandId]
if (command == null) return
command.click(event, BrowserWindow.getFocusedWindow(), webContents.getFocusedWebContents())
},
menuWillShow: () => {
// Make sure radio groups have at least one menu item seleted.
var checked, group, id, j, len, radioItem, ref1
ref1 = this.groupsMap
for (id in ref1) {
group = ref1[id]
checked = false
for (j = 0, len = group.length; j < len; j++) {
radioItem = group[j]
if (!radioItem.checked) {
continue
}
checked = true
break
}
if (!checked) {
v8Util.setHiddenValue(group[0], 'checked', true)
}
}
}
}
}
Menu.prototype.popup = function (sender, x, y, positioningItem) {
// menu.popup(x, y, positioningItem)
let win
if (typeof sender === 'object') {
if (sender.constructor === BrowserWindow) {
win = sender
sender = win.webContents
} else {
const embedder = sender.hostWebContents || sender
win = BrowserWindow.fromWebContents(embedder)
}
} else {
// Shift.
positioningItem = y
y = x
x = win
win = BrowserWindow.getFocusedWindow()
sender = win.webContents
}
if (win == null || win.isDestroyed()) {
return
}
this.sourceWebContents = sender
if (this.sourceWebContents == null || this.sourceWebContents.isDestroyed()) {
return
}
// menu.popup(win, {})
if (x != null && typeof x === 'object') {
const options = x
x = options.x
y = options.y
positioningItem = options.positioningItem
}
// Default to showing under mouse location.
if (typeof x !== 'number') x = -1
if (typeof y !== 'number') y = -1
// Default to not highlighting any item.
if (typeof positioningItem !== 'number') positioningItem = -1
if (this.sourceWebContents.onContextMenuShow()) {
this.popupAt(win, x, y, positioningItem, this.closePopup.bind(this))
}
}
Menu.prototype.closePopup = function (window_id) {
this.closePopupAt(window_id)
if (!this.sourceWebContents.isDestroyed()) {
this.sourceWebContents.onContextMenuClose()
}
}
Menu.prototype.append = function (item) {
return this.insert(this.getItemCount(), item)
}
Menu.prototype.insert = function (pos, item) {
var base, name
if ((item != null ? item.constructor : void 0) !== MenuItem) {
throw new TypeError('Invalid item')
}
switch (item.type) {
case 'normal':
this.insertItem(pos, item.commandId, item.label)
break
case 'checkbox':
this.insertCheckItem(pos, item.commandId, item.label)
break
case 'separator':
this.insertSeparator(pos)
break
case 'submenu':
this.insertSubMenu(pos, item.commandId, item.label, item.submenu)
break
case 'radio':
// Grouping radio menu items.
item.overrideReadOnlyProperty('groupId', generateGroupId(this.items, pos))
if ((base = this.groupsMap)[name = item.groupId] == null) {
base[name] = []
}
this.groupsMap[item.groupId].push(item)
// Setting a radio menu item should flip other items in the group.
v8Util.setHiddenValue(item, 'checked', item.checked)
Object.defineProperty(item, 'checked', {
enumerable: true,
get: function () {
return v8Util.getHiddenValue(item, 'checked')
},
set: () => {
var j, len, otherItem, ref1
ref1 = this.groupsMap[item.groupId]
for (j = 0, len = ref1.length; j < len; j++) {
otherItem = ref1[j]
if (otherItem !== item) {
v8Util.setHiddenValue(otherItem, 'checked', false)
}
}
return v8Util.setHiddenValue(item, 'checked', true)
}
})
this.insertRadioItem(pos, item.commandId, item.label, item.groupId)
}
if (item.sublabel != null) {
this.setSublabel(pos, item.sublabel)
}
if (item.icon != null) {
this.setIcon(pos, item.icon)
}
if (item.role != null) {
this.setRole(pos, item.role)
}
// Make menu accessable to items.
item.overrideReadOnlyProperty('menu', this)
// Remember the items.
this.items.splice(pos, 0, item)
this.commandsMap[item.commandId] = item
}
// Force menuWillShow to be called
Menu.prototype._callMenuWillShow = function () {
if (this.delegate != null) {
this.delegate.menuWillShow()
}
this.items.forEach(function (item) {
if (item.submenu != null) {
item.submenu._callMenuWillShow()
}
})
}
var applicationMenu = null
Menu.setApplicationMenu = function (menu) {
if (!(menu === null || menu.constructor === Menu)) {
throw new TypeError('Invalid menu')
}
// Keep a reference.
applicationMenu = menu
if (process.platform === 'darwin') {
if (menu === null) {
return
}
menu._callMenuWillShow()
bindings.setApplicationMenu(menu)
} else {
BrowserWindow.getAllWindows().forEach(function (window) {
window.setMenu(menu)
})
}
}
Menu.getApplicationMenu = function () {
return applicationMenu
}
Menu.sendActionToFirstResponder = bindings.sendActionToFirstResponder
Menu.buildFromTemplate = function (template) {
var insertIndex, item, j, k, key, len, len1, menu, menuItem, positionedTemplate
if (!Array.isArray(template)) {
throw new TypeError('Invalid template for Menu')
}
positionedTemplate = []
insertIndex = 0
for (j = 0, len = template.length; j < len; j++) {
item = template[j]
if (item.position) {
insertIndex = indexToInsertByPosition(positionedTemplate, item.position)
} else {
// If no |position| is specified, insert after last item.
insertIndex++
}
positionedTemplate.splice(insertIndex, 0, item)
}
menu = new Menu()
for (k = 0, len1 = positionedTemplate.length; k < len1; k++) {
item = positionedTemplate[k]
if (typeof item !== 'object') {
throw new TypeError('Invalid template for MenuItem')
}
menuItem = new MenuItem(item)
for (key in item) {
// Preserve extra fields specified by user
if (!menuItem.hasOwnProperty(key)) {
menuItem[key] = item[key]
}
}
menu.append(menuItem)
}
return menu
}
module.exports = Menu
|
/* global device: false */
/* global PushNotification: false */
var getService = function() {
if (/android/i.test(device.platform)) {
return 'gcm';
} else if (/ios/i.test(device.platform)) {
return 'apn';
} else if (/win/i.test(device.platform)) {
return 'mpns';
}
return 'unknown';
};
/**
* https://github.com/phonegap/phonegap-plugin-push#pushnotificationinitoptions
*/
class PushHandle extends EventState {
constructor() {
super();
this.configured = false;
this.debug = false;
this.token = null;
}
log() {
if (this.debug) {
console.log(...arguments);
}
}
setBadge(count) {
this.once('ready', () => {
if (/ios/i.test(device.platform)) {
this.log('Push.setBadge:', count);
// xxx: at the moment only supported on iOS
this.push.setApplicationIconBadgeNumber(() => {
this.log('Push.setBadge: was set to', count);
}, (e) => {
this.emit('error', {
type: getService() + '.cordova',
error: 'Push.setBadge Error: ' + e.message
});
}, count);
}
});
}
unregister(successHandler, errorHandler) {
if (this.push) {
this.push.unregister(successHandler, errorHandler);
} else {
errorHandler(new Error('Push.unregister, Error: "Push not configured"'));
}
}
Configure(options = {}) {
if (!this.configured) {
this.log('Push.Configure:', options);
this.configured = true;
Meteor.startup(() => {
if (typeof PushNotification !== 'undefined') {
this.push = PushNotification.init(options);
this.push.on('registration', (data) => {
// xxx: we need to check that the token has changed before emitting
// a new token state - sometimes this event is triggered twice
if (data && data.registrationId && this.token !== data.registrationId) {
this.token = data.registrationId;
var token = {
[getService()]: data.registrationId
};
this.log('Push.Token:', token);
this.emitState('token', token);
}
this.emitState('registration', ...arguments);
});
this.push.on('notification', (data) => {
this.log('Push.Notification:', data);
// xxx: check ejson support on "additionalData" json object
if (data.additionalData.ejson) {
if (data.additionalData.ejson === ''+data.additionalData.ejson) {
try {
data.payload = EJSON.parse(data.additionalData.ejson);
this.log('Push.Parsed.EJSON.Payload:', data.payload);
} catch(err) {
this.log('Push.Parsed.EJSON.Payload.Error', err.message, data.payload);
}
} else {
data.payload = EJSON.fromJSONValue(data.additionalData.ejson);
this.log('Push.EJSON.Payload:', data.payload);
}
}
// Emit alert event - this requires the app to be in forground
if (data.message && data.additionalData.foreground) {
this.emit('alert', data);
}
// Emit sound event
if (data.sound) {
this.emit('sound', data);
}
// Emit badge event
if (typeof data.count !== 'undefined') {
this.log('Push.SettingBadge:', data.count);
this.setBadge(data.count);
this.emit('badge', data);
}
if (data.additionalData.foreground) {
this.log('Push.Message: Got message while app is open:', data);
this.emit('message', data);
} else {
this.log('Push.Startup: Got message while app was closed/in background:', data);
this.emitState('startup', data);
}
this.emitState();
});
this.push.on('error', (e) => {
this.log('Push.Error:', e);
this.emit('error', {
type: getService() + '.cordova',
error: e.message
});
});
this.emitState('ready');
}
});
initPushUpdates(options.appName);
} else {
this.log('Push.Error: "Push.Configure may only be called once"');
throw new Error('Push.Configure may only be called once');
}
}
}
Push = new PushHandle();
|
var searchData=
[
['randomdouble',['randomDouble',['../namespace_num_utils.html#a402b26db626888d32e79bfab0e6ba5c2',1,'NumUtils']]],
['randomint',['randomInt',['../namespace_num_utils.html#abb2bad9628db7cd63498680a6f84e13c',1,'NumUtils']]],
['read_5fkernels_5ffrom_5ffile',['read_kernels_from_file',['../class_c_l_helper.html#a14ace996406fabec7232dc354b0aee27',1,'CLHelper']]],
['readasstring',['readAsString',['../class_file_handle.html#a9ba334d8e171983edc20759217bb8558',1,'FileHandle']]],
['readasvector',['readAsVector',['../class_file_handle.html#a941b1e265de1520cb7e1ac26ece6d99b',1,'FileHandle']]],
['readfullfile',['readFullFile',['../namespace_f_s_utils.html#a716aadc6305897ef4710c2f261db73c9',1,'FSUtils']]],
['readlinebyline',['readLineByLine',['../namespace_f_s_utils.html#aa911eba466bd3ba571e86dc3ee024a97',1,'FSUtils']]],
['removecharfromstr',['removeCharFromStr',['../namespace_str_utils.html#a1d9112fe1be09aeafa3539fb771dd7c8',1,'StrUtils']]],
['resumetimer',['resumeTimer',['../class_timer.html#ade1f50ac610d5fe49228f4e6dc3d4774',1,'Timer']]]
];
|
export const message = "Hello Chunk";
|
/*!
DataTables Foundation integration
©2011-2014 SpryMedia Ltd - datatables.net/license
*/
(function(){var d=function(e,f){e.extend(f.ext.classes,{sWrapper:"dataTables_wrapper dt-foundation",sProcessing:"dataTables_processing panel"});e.extend(!0,f.defaults,{dom:"<'row'<'small-6 columns'l><'small-6 columns'f>r>t<'row'<'small-6 columns'i><'small-6 columns'p>>",renderer:"foundation"});f.ext.renderer.pageButton.foundation=function(g,d,q,k,h,l){var m=new f.Api(g),r=g.oClasses,i=g.oLanguage.oPaginate,b,c,p=function(d,f){var j,n,o,a,k=function(a){a.preventDefault();!e(a.currentTarget).hasClass("unavailable")&&
m.page()!=a.data.action&&m.page(a.data.action).draw("page")};j=0;for(n=f.length;j<n;j++)if(a=f[j],e.isArray(a))p(d,a);else{c=b="";switch(a){case "ellipsis":b="…";c="unavailable";break;case "first":b=i.sFirst;c=a+(0<h?"":" unavailable");break;case "previous":b=i.sPrevious;c=a+(0<h?"":" unavailable");break;case "next":b=i.sNext;c=a+(h<l-1?"":" unavailable");break;case "last":b=i.sLast;c=a+(h<l-1?"":" unavailable");break;default:b=a+1,c=h===a?"current":""}b&&(o=e("<li>",{"class":r.sPageButton+
" "+c,"aria-controls":g.sTableId,tabindex:g.iTabIndex,id:0===q&&"string"===typeof a?g.sTableId+"_"+a:null}).append(e("<a>",{href:"#"}).html(b)).appendTo(d),g.oApi._fnBindAction(o,{action:a},k))}};p(e(d).empty().html('<ul class="pagination"/>').children("ul"),k)}};"function"===typeof define&&define.amd?define(["jquery","datatables"],d):"object"===typeof exports?d(require("jquery"),require("datatables")):jQuery&&d(jQuery,jQuery.fn.dataTable)})(window,document);
|
/* global Restivus */
class API extends Restivus {
constructor(properties) {
super(properties);
this.logger = new Logger(`API ${properties.version ? properties.version : 'default'} Logger`, {});
this.authMethods = [];
this.helperMethods = new Map();
this.defaultFieldsToExclude = {
joinCode: 0,
$loki: 0,
meta: 0
};
}
addAuthMethod(method) {
this.authMethods.push(method);
}
success(result={}) {
if (_.isObject(result)) {
result.success = true;
}
return {
statusCode: 200,
body: result
};
}
failure(result, errorType) {
if (_.isObject(result)) {
result.success = false;
} else {
result = {
success: false,
error: result
};
if (errorType) {
result.errorType = errorType;
}
}
return {
statusCode: 400,
body: result
};
}
unauthorized(msg) {
return {
statusCode: 403,
body: {
success: false,
error: msg ? msg : 'unauthorized'
}
};
}
addRoute(routes, options, endpoints) {
//Note: required if the developer didn't provide options
if (typeof endpoints === 'undefined') {
endpoints = options;
options = {};
}
//Allow for more than one route using the same option and endpoints
if (!_.isArray(routes)) {
routes = [routes];
}
routes.forEach((route) => {
//Note: This is required due to Restivus calling `addRoute` in the constructor of itself
if (this.helperMethods) {
Object.keys(endpoints).forEach((method) => {
if (typeof endpoints[method] === 'function') {
endpoints[method] = { action: endpoints[method] };
}
//Add a try/catch for each much
const originalAction = endpoints[method].action;
endpoints[method].action = function() {
this.logger.debug(`${this.request.method.toUpperCase()}: ${this.request.url}`);
let result;
try {
result = originalAction.apply(this);
} catch (e) {
this.logger.debug(`${method} ${route} threw an error:`, e);
return RocketChat.API.v1.failure(e.message, e.error);
}
return result ? result : RocketChat.API.v1.success();
};
for (const [name, helperMethod] of this.helperMethods) {
endpoints[method][name] = helperMethod;
}
//Allow the endpoints to make usage of the logger which respects the user's settings
endpoints[method].logger = this.logger;
});
}
super.addRoute(route, options, endpoints);
});
}
}
RocketChat.API = {};
const getUserAuth = function _getUserAuth() {
const invalidResults = [undefined, null, false];
return {
token: 'services.resume.loginTokens.hashedToken',
user: function() {
if (this.bodyParams && this.bodyParams.payload) {
this.bodyParams = JSON.parse(this.bodyParams.payload);
}
for (let i = 0; i < RocketChat.API.v1.authMethods.length; i++) {
const method = RocketChat.API.v1.authMethods[i];
if (typeof method === 'function') {
const result = method.apply(this, arguments);
if (!invalidResults.includes(result)) {
return result;
}
}
}
let token;
if (this.request.headers['x-auth-token']) {
token = Accounts._hashLoginToken(this.request.headers['x-auth-token']);
}
return {
userId: this.request.headers['x-user-id'],
token
};
}
};
};
RocketChat.API.v1 = new API({
version: 'v1',
useDefaultAuth: true,
prettyJson: true,
enableCors: false,
auth: getUserAuth()
});
RocketChat.API.default = new API({
useDefaultAuth: true,
prettyJson: true,
enableCors: false,
auth: getUserAuth()
});
|
import faker from 'faker'
import React from 'react'
import CardHeader from 'src/views/Card/CardHeader'
import * as common from 'test/specs/commonTests'
describe('CardHeader', () => {
common.isConformant(CardHeader)
common.rendersChildren(CardHeader)
describe('description prop', () => {
it('renders child text', () => {
const text = faker.hacker.phrase()
shallow(<CardHeader content={text} />)
.should.contain.text(text)
})
})
})
|
/* @flow */
const entries = require('lodash/entries');
module.exports = getDependencyRegistry;
function getDependencyRegistry(file: File, seed: DependencyRegistry = {}): DependencyRegistry { // eslint-disable-line no-use-before-define
return entries(file.dependencies || {})
.reduce((registry, entry) => {
const [name, data] = entry;
registry[file.path] = seed[file.path] || {};
registry[file.path][name] = data.path;
getDependencyRegistry(data, registry);
return registry;
}, seed);
}
type File = { // eslint-disable-line no-undef
buffer: Buffer;
path: string;
};
type DependencyRegistry = { // eslint-disable-line no-undef
[path: string]: {
[name: string]: string;
}
};
|
(function(win) {
var dataType = {
form: getFormData,
json: getJsonData,
data: getData
};
function genUId() {
var date = new Date().getTime();
var uuid = 'xxxxxx4xxxyxxxxxxx'.replace(/[xy]/g, function(c) {
var r = (date + Math.random() * 16) % 16 | 0;
date = Math.floor(date / 16);
return (c == 'x' ? r : (r & 0x3 | 0x8)).toString(16);
});
return uuid;
};
function mergeOption(opts) {
var options = {
domain: '',
method: 'POST',
file_data_name: 'file',
unique_key: 'key',
base64_size: 4 * 1024 * 1024,
chunk_size: 4 * 1024 * 1024,
headers: {},
multi_parmas: {},
query: {},
support_options: true,
data: dataType.form,
genUId: genUId
};
if (!opts || !opts.domain) {
throw new Error('domain is null');
}
for (var key in opts) {
options[key] = opts[key];
}
return options;
}
function mEach(m, callback) {
for (var key in m) {
callback(key, m[key]);
}
}
function getFormData(file, opts) {
var form = new FormData();
if (opts.unique_key) {
var suffix = file.name.substr(file.name.lastIndexOf('.'));
var unique_value = genUId() + suffix;
form.append(opts.unique_key, unique_value);
opts.unique_value = unique_value;
}
form.append(opts.file_data_name, file);
mEach(opts.multi_parmas, function(key, value) {
form.append(key, value);
});
return form;
}
function getJsonData(file, opts) {
var data = {};
if (opts.unique_key) {
var suffix = file.name.substr(file.name.lastIndexOf('.'));
var unique_value = genUId() + suffix;
data[opts.unique_key] = unique_value;
opts.unique_value = unique_value;
}
data[opts.file_data_name] = file;
mEach(opts.multi_parmas, function(key, value) {
data[key] = value;
});
return JSON.stringify(data);
}
function getData(file, opts) {
return file;
}
function Upload(options) {
this.options = mergeOption(options);
this.setOptions = function(opts) {
var me = this;
mEach(opts, function(key, value) {
me.options[key] = value;
});
};
this.upload = function(file, callback) {
if (!file) {
callback.onError('upload file is null.');
return;
}
var me = this;
uploadProcess(file, this.options, {
onProgress: function(loaded, total) {
callback.onProgress(loaded, total);
},
onCompleted: function(data) {
callback.onCompleted(data);
},
onError: function(errorCode) {
callback.onError(errorCode);
},
onOpen: function(xhr) {
me.xhr = xhr;
}
});
};
this.cancel = function() {
this.xhr && this.xhr.abort();
};
}
function init(options) {
return new Upload(options);
}
function getResizeRatio(imageInfo,config){
//hasOwnProperty?
var ratio = 1;
var oWidth = imageInfo.width;
var maxWidth = config.maxWidth || 0;
if(maxWidth > 0 && oWidth > maxWidth){
ratio = maxWidth/oWidth;
}
var oHeight = imageInfo.height;
var maxHeight = config.maxHeight || 0;
if(maxHeight > 0 && oHeight > maxHeight){
var ratioHeight = maxHeight/oHeight;
ratio = Math.min(ratio,ratioHeight);
}
var maxSize = config.maxSize || 0;
var oSize = Math.ceil(imageInfo.size/1000); //K,Math.ceil(0.3) = 1;
if(oSize > maxSize){
ratioSize = maxSize/oSize;
ratio = Math.min(ratio,ratioSize);
}
return ratio;
}
function resize(file,config,callback){
//file对象没有高宽
var type = file.type; //image format
var canvas = document.createElement("canvas");
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function(evt){
var imageData = evt.target.result;
var img = new Image();
img.src = imageData;
var width = img.width;
var height = img.height;
var imageInfo = {
width : width,
height : height,
size : evt.total
}
var ratio = getResizeRatio(imageInfo,config);
var newImageData = imageData;
if(ratio < 1){
newImageData = compress(img, width*ratio, height*ratio);;
}
callback(newImageData);
}
function compress(img, width, height){
canvas.width = width;
canvas.height = height;
var context = canvas.getContext('2d');
context.drawImage(img, 0, 0, width, height);
/*
If the height or width of the canvas is 0, the string "data:," is returned.
If the requested type is not image/png, but the returned value starts with data:image/png, then the requested type is not supported.
Chrome also supports the image/webp type.
*/
var supportTypes = {
"image/jpg" : true,
"image/png" : true,
"image/webp" : supportWebP()
};
// var exportType = "image/png";
// if(supportTypes[type]){
// exportType = type;
// }
// 多端一致,缩略图必须是 jpg
var exportType = "image/jpg";
var newImageData = canvas.toDataURL(exportType);
return newImageData;
}
function supportWebP(){
try{
return (canvas.toDataURL('image/webp').indexOf('data:image/webp') == 0);
}catch(err) {
return false;
}
}
}
win.UploadFile = {
init: init,
dataType: dataType,
resize : resize
};
})(window); |
/*! WOW - v1.1.2 - 2015-08-19
* Copyright (c) 2015 Matthieu Aussaguel; Licensed MIT */
(function() {
var a, b, c, d, e, f = function(a, b) {
return function() {
return a.apply(b, arguments) } },
g = [].indexOf || function(a) {
for (var b = 0, c = this.length; c > b; b++)
if (b in this && this[b] === a) return b;
return -1 };
b = function() {
function a() {}
return a.prototype.extend = function(a, b) {
var c, d;
for (c in b) d = b[c], null == a[c] && (a[c] = d);
return a }, a.prototype.isMobile = function(a) {
return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(a) }, a.prototype.createEvent = function(a, b, c, d) {
var e;
return null == b && (b = !1), null == c && (c = !1), null == d && (d = null), null != document.createEvent ? (e = document.createEvent("CustomEvent"), e.initCustomEvent(a, b, c, d)) : null != document.createEventObject ? (e = document.createEventObject(), e.eventType = a) : e.eventName = a, e }, a.prototype.emitEvent = function(a, b) {
return null != a.dispatchEvent ? a.dispatchEvent(b) : b in (null != a) ? a[b]() : "on" + b in (null != a) ? a["on" + b]() : void 0 }, a.prototype.addEvent = function(a, b, c) {
return null != a.addEventListener ? a.addEventListener(b, c, !1) : null != a.attachEvent ? a.attachEvent("on" + b, c) : a[b] = c }, a.prototype.removeEvent = function(a, b, c) {
return null != a.removeEventListener ? a.removeEventListener(b, c, !1) : null != a.detachEvent ? a.detachEvent("on" + b, c) : delete a[b] }, a.prototype.innerHeight = function() {
return "innerHeight" in window ? window.innerHeight : document.documentElement.clientHeight }, a }(), c = this.WeakMap || this.MozWeakMap || (c = function() {
function a() { this.keys = [], this.values = [] }
return a.prototype.get = function(a) {
var b, c, d, e, f;
for (f = this.keys, b = d = 0, e = f.length; e > d; b = ++d)
if (c = f[b], c === a) return this.values[b] }, a.prototype.set = function(a, b) {
var c, d, e, f, g;
for (g = this.keys, c = e = 0, f = g.length; f > e; c = ++e)
if (d = g[c], d === a) return void(this.values[c] = b);
return this.keys.push(a), this.values.push(b) }, a }()), a = this.MutationObserver || this.WebkitMutationObserver || this.MozMutationObserver || (a = function() {
function a() { "undefined" != typeof console && null !== console && console.warn("MutationObserver is not supported by your browser."), "undefined" != typeof console && null !== console && console.warn("WOW.js cannot detect dom mutations, please call .sync() after loading new content.") }
return a.notSupported = !0, a.prototype.observe = function() {}, a }()), d = this.getComputedStyle || function(a) {
return this.getPropertyValue = function(b) {
var c;
return "float" === b && (b = "styleFloat"), e.test(b) && b.replace(e, function(a, b) {
return b.toUpperCase() }), (null != (c = a.currentStyle) ? c[b] : void 0) || null }, this }, e = /(\-([a-z]){1})/g, this.WOW = function() {
function e(a) { null == a && (a = {}), this.scrollCallback = f(this.scrollCallback, this), this.scrollHandler = f(this.scrollHandler, this), this.resetAnimation = f(this.resetAnimation, this), this.start = f(this.start, this), this.scrolled = !0, this.config = this.util().extend(a, this.defaults), null != a.scrollContainer && (this.config.scrollContainer = document.querySelector(a.scrollContainer)), this.animationNameCache = new c, this.wowEvent = this.util().createEvent(this.config.boxClass) }
return e.prototype.defaults = { boxClass: "wow", animateClass: "animated", offset: 0, mobile: !0, live: !0, callback: null, scrollContainer: null }, e.prototype.init = function() {
var a;
return this.element = window.document.documentElement, "interactive" === (a = document.readyState) || "complete" === a ? this.start() : this.util().addEvent(document, "DOMContentLoaded", this.start), this.finished = [] }, e.prototype.start = function() {
var b, c, d, e;
if (this.stopped = !1, this.boxes = function() {
var a, c, d, e;
for (d = this.element.querySelectorAll("." + this.config.boxClass), e = [], a = 0, c = d.length; c > a; a++) b = d[a], e.push(b);
return e }.call(this), this.all = function() {
var a, c, d, e;
for (d = this.boxes, e = [], a = 0, c = d.length; c > a; a++) b = d[a], e.push(b);
return e }.call(this), this.boxes.length)
if (this.disabled()) this.resetStyle();
else
for (e = this.boxes, c = 0, d = e.length; d > c; c++) b = e[c], this.applyStyle(b, !0);
return this.disabled() || (this.util().addEvent(this.config.scrollContainer || window, "scroll", this.scrollHandler), this.util().addEvent(window, "resize", this.scrollHandler), this.interval = setInterval(this.scrollCallback, 50)), this.config.live ? new a(function(a) {
return function(b) {
var c, d, e, f, g;
for (g = [], c = 0, d = b.length; d > c; c++) f = b[c], g.push(function() {
var a, b, c, d;
for (c = f.addedNodes || [], d = [], a = 0, b = c.length; b > a; a++) e = c[a], d.push(this.doSync(e));
return d }.call(a));
return g } }(this)).observe(document.body, { childList: !0, subtree: !0 }) : void 0 }, e.prototype.stop = function() {
return this.stopped = !0, this.util().removeEvent(this.config.scrollContainer || window, "scroll", this.scrollHandler), this.util().removeEvent(window, "resize", this.scrollHandler), null != this.interval ? clearInterval(this.interval) : void 0 }, e.prototype.sync = function() {
return a.notSupported ? this.doSync(this.element) : void 0 }, e.prototype.doSync = function(a) {
var b, c, d, e, f;
if (null == a && (a = this.element), 1 === a.nodeType) {
for (a = a.parentNode || a, e = a.querySelectorAll("." + this.config.boxClass), f = [], c = 0, d = e.length; d > c; c++) b = e[c], g.call(this.all, b) < 0 ? (this.boxes.push(b), this.all.push(b), this.stopped || this.disabled() ? this.resetStyle() : this.applyStyle(b, !0), f.push(this.scrolled = !0)) : f.push(void 0);
return f } }, e.prototype.show = function(a) {
return this.applyStyle(a), a.className = a.className + " " + this.config.animateClass, null != this.config.callback && this.config.callback(a), this.util().emitEvent(a, this.wowEvent), this.util().addEvent(a, "animationend", this.resetAnimation), this.util().addEvent(a, "oanimationend", this.resetAnimation), this.util().addEvent(a, "webkitAnimationEnd", this.resetAnimation), this.util().addEvent(a, "MSAnimationEnd", this.resetAnimation), a }, e.prototype.applyStyle = function(a, b) {
var c, d, e;
return d = a.getAttribute("data-wow-duration"), c = a.getAttribute("data-wow-delay"), e = a.getAttribute("data-wow-iteration"), this.animate(function(f) {
return function() {
return f.customStyle(a, b, d, c, e) } }(this)) }, e.prototype.animate = function() {
return "requestAnimationFrame" in window ? function(a) {
return window.requestAnimationFrame(a) } : function(a) {
return a() } }(), e.prototype.resetStyle = function() {
var a, b, c, d, e;
for (d = this.boxes, e = [], b = 0, c = d.length; c > b; b++) a = d[b], e.push(a.style.visibility = "visible");
return e }, e.prototype.resetAnimation = function(a) {
var b;
return a.type.toLowerCase().indexOf("animationend") >= 0 ? (b = a.target || a.srcElement, b.className = b.className.replace(this.config.animateClass, "").trim()) : void 0 }, e.prototype.customStyle = function(a, b, c, d, e) {
return b && this.cacheAnimationName(a), a.style.visibility = b ? "hidden" : "visible", c && this.vendorSet(a.style, { animationDuration: c }), d && this.vendorSet(a.style, { animationDelay: d }), e && this.vendorSet(a.style, { animationIterationCount: e }), this.vendorSet(a.style, { animationName: b ? "none" : this.cachedAnimationName(a) }), a }, e.prototype.vendors = ["moz", "webkit"], e.prototype.vendorSet = function(a, b) {
var c, d, e, f;
d = [];
for (c in b) e = b[c], a["" + c] = e, d.push(function() {
var b, d, g, h;
for (g = this.vendors, h = [], b = 0, d = g.length; d > b; b++) f = g[b], h.push(a["" + f + c.charAt(0).toUpperCase() + c.substr(1)] = e);
return h }.call(this));
return d }, e.prototype.vendorCSS = function(a, b) {
var c, e, f, g, h, i;
for (h = d(a), g = h.getPropertyCSSValue(b), f = this.vendors, c = 0, e = f.length; e > c; c++) i = f[c], g = g || h.getPropertyCSSValue("-" + i + "-" + b);
return g }, e.prototype.animationName = function(a) {
var b;
try { b = this.vendorCSS(a, "animation-name").cssText } catch (c) { b = d(a).getPropertyValue("animation-name") }
return "none" === b ? "" : b }, e.prototype.cacheAnimationName = function(a) {
return this.animationNameCache.set(a, this.animationName(a)) }, e.prototype.cachedAnimationName = function(a) {
return this.animationNameCache.get(a) }, e.prototype.scrollHandler = function() {
return this.scrolled = !0 }, e.prototype.scrollCallback = function() {
var a;
return !this.scrolled || (this.scrolled = !1, this.boxes = function() {
var b, c, d, e;
for (d = this.boxes, e = [], b = 0, c = d.length; c > b; b++) a = d[b], a && (this.isVisible(a) ? this.show(a) : e.push(a));
return e }.call(this), this.boxes.length || this.config.live) ? void 0 : this.stop() }, e.prototype.offsetTop = function(a) {
for (var b; void 0 === a.offsetTop;) a = a.parentNode;
for (b = a.offsetTop; a = a.offsetParent;) b += a.offsetTop;
return b }, e.prototype.isVisible = function(a) {
var b, c, d, e, f;
return c = a.getAttribute("data-wow-offset") || this.config.offset, f = this.config.scrollContainer && this.config.scrollContainer.scrollTop || window.pageYOffset, e = f + Math.min(this.element.clientHeight, this.util().innerHeight()) - c, d = this.offsetTop(a), b = d + a.clientHeight, e >= d && b >= f }, e.prototype.util = function() {
return null != this._util ? this._util : this._util = new b }, e.prototype.disabled = function() {
return !this.config.mobile && this.util().isMobile(navigator.userAgent) }, e }() }).call(this); |
// Easy Responsive Tabs Plugin
// Author: Samson.Onna <Email : samson3d@gmail.com>
(function ($) {
$.fn.extend({
easyResponsiveTabs: function (options) {
//Set the default values, use comma to separate the settings, example:
var defaults = {
type: 'default', //default, vertical, accordion;
width: 'auto',
fit: true
}
//Variables
var options = $.extend(defaults, options);
var opt = options, jtype = opt.type, jfit = opt.fit, jwidth = opt.width, vtabs = 'vertical', accord = 'accordion';
//Main function
this.each(function () {
var $respTabs = $(this);
$respTabs.find('ul.resp-tabs-list li').addClass('resp-tab-item');
$respTabs.css({
'display': 'block',
'width': jwidth
});
$respTabs.find('.resp-tabs-container > div').addClass('resp-tab-content');
jtab_options();
//Properties Function
function jtab_options() {
if (jtype == vtabs) {
$respTabs.addClass('resp-vtabs');
}
if (jfit == true) {
$respTabs.css({ width: '100%', margin: '0px' });
}
if (jtype == accord) {
$respTabs.addClass('resp-easy-accordion');
$respTabs.find('.resp-tabs-list').css('display', 'none');
}
}
//Assigning the h2 markup to accordion title
var $tabItemh2;
$respTabs.find('.resp-tab-content').before("<h2 class='resp-accordion' role='tab'><span class='resp-arrow'></span></h2>");
var itemCount = 0;
$respTabs.find('.resp-accordion').each(function () {
$tabItemh2 = $(this);
var innertext = $respTabs.find('.resp-tab-item:eq(' + itemCount + ')').html();
$respTabs.find('.resp-accordion:eq(' + itemCount + ')').append(innertext);
$tabItemh2.attr('aria-controls', 'tab_item-' + (itemCount));
itemCount++;
});
//Assigning the 'aria-controls' to Tab items
var count = 0,
$tabContent;
$respTabs.find('.resp-tab-item').each(function () {
$tabItem = $(this);
$tabItem.attr('aria-controls', 'tab_item-' + (count));
$tabItem.attr('role', 'tab');
//First active tab
$respTabs.find('.resp-tab-item').first().addClass('resp-tab-active');
$respTabs.find('.resp-accordion').first().addClass('resp-tab-active');
$respTabs.find('.resp-tab-content').first().addClass('resp-tab-content-active').attr('style', 'display:block');
//Assigning the 'aria-labelledby' attr to tab-content
var tabcount = 0;
$respTabs.find('.resp-tab-content').each(function () {
$tabContent = $(this);
$tabContent.attr('aria-labelledby', 'tab_item-' + (tabcount));
tabcount++;
});
count++;
});
//Tab Click action function
$respTabs.find("[role=tab]").each(function () {
var $currentTab = $(this);
$currentTab.click(function () {
var $tabAria = $currentTab.attr('aria-controls');
if ($currentTab.hasClass('resp-accordion') && $currentTab.hasClass('resp-tab-active')) {
$respTabs.find('.resp-tab-content-active').slideUp('', function () { $(this).addClass('resp-accordion-closed'); });
$currentTab.removeClass('resp-tab-active');
return false;
}
if (!$currentTab.hasClass('resp-tab-active') && $currentTab.hasClass('resp-accordion')) {
$respTabs.find('.resp-tab-active').removeClass('resp-tab-active');
$respTabs.find('.resp-tab-content-active').slideUp().removeClass('resp-tab-content-active resp-accordion-closed');
$respTabs.find("[aria-controls=" + $tabAria + "]").addClass('resp-tab-active');
$respTabs.find('.resp-tab-content[aria-labelledby = ' + $tabAria + ']').slideDown().addClass('resp-tab-content-active');
} else {
$respTabs.find('.resp-tab-active').removeClass('resp-tab-active');
$respTabs.find('.resp-tab-content-active').removeAttr('style').removeClass('resp-tab-content-active').removeClass('resp-accordion-closed');
$respTabs.find("[aria-controls=" + $tabAria + "]").addClass('resp-tab-active');
$respTabs.find('.resp-tab-content[aria-labelledby = ' + $tabAria + ']').addClass('resp-tab-content-active').attr('style', 'display:block');
}
});
//Window resize function
$(window).resize(function () {
$respTabs.find('.resp-accordion-closed').removeAttr('style');
});
});
});
}
});
})(jQuery);
|
/*
* This file is part of the Kreta package.
*
* (c) Beñat Espiña <benatespina@gmail.com>
* (c) Gorka Laucirica <gorka.lauzirika@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
import {combineReducers} from 'redux';
import {routeReducer as routing} from 'react-router-redux';
import {reducer as form} from 'redux-form';
import currentOrganization from './reducers/CurrentOrganization';
import currentProject from './reducers/CurrentProject';
import dashboard from './reducers/Dashboard';
import mainMenu from './reducers/MainMenu';
import notification from './reducers/Notification';
import organization from './reducers/Organization';
import profile from './reducers/Profile';
import projects from './reducers/Projects';
import user from './reducers/User';
export default combineReducers({
currentOrganization,
currentProject,
dashboard,
mainMenu,
form,
notification,
organization,
profile,
projects,
user,
routing,
});
|
import PolicyBase from './policy_base'
export default class <%= policy_class_name %> extends PolicyBase {
constructor(user, record = null) {
super(user, record)
}
index() {
// return false
}
show() {
// return false
}
create() {
// return false
}
update() {
// return false
}
destroy() {
// return false
}
}
|
//>>built
define(["dojo/_base/declare","dojo/_base/lang","dojo/_base/connect","dojo/_base/fx","./AnalogIndicatorBase"],function(k,l,m,n,p){return k("dojox.gauges.AnalogArcIndicator",[p],{_createArc:function(e){if(this.shape){var d=this._gauge._mod360(this._gauge.startAngle),a=this._gauge._getRadians(this._gauge._getAngle(e)),b=this._gauge._getRadians(d);"cclockwise"==this._gauge.orientation&&(d=a,a=b,b=d);d=0;(b<=a?a-b:2*Math.PI+a-b)>Math.PI&&(d=1);var g=Math.cos(a),a=Math.sin(a),h=Math.cos(b),b=Math.sin(b),
f=this.offset+this.width,c=["M"];c.push(this._gauge.cx+this.offset*b);c.push(this._gauge.cy-this.offset*h);c.push("A",this.offset,this.offset,0,d,1);c.push(this._gauge.cx+this.offset*a);c.push(this._gauge.cy-this.offset*g);c.push("L");c.push(this._gauge.cx+f*a);c.push(this._gauge.cy-f*g);c.push("A",f,f,0,d,0);c.push(this._gauge.cx+f*b);c.push(this._gauge.cy-f*h);c.push("z");this.shape.setShape(c.join(" "));this.currentValue=e}},draw:function(e,d){var a=this.value;a<this._gauge.min&&(a=this._gauge.min);
a>this._gauge.max&&(a=this._gauge.max);if(this.shape)d?this._createArc(a):(e=new n.Animation({curve:[this.currentValue,a],duration:this.duration,easing:this.easing}),m.connect(e,"onAnimate",l.hitch(this,this._createArc)),e.play());else{d=this.color?this.color:"black";var b={color:this.strokeColor?this.strokeColor:d,width:1};this.color.type&&!this.strokeColor&&(b.color=this.color.colors[0].color);this.shape=e.createPath().setStroke(b).setFill(d);this._createArc(a);this.shape.connect("onmouseover",
this,this.handleMouseOver);this.shape.connect("onmouseout",this,this.handleMouseOut);this.shape.connect("onmousedown",this,this.handleMouseDown);this.shape.connect("touchstart",this,this.handleTouchStart)}}})}); |
var cluster = require('cluster');
exports.Runner = function (req, res) {
console.log('req.originalUrl :', req.originalUrl);
console.log('req.baseUrl :', req.baseUrl);
console.log('req.protocol :', req.protocol);
console.log('req.hostname :', req.hostname);
console.log('req.query :', req.query);
console.log('req.pathname :', req.pathname);
console.log('req.cookies :', req.cookies);
console.log('req.params :', req.params);
console.log('req.session :', req.session);
console.log('req.body :', req.body);
console.log('req.files :', req.files);
console.log('multipartResolver :', req.context.parentContext.multipartResolver);
res.cookie('MAS', 'zw0001', {maxAge: 20});
req.session.user = {name: 'wanglei2', r: Math.random()};
console.log('#################OVER');
res.ok();
}; |
describe("HelloKitty", function() {
var helloKitty
, goodPicture = "hk_good.gif"
, badPicture = "hk_bad.gif"
, deadPicture = "hk_dead.png";
beforeEach(function() {
helloKitty = new HelloKitty();
});
it("must have a Tamagocci as Prototype", function() {
// Then
expect(helloKitty instanceof Tamagocci).toBe(true);
});
it("must return a happy picture after birth", function() {
// Then
expect(helloKitty.getPicture()).toBe(goodPicture);
});
it("must return a bad picture when weight is less than 3 units over min weight", function() {
// When
helloKitty.weight = helloKitty.minWeight + 2;
// Then
expect(helloKitty.getPicture()).toBe(badPicture);
});
it("must return a bad picture when weight is more than 3 units under max weight", function() {
// When
helloKitty.weight = helloKitty.maxWeight - 2;
// Then
expect(helloKitty.getPicture()).toBe(badPicture);
});
it("must return a bad picture when happiness is less than 3", function() {
// When
helloKitty.happiness = 2;
// Then
expect(helloKitty.getPicture()).toBe(badPicture);
});
it("must return a dead picture when is dead", function() {
// When
helloKitty.isDead = true;
// Then
expect(helloKitty.getPicture()).toBe(deadPicture);
});
}); |
//>>built
define("dojo/_base/lang dojo/_base/declare dojo/_base/Color ../utils ../../RectangularGauge ../../LinearScaler ../../RectangularScale ../../RectangularValueIndicator ../../RectangularRangeIndicator ../../TextIndicator ../DefaultPropertiesMixin".split(" "),function(f,l,k,a,m,n,p,q,u,r,t){return l("dojox.dgauges.components.default.VerticalLinearGauge",[m,t],{borderColor:"#C9DFF2",fillColor:"#FCFCFF",indicatorColor:"#F01E28",constructor:function(){this.orientation="vertical";this.borderColor=new k(this.borderColor);
this.fillColor=new k(this.fillColor);this.indicatorColor=new k(this.indicatorColor);this.addElement("background",f.hitch(this,this.drawBackground));var a=new n,b=new p;b.set("scaler",a);b.set("labelPosition","leading");b.set("paddingBottom",20);b.set("paddingLeft",25);this.addElement("scale",b);a=new q;a.indicatorShapeFunc=f.hitch(this,function(a){return a.createPolyline([0,0,10,0,0,10,-10,0,0,0]).setStroke({color:"blue",width:.25}).setFill(this.indicatorColor)});a.set("paddingLeft",45);a.set("interactionArea",
"gauge");b.addIndicator("indicator",a);this.addElement("indicatorTextBorder",f.hitch(this,this.drawTextBorder),"leading");b=new r;b.set("indicator",a);b.set("x",22.5);b.set("y",30);this.addElement("indicatorText",b)},drawBackground:function(h,b,d){b=49;var c=0,g=3,e=a.createGradient([0,a.brightness(this.borderColor,-20),.1,a.brightness(this.borderColor,-40)]);h.createRect({x:0,y:0,width:b,height:d,r:g}).setFill(f.mixin({type:"linear",x1:0,y1:0,x2:b,y2:d},e)).setStroke({color:"#A5A5A5",width:.2});
e=a.createGradient([0,a.brightness(this.borderColor,70),1,a.brightness(this.borderColor,-50)]);c=4;h.createRect({x:c,y:c,width:b-2*c,height:d-2*c,r:2}).setFill(f.mixin({type:"linear",x1:0,y1:0,x2:b,y2:d},e));c=6;g=1;e=a.createGradient([0,a.brightness(this.borderColor,60),1,a.brightness(this.borderColor,-40)]);h.createRect({x:c,y:c,width:b-2*c,height:d-2*c,r:g}).setFill(f.mixin({type:"linear",x1:0,y1:0,x2:b,y2:d},e));c=7;g=0;e=a.createGradient([0,a.brightness(this.borderColor,70),1,a.brightness(this.borderColor,
-40)]);h.createRect({x:c,y:c,width:b-2*c,height:d-2*c,r:g}).setFill(f.mixin({type:"linear",x1:b,y1:0,x2:0,y2:d},e));c=5;g=0;e=a.createGradient([0,[255,255,255,220],.8,a.brightness(this.fillColor,-5),1,a.brightness(this.fillColor,-30)]);h.createRect({x:c,y:c,width:b-2*c,height:d-2*c,r:g}).setFill(f.mixin({type:"radial",cx:0,cy:d/2,r:d},e)).setStroke({color:a.brightness(this.fillColor,-40),width:.4})},drawTextBorder:function(a){return a.createRect({x:5,y:5,width:40,height:40}).setStroke({color:"#CECECE",
width:1})}})}); |
var SP_NOACTION = 0;
var SP_RESIZETOFIT = 1;
var SP_CUSTOMACTION = 2;
var SP_HISTORY_STATE = 'Apply save preset';
var SP_SETTINGS_PATH = new File(app.preferencesFolder + '/Save%20Panel/').fsName + '/';
function spActionToString(action)
{
if (SP_NOACTION == action)
return 'Nothing';
else if (SP_RESIZETOFIT == action)
return 'Resize to fit';
else if (SP_CUSTOMACTION == action)
return 'Custom action';
return false;
}
|
/**
* @file Visual mapping.
*/
define(function (require) {
var zrUtil = require('zrender/core/util');
var zrColor = require('zrender/tool/color');
var linearMap = require('../util/number').linearMap;
var each = zrUtil.each;
var isObject = zrUtil.isObject;
var CATEGORY_DEFAULT_VISUAL_INDEX = -1;
/**
* @param {Object} option
* @param {string} [option.type] See visualHandlers.
* @param {string} [option.mappingMethod] 'linear' or 'piecewise' or 'category' or 'fixed'
* @param {Array.<number>=} [option.dataExtent] [minExtent, maxExtent],
* required when mappingMethod is 'linear'
* @param {Array.<Object>=} [option.pieceList] [
* {value: someValue},
* {interval: [min1, max1], visual: {...}},
* {interval: [min2, max2]}
* ],
* required when mappingMethod is 'piecewise'.
* Visual for only each piece can be specified.
* @param {Array.<string|Object>=} [option.categories] ['cate1', 'cate2']
* required when mappingMethod is 'category'.
* If no option.categories, categories is set
* as [0, 1, 2, ...].
* @param {boolean} [option.loop=false] Whether loop mapping when mappingMethod is 'category'.
* @param {(Array|Object|*)} [option.visual] Visual data.
* when mappingMethod is 'category',
* visual data can be array or object
* (like: {cate1: '#222', none: '#fff'})
* or primary types (which represents
* defualt category visual), otherwise visual
* can be array or primary (which will be
* normalized to array).
*
*/
var VisualMapping = function (option) {
var mappingMethod = option.mappingMethod;
var visualType = option.type;
/**
* @readOnly
* @type {Object}
*/
var thisOption = this.option = zrUtil.clone(option);
/**
* @readOnly
* @type {string}
*/
this.type = visualType;
/**
* @readOnly
* @type {string}
*/
this.mappingMethod = mappingMethod;
/**
* @private
* @type {Function}
*/
this._normalizeData = normalizers[mappingMethod];
var visualHandler = visualHandlers[visualType];
/**
* @public
* @type {Function}
*/
this.applyVisual = visualHandler.applyVisual;
/**
* @public
* @type {Function}
*/
this.getColorMapper = visualHandler.getColorMapper;
/**
* @private
* @type {Function}
*/
this._doMap = visualHandler._doMap[mappingMethod];
if (mappingMethod === 'piecewise') {
normalizeVisualRange(thisOption);
preprocessForPiecewise(thisOption);
}
else if (mappingMethod === 'category') {
thisOption.categories
? preprocessForSpecifiedCategory(thisOption)
// categories is ordinal when thisOption.categories not specified,
// which need no more preprocess except normalize visual.
: normalizeVisualRange(thisOption, true);
}
else { // mappingMethod === 'linear' or 'fixed'
zrUtil.assert(mappingMethod !== 'linear' || thisOption.dataExtent);
normalizeVisualRange(thisOption);
}
};
VisualMapping.prototype = {
constructor: VisualMapping,
mapValueToVisual: function (value) {
var normalized = this._normalizeData(value);
return this._doMap(normalized, value);
},
getNormalizer: function () {
return zrUtil.bind(this._normalizeData, this);
}
};
var visualHandlers = VisualMapping.visualHandlers = {
color: {
applyVisual: makeApplyVisual('color'),
/**
* Create a mapper function
* @return {Function}
*/
getColorMapper: function () {
var thisOption = this.option;
return zrUtil.bind(
thisOption.mappingMethod === 'category'
? function (value, isNormalized) {
!isNormalized && (value = this._normalizeData(value));
return doMapCategory.call(this, value);
}
: function (value, isNormalized, out) {
// If output rgb array
// which will be much faster and useful in pixel manipulation
var returnRGBArray = !!out;
!isNormalized && (value = this._normalizeData(value));
out = zrColor.fastMapToColor(value, thisOption.parsedVisual, out);
return returnRGBArray ? out : zrColor.stringify(out, 'rgba');
},
this
);
},
_doMap: {
linear: function (normalized) {
return zrColor.stringify(
zrColor.fastMapToColor(normalized, this.option.parsedVisual),
'rgba'
);
},
category: doMapCategory,
piecewise: function (normalized, value) {
var result = getSpecifiedVisual.call(this, value);
if (result == null) {
result = zrColor.stringify(
zrColor.fastMapToColor(normalized, this.option.parsedVisual),
'rgba'
);
}
return result;
},
fixed: doMapFixed
}
},
colorHue: makePartialColorVisualHandler(function (color, value) {
return zrColor.modifyHSL(color, value);
}),
colorSaturation: makePartialColorVisualHandler(function (color, value) {
return zrColor.modifyHSL(color, null, value);
}),
colorLightness: makePartialColorVisualHandler(function (color, value) {
return zrColor.modifyHSL(color, null, null, value);
}),
colorAlpha: makePartialColorVisualHandler(function (color, value) {
return zrColor.modifyAlpha(color, value);
}),
opacity: {
applyVisual: makeApplyVisual('opacity'),
_doMap: makeDoMap([0, 1])
},
symbol: {
applyVisual: function (value, getter, setter) {
var symbolCfg = this.mapValueToVisual(value);
if (zrUtil.isString(symbolCfg)) {
setter('symbol', symbolCfg);
}
else if (isObject(symbolCfg)) {
for (var name in symbolCfg) {
if (symbolCfg.hasOwnProperty(name)) {
setter(name, symbolCfg[name]);
}
}
}
},
_doMap: {
linear: doMapToArray,
category: doMapCategory,
piecewise: function (normalized, value) {
var result = getSpecifiedVisual.call(this, value);
if (result == null) {
result = doMapToArray.call(this, normalized);
}
return result;
},
fixed: doMapFixed
}
},
symbolSize: {
applyVisual: makeApplyVisual('symbolSize'),
_doMap: makeDoMap([0, 1])
}
};
function preprocessForPiecewise(thisOption) {
var pieceList = thisOption.pieceList;
thisOption.hasSpecialVisual = false;
zrUtil.each(pieceList, function (piece, index) {
piece.originIndex = index;
// piece.visual is "result visual value" but not
// a visual range, so it does not need to be normalized.
if (piece.visual != null) {
thisOption.hasSpecialVisual = true;
}
});
}
function preprocessForSpecifiedCategory(thisOption) {
// Hash categories.
var categories = thisOption.categories;
var visual = thisOption.visual;
var categoryMap = thisOption.categoryMap = {};
each(categories, function (cate, index) {
categoryMap[cate] = index;
});
// Process visual map input.
if (!zrUtil.isArray(visual)) {
var visualArr = [];
if (zrUtil.isObject(visual)) {
each(visual, function (v, cate) {
var index = categoryMap[cate];
visualArr[index != null ? index : CATEGORY_DEFAULT_VISUAL_INDEX] = v;
});
}
else { // Is primary type, represents default visual.
visualArr[CATEGORY_DEFAULT_VISUAL_INDEX] = visual;
}
visual = setVisualToOption(thisOption, visualArr);
}
// Remove categories that has no visual,
// then we can mapping them to CATEGORY_DEFAULT_VISUAL_INDEX.
for (var i = categories.length - 1; i >= 0; i--) {
if (visual[i] == null) {
delete categoryMap[categories[i]];
categories.pop();
}
}
}
function normalizeVisualRange(thisOption, isCategory) {
var visual = thisOption.visual;
var visualArr = [];
if (zrUtil.isObject(visual)) {
each(visual, function (v) {
visualArr.push(v);
});
}
else if (visual != null) {
visualArr.push(visual);
}
var doNotNeedPair = {color: 1, symbol: 1};
if (!isCategory
&& visualArr.length === 1
&& !doNotNeedPair.hasOwnProperty(thisOption.type)
) {
// Do not care visualArr.length === 0, which is illegal.
visualArr[1] = visualArr[0];
}
setVisualToOption(thisOption, visualArr);
}
function makePartialColorVisualHandler(applyValue) {
return {
applyVisual: function (value, getter, setter) {
value = this.mapValueToVisual(value);
// Must not be array value
setter('color', applyValue(getter('color'), value));
},
_doMap: makeDoMap([0, 1])
};
}
function doMapToArray(normalized) {
var visual = this.option.visual;
return visual[
Math.round(linearMap(normalized, [0, 1], [0, visual.length - 1], true))
] || {};
}
function makeApplyVisual(visualType) {
return function (value, getter, setter) {
setter(visualType, this.mapValueToVisual(value));
};
}
function doMapCategory(normalized) {
var visual = this.option.visual;
return visual[
(this.option.loop && normalized !== CATEGORY_DEFAULT_VISUAL_INDEX)
? normalized % visual.length
: normalized
];
}
function doMapFixed() {
return this.option.visual[0];
}
function makeDoMap(sourceExtent) {
return {
linear: function (normalized) {
return linearMap(normalized, sourceExtent, this.option.visual, true);
},
category: doMapCategory,
piecewise: function (normalized, value) {
var result = getSpecifiedVisual.call(this, value);
if (result == null) {
result = linearMap(normalized, sourceExtent, this.option.visual, true);
}
return result;
},
fixed: doMapFixed
};
}
function getSpecifiedVisual(value) {
var thisOption = this.option;
var pieceList = thisOption.pieceList;
if (thisOption.hasSpecialVisual) {
var pieceIndex = VisualMapping.findPieceIndex(value, pieceList);
var piece = pieceList[pieceIndex];
if (piece && piece.visual) {
return piece.visual[this.type];
}
}
}
function setVisualToOption(thisOption, visualArr) {
thisOption.visual = visualArr;
if (thisOption.type === 'color') {
thisOption.parsedVisual = zrUtil.map(visualArr, function (item) {
return zrColor.parse(item);
});
}
return visualArr;
}
/**
* Normalizers by mapping methods.
*/
var normalizers = {
linear: function (value) {
return linearMap(value, this.option.dataExtent, [0, 1], true);
},
piecewise: function (value) {
var pieceList = this.option.pieceList;
var pieceIndex = VisualMapping.findPieceIndex(value, pieceList, true);
if (pieceIndex != null) {
return linearMap(pieceIndex, [0, pieceList.length - 1], [0, 1], true);
}
},
category: function (value) {
var index = this.option.categories
? this.option.categoryMap[value]
: value; // ordinal
return index == null ? CATEGORY_DEFAULT_VISUAL_INDEX : index;
},
fixed: zrUtil.noop
};
/**
* List available visual types.
*
* @public
* @return {Array.<string>}
*/
VisualMapping.listVisualTypes = function () {
var visualTypes = [];
zrUtil.each(visualHandlers, function (handler, key) {
visualTypes.push(key);
});
return visualTypes;
};
/**
* @public
*/
VisualMapping.addVisualHandler = function (name, handler) {
visualHandlers[name] = handler;
};
/**
* @public
*/
VisualMapping.isValidType = function (visualType) {
return visualHandlers.hasOwnProperty(visualType);
};
/**
* Convinent method.
* Visual can be Object or Array or primary type.
*
* @public
*/
VisualMapping.eachVisual = function (visual, callback, context) {
if (zrUtil.isObject(visual)) {
zrUtil.each(visual, callback, context);
}
else {
callback.call(context, visual);
}
};
VisualMapping.mapVisual = function (visual, callback, context) {
var isPrimary;
var newVisual = zrUtil.isArray(visual)
? []
: zrUtil.isObject(visual)
? {}
: (isPrimary = true, null);
VisualMapping.eachVisual(visual, function (v, key) {
var newVal = callback.call(context, v, key);
isPrimary ? (newVisual = newVal) : (newVisual[key] = newVal);
});
return newVisual;
};
/**
* @public
* @param {Object} obj
* @return {Object} new object containers visual values.
* If no visuals, return null.
*/
VisualMapping.retrieveVisuals = function (obj) {
var ret = {};
var hasVisual;
obj && each(visualHandlers, function (h, visualType) {
if (obj.hasOwnProperty(visualType)) {
ret[visualType] = obj[visualType];
hasVisual = true;
}
});
return hasVisual ? ret : null;
};
/**
* Give order to visual types, considering colorSaturation, colorAlpha depends on color.
*
* @public
* @param {(Object|Array)} visualTypes If Object, like: {color: ..., colorSaturation: ...}
* IF Array, like: ['color', 'symbol', 'colorSaturation']
* @return {Array.<string>} Sorted visual types.
*/
VisualMapping.prepareVisualTypes = function (visualTypes) {
if (isObject(visualTypes)) {
var types = [];
each(visualTypes, function (item, type) {
types.push(type);
});
visualTypes = types;
}
else if (zrUtil.isArray(visualTypes)) {
visualTypes = visualTypes.slice();
}
else {
return [];
}
visualTypes.sort(function (type1, type2) {
// color should be front of colorSaturation, colorAlpha, ...
// symbol and symbolSize do not matter.
return (type2 === 'color' && type1 !== 'color' && type1.indexOf('color') === 0)
? 1 : -1;
});
return visualTypes;
};
/**
* 'color', 'colorSaturation', 'colorAlpha', ... are depends on 'color'.
* Other visuals are only depends on themself.
*
* @public
* @param {string} visualType1
* @param {string} visualType2
* @return {boolean}
*/
VisualMapping.dependsOn = function (visualType1, visualType2) {
return visualType2 === 'color'
? !!(visualType1 && visualType1.indexOf(visualType2) === 0)
: visualType1 === visualType2;
};
/**
* @param {number} value
* @param {Array.<Object>} pieceList [{value: ..., interval: [min, max]}, ...]
* Always from small to big.
* @param {boolean} [findClosestWhenOutside=false]
* @return {number} index
*/
VisualMapping.findPieceIndex = function (value, pieceList, findClosestWhenOutside) {
var possibleI;
var abs = Infinity;
// value has the higher priority.
for (var i = 0, len = pieceList.length; i < len; i++) {
var pieceValue = pieceList[i].value;
if (pieceValue != null) {
if (pieceValue === value
// FIXME
// It is supposed to compare value according to value type of dimension,
// but currently value type can exactly be string or number.
// Compromise for numeric-like string (like '12'), especially
// in the case that visualMap.categories is ['22', '33'].
|| (typeof pieceValue === 'string' && pieceValue === value + '')
) {
return i;
}
findClosestWhenOutside && updatePossible(pieceValue, i);
}
}
for (var i = 0, len = pieceList.length; i < len; i++) {
var piece = pieceList[i];
var interval = piece.interval;
var close = piece.close;
if (interval) {
if (interval[0] === -Infinity) {
if (littleThan(close[1], value, interval[1])) {
return i;
}
}
else if (interval[1] === Infinity) {
if (littleThan(close[0], interval[0], value)) {
return i;
}
}
else if (
littleThan(close[0], interval[0], value)
&& littleThan(close[1], value, interval[1])
) {
return i;
}
findClosestWhenOutside && updatePossible(interval[0], i);
findClosestWhenOutside && updatePossible(interval[1], i);
}
}
if (findClosestWhenOutside) {
return value === Infinity
? pieceList.length - 1
: value === -Infinity
? 0
: possibleI;
}
function updatePossible(val, index) {
var newAbs = Math.abs(val - value);
if (newAbs < abs) {
abs = newAbs;
possibleI = index;
}
}
};
function littleThan(close, a, b) {
return close ? a <= b : a < b;
}
return VisualMapping;
}); |
'use strict';
// Use Applicaion configuration module to register a new module
ApplicationConfiguration.registerModule('blogs'); |
import { useMemo, useCallback } from "react";
import isString from "lodash/isString";
import queryString from "query-string";
import { useHistory } from "react-router-dom";
import useQueryParams from "../useQueryParams";
export function useParsedTags() {
const queryParams = useQueryParams();
const tags = useMemo(() => toArray(queryParams.tag), [queryParams.tag]);
const excludedTags = useMemo(() => toArray(queryParams.excludedTag), [queryParams.excludedTag]);
return useMemo(() => {
return {
tags,
excludedTags
};
}, [tags, excludedTags]);
}
export function useNavigateToTags() {
const history = useHistory();
return useCallback(
({ tags, excludedTags }) => {
history.push({
search: queryString.stringify({
tag: tags,
excludedTag: excludedTags
})
});
},
[history]
);
}
function toArray(value) {
if (!value) {
return [];
}
if (isString(value)) {
return [value];
}
return value;
}
|
var path = require('path');
var fs = require('fs');
var paths = {};
// BACKSTOP MODULE PATH
paths.backstop = path.join(__dirname, '../..');
// BACKSTOP CONFIG PATH
paths.backstopConfigFileName = path.join(paths.backstop, '../..', 'backstop.json');
// BITMAPS PATHS -- note: this path is overwritten if config files exist. see below.
paths.bitmaps_reference = paths.backstop + '/bitmaps_reference';
paths.bitmaps_test = paths.backstop + '/bitmaps_test';
// COMPARE PATHS -- note: compareConfigFileName is overwritten if config files exist. see below.
paths.comparePath = paths.backstop + '/compare';
paths.compareConfigFileName = paths.comparePath+'/config.json';
paths.compareReportURL = 'http://localhost:3001/compare/';
// CAPTURE CONFIG PATHS
paths.captureConfigFileName = paths.backstop + '/capture/config.json';
paths.captureConfigFileNameCache = paths.backstop + '/capture/.config.json.cache';
paths.captureConfigFileNameDefault = paths.backstop + '/capture/config.default.json';
// SERVER PID PATH
paths.serverPidFile = paths.backstop + '/server.pid';
// ACTIVE CAPTURE CONFIG PATH
paths.activeCaptureConfigPath = '';
if(!fs.existsSync(paths.backstopConfigFileName)){
console.log('\nCould not find a valid config file.');
console.log('\nTo run your own tests create a config here...\n ==> '+paths.backstopConfigFileName);
console.log('\nRun `$ gulp genConfig` to generate a config template file in this location.\n')
paths.activeCaptureConfigPath = paths.captureConfigFileNameDefault;
}else{
// console.log('\nBackstopJS Config loaded.\n')
paths.activeCaptureConfigPath = paths.backstopConfigFileName;
}
// overwrite default filepaths if config files exist
if(fs.existsSync(paths.activeCaptureConfigPath)){
var configJSON = fs.readFileSync(paths.activeCaptureConfigPath, "utf8");
var config = JSON.parse(configJSON);
if (config.paths) {
paths.bitmaps_reference = config.paths.bitmaps_reference || paths.bitmaps_reference;
paths.bitmaps_test = config.paths.bitmaps_test || paths.bitmaps_test;
paths.compareConfigFileName = config.paths.compare_data || paths.compareConfigFileName;
}
paths.engine = config.engine || null;
}
module.exports = paths;
|
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var angular2_1 = require('angular2/angular2');
var Panel = require('./Panel');
var AnchorModeField = require('../field/AnchorModeField');
var tpl = require('./transform-panel.html');
var TransformPanel = (function () {
function TransformPanel() {
}
TransformPanel = __decorate([
angular2_1.Component({
selector: 'transform-panel',
properties: ['objdata']
}),
angular2_1.View({
template: tpl,
styles: [],
directives: [AnchorModeField, Panel, angular2_1.coreDirectives, angular2_1.formDirectives]
}),
__metadata('design:paramtypes', [])
], TransformPanel);
return TransformPanel;
})();
module.exports = TransformPanel;
//# sourceMappingURL=TransformPanel.js.map |
var assert = require('./assert');
var isTypeName = require('./isTypeName');
var String = require('./String');
var Function = require('./Function');
var isBoolean = require('./isBoolean');
var isObject = require('./isObject');
var isNil = require('./isNil');
var create = require('./create');
var getTypeName = require('./getTypeName');
var dict = require('./dict');
var getDefaultInterfaceName = require('./getDefaultInterfaceName');
var isIdentity = require('./isIdentity');
var is = require('./is');
var extend = require('./extend');
function extendInterface(mixins, name) {
return extend(inter, mixins, name);
}
function getOptions(options) {
if (!isObject(options)) {
options = isNil(options) ? {} : { name: options };
}
if (!options.hasOwnProperty('strict')) {
options.strict = inter.strict;
}
return options;
}
function inter(props, options) {
options = getOptions(options);
var name = options.name;
var strict = options.strict;
if (process.env.NODE_ENV !== 'production') {
assert(dict(String, Function).is(props), function () { return 'Invalid argument props ' + assert.stringify(props) + ' supplied to interface(props, [options]) combinator (expected a dictionary String -> Type)'; });
assert(isTypeName(name), function () { return 'Invalid argument name ' + assert.stringify(name) + ' supplied to interface(props, [options]) combinator (expected a string)'; });
assert(isBoolean(strict), function () { return 'Invalid argument strict ' + assert.stringify(strict) + ' supplied to struct(props, [options]) combinator (expected a boolean)'; });
}
var displayName = name || getDefaultInterfaceName(props);
var identity = Object.keys(props).map(function (prop) { return props[prop]; }).every(isIdentity);
function Interface(value, path) {
if (process.env.NODE_ENV === 'production') {
if (identity) {
return value; // just trust the input if elements must not be hydrated
}
}
if (process.env.NODE_ENV !== 'production') {
path = path || [displayName];
assert(!isNil(value), function () { return 'Invalid value ' + value + ' supplied to ' + path.join('/'); });
// strictness
if (strict) {
for (var k in value) {
assert(props.hasOwnProperty(k), function () { return 'Invalid additional prop "' + k + '" supplied to ' + path.join('/'); });
}
}
}
var idempotent = true;
var ret = {};
for (var prop in props) {
var expected = props[prop];
var actual = value[prop];
var instance = create(expected, actual, ( process.env.NODE_ENV !== 'production' ? path.concat(prop + ': ' + getTypeName(expected)) : null ));
idempotent = idempotent && ( actual === instance );
ret[prop] = instance;
}
if (idempotent) { // implements idempotency
ret = value;
}
if (process.env.NODE_ENV !== 'production') {
Object.freeze(ret);
}
return ret;
}
Interface.meta = {
kind: 'interface',
props: props,
name: name,
identity: identity,
strict: strict
};
Interface.displayName = displayName;
Interface.is = function (x) {
if (strict) {
for (var k in x) {
if (!props.hasOwnProperty(k)) {
return false;
}
}
}
for (var prop in props) {
if (!is(x[prop], props[prop])) {
return false;
}
}
return true;
};
Interface.update = function (instance, patch) {
return Interface(assert.update(instance, patch));
};
Interface.extend = function (xs, name) {
return extendInterface([Interface].concat(xs), name);
};
return Interface;
}
inter.strict = false;
inter.getOptions = getOptions;
inter.getDefaultName = getDefaultInterfaceName;
inter.extend = extendInterface;
module.exports = inter;
|
import React from 'react'
import { shallow } from 'enzyme'
import Icon from '../Icon'
it('renders without crashing', () => {
shallow(<Icon />)
})
|
import createSvgIcon from './utils/createSvgIcon';
import { jsx as _jsx } from "react/jsx-runtime";
export default createSvgIcon( /*#__PURE__*/_jsx("path", {
d: "m7 14 5-5 5 5z"
}), 'ArrowDropUp'); |
import { getFormJobs } from "./PlanConfigurer";
import path from "path";
const configSchema = {
type: "object",
schemas: {
configFile: {
type: "file",
label: "configfile",
default: "",
tester: (packagePath, dirname) =>
path.basename(packagePath).indexOf("jest.config") !== -1 ||
path.basename(packagePath).indexOf(".jest.") !== -1 ||
path.basename(packagePath) === "package.json",
},
modifiedOnly: {
type: "boolean",
label: "only modified files (must be in a Git repo)",
default: false,
},
watch: {
type: "boolean",
label: "Watch mode",
default: true,
},
binary: {
type: "conditional",
expression: {
type: "enum",
enum: [
{ value: "local", description: "local" },
{ value: "global", description: "global" },
],
},
cases: {
local: null,
global: {
type: "object",
schemas: {
a: {
type: "string",
},
},
},
},
},
environmentVariables: {
type: "array",
title: "Environment Variables",
items: {
type: "string",
title: "Variable",
placeholder: "NAME=value",
},
},
},
};
describe("PlanConfigurer", () => {
describe("getFormJobs", () => {
it("converts to jobs", () => {
const subject = getFormJobs({}, { config: configSchema });
expect(subject).toMatchSnapshot();
});
it("converts to jobs taking value in account", () => {
const subject = getFormJobs(
{
environmentVariables: { 0: "HAHA=HEHE", 1: "BABA=BEBE" },
binary: { expressionValue: "global", caseValue: "" },
},
{ config: configSchema },
);
expect(subject).toMatchSnapshot();
});
});
});
|
var chai = require('chai');
var assert = chai.assert;
var expect = chai.expect;
var should = chai.should;
var path = require('path');
var url = require('url');
var rewire = require("rewire");
var handler = rewire('../lib/handler');
var request = require('supertest');
var express = require('express');
var bodyParser = require('body-parser');
app = express();
describe('handler.js', function () {
var getFilenames = handler.__get__('getFilenames');
var findExists = handler.__get__('findExists');
describe('.getFilenames()', function () {
it('should return 0 results when req.path = /mock || /mock/', function () {
var reqPath = '/mock';
var r = [];
var files = getFilenames(reqPath, reqPath);
assert.deepEqual(r, files);
files = getFilenames(reqPath + '/', reqPath);
assert.deepEqual(r, files);
});
it('should return 2 results when req.path = /mock/a', function () {
var reqPath = '/mock/a';
var r = ['a', 'id'];
var files = getFilenames(reqPath, '/mock');
assert.deepEqual(r, files);
reqPath += '/';
files = getFilenames(reqPath, '/mock');
assert.deepEqual(r, files);
});
it('should return 3 results when req.path = /mock/a/b', function () {
var reqPath = '/mock/a/b';
var r = ['a-b', 'id-b', 'a-id', 'id-id'];
var files = getFilenames(reqPath, '/mock');
assert.deepEqual(r, files);
});
});
describe('.findExists()', function () {
it('should return null when req.path = /mock/a/b and no a-b.js, id-a.js, a-id.js file', function () {
var reqPath = '/mock/a/b';
var files = getFilenames(reqPath, '/mock');
var existsFilename = findExists(files, path.join(process.cwd(), 'test'));
assert.isUndefined(existsFilename);
});
it('should return c when req.path = /mock/c and has c.js', function () {
var reqPath = '/mock/c';
var files = getFilenames(reqPath, '/mock');
var existsFilename = findExists(files, path.join(process.cwd(), 'test'));
assert.equal('c', existsFilename);
});
});
var aget = function (_path) {
var base = '/mock/';
app.get(url.resolve(base, _path), function (req, res) {
handler.on(req, res, path.join(process.cwd(), 'test'), base);
});
}
describe('.on()', function () {
aget('/*');
it('should response with json when request /mock/c', function (done) {
request(app)
.get('/mock/c')
.expect('Content-Type', /json/)
.expect(200, done);
});
it('should response with json when request /mock/{id}', function (done) {
request(app)
.get('/mock/1234')
.expect('Content-Type', /text\/html/)
.expect(200, done);
});
it('should response with 404 when request /mock/a', function (done) {
request(app)
.get('/mock/a')
.expect('Content-Type', /text\/html/)
.expect(200, done);
});
it('should response with json when request /mock/p/q', function (done) {
request(app)
.get('/mock/p/q')
.expect('Content-Type', /json/)
.expect(200, done);
});
it('should response with json when request /mock/p/{id}', function (done) {
request(app)
.get('/mock/p/1234')
.expect('Content-Type', /json/)
.expect(200, done);
});
it('should response with json when request /mock/{id}/q', function (done) {
request(app)
.get('/mock/1234/q')
.expect('Content-Type', /text\/html/)
.expect(200, done);
});
});
});
|
secrets = require("./secrets");
module.exports = {
mixpanel: (function() {
return require('mixpanel').init(secrets.MIXPANEL.TOKEN);
})()
}; |
/**
* Color manipulation functions below are adapted from
* https://github.com/d3/d3-color.
*/
var Xn = 0.950470;
var Yn = 1;
var Zn = 1.088830;
var t0 = 4 / 29;
var t1 = 6 / 29;
var t2 = 3 * t1 * t1;
var t3 = t1 * t1 * t1;
var twoPi = 2 * Math.PI;
/**
* Convert an RGB pixel into an HCL pixel.
* @param {ol.raster.Pixel} pixel A pixel in RGB space.
* @return {ol.raster.Pixel} A pixel in HCL space.
*/
function rgb2hcl(pixel) {
var red = rgb2xyz(pixel[0]);
var green = rgb2xyz(pixel[1]);
var blue = rgb2xyz(pixel[2]);
var x = xyz2lab(
(0.4124564 * red + 0.3575761 * green + 0.1804375 * blue) / Xn);
var y = xyz2lab(
(0.2126729 * red + 0.7151522 * green + 0.0721750 * blue) / Yn);
var z = xyz2lab(
(0.0193339 * red + 0.1191920 * green + 0.9503041 * blue) / Zn);
var l = 116 * y - 16;
var a = 500 * (x - y);
var b = 200 * (y - z);
var c = Math.sqrt(a * a + b * b);
var h = Math.atan2(b, a);
if (h < 0) {
h += twoPi;
}
pixel[0] = h;
pixel[1] = c;
pixel[2] = l;
return pixel;
}
/**
* Convert an HCL pixel into an RGB pixel.
* @param {ol.raster.Pixel} pixel A pixel in HCL space.
* @return {ol.raster.Pixel} A pixel in RGB space.
*/
function hcl2rgb(pixel) {
var h = pixel[0];
var c = pixel[1];
var l = pixel[2];
var a = Math.cos(h) * c;
var b = Math.sin(h) * c;
var y = (l + 16) / 116;
var x = isNaN(a) ? y : y + a / 500;
var z = isNaN(b) ? y : y - b / 200;
y = Yn * lab2xyz(y);
x = Xn * lab2xyz(x);
z = Zn * lab2xyz(z);
pixel[0] = xyz2rgb(3.2404542 * x - 1.5371385 * y - 0.4985314 * z);
pixel[1] = xyz2rgb(-0.9692660 * x + 1.8760108 * y + 0.0415560 * z);
pixel[2] = xyz2rgb(0.0556434 * x - 0.2040259 * y + 1.0572252 * z);
return pixel;
}
function xyz2lab(t) {
return t > t3 ? Math.pow(t, 1 / 3) : t / t2 + t0;
}
function lab2xyz(t) {
return t > t1 ? t * t * t : t2 * (t - t0);
}
function rgb2xyz(x) {
return (x /= 255) <= 0.04045 ? x / 12.92 : Math.pow((x + 0.055) / 1.055, 2.4);
}
function xyz2rgb(x) {
return 255 * (x <= 0.0031308 ?
12.92 * x : 1.055 * Math.pow(x, 1 / 2.4) - 0.055);
}
var raster = new ol.source.Raster({
sources: [new ol.source.Stamen({
layer: 'watercolor'
})],
operation: function(pixels, data) {
var hcl = rgb2hcl(pixels[0]);
var h = hcl[0] + Math.PI * data.hue / 180;
if (h < 0) {
h += twoPi;
} else if (h > twoPi) {
h -= twoPi;
}
hcl[0] = h;
hcl[1] *= (data.chroma / 100);
hcl[2] *= (data.lightness / 100);
return hcl2rgb(hcl);
},
lib: {
rgb2hcl: rgb2hcl,
hcl2rgb: hcl2rgb,
rgb2xyz: rgb2xyz,
lab2xyz: lab2xyz,
xyz2lab: xyz2lab,
xyz2rgb: xyz2rgb,
Xn: Xn,
Yn: Yn,
Zn: Zn,
t0: t0,
t1: t1,
t2: t2,
t3: t3,
twoPi: twoPi
}
});
var controls = {};
raster.on('beforeoperations', function(event) {
var data = event.data;
for (var id in controls) {
data[id] = Number(controls[id].value);
}
});
var map = new ol.Map({
layers: [
new ol.layer.Image({
source: raster
})
],
target: 'map',
view: new ol.View({
center: [0, 2500000],
zoom: 2,
maxZoom: 18
})
});
var controlIds = ['hue', 'chroma', 'lightness'];
controlIds.forEach(function(id) {
var control = document.getElementById(id);
var output = document.getElementById(id + 'Out');
control.addEventListener('input', function() {
output.innerText = control.value;
raster.changed();
});
output.innerText = control.value;
controls[id] = control;
});
|
const util = require('util');
module.exports = function (req, res, utils) {
var deferred = Promise.defer();
utils.request({
url: 'open/get_posts_by_category',
method: 'POST',
qs: {
siteId: req.site.id,
categoryId: 'susdanwmf4pckzxn7w24jw',
pageSize: 5
}
}, function (result) {
var data = {
category: {},
list: [],
first: undefined
};
if (result.code != 200) {
deferred.resolve(data);
return;
};
result.body = JSON.parse(result.body);
data.category = { href: util.format('category?id=%s', result.body.category.id) };
result.body.data.forEach(function (e) {
//设置第一个显示的新闻
if (!data.first) {
e.text ? e.text : (e.text = e.title);
e.image_url ? (e.image_url = util.format('%s&width=120&height=75', e.image_url)) : '';
data.first = {
image: e.image_url,
title: utils.subString(e.title, 13),
text: (e.image_url ? utils.subString(e.text, 27) : utils.subString(e.text, 50)),
href: util.format('detail?id=%s', e.id)
};
return false;
}
data.list.push({
ori_title: e.title,
title: utils.subString(e.title, 25),
date: e.date_published,
href: util.format('detail?id=%s', e.id)
});
}, this);
deferred.resolve({ data: data });
},deferred);
return deferred.promise;
} |
angular.module('services.CurrentAppService', [])
.service('CurrentAppService', ['$log', 'config', '$q', '$http', 'AppService',
function ($log, config, $q, $http, AppService) {
return {
getCurrentApp: function () {
var defer = $q.defer();
console.log("getting apps");
$http.get(config.apiUrl + '/apps')
.success(function (data) {
defer.resolve(data);
AppService.setLoggedInApps(data);
})
return defer.promise;
}
}
}
])
|
version https://git-lfs.github.com/spec/v1
oid sha256:2099c84446b54becdcbf7a805f82b82bbd692b31a23b8553c957d46e8a180f24
size 27435
|
// This compiler is based on the meteor core Spacebars compiler. The main goal
// of this object is to transform the jade syntax-tree to a spacebars
// syntax-tree.
//
// XXX Source-mapping: Jade give us the line number, so we could implement a
// simple line-mapping but it's not yet supported by the spacebars compiler.
// Internal identifier to indicate that we should not insert a new line
// character before a value. This has the side effect that a user cannot start
// a new line starting with this value in one of its templates.
var noNewLinePrefix = "__noNewLine__";
var startsWithNoNewLinePrefix = new RegExp("^" + noNewLinePrefix);
var stringRepresentationToLiteral = function(val) {
if (! _.isString(val))
return null;
var scanner = new HTMLTools.Scanner(val);
var parsed = BlazeTools.parseStringLiteral(scanner);
return parsed ? parsed.value : null;
};
// XXX Obiously we shouldn't have a special case for the markdown component
var isSpecialMarkdownComponent = function(node) {
return node.type === "Mixin" && node.name === "markdown";
};
var isTextOnlyNode = function(node) {
// XXX Is this list defined somewhere in spacebars-compiler?
var textOnlyTags = ['textarea', 'script', 'style'];
return node.textOnly &&
node.type === "Tag" &&
textOnlyTags.indexOf(node.name) !== -1;
};
// Helper function to generation an error from a message and a node
var throwError = function (message, node) {
message = message || "Syntax error";
if (node.line)
message += " on line " + node.line;
throw new Error(message);
};
FileCompiler = function(tree, options) {
var self = this;
self.nodes = tree.nodes;
self.filename = options && options.filename || "";
self.head = null;
self.body = null;
self.bodyAttrs = {};
self.templates = {};
};
_.extend(FileCompiler.prototype, {
compile: function () {
var self = this;
for (var i = 0; i < self.nodes.length; i++)
self.registerRootNode(self.nodes[i]);
return {
head: self.head,
body: self.body,
bodyAttrs: self.bodyAttrs,
templates: self.templates
};
},
registerRootNode: function(node) {
// XXX This is mostly the same code as the `templating` core package
// The `templating` package should be more generic to allow others templates
// engine to use its methods.
var self = this;
// Ignore top level comments
if (node.type === "Comment" || node.type === "BlockComment" ||
node.type === "TAG" && _.isUndefined(node.name)) {
return;
}
// Doctypes
else if (node.type === "Doctype") {
throwError("Meteor sets the doctype for you", node);
}
// There are two specials templates: head and body
else if (node.name === "body" || node.name === "head") {
var template = node.name;
if (self[template] !== null)
throwError(template + " is set twice", node);
if (node.name === "head" && node.attrs.length > 0)
throwError("Attributes on head are not supported", node);
else if(node.name === "body" && node.attrs.length > 0)
self.bodyAttrs = self.formatBodyAttrs(node.attrs);
self[template] = new TemplateCompiler(node.block).compile();
}
// Templates
else if (node.name === "template") {
if (node.attrs.length !== 1 || node.attrs[0].name !== 'name')
throwError('Templates must only have a "name" attribute', node);
var name = node.attrs[0].val.slice(1, -1);
if (name === "content")
throwError('Template can\'t be named "content"', node);
if (_.has(self.templates, name))
throwError('Template "' + name + '" is set twice', node);
self.templates[name] = new TemplateCompiler(node.block).compile();
}
// Otherwise this is an error, we do not allow tags, mixins, if, etc.
// outside templates
else
throwError(node.type + ' must be in a template', node);
},
formatBodyAttrs: function(attrsList) {
var attrsDict = {};
_.each(attrsList, function(attr) {
if (attr.escaped)
attr.val = attr.val.slice(1, -1);
attrsDict[attr.name] = attr.val;
});
return attrsDict;
}
});
TemplateCompiler = function(tree, options) {
var self = this;
self.tree = tree;
self.filename = options && options.filename || "";
};
_.extend(TemplateCompiler.prototype, {
compile: function () {
var self = this;
return self._optimize(self.visitBlock(self.tree));
},
visitBlock: function (block) {
if (_.isUndefined(block) || _.isNull(block) || ! _.has(block, 'nodes'))
return [];
var self = this;
var buffer = [];
var nodes = block.nodes;
var currentNode, elseNode, stack;
for (var i = 0; i < nodes.length; i++) {
currentNode = nodes[i];
// If the node is a Mixin (ie Component), we check if there are some
// `else if` and `else` blocks after it and if so, we groups thoses
// nodes by two with the following transformation:
// if a if a
// else if b else
// else => if b
// else
if (currentNode.type === "Mixin") {
// Create the stack [nodeIf, nodeElseIf..., nodeElse]
stack = [];
while (currentNode.name === "if" && nodes[i+1] &&
nodes[i+1].type === "Mixin" && nodes[i+1].name === "else if")
stack.push(nodes[++i]);
if (nodes[i+1] && nodes[i+1].type === "Mixin" &&
nodes[i+1].name === "else")
stack.push(nodes[++i]);
// Transform the stack
elseNode = stack.shift();
if (elseNode && elseNode.name === "else if") {
elseNode.name = "if";
elseNode = {
name: "else",
type: "Mixin",
block: { nodes: [elseNode].concat(stack) },
call: false
};
}
}
buffer.push(self.visitNode(currentNode, elseNode));
}
return buffer;
},
getRawText: function(block) {
var self = this;
var parts = _(block.nodes).pluck('val');
parts = self._interposeEOL(parts);
return parts.reduce(function(a, b) { return a + b; }, '');
},
visitNode: function(node, elseNode) {
var self = this;
var attrs = self.visitAttributes(node.attrs);
var content;
if (node.code) {
content = self.visitCode(node.code);
} else if (isTextOnlyNode(node) || isSpecialMarkdownComponent(node)) {
content = self.getRawText(node.block);
if (isSpecialMarkdownComponent(node)) {
content = self.parseText(content, {textMode: HTML.TEXTMODE.STRING});
}
} else {
content = self.visitBlock(node.block);
}
var elseContent = self.visitBlock(elseNode && elseNode.block);
return self['visit' + node.type](node, attrs, content, elseContent);
},
visitCode: function(code) {
// XXX Need to improve this for "anonymous helpers"
var val = code.val;
// First case this is a string
var strLiteral = stringRepresentationToLiteral(val);
if (strLiteral !== null) {
return noNewLinePrefix + strLiteral;
} else {
return [ this._spacebarsParse(this.lookup(code.val, code.escape)) ];
}
},
// We interpret "Mixins" as "Components"
// Thanks to our customize Lexer, `if`, `unless`, `with` and `each` are
// retrieved as Mixins by the parser
visitMixin: function(node, attrs, content, elseContent) {
var self = this;
var componentName = node.name;
if (componentName === "else")
throwError("Unexpected else block", node);
var spacebarsSymbol = content.length === 0 ? ">" : "#";
var args = node.args || "";
var mustache = "{{" + spacebarsSymbol + componentName + " " + args + "}}";
var tag = self._spacebarsParse(mustache);
// Optimize arrays
content = self._optimize(content);
elseContent = self._optimize(elseContent);
if (content)
tag.content = content;
if (elseContent)
tag.elseContent = elseContent;
return tag;
},
visitTag: function(node, attrs, content) {
var self = this;
var tagName = node.name.toLowerCase();
content = self._optimize(content, true);
if (tagName === "textarea") {
attrs.value = content;
content = null;
} else if (tagName === "style") {
content = self.parseText(content);
}
if (! _.isArray(content))
content = content ? [content] : [];
if (! _.isEmpty(attrs))
content.unshift(attrs);
return HTML.getTag(tagName).apply(null, content);
},
visitText: function(node) {
var self = this;
return node.val ? self.parseText(node.val) : null;
},
parseText: function(text, options) {
// The parser doesn't parse #{expression} and !{unescapedExpression}
// syntaxes. So let's do it.
// Since we rely on the Spacebars parser for this, we support the
// {{mustache}} and {{{unescapedMustache}}} syntaxes as well.
text = text.replace(/#\{\s*((\.{1,2}\/)*[\w\.-]+)\s*\}/g, "{{$1}}");
text = text.replace(/!\{\s*((\.{1,2}\/)*[\w\.-]+)\s*\}/g, "{{{$1}}}");
options = options || {};
options.getTemplateTag = SpacebarsCompiler.TemplateTag.parseCompleteTag;
return HTMLTools.parseFragment(text, options);
},
visitComment: function (comment) {
// If buffer boolean is true we want to display this comment in the DOM
if (comment.buffer)
return HTML.Comment(comment.val);
},
visitBlockComment: function (comment) {
var self = this;
comment.val = "\n" + _.pluck(comment.block.nodes, "val").join("\n") + "\n";
return self.visitComment(comment);
},
visitFilter: function (filter, attrs, content) {
throwError("Jade filters are not supported in meteor-jade", filter);
},
visitWhen: function (node) {
throwError("Case statements are not supported in meteor-jade", node);
},
visitAttributes: function (attrs) {
// The jade parser provide an attribute tree of this type:
// [{name: "class", val: "val1", escaped: true}, {name: "id" val: "val2"}]
// Let's transform that into:
// {"class": "val1", id: "val2"}
// Moreover if an "id" or "class" attribute is used more than once we need
// to concatenate the values.
if (_.isUndefined(attrs))
return;
if (_.isString(attrs))
return attrs;
var self = this;
var dict = {};
var concatAttributes = function(a, b) {
if (_.isString(a) && _.isString(b))
return a + b;
if (_.isUndefined(a))
return b;
if (! _.isArray(a)) a = [a];
if (! _.isArray(b)) b = [b];
return a.concat(b);
};
var dynamicAttrs = [];
_.each(attrs, function (attr) {
var val = attr.val;
var key = attr.name;
// XXX We need a better handler for JavaScript code
// First case this is a string
var strLiteral = stringRepresentationToLiteral(val);
if (strLiteral) {
val = self.parseText(strLiteral, { textMode: HTML.TEXTMODE.STRING });
val.position = HTMLTools.TEMPLATE_TAG_POSITION.IN_ATTRIBUTE;
}
// For cases like <input required> Spacebars compiler expect the attribute
// to have the value `""` but Jade parser returns `true`
else if (val === true || val === "''" || val === '""') {
val = "";
// Otherwise this is some code we need to evaluate
} else {
val = self._spacebarsParse(self.lookup(val, attr.escaped));
val.position = HTMLTools.TEMPLATE_TAG_POSITION.IN_ATTRIBUTE;
}
if (key === "$dyn") {
val.position = HTMLTools.TEMPLATE_TAG_POSITION.IN_START_TAG;
return dynamicAttrs.push(val);
}
// If a user has defined such kind of tag: div.myClass(class="myClass2")
// we need to concatenate classes (and ids)
else if ((key === "class" || key === "id") && dict[key])
val = [" ", val];
dict[key] = concatAttributes(dict[key], val);
});
if (dynamicAttrs.length === 0) {
return dict;
} else {
dynamicAttrs.unshift(dict);
return HTML.Attrs.apply(null, dynamicAttrs);
}
},
lookup: function (val, escape) {
var mustache = "{{" + val + "}}";
if (! escape)
mustache = "{" + mustache + "}";
return HTMLTools.parseFragment(mustache);
},
_spacebarsParse: SpacebarsCompiler.TemplateTag.parse,
_removeNewLinePrefixes: function(array) {
var removeNewLinePrefix = function(val) {
if (startsWithNoNewLinePrefix.test(val))
return val.slice(noNewLinePrefix.length);
else
return val;
};
if (! _.isArray(array))
return removeNewLinePrefix(array);
else
return _.map(array, removeNewLinePrefix);
},
_interposeEOL: function(array) {
for (var i = array.length - 1; i > 0; i--) {
if (! startsWithNoNewLinePrefix.test(array[i]))
array.splice(i, 0, "\n");
}
return array;
},
_optimize: function(content, interposeEOL) {
var self = this;
if (! _.isArray(content))
return self._removeNewLinePrefixes(content);
if (content.length === 0)
return undefined;
if (content.length === 1)
content = self._optimize(content[0]);
else if (interposeEOL)
content = self._interposeEOL(content);
else
content = content;
return self._removeNewLinePrefixes(content);
}
});
|
import { combineReducers } from 'redux';
import forms from './forms';
import user from './user';
import whoami from './whoami';
export default combineReducers({
forms,
user,
whoami,
});
|
'use strict';
/**
* Module dependencies.
*/
var util = require('util');
var request = require('request');
var path = require('path');
var nconf = require('nconf').file({
file: path.join(__dirname, '..', 'config', 'global.json')
});
/**
* Logger
*/
var LogglyStream = function() {
this.options = {
enabled: nconf.get('Logging:Loggly:Enabled'),
tags: nconf.get('Logging:Loggly:Tags').concat([process.env.NODE_ENV]),
endpoint: nconf.get('Logging:Loggly:Endpoint')
};
this.options.endpoint = util.format('%stag/%s', this.options.endpoint, this.options.tags.join(','));
};
LogglyStream.prototype.write = function(record) {
if (!this.options.enabled || typeof (record) !== 'object') {
return;
}
var requestObject = {
method: 'POST',
uri: this.options.endpoint,
json: record
};
request(requestObject, function(err) {
if (err) {
console.log('LogglyStream - Error:');
console.error(err);
}
});
};
/**
* Export
*/
module.exports = LogglyStream;
|
var run_tl = new TimelineLite({
onComplete: function() {
run_tl.play(0);
},
}),
jump_tl = new TimelineLite({
paused:true,
onComplete:function() {
run_tl.play(0);
}
}),
dur = 0.125;
TweenLite.defaultEase = Linear.easeNone;
run_tl.timeScale(1.25);
run_tl.add("Step")
.add(bodyTl(), "Step")
.add(armsTl(), "Step")
.add(legRTl(), "Step")
.add(legLTl(), "Step")
// Running Methods
function armsTl() {
var arms_tl = new TimelineLite();
arms_tl.add("Start")
.to(armR, dur * 3, {
x: "150",
ease: Power1.easeInOut
}, "Start")
.to(armL, dur * 2.75, {
x: "-100",
ease: Power1.easeInOut
}, "Start")
.add("Return")
.to(armR, dur * 2.5, {
x: "0",
ease: Power1.easeInOut
}, "Return")
.to(armL, dur * 3, {
x: "0",
ease: Power1.easeInOut
}, "Return")
console.log("Arms TL", arms_tl.totalDuration());
return arms_tl;
}
function bodyTl() {
var body_tl = new TimelineLite();
body_tl.add(bodyBounce())
.add(bodyBounce())
console.log("Body TL", body_tl.totalDuration());
return body_tl;
}
function bodyBounce() {
var tl = new TimelineLite();
tl.add("Up")
.to(momo, dur, {
y: "-50",
ease: Power2.easeInOut
}, "Up")
.to(shadow, dur, {scale: 0.98, opacity: 0.9, transformOrigin: "50% 50%", ease: Power2.easeInOut}, "Up")
.add("Down")
.to(momo, dur, {
y: "0",
ease: Power2.easeIn
}, "Down")
.to(shadow, dur, {
scale: 1,
opacity: 1,
ease: Power2.easeIn
}, "Down")
.to(cap, dur, {
y: "-50",
ease: Power2.easeInOut
}, "Up+=" + dur * 0.8)
.to(cap, dur, {
y: "0",
ease: Power2.easeIn
})
return tl;
}
function legLTl() {
var tl = new TimelineLite();
tl.add("Start").set(legL, {x: "-30",y: "10"})
.to(legL, dur * 2, {
y: "-30",
rotation: "30",
transformOrigin: "50% 0"
})
.to(legL, dur, {
x: 0,
y: 0,
rotation: 0
})
.to(legL, dur, {
x: "80",
y: "10",
rotation: 0
})
.to(legL, dur * 2, {
x: "-30"
})
console.log("LegL:", tl.totalDuration());
return tl;
}
function legRTl() {
var tl = new TimelineLite();
tl
.set(legL, {y:10})
.to(legR, dur, {
y: "10",
x: "80"
})
.to(legR, dur * 2, {
x: "-30"
})
.to(legR, dur * 2, {
y: "-30",
rotation: "30",
transformOrigin: "50% 0"
})
.to(legR, dur, {
x: 0,
y: 0,
rotation: 0
})
console.log("LegR:", tl.totalDuration());
return tl;
}
// Jumping Methods
jump_tl.add("Up")
.to(momo, dur*2, {y:"-300", ease:Power2.easeInOut}, "Up+="+dur*0.3)
.to(shadow, dur*2, {scale:0.6, autoAlpha:0.5, transformOrigin:"50% 50%", ease:Power2.easeInOut}, "Up+="+dur*0.3)
.to(legR, dur, {y:"40", rotation:"20", transformOrigin:"50% 0", ease:Power2.easeInOut}, "Up+="+dur*0.3)
.to(face, dur, {y:"30", ease:Power4.easeInOut}, "Up+="+dur)
.to(armL, dur*2, {y:"-200", x:"50", ease:Power4.easeOut}, "Up")
.to(armR, dur*2, {y:"50", x:"-50", ease:Power4.easeOut}, "Up+="+dur*0.3)
.set([openR,openL], {autoAlpha:0})
.set([blinkR,blinkL], {autoAlpha:1})
.add("Down")
.to(momo, dur*2, {y:"20", ease:Power2.easeIn}, "Down")
.to(shadow, dur*2, {scale:1.01, autoAlpha:1, ease:Power2.easeIn}, "Down")
.staggerTo([legL,legR], dur, {y:"-20", rotation:0, ease:Power2.easeInOut}, 0.1, "Down")
.to(legL, dur, {x:"30", rotation:"-20", transformOrigin:"50% 0", ease:Power2.easeInOut}, "Down+="+dur*0.5)
.to(face, dur, {y:"-30", ease:Power4.easeInOut}, "Down+="+dur)
.to(armL, dur*2, {y:"-400", x:0, ease:Power2.easeIn}, "Down")
.to(armR, dur*2, {y:"-50", x:"-50", ease:Power2.easeInOut}, "Down")
.to(cap, dur*2, {y:"-200", rotation:"-20", ease:Power2.easeIn}, "Down")
.set(legR, {x:0})
.set(legL, {x:"-30"})
.add("Bounce")
.set(legL, {x:0, rotation:0})
.set([openR,openL], {autoAlpha:1})
.set([blinkR,blinkL], {autoAlpha:0})
.to(momo, dur*2, {y:0, ease:Power2.easeOut}, "Bounce")
.to([legL,legR], dur*2, {y:10, ease:Power2.easeOut}, "Bounce")
.to(shadow, dur*2, {scale:1, ease:Power2.easeIn}, "Bounce")
.to([armL,armR,face], dur*2, {y:0, x:0, ease:Back.easeOut}, "Bounce")
.to(cap, dur*4, {y:0, rotation:0, ease:Bounce.easeOut}, "Bounce")
// AUDIO
// Looping Theme
var audio = new Audio('https://s3-us-west-2.amazonaws.com/s.cdpn.io/259155/momoBros.mp3');
audio.loop = true;
audio.play();
// Jump
var jumpFx = new Audio('https://s3-us-west-2.amazonaws.com/s.cdpn.io/259155/MomoJump.mp3');
var toggle = document.getElementById('mute');
toggle.addEventListener('click', function() {
if(!audio.paused) {
audio.pause();
} else {
audio.play();
}
})
// BUTTON BEHAVIOUR
var btn = document.querySelector('button');
btn.addEventListener('click', function(e) {
if(!jump_tl.isActive()) {
jump_tl.play(0);
jumpFx.play();
run_tl.pause();
}
// if (run_tl.isActive()) {
// } else {
// run_tl.play();
// }
}); |
export default class {
constructor() {
this.name = 'bob';
}
}
|
/*!
* Ext JS Library 3.4.0
* Copyright(c) 2006-2011 Sencha Inc.
* licensing@sencha.com
* http://www.sencha.com/license
*/
/*!
* Ext JS Library 3.4.0
* Copyright(c) 2006-2011 Sencha Inc.
* licensing@sencha.com
* http://www.sencha.com/license
*/
/*!
* Ext JS Library 3.4.0
* Copyright(c) 2006-2011 Sencha Inc.
* licensing@sencha.com
* http://www.sencha.com/license
*/
/*!
* Ext JS Library 3.4.0
* Copyright(c) 2006-2011 Sencha Inc.
* licensing@sencha.com
* http://www.sencha.com/license
*/
/*!
* Ext JS Library 3.4.0
* Copyright(c) 2006-2011 Sencha Inc.
* licensing@sencha.com
* http://www.sencha.com/license
*/
/*!
* Ext JS Library 3.4.0
* Copyright(c) 2006-2011 Sencha Inc.
* licensing@sencha.com
* http://www.sencha.com/license
*/
/*!
* Ext JS Library 3.4.0
* Copyright(c) 2006-2011 Sencha Inc.
* licensing@sencha.com
* http://www.sencha.com/license
*/
/**
* @class Ext.data.XmlWriter
* @extends Ext.data.DataWriter
* DataWriter extension for writing an array or single {@link Ext.data.Record} object(s) in preparation for executing a remote CRUD action via XML.
* XmlWriter uses an instance of {@link Ext.XTemplate} for maximum flexibility in defining your own custom XML schema if the default schema is not appropriate for your needs.
* See the {@link #tpl} configuration-property.
*/
Ext.data.XmlWriter = function(params) {
Ext.data.XmlWriter.superclass.constructor.apply(this, arguments);
// compile the XTemplate for rendering XML documents.
this.tpl = (typeof(this.tpl) === 'string') ? new Ext.XTemplate(this.tpl).compile() : this.tpl.compile();
};
Ext.extend(Ext.data.XmlWriter, Ext.data.DataWriter, {
/**
* @cfg {String} documentRoot [xrequest] (Optional) The name of the XML document root-node. <b>Note:</b>
* this parameter is required </b>only when</b> sending extra {@link Ext.data.Store#baseParams baseParams} to the server
* during a write-request -- if no baseParams are set, the {@link Ext.data.XmlReader#record} meta-property can
* suffice as the XML document root-node for write-actions involving just a <b>single record</b>. For requests
* involving <b>multiple</b> records and <b>NO</b> baseParams, the {@link Ext.data.XmlWriter#root} property can
* act as the XML document root.
*/
documentRoot: 'xrequest',
/**
* @cfg {Boolean} forceDocumentRoot [false] Set to <tt>true</tt> to force XML documents having a root-node as defined
* by {@link #documentRoot}, even with no baseParams defined.
*/
forceDocumentRoot: false,
/**
* @cfg {String} root [records] The name of the containing element which will contain the nodes of an write-action involving <b>multiple</b> records. Each
* xml-record written to the server will be wrapped in an element named after {@link Ext.data.XmlReader#record} property.
* eg:
<code><pre>
<?xml version="1.0" encoding="UTF-8"?>
<user><first>Barney</first></user>
</code></pre>
* However, when <b>multiple</b> records are written in a batch-operation, these records must be wrapped in a containing
* Element.
* eg:
<code><pre>
<?xml version="1.0" encoding="UTF-8"?>
<records>
<first>Barney</first></user>
<records><first>Barney</first></user>
</records>
</code></pre>
* Defaults to <tt>records</tt>. Do not confuse the nature of this property with that of {@link #documentRoot}
*/
root: 'records',
/**
* @cfg {String} xmlVersion [1.0] The <tt>version</tt> written to header of xml documents.
<code><pre><?xml version="1.0" encoding="ISO-8859-15"?></pre></code>
*/
xmlVersion : '1.0',
/**
* @cfg {String} xmlEncoding [ISO-8859-15] The <tt>encoding</tt> written to header of xml documents.
<code><pre><?xml version="1.0" encoding="ISO-8859-15"?></pre></code>
*/
xmlEncoding: 'ISO-8859-15',
/**
* @cfg {String/Ext.XTemplate} tpl The XML template used to render {@link Ext.data.Api#actions write-actions} to your server.
* <p>One can easily provide his/her own custom {@link Ext.XTemplate#constructor template-definition} if the default does not suffice.</p>
* <p>Defaults to:</p>
<code><pre>
<?xml version="{version}" encoding="{encoding}"?>
<tpl if="documentRoot"><{documentRoot}>
<tpl for="baseParams">
<tpl for=".">
<{name}>{value}</{name}>
</tpl>
</tpl>
<tpl if="records.length > 1"><{root}>',
<tpl for="records">
<{parent.record}>
<tpl for=".">
<{name}>{value}</{name}>
</tpl>
</{parent.record}>
</tpl>
<tpl if="records.length > 1"></{root}></tpl>
<tpl if="documentRoot"></{documentRoot}></tpl>
</pre></code>
* <p>Templates will be called with the following API</p>
* <ul>
* <li>{String} version [1.0] The xml version.</li>
* <li>{String} encoding [ISO-8859-15] The xml encoding.</li>
* <li>{String/false} documentRoot The XML document root-node name or <tt>false</tt> if not required. See {@link #documentRoot} and {@link #forceDocumentRoot}.</li>
* <li>{String} record The meta-data parameter defined on your {@link Ext.data.XmlReader#record} configuration represents the name of the xml-tag containing each record.</li>
* <li>{String} root The meta-data parameter defined by {@link Ext.data.XmlWriter#root} configuration-parameter. Represents the name of the xml root-tag when sending <b>multiple</b> records to the server.</li>
* <li>{Array} records The records being sent to the server, ie: the subject of the write-action being performed. The records parameter will be always be an array, even when only a single record is being acted upon.
* Each item within the records array will contain an array of field objects having the following properties:
* <ul>
* <li>{String} name The field-name of the record as defined by your {@link Ext.data.Record#create Ext.data.Record definition}. The "mapping" property will be used, otherwise it will match the "name" property. Use this parameter to define the XML tag-name of the property.</li>
* <li>{Mixed} value The record value of the field enclosed within XML tags specified by name property above.</li>
* </ul></li>
* <li>{Array} baseParams. The baseParams as defined upon {@link Ext.data.Store#baseParams}. Note that the baseParams have been converted into an array of [{name : "foo", value: "bar"}, ...] pairs in the same manner as the <b>records</b> parameter above. See {@link #documentRoot} and {@link #forceDocumentRoot}.</li>
* </ul>
*/
// Encoding the ? here in case it's being included by some kind of page that will parse it (eg. PHP)
tpl: '<tpl for="."><\u003fxml version="{version}" encoding="{encoding}"\u003f><tpl if="documentRoot"><{documentRoot}><tpl for="baseParams"><tpl for="."><{name}>{value}</{name}></tpl></tpl></tpl><tpl if="records.length>1"><{root}></tpl><tpl for="records"><{parent.record}><tpl for="."><{name}>{value}</{name}></tpl></{parent.record}></tpl><tpl if="records.length>1"></{root}></tpl><tpl if="documentRoot"></{documentRoot}></tpl></tpl>',
/**
* XmlWriter implementation of the final stage of a write action.
* @param {Object} params Transport-proxy's (eg: {@link Ext.Ajax#request}) params-object to write-to.
* @param {Object} baseParams as defined by {@link Ext.data.Store#baseParams}. The baseParms must be encoded by the extending class, eg: {@link Ext.data.JsonWriter}, {@link Ext.data.XmlWriter}.
* @param {Object/Object[]} data Data-object representing the compiled Store-recordset.
*/
render : function(params, baseParams, data) {
baseParams = this.toArray(baseParams);
params.xmlData = this.tpl.applyTemplate({
version: this.xmlVersion,
encoding: this.xmlEncoding,
documentRoot: (baseParams.length > 0 || this.forceDocumentRoot === true) ? this.documentRoot : false,
record: this.meta.record,
root: this.root,
baseParams: baseParams,
records: (Ext.isArray(data[0])) ? data : [data]
});
},
/**
* createRecord
* @protected
* @param {Ext.data.Record} rec
* @return {Array} Array of <tt>name:value</tt> pairs for attributes of the {@link Ext.data.Record}. See {@link Ext.data.DataWriter#toHash}.
*/
createRecord : function(rec) {
return this.toArray(this.toHash(rec));
},
/**
* updateRecord
* @protected
* @param {Ext.data.Record} rec
* @return {Array} Array of {name:value} pairs for attributes of the {@link Ext.data.Record}. See {@link Ext.data.DataWriter#toHash}.
*/
updateRecord : function(rec) {
return this.toArray(this.toHash(rec));
},
/**
* destroyRecord
* @protected
* @param {Ext.data.Record} rec
* @return {Array} Array containing a attribute-object (name/value pair) representing the {@link Ext.data.DataReader#idProperty idProperty}.
*/
destroyRecord : function(rec) {
var data = {};
data[this.meta.idProperty] = rec.id;
return this.toArray(data);
}
});
/*!
* Ext JS Library 3.4.0
* Copyright(c) 2006-2011 Sencha Inc.
* licensing@sencha.com
* http://www.sencha.com/license
*/
/**
* @class Ext.data.XmlReader
* @extends Ext.data.DataReader
* <p>Data reader class to create an Array of {@link Ext.data.Record} objects from an XML document
* based on mappings in a provided {@link Ext.data.Record} constructor.</p>
* <p><b>Note</b>: that in order for the browser to parse a returned XML document, the Content-Type
* header in the HTTP response must be set to "text/xml" or "application/xml".</p>
* <p>Example code:</p>
* <pre><code>
var Employee = Ext.data.Record.create([
{name: 'name', mapping: 'name'}, // "mapping" property not needed if it is the same as "name"
{name: 'occupation'} // This field will use "occupation" as the mapping.
]);
var myReader = new Ext.data.XmlReader({
totalProperty: "results", // The element which contains the total dataset size (optional)
record: "row", // The repeated element which contains row information
idProperty: "id" // The element within the row that provides an ID for the record (optional)
messageProperty: "msg" // The element within the response that provides a user-feedback message (optional)
}, Employee);
</code></pre>
* <p>
* This would consume an XML file like this:
* <pre><code>
<?xml version="1.0" encoding="UTF-8"?>
<dataset>
<results>2</results>
<row>
<id>1</id>
<name>Bill</name>
<occupation>Gardener</occupation>
</row>
<row>
<id>2</id>
<name>Ben</name>
<occupation>Horticulturalist</occupation>
</row>
</dataset>
</code></pre>
* @cfg {String} totalProperty The DomQuery path from which to retrieve the total number of records
* in the dataset. This is only needed if the whole dataset is not passed in one go, but is being
* paged from the remote server.
* @cfg {String} record The DomQuery path to the repeated element which contains record information.
* @cfg {String} record The DomQuery path to the repeated element which contains record information.
* @cfg {String} successProperty The DomQuery path to the success attribute used by forms.
* @cfg {String} idPath The DomQuery path relative from the record element to the element that contains
* a record identifier value.
* @constructor
* Create a new XmlReader.
* @param {Object} meta Metadata configuration options
* @param {Object} recordType Either an Array of field definition objects as passed to
* {@link Ext.data.Record#create}, or a Record constructor object created using {@link Ext.data.Record#create}.
*/
Ext.data.XmlReader = function(meta, recordType){
meta = meta || {};
// backwards compat, convert idPath or id / success
Ext.applyIf(meta, {
idProperty: meta.idProperty || meta.idPath || meta.id,
successProperty: meta.successProperty || meta.success
});
Ext.data.XmlReader.superclass.constructor.call(this, meta, recordType || meta.fields);
};
Ext.extend(Ext.data.XmlReader, Ext.data.DataReader, {
/**
* This method is only used by a DataProxy which has retrieved data from a remote server.
* @param {Object} response The XHR object which contains the parsed XML document. The response is expected
* to contain a property called <tt>responseXML</tt> which refers to an XML document object.
* @return {Object} records A data block which is used by an {@link Ext.data.Store} as
* a cache of Ext.data.Records.
*/
read : function(response){
var doc = response.responseXML;
if(!doc) {
throw {message: "XmlReader.read: XML Document not available"};
}
return this.readRecords(doc);
},
/**
* Create a data block containing Ext.data.Records from an XML document.
* @param {Object} doc A parsed XML document.
* @return {Object} records A data block which is used by an {@link Ext.data.Store} as
* a cache of Ext.data.Records.
*/
readRecords : function(doc){
/**
* After any data loads/reads, the raw XML Document is available for further custom processing.
* @type XMLDocument
*/
this.xmlData = doc;
var root = doc.documentElement || doc,
q = Ext.DomQuery,
totalRecords = 0,
success = true;
if(this.meta.totalProperty){
totalRecords = this.getTotal(root, 0);
}
if(this.meta.successProperty){
success = this.getSuccess(root);
}
var records = this.extractData(q.select(this.meta.record, root), true); // <-- true to return Ext.data.Record[]
// TODO return Ext.data.Response instance. @see #readResponse
return {
success : success,
records : records,
totalRecords : totalRecords || records.length
};
},
/**
* Decode an XML response from server.
* @param {String} action [{@link Ext.data.Api#actions} create|read|update|destroy]
* @param {Object} response HTTP Response object from browser.
* @return {Ext.data.Response} An instance of {@link Ext.data.Response}
*/
readResponse : function(action, response) {
var q = Ext.DomQuery,
doc = response.responseXML,
root = doc.documentElement || doc;
// create general Response instance.
var res = new Ext.data.Response({
action: action,
success : this.getSuccess(root),
message: this.getMessage(root),
data: this.extractData(q.select(this.meta.record, root) || q.select(this.meta.root, root), false),
raw: doc
});
if (Ext.isEmpty(res.success)) {
throw new Ext.data.DataReader.Error('successProperty-response', this.meta.successProperty);
}
// Create actions from a response having status 200 must return pk
if (action === Ext.data.Api.actions.create) {
var def = Ext.isDefined(res.data);
if (def && Ext.isEmpty(res.data)) {
throw new Ext.data.JsonReader.Error('root-empty', this.meta.root);
}
else if (!def) {
throw new Ext.data.JsonReader.Error('root-undefined-response', this.meta.root);
}
}
return res;
},
getSuccess : function() {
return true;
},
/**
* build response-data extractor functions.
* @private
* @ignore
*/
buildExtractors : function() {
if(this.ef){
return;
}
var s = this.meta,
Record = this.recordType,
f = Record.prototype.fields,
fi = f.items,
fl = f.length;
if(s.totalProperty) {
this.getTotal = this.createAccessor(s.totalProperty);
}
if(s.successProperty) {
this.getSuccess = this.createAccessor(s.successProperty);
}
if (s.messageProperty) {
this.getMessage = this.createAccessor(s.messageProperty);
}
this.getRoot = function(res) {
return (!Ext.isEmpty(res[this.meta.record])) ? res[this.meta.record] : res[this.meta.root];
};
if (s.idPath || s.idProperty) {
var g = this.createAccessor(s.idPath || s.idProperty);
this.getId = function(rec) {
var id = g(rec) || rec.id;
return (id === undefined || id === '') ? null : id;
};
} else {
this.getId = function(){return null;};
}
var ef = [];
for(var i = 0; i < fl; i++){
f = fi[i];
var map = (f.mapping !== undefined && f.mapping !== null) ? f.mapping : f.name;
ef.push(this.createAccessor(map));
}
this.ef = ef;
},
/**
* Creates a function to return some particular key of data from a response.
* @param {String} key
* @return {Function}
* @private
* @ignore
*/
createAccessor : function(){
var q = Ext.DomQuery;
return function(key) {
if (Ext.isFunction(key)) {
return key;
}
switch(key) {
case this.meta.totalProperty:
return function(root, def){
return q.selectNumber(key, root, def);
};
break;
case this.meta.successProperty:
return function(root, def) {
var sv = q.selectValue(key, root, true);
var success = sv !== false && sv !== 'false';
return success;
};
break;
default:
return function(root, def) {
return q.selectValue(key, root, def);
};
break;
}
};
}(),
/**
* extracts values and type-casts a row of data from server, extracted by #extractData
* @param {Hash} data
* @param {Ext.data.Field[]} items
* @param {Number} len
* @private
* @ignore
*/
extractValues : function(data, items, len) {
var f, values = {};
for(var j = 0; j < len; j++){
f = items[j];
var v = this.ef[j](data);
values[f.name] = f.convert((v !== undefined) ? v : f.defaultValue, data);
}
return values;
}
});/*!
* Ext JS Library 3.4.0
* Copyright(c) 2006-2011 Sencha Inc.
* licensing@sencha.com
* http://www.sencha.com/license
*/
/**
* @class Ext.data.XmlStore
* @extends Ext.data.Store
* <p>Small helper class to make creating {@link Ext.data.Store}s from XML data easier.
* A XmlStore will be automatically configured with a {@link Ext.data.XmlReader}.</p>
* <p>A store configuration would be something like:<pre><code>
var store = new Ext.data.XmlStore({
// store configs
autoDestroy: true,
storeId: 'myStore',
url: 'sheldon.xml', // automatically configures a HttpProxy
// reader configs
record: 'Item', // records will have an "Item" tag
idPath: 'ASIN',
totalRecords: '@TotalResults'
fields: [
// set up the fields mapping into the xml doc
// The first needs mapping, the others are very basic
{name: 'Author', mapping: 'ItemAttributes > Author'},
'Title', 'Manufacturer', 'ProductGroup'
]
});
* </code></pre></p>
* <p>This store is configured to consume a returned object of the form:<pre><code>
<?xml version="1.0" encoding="UTF-8"?>
<ItemSearchResponse xmlns="http://webservices.amazon.com/AWSECommerceService/2009-05-15">
<Items>
<Request>
<IsValid>True</IsValid>
<ItemSearchRequest>
<Author>Sidney Sheldon</Author>
<SearchIndex>Books</SearchIndex>
</ItemSearchRequest>
</Request>
<TotalResults>203</TotalResults>
<TotalPages>21</TotalPages>
<Item>
<ASIN>0446355453</ASIN>
<DetailPageURL>
http://www.amazon.com/
</DetailPageURL>
<ItemAttributes>
<Author>Sidney Sheldon</Author>
<Manufacturer>Warner Books</Manufacturer>
<ProductGroup>Book</ProductGroup>
<Title>Master of the Game</Title>
</ItemAttributes>
</Item>
</Items>
</ItemSearchResponse>
* </code></pre>
* An object literal of this form could also be used as the {@link #data} config option.</p>
* <p><b>Note:</b> Although not listed here, this class accepts all of the configuration options of
* <b>{@link Ext.data.XmlReader XmlReader}</b>.</p>
* @constructor
* @param {Object} config
* @xtype xmlstore
*/
Ext.data.XmlStore = Ext.extend(Ext.data.Store, {
/**
* @cfg {Ext.data.DataReader} reader @hide
*/
constructor: function(config){
Ext.data.XmlStore.superclass.constructor.call(this, Ext.apply(config, {
reader: new Ext.data.XmlReader(config)
}));
}
});
Ext.reg('xmlstore', Ext.data.XmlStore); |
'use strict';
var test = require('selenium-webdriver/testing'),
By = require('selenium-webdriver').By,
until = require('selenium-webdriver').until,
Promise = require("bluebird"),
expect = require('chai').expect,
moment = require('moment'),
add_new_user_func = require('../../lib/add_new_user'),
check_elements_func = require('../../lib/check_elements'),
config = require('../../lib/config'),
login_user_func = require('../../lib/login_with_user'),
logout_user_func = require('../../lib/logout_user'),
open_page_func = require('../../lib/open_page'),
register_new_user_func = require('../../lib/register_new_user'),
submit_form_func = require('../../lib/submit_form'),
user_info_func = require('../../lib/user_info'),
application_host = config.get_application_host();
/*
* Scenario (based in bug #166):
*
* * Create company
* * Obtain admoin details and go to admin details page
* * Update admin's details to have start date as very beginnign of this year
* * Add one week length holiday and approve it
* * Check that allowance section of user details page shows "15 out of 20"
* * Go to employees list page and make sure used shows 5 and remaining 15
* * Initiate revoke procedure (but not finish)
* * Go to employees list page and make sure used shows 5 and remaining 15
*
* */
describe('Leave request cancelation', function(){
this.timeout( config.get_execution_timeout() );
var driver, email_A, user_id_A;
it("Register new company", function(done){
register_new_user_func({
application_host : application_host,
})
.then(function(data){
driver = data.driver;
email_A = data.email;
done();
});
});
it("Obtain information about admin user A", function(done){
user_info_func({
driver : driver,
email : email_A,
})
.then(function(data){
user_id_A = data.user.id;
done();
});
});
it('Open user A details page', function(done){
open_page_func({
url : application_host + 'users/edit/'+user_id_A+'/',
driver : driver,
})
.then(function(){ done() });
});
it('Update admin details to have start date at very beginig of this year', function(done){
submit_form_func({
driver : driver,
form_params : [{
selector : 'input#start_date_inp',
value : moment().startOf('year').format('YYYY-MM-DD'),
}],
submit_button_selector : 'button#save_changes_btn',
message : /Details for .+ were updated/,
should_be_successful : true,
})
.then(function(){ done() });
});
it("Open calendar page", function(done){
open_page_func({
url : application_host + 'calendar/?year=2015&show_full_year=1',
driver : driver,
})
.then(function(){done()});
});
it("Open Book leave popup window", function(done){
driver.findElement(By.css('#book_time_off_btn'))
.then(function(el){ return el.click() })
.then(function(el){
// This is very important line when working with Bootstrap modals!
return driver.sleep(1000);
})
.then(function(){ done() });
});
it("Submit new leave request for user A one weekday", function(done){
submit_form_func({
driver : driver,
form_params : [{
selector : 'input#from',
value : '2017-05-01',
},{
selector : 'input#to',
value : '2017-05-07',
}],
message : /New leave request was added/,
})
.then(function(){done()});
});
it("Open requests page", function( done ){
open_page_func({
url : application_host + 'requests/',
driver : driver,
})
.then(function(){ done() });
});
it("Approve new leave request", function(done){
driver.findElement(By.css(
'tr[vpp="pending_for__'+email_A+'"] .btn-success'
))
.then(function(el){ return el.click(); })
.then(function(){
// Wait until page properly is reloaded
return driver.wait(until.elementLocated(By.css('h1')), 1000);
})
.then(function(){done()});
});
it('Open user A details page (abcenses section)', function(done){
open_page_func({
url : application_host + 'users/edit/'+user_id_A+'/absences/',
driver : driver,
})
.then(function(){ done() });
});
it('Check that allowance section of user details page shows "15 out of 20"', function(done){
driver
.findElement( By.css('#days_remaining_inp') )
.then(function(inp){
return inp.getAttribute('value');
})
.then(function(text){
expect( text ).to.be.eq('15 out of 20');
done();
})
});
it('Open employees list page', function(done){
open_page_func({
url : application_host + 'users',
driver : driver,
})
.then(function(){ done() });
});
it('Ensure "remaining" 15', function(done){
driver
.findElement( By.css('tr[data-vpp-user-row="'+user_id_A+'"] .vpp-days-remaining') )
.then(function(el){ return el.getText() })
.then(function(text){
expect( text ).to.be.eq('15');
done();
})
});
it('Ensure "used" shows 5', function(done){
driver
.findElement( By.css('tr[data-vpp-user-row="'+user_id_A+'"] .vpp-days-used') )
.then(function(el){ return el.getText() })
.then(function(text){
expect( text ).to.be.eq('5');
done();
})
});
it("Open requests page", function(done){
open_page_func({
url : application_host + 'requests/',
driver : driver,
})
.then(function(){ done() });
});
it('Initiate revoke procedure (but not finish)', function(done){
driver
.findElement(By.css(
'button.revoke-btn'
))
.then(function(el){ return el.click(); })
.then(function(){
// Wait until page properly is reloaded
return driver.wait(until.elementLocated(By.css('h1')), 1000);
})
.then(function(){ done() });
});
it('Open user A details page (abcenses section)', function(done){
open_page_func({
url : application_host + 'users/edit/'+user_id_A+'/absences/',
driver : driver,
})
.then(function(){ done() });
});
it('Check that allowance section of user details page shows "15 out of 20"', function(done){
driver
.findElement( By.css('#days_remaining_inp') )
.then(function(inp){
return inp.getAttribute('value');
})
.then(function(text){
expect( text ).to.be.eq('15 out of 20');
done();
})
});
it('Open employees list page', function(done){
open_page_func({
url : application_host + 'users',
driver : driver,
})
.then(function(){ done() });
});
it('Ensure "remaining" 15', function(done){
driver
.findElement( By.css('tr[data-vpp-user-row="'+user_id_A+'"] .vpp-days-remaining') )
.then(function(el){ return el.getText() })
.then(function(text){
expect( text ).to.be.eq('15');
done();
})
});
it('Ensure "used" shows 5', function(done){
driver
.findElement( By.css('tr[data-vpp-user-row="'+user_id_A+'"] .vpp-days-used') )
.then(function(el){ return el.getText() })
.then(function(text){
expect( text ).to.be.eq('5');
done();
})
});
after(function(done){
driver.quit().then(function(){ done(); });
});
});
|
(function () {
'use strict';
var module = angular.module('fim.base');
module.config(function($routeProvider) {
$routeProvider
.when('/wallet', {
templateUrl: 'partials/wallet.html',
controller: 'WalletController'
});
});
module.controller('WalletController', function($scope, $rootScope, WalletService, plugins) {
var login = new WalletService();
$scope.entries = [];
function reload() {
$scope.entries = login._getList().map(function (a) {
return { name: a[0], cipher_key: a[1], account: a[2], engine: a[3] }
});
}
reload();
$scope.remove = function (a) {
plugins.get('alerts').confirm({
title: 'Remove key',
message: "Do you want to remove this encrypted key? (cannot be undone)"
}).then(
function (confirmed) {
if (confirmed) {
var list = login._getList().filter(function (_a) {
return !(a.name == _a[0] && a.cipher_key == _a[1] && a.account == _a[2] && a.engine == _a[3]);
});
login._saveList(list);
$scope.$evalAsync(reload);
}
}
);
}
$scope.loadBackup = function () {
}
});
})(); |
todoApp = angular.module('todoApp', ['ngRoute'])
.config(function($routeProvider) {
$routeProvider
.when('/', {
templateUrl: '/partials/todo.html',
controller: 'TodoCtrl'
}).otherwise({
redirectTo: '/'
});
}); |
/**
* JQuery tabIndexList - v 0.0.2 - 2013-08-05
* Copyright (c) Mar, G. (Terra Networks Brasil); Licensed MIT
*/
(function($){
'use strict';
var pluginName = 'tabIndexList',
version = '0.0.2',
defaults = {
/**
* a name can be associated to more with one element,
* if this parameter are flagged true only first element with this name is added to tabindex order,
* therwise all elements are added in tablist, will ordered according found in the html.
*/
onlyFirst : false
};
var _tabIndexList = function(itensList, options) {
if (options) {
$.extend(defaults, options);
}
var c = 0,
l = itensList.length;
for (var i=0; i<l; ++i) {
var element = $("*[name='"+itensList[i]+"']");
if (element.length > 0) {
element[0].tabIndex = ++c;
if (element.length > 1) {
var le = element.length;
for (var j=1; j<le; ++j) {
element[j].tabIndex = defaults.onlyFirst ? -1 : ++c;
}
}
}
}
};
$.tabIndexList = function(itensList, options) {
_tabIndexList(itensList, options);
};
})(jQuery);
|
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.dragula = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
'use strict';
var cache = {};
var start = '(?:^|\\s)';
var end = '(?:\\s|$)';
function lookupClass (className) {
var cached = cache[className];
if (cached) {
cached.lastIndex = 0;
} else {
cache[className] = cached = new RegExp(start + className + end, 'g');
}
return cached;
}
function addClass (el, className) {
var current = el.className;
if (!current.length) {
el.className = className;
} else if (!lookupClass(className).test(current)) {
el.className += ' ' + className;
}
}
function rmClass (el, className) {
el.className = el.className.replace(lookupClass(className), ' ').trim();
}
module.exports = {
add: addClass,
rm: rmClass
};
},{}],2:[function(require,module,exports){
(function (global){
'use strict';
var emitter = require('contra/emitter');
var crossvent = require('crossvent');
var classes = require('./classes');
var doc = document;
var documentElement = doc.documentElement;
function dragula (initialContainers, options) {
var len = arguments.length;
if (len === 1 && Array.isArray(initialContainers) === false) {
options = initialContainers;
initialContainers = [];
}
var _mirror; // mirror image
var _source; // source container
var _item; // item being dragged
var _offsetX; // reference x
var _offsetY; // reference y
var _moveX; // reference move x
var _moveY; // reference move y
var _initialSibling; // reference sibling when grabbed
var _currentSibling; // reference sibling now
var _copy; // item used for copying
var _renderTimer; // timer for setTimeout renderMirrorImage
var _lastDropTarget = null; // last container item was over
var _grabbed; // holds mousedown context until first mousemove
var o = options || {};
if (o.moves === void 0) { o.moves = always; }
if (o.accepts === void 0) { o.accepts = always; }
if (o.invalid === void 0) { o.invalid = invalidTarget; }
if (o.containers === void 0) { o.containers = initialContainers || []; }
if (o.isContainer === void 0) { o.isContainer = never; }
if (o.copy === void 0) { o.copy = false; }
if (o.copySortSource === void 0) { o.copySortSource = false; }
if (o.revertOnSpill === void 0) { o.revertOnSpill = false; }
if (o.removeOnSpill === void 0) { o.removeOnSpill = false; }
if (o.direction === void 0) { o.direction = 'vertical'; }
if (o.ignoreInputTextSelection === void 0) { o.ignoreInputTextSelection = true; }
if (o.mirrorContainer === void 0) { o.mirrorContainer = doc.body; }
var drake = emitter({
containers: o.containers,
start: manualStart,
end: end,
cancel: cancel,
remove: remove,
destroy: destroy,
canMove: canMove,
dragging: false
});
if (o.removeOnSpill === true) {
drake.on('over', spillOver).on('out', spillOut);
}
events();
return drake;
function isContainer (el) {
return drake.containers.indexOf(el) !== -1 || o.isContainer(el);
}
function events (remove) {
var op = remove ? 'remove' : 'add';
touchy(documentElement, op, 'mousedown', grab);
touchy(documentElement, op, 'mouseup', release);
}
function eventualMovements (remove) {
var op = remove ? 'remove' : 'add';
touchy(documentElement, op, 'mousemove', startBecauseMouseMoved);
}
function movements (remove) {
var op = remove ? 'remove' : 'add';
crossvent[op](documentElement, 'selectstart', preventGrabbed); // IE8
crossvent[op](documentElement, 'click', preventGrabbed);
}
function destroy () {
events(true);
release({});
}
function preventGrabbed (e) {
if (_grabbed) {
e.preventDefault();
}
}
function grab (e) {
_moveX = e.clientX;
_moveY = e.clientY;
var ignore = whichMouseButton(e) !== 1 || e.metaKey || e.ctrlKey;
if (ignore) {
return; // we only care about honest-to-god left clicks and touch events
}
var item = e.target;
var context = canStart(item);
if (!context) {
return;
}
_grabbed = context;
eventualMovements();
if (e.type === 'mousedown') {
if (isInput(item)) { // see also: https://github.com/bevacqua/dragula/issues/208
item.focus(); // fixes https://github.com/bevacqua/dragula/issues/176
} else {
e.preventDefault(); // fixes https://github.com/bevacqua/dragula/issues/155
}
}
}
function startBecauseMouseMoved (e) {
if (!_grabbed) {
return;
}
if (whichMouseButton(e) === 0) {
release({});
return; // when text is selected on an input and then dragged, mouseup doesn't fire. this is our only hope
}
// truthy check fixes #239, equality fixes #207
if (e.clientX !== void 0 && e.clientX === _moveX && e.clientY !== void 0 && e.clientY === _moveY) {
return;
}
if (o.ignoreInputTextSelection) {
var clientX = getCoord('clientX', e);
var clientY = getCoord('clientY', e);
var elementBehindCursor = doc.elementFromPoint(clientX, clientY);
if (isInput(elementBehindCursor)) {
return;
}
}
var grabbed = _grabbed; // call to end() unsets _grabbed
eventualMovements(true);
movements();
end();
start(grabbed);
var offset = getOffset(_item);
_offsetX = getCoord('pageX', e) - offset.left;
_offsetY = getCoord('pageY', e) - offset.top;
classes.add(_copy || _item, 'gu-transit');
renderMirrorImage();
drag(e);
}
function canStart (item) {
if (drake.dragging && _mirror) {
return;
}
if (isContainer(item)) {
return; // don't drag container itself
}
var handle = item;
while (getParent(item) && isContainer(getParent(item)) === false) {
if (o.invalid(item, handle)) {
return;
}
item = getParent(item); // drag target should be a top element
if (!item) {
return;
}
}
var source = getParent(item);
if (!source) {
return;
}
if (o.invalid(item, handle)) {
return;
}
var movable = o.moves(item, source, handle, nextEl(item));
if (!movable) {
return;
}
return {
item: item,
source: source
};
}
function canMove (item) {
return !!canStart(item);
}
function manualStart (item) {
var context = canStart(item);
if (context) {
start(context);
}
}
function start (context) {
if (isCopy(context.item, context.source)) {
_copy = context.item.cloneNode(true);
drake.emit('cloned', _copy, context.item, 'copy');
}
_source = context.source;
_item = context.item;
_initialSibling = _currentSibling = nextEl(context.item);
drake.dragging = true;
drake.emit('drag', _item, _source);
}
function invalidTarget () {
return false;
}
function end () {
if (!drake.dragging) {
return;
}
var item = _copy || _item;
drop(item, getParent(item));
}
function ungrab () {
_grabbed = false;
eventualMovements(true);
movements(true);
}
function release (e) {
ungrab();
if (!drake.dragging) {
return;
}
var item = _copy || _item;
var clientX = getCoord('clientX', e);
var clientY = getCoord('clientY', e);
var elementBehindCursor = getElementBehindPoint(_mirror, clientX, clientY);
var dropTarget = findDropTarget(elementBehindCursor, clientX, clientY);
if (dropTarget && ((_copy && o.copySortSource) || (!_copy || dropTarget !== _source))) {
drop(item, dropTarget);
} else if (o.removeOnSpill) {
remove();
} else {
cancel();
}
}
function drop (item, target) {
var parent = getParent(item);
if (_copy && o.copySortSource && target === _source) {
parent.removeChild(_item);
}
if (isInitialPlacement(target)) {
drake.emit('cancel', item, _source, _source);
} else {
drake.emit('drop', item, target, _source, _currentSibling);
}
cleanup();
}
function remove () {
if (!drake.dragging) {
return;
}
var item = _copy || _item;
var parent = getParent(item);
if (parent) {
parent.removeChild(item);
}
drake.emit(_copy ? 'cancel' : 'remove', item, parent, _source);
cleanup();
}
function cancel (revert) {
if (!drake.dragging) {
return;
}
var reverts = arguments.length > 0 ? revert : o.revertOnSpill;
var item = _copy || _item;
var parent = getParent(item);
var initial = isInitialPlacement(parent);
if (initial === false && reverts) {
if (_copy) {
parent.removeChild(_copy);
} else {
_source.insertBefore(item, _initialSibling);
}
}
if (initial || reverts) {
drake.emit('cancel', item, _source, _source);
} else {
drake.emit('drop', item, parent, _source, _currentSibling);
}
cleanup();
}
function cleanup () {
var item = _copy || _item;
ungrab();
removeMirrorImage();
if (item) {
classes.rm(item, 'gu-transit');
}
if (_renderTimer) {
clearTimeout(_renderTimer);
}
drake.dragging = false;
if (_lastDropTarget) {
drake.emit('out', item, _lastDropTarget, _source);
}
drake.emit('dragend', item);
_source = _item = _copy = _initialSibling = _currentSibling = _renderTimer = _lastDropTarget = null;
}
function isInitialPlacement (target, s) {
var sibling;
if (s !== void 0) {
sibling = s;
} else if (_mirror) {
sibling = _currentSibling;
} else {
sibling = nextEl(_copy || _item);
}
return target === _source && sibling === _initialSibling;
}
function findDropTarget (elementBehindCursor, clientX, clientY) {
var target = elementBehindCursor;
while (target && !accepted()) {
target = getParent(target);
}
return target;
function accepted () {
var droppable = isContainer(target);
if (droppable === false) {
return false;
}
var immediate = getImmediateChild(target, elementBehindCursor);
var reference = getReference(target, immediate, clientX, clientY);
var initial = isInitialPlacement(target, reference);
if (initial) {
return true; // should always be able to drop it right back where it was
}
return o.accepts(_item, target, _source, reference);
}
}
function drag (e) {
if (!_mirror) {
return;
}
e.preventDefault();
var clientX = getCoord('clientX', e);
var clientY = getCoord('clientY', e);
var x = clientX - _offsetX;
var y = clientY - _offsetY;
_mirror.style.left = x + 'px';
_mirror.style.top = y + 'px';
var item = _copy || _item;
var elementBehindCursor = getElementBehindPoint(_mirror, clientX, clientY);
var dropTarget = findDropTarget(elementBehindCursor, clientX, clientY);
var changed = dropTarget !== null && dropTarget !== _lastDropTarget;
if (changed || dropTarget === null) {
out();
_lastDropTarget = dropTarget;
over();
}
var parent = getParent(item);
if (dropTarget === _source && _copy && !o.copySortSource) {
if (parent) {
parent.removeChild(item);
}
return;
}
var reference;
var immediate = getImmediateChild(dropTarget, elementBehindCursor);
if (immediate !== null) {
reference = getReference(dropTarget, immediate, clientX, clientY);
} else if (o.revertOnSpill === true && !_copy) {
reference = _initialSibling;
dropTarget = _source;
} else {
if (_copy && parent) {
parent.removeChild(item);
}
return;
}
if (
(reference === null && changed) ||
reference !== item &&
reference !== nextEl(item)
) {
_currentSibling = reference;
dropTarget.insertBefore(item, reference);
drake.emit('shadow', item, dropTarget, _source);
}
function moved (type) { drake.emit(type, item, _lastDropTarget, _source); }
function over () { if (changed) { moved('over'); } }
function out () { if (_lastDropTarget) { moved('out'); } }
}
function spillOver (el) {
classes.rm(el, 'gu-hide');
}
function spillOut (el) {
if (drake.dragging) { classes.add(el, 'gu-hide'); }
}
function renderMirrorImage () {
if (_mirror) {
return;
}
var rect = _item.getBoundingClientRect();
_mirror = _item.cloneNode(true);
_mirror.style.width = getRectWidth(rect) + 'px';
_mirror.style.height = getRectHeight(rect) + 'px';
classes.rm(_mirror, 'gu-transit');
classes.add(_mirror, 'gu-mirror');
o.mirrorContainer.appendChild(_mirror);
touchy(documentElement, 'add', 'mousemove', drag);
classes.add(o.mirrorContainer, 'gu-unselectable');
drake.emit('cloned', _mirror, _item, 'mirror');
}
function removeMirrorImage () {
if (_mirror) {
classes.rm(o.mirrorContainer, 'gu-unselectable');
touchy(documentElement, 'remove', 'mousemove', drag);
getParent(_mirror).removeChild(_mirror);
_mirror = null;
}
}
function getImmediateChild (dropTarget, target) {
var immediate = target;
while (immediate !== dropTarget && getParent(immediate) !== dropTarget) {
immediate = getParent(immediate);
}
if (immediate === documentElement) {
return null;
}
return immediate;
}
function getReference (dropTarget, target, x, y) {
var horizontal = o.direction === 'horizontal';
var reference = target !== dropTarget ? inside() : outside();
return reference;
function outside () { // slower, but able to figure out any position
var len = dropTarget.children.length;
var i;
var el;
var rect;
for (i = 0; i < len; i++) {
el = dropTarget.children[i];
rect = el.getBoundingClientRect();
if (horizontal && (rect.left + rect.width / 2) > x) { return el; }
if (!horizontal && (rect.top + rect.height / 2) > y) { return el; }
}
return null;
}
function inside () { // faster, but only available if dropped inside a child element
var rect = target.getBoundingClientRect();
if (horizontal) {
return resolve(x > rect.left + getRectWidth(rect) / 2);
}
return resolve(y > rect.top + getRectHeight(rect) / 2);
}
function resolve (after) {
return after ? nextEl(target) : target;
}
}
function isCopy (item, container) {
return typeof o.copy === 'boolean' ? o.copy : o.copy(item, container);
}
}
function touchy (el, op, type, fn) {
var touch = {
mouseup: 'touchend',
mousedown: 'touchstart',
mousemove: 'touchmove'
};
var pointers = {
mouseup: 'pointerup',
mousedown: 'pointerdown',
mousemove: 'pointermove'
};
var microsoft = {
mouseup: 'MSPointerUp',
mousedown: 'MSPointerDown',
mousemove: 'MSPointerMove'
};
if (global.navigator.pointerEnabled) {
crossvent[op](el, pointers[type], fn);
} else if (global.navigator.msPointerEnabled) {
crossvent[op](el, microsoft[type], fn);
} else {
crossvent[op](el, touch[type], fn);
crossvent[op](el, type, fn);
}
}
function whichMouseButton (e) {
if (e.touches !== void 0) { return e.touches.length; }
if (e.which !== void 0 && e.which !== 0) { return e.which; } // see https://github.com/bevacqua/dragula/issues/261
if (e.buttons !== void 0) { return e.buttons; }
var button = e.button;
if (button !== void 0) { // see https://github.com/jquery/jquery/blob/99e8ff1baa7ae341e94bb89c3e84570c7c3ad9ea/src/event.js#L573-L575
return button & 1 ? 1 : button & 2 ? 3 : (button & 4 ? 2 : 0);
}
}
function getOffset (el) {
var rect = el.getBoundingClientRect();
return {
left: rect.left + getScroll('scrollLeft', 'pageXOffset'),
top: rect.top + getScroll('scrollTop', 'pageYOffset')
};
}
function getScroll (scrollProp, offsetProp) {
if (typeof global[offsetProp] !== 'undefined') {
return global[offsetProp];
}
if (documentElement.clientHeight) {
return documentElement[scrollProp];
}
return doc.body[scrollProp];
}
function getElementBehindPoint (point, x, y) {
var p = point || {};
var state = p.className;
var el;
p.className += ' gu-hide';
el = doc.elementFromPoint(x, y);
p.className = state;
return el;
}
function never () { return false; }
function always () { return true; }
function getRectWidth (rect) { return rect.width || (rect.right - rect.left); }
function getRectHeight (rect) { return rect.height || (rect.bottom - rect.top); }
function getParent (el) { return el.parentNode === doc ? null : el.parentNode; }
function isInput (el) { return el.tagName === 'INPUT' || el.tagName === 'TEXTAREA' || el.tagName === 'SELECT' || isEditable(el); }
function isEditable (el) {
if (!el) { return false; } // no parents were editable
if (el.contentEditable === 'false') { return false; } // stop the lookup
if (el.contentEditable === 'true') { return true; } // found a contentEditable element in the chain
return isEditable(getParent(el)); // contentEditable is set to 'inherit'
}
function nextEl (el) {
return el.nextElementSibling || manually();
function manually () {
var sibling = el;
do {
sibling = sibling.nextSibling;
} while (sibling && sibling.nodeType !== 1);
return sibling;
}
}
function getEventHost (e) {
// on touchend event, we have to use `e.changedTouches`
// see http://stackoverflow.com/questions/7192563/touchend-event-properties
// see https://github.com/bevacqua/dragula/issues/34
if (e.targetTouches && e.targetTouches.length) {
return e.targetTouches[0];
}
if (e.changedTouches && e.changedTouches.length) {
return e.changedTouches[0];
}
return e;
}
function getCoord (coord, e) {
var host = getEventHost(e);
var missMap = {
pageX: 'clientX', // IE8
pageY: 'clientY' // IE8
};
if (coord in missMap && !(coord in host) && missMap[coord] in host) {
coord = missMap[coord];
}
return host[coord];
}
module.exports = dragula;
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"./classes":1,"contra/emitter":4,"crossvent":8}],3:[function(require,module,exports){
'use strict';
var ticky = require('ticky');
module.exports = function debounce (fn, args, ctx) {
if (!fn) { return; }
ticky(function run () {
fn.apply(ctx || null, args || []);
});
};
},{"ticky":6}],4:[function(require,module,exports){
'use strict';
var atoa = require('atoa');
var debounce = require('./debounce');
module.exports = function emitter (thing, options) {
var opts = options || {};
var evt = {};
if (thing === undefined) { thing = {}; }
thing.on = function (type, fn) {
if (!evt[type]) {
evt[type] = [fn];
} else {
evt[type].push(fn);
}
return thing;
};
thing.once = function (type, fn) {
fn._once = true; // thing.off(fn) still works!
thing.on(type, fn);
return thing;
};
thing.off = function (type, fn) {
var c = arguments.length;
if (c === 1) {
delete evt[type];
} else if (c === 0) {
evt = {};
} else {
var et = evt[type];
if (!et) { return thing; }
et.splice(et.indexOf(fn), 1);
}
return thing;
};
thing.emit = function () {
var args = atoa(arguments);
return thing.emitterSnapshot(args.shift()).apply(this, args);
};
thing.emitterSnapshot = function (type) {
var et = (evt[type] || []).slice(0);
return function () {
var args = atoa(arguments);
var ctx = this || thing;
if (type === 'error' && opts.throws !== false && !et.length) { throw args.length === 1 ? args[0] : args; }
et.forEach(function emitter (listen) {
if (opts.async) { debounce(listen, args, ctx); } else { listen.apply(ctx, args); }
if (listen._once) { thing.off(type, listen); }
});
return thing;
};
};
return thing;
};
},{"./debounce":3,"atoa":5}],5:[function(require,module,exports){
module.exports = function atoa (a, n) { return Array.prototype.slice.call(a, n); }
},{}],6:[function(require,module,exports){
var si = typeof setImmediate === 'function', tick;
if (si) {
tick = function (fn) { setImmediate(fn); };
} else {
tick = function (fn) { setTimeout(fn, 0); };
}
module.exports = tick;
},{}],7:[function(require,module,exports){
(function (global){
var NativeCustomEvent = global.CustomEvent;
function useNative () {
try {
var p = new NativeCustomEvent('cat', { detail: { foo: 'bar' } });
return 'cat' === p.type && 'bar' === p.detail.foo;
} catch (e) {
}
return false;
}
/**
* Cross-browser `CustomEvent` constructor.
*
* https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent.CustomEvent
*
* @public
*/
module.exports = useNative() ? NativeCustomEvent :
// IE >= 9
'function' === typeof document.createEvent ? function CustomEvent (type, params) {
var e = document.createEvent('CustomEvent');
if (params) {
e.initCustomEvent(type, params.bubbles, params.cancelable, params.detail);
} else {
e.initCustomEvent(type, false, false, void 0);
}
return e;
} :
// IE <= 8
function CustomEvent (type, params) {
var e = document.createEventObject();
e.type = type;
if (params) {
e.bubbles = Boolean(params.bubbles);
e.cancelable = Boolean(params.cancelable);
e.detail = params.detail;
} else {
e.bubbles = false;
e.cancelable = false;
e.detail = void 0;
}
return e;
}
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{}],8:[function(require,module,exports){
(function (global){
'use strict';
var customEvent = require('custom-event');
var eventmap = require('./eventmap');
var doc = global.document;
var addEvent = addEventEasy;
var removeEvent = removeEventEasy;
var hardCache = [];
if (!global.addEventListener) {
addEvent = addEventHard;
removeEvent = removeEventHard;
}
module.exports = {
add: addEvent,
remove: removeEvent,
fabricate: fabricateEvent
};
function addEventEasy (el, type, fn, capturing) {
return el.addEventListener(type, fn, capturing);
}
function addEventHard (el, type, fn) {
return el.attachEvent('on' + type, wrap(el, type, fn));
}
function removeEventEasy (el, type, fn, capturing) {
return el.removeEventListener(type, fn, capturing);
}
function removeEventHard (el, type, fn) {
var listener = unwrap(el, type, fn);
if (listener) {
return el.detachEvent('on' + type, listener);
}
}
function fabricateEvent (el, type, model) {
var e = eventmap.indexOf(type) === -1 ? makeCustomEvent() : makeClassicEvent();
if (el.dispatchEvent) {
el.dispatchEvent(e);
} else {
el.fireEvent('on' + type, e);
}
function makeClassicEvent () {
var e;
if (doc.createEvent) {
e = doc.createEvent('Event');
e.initEvent(type, true, true);
} else if (doc.createEventObject) {
e = doc.createEventObject();
}
return e;
}
function makeCustomEvent () {
return new customEvent(type, { detail: model });
}
}
function wrapperFactory (el, type, fn) {
return function wrapper (originalEvent) {
var e = originalEvent || global.event;
e.target = e.target || e.srcElement;
e.preventDefault = e.preventDefault || function preventDefault () { e.returnValue = false; };
e.stopPropagation = e.stopPropagation || function stopPropagation () { e.cancelBubble = true; };
e.which = e.which || e.keyCode;
fn.call(el, e);
};
}
function wrap (el, type, fn) {
var wrapper = unwrap(el, type, fn) || wrapperFactory(el, type, fn);
hardCache.push({
wrapper: wrapper,
element: el,
type: type,
fn: fn
});
return wrapper;
}
function unwrap (el, type, fn) {
var i = find(el, type, fn);
if (i) {
var wrapper = hardCache[i].wrapper;
hardCache.splice(i, 1); // free up a tad of memory
return wrapper;
}
}
function find (el, type, fn) {
var i, item;
for (i = 0; i < hardCache.length; i++) {
item = hardCache[i];
if (item.element === el && item.type === type && item.fn === fn) {
return i;
}
}
}
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"./eventmap":9,"custom-event":7}],9:[function(require,module,exports){
(function (global){
'use strict';
var eventmap = [];
var eventname = '';
var ron = /^on/;
for (eventname in global) {
if (ron.test(eventname)) {
eventmap.push(eventname.slice(2));
}
}
module.exports = eventmap;
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{}]},{},[2])(2)
}); |
const remote = require('electron').remote;
const main = remote.require('./main.js');
const texts = main.getTexts('general');
//const state1Msg = 'Hubo uno o varios problemas, inténtalo de nuevo más tarde o contacta con el administrador a través del correo hector.zaragoza.arranz@gmail.com, ¡no muerdo!';
const state1Msg = texts['messages'].state1Msg;
function confirmDialog(confirmFunction, text) {
swal({
//title: '¿Está seguro de realizar esta operación?',
title: texts['confirmation'].title,
text: text,
type: 'warning',
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
//confirmButtonText: 'Sí, estoy seguro',
confirmButtonText: texts['confirmation'].okBtn,
//cancelButtonText: 'No, sácame de aquí'
cancelButtonText: texts['confirmation'].cancelBtn,
}).then(confirmFunction);
}
|
const expect = require('expect.js')
describe('CJS-build', function() {
it('can be imported', function() {
const theLib = require('../dist/cjs')
expect(theLib).not.to.be(undefined)
})
it('import has content', function() {
const { Schema } = require('../dist/cjs')
expect(Schema).not.to.be(undefined)
})
})
describe('UMD-build', function() {
it('can be imported', function() {
const theLib = require('../dist/umd')
expect(theLib).not.to.be(undefined)
})
it('import has content', function() {
const { Schema } = require('../dist/umd')
expect(Schema).not.to.be(undefined)
})
}) |
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(["require", "exports"], function (require, exports) {
'use strict';
Object.defineProperty(exports, "__esModule", { value: true });
exports.conf = {
comments: {
lineComment: '//',
blockComment: ['/*', '*/'],
},
brackets: [
['{', '}'],
['[', ']'],
['(', ')']
],
autoClosingPairs: [
{ open: '{', close: '}' },
{ open: '[', close: ']' },
{ open: '(', close: ')' },
{ open: '"', close: '"' },
{ open: '\'', close: '\'' },
],
surroundingPairs: [
{ open: '{', close: '}' },
{ open: '[', close: ']' },
{ open: '(', close: ')' },
{ open: '"', close: '"' },
{ open: '\'', close: '\'' },
]
};
exports.language = {
defaultToken: '',
tokenPostfix: '.objective-c',
keywords: [
'#import',
'#include',
'#define',
'#else',
'#endif',
'#if',
'#ifdef',
'#ifndef',
'#ident',
'#undef',
'@class',
'@defs',
'@dynamic',
'@encode',
'@end',
'@implementation',
'@interface',
'@package',
'@private',
'@protected',
'@property',
'@protocol',
'@public',
'@selector',
'@synthesize',
'__declspec',
'assign',
'auto',
'BOOL',
'break',
'bycopy',
'byref',
'case',
'char',
'Class',
'const',
'copy',
'continue',
'default',
'do',
'double',
'else',
'enum',
'extern',
'FALSE',
'false',
'float',
'for',
'goto',
'if',
'in',
'int',
'id',
'inout',
'IMP',
'long',
'nil',
'nonatomic',
'NULL',
'oneway',
'out',
'private',
'public',
'protected',
'readwrite',
'readonly',
'register',
'return',
'SEL',
'self',
'short',
'signed',
'sizeof',
'static',
'struct',
'super',
'switch',
'typedef',
'TRUE',
'true',
'union',
'unsigned',
'volatile',
'void',
'while',
],
decpart: /\d(_?\d)*/,
decimal: /0|@decpart/,
tokenizer: {
root: [
{ include: '@comments' },
{ include: '@whitespace' },
{ include: '@numbers' },
{ include: '@strings' },
[/[,:;]/, 'delimiter'],
[/[{}\[\]()<>]/, '@brackets'],
[/[a-zA-Z@#]\w*/, {
cases: {
'@keywords': 'keyword',
'@default': 'identifier'
}
}],
[/[<>=\\+\\-\\*\\/\\^\\|\\~,]|and\\b|or\\b|not\\b]/, 'operator'],
],
whitespace: [
[/\s+/, 'white'],
],
comments: [
['\\/\\*', 'comment', '@comment'],
['\\/\\/+.*', 'comment'],
],
comment: [
['\\*\\/', 'comment', '@pop'],
['.', 'comment',],
],
numbers: [
[/0[xX][0-9a-fA-F]*(_?[0-9a-fA-F])*/, 'number.hex'],
[/@decimal((\.@decpart)?([eE][\-+]?@decpart)?)[fF]*/, {
cases: {
'(\\d)*': 'number',
'$0': 'number.float'
}
}]
],
// Recognize strings, including those broken across lines with \ (but not without)
strings: [
[/'$/, 'string.escape', '@popall'],
[/'/, 'string.escape', '@stringBody'],
[/"$/, 'string.escape', '@popall'],
[/"/, 'string.escape', '@dblStringBody']
],
stringBody: [
[/[^\\']+$/, 'string', '@popall'],
[/[^\\']+/, 'string'],
[/\\./, 'string'],
[/'/, 'string.escape', '@popall'],
[/\\$/, 'string']
],
dblStringBody: [
[/[^\\"]+$/, 'string', '@popall'],
[/[^\\"]+/, 'string'],
[/\\./, 'string'],
[/"/, 'string.escape', '@popall'],
[/\\$/, 'string']
]
}
};
});
|
// flow-typed signature: b53256ed2969efa65cf5a334cc66b9cf
// flow-typed version: <<STUB>>/eslint-formatter-pretty_v^1.1.0/flow_v0.48.0
/**
* This is an autogenerated libdef stub for:
*
* 'eslint-formatter-pretty'
*
* Fill this stub out by replacing all the `any` types.
*
* Once filled out, we encourage you to share your work with the
* community by sending a pull request to:
* https://github.com/flowtype/flow-typed
*/
declare module 'eslint-formatter-pretty' {
declare module.exports: any;
}
/**
* We include stubs for each file inside this npm package in case you need to
* require those files directly. Feel free to delete any files that aren't
* needed.
*/
// Filename aliases
declare module 'eslint-formatter-pretty/index' {
declare module.exports: $Exports<'eslint-formatter-pretty'>;
}
declare module 'eslint-formatter-pretty/index.js' {
declare module.exports: $Exports<'eslint-formatter-pretty'>;
}
|
Core = {};
Core.Schemas = {};
Core.Helpers = {};
_.extend(Core, {
/**
* Core.schemaIdAutoValue
* @summary used for schemea injection autoValue
* @example autoValue: Core.schemaIdAutoValue
* @return {String} returns randomId
*/
schemaIdAutoValue: function () {
if (this.isSet && Meteor.isServer) {
return this.value;
} else if (Meteor.isServer || Meteor.isClient && this.isInsert) {
return Random.id();
}
return this.unset();
}
})
|
/* global location */
/* Centralized place to reference utilities since utils is exposed to the user. */
var debug = require('./debug');
var deepAssign = require('deep-assign');
var device = require('./device');
var objectAssign = require('object-assign');
var objectPool = require('./object-pool');
var warn = debug('utils:warn');
module.exports.bind = require('./bind');
module.exports.coordinates = require('./coordinates');
module.exports.debug = debug;
module.exports.device = device;
module.exports.entity = require('./entity');
module.exports.forceCanvasResizeSafariMobile = require('./forceCanvasResizeSafariMobile');
module.exports.material = require('./material');
module.exports.objectPool = objectPool;
module.exports.styleParser = require('./styleParser');
module.exports.trackedControls = require('./tracked-controls');
module.exports.checkHeadsetConnected = function () {
warn('`utils.checkHeadsetConnected` has moved to `utils.device.checkHeadsetConnected`');
return device.checkHeadsetConnected(arguments);
};
module.exports.isGearVR = function () {
warn('`utils.isGearVR` has moved to `utils.device.isGearVR`');
return device.isGearVR(arguments);
};
module.exports.isIOS = function () {
warn('`utils.isIOS` has moved to `utils.device.isIOS`');
return device.isIOS(arguments);
};
module.exports.isMobile = function () {
warn('`utils.isMobile has moved to `utils.device.isMobile`');
return device.isMobile(arguments);
};
/**
* Returns throttle function that gets called at most once every interval.
*
* @param {function} functionToThrottle
* @param {number} minimumInterval - Minimal interval between calls (milliseconds).
* @param {object} optionalContext - If given, bind function to throttle to this context.
* @returns {function} Throttled function.
*/
module.exports.throttle = function (functionToThrottle, minimumInterval, optionalContext) {
var lastTime;
if (optionalContext) {
functionToThrottle = module.exports.bind(functionToThrottle, optionalContext);
}
return function () {
var time = Date.now();
var sinceLastTime = typeof lastTime === 'undefined' ? minimumInterval : time - lastTime;
if (typeof lastTime === 'undefined' || (sinceLastTime >= minimumInterval)) {
lastTime = time;
functionToThrottle.apply(null, arguments);
}
};
};
/**
* Returns throttle function that gets called at most once every interval.
* Uses the time/timeDelta timestamps provided by the global render loop for better perf.
*
* @param {function} functionToThrottle
* @param {number} minimumInterval - Minimal interval between calls (milliseconds).
* @param {object} optionalContext - If given, bind function to throttle to this context.
* @returns {function} Throttled function.
*/
module.exports.throttleTick = function (functionToThrottle, minimumInterval, optionalContext) {
var lastTime;
if (optionalContext) {
functionToThrottle = module.exports.bind(functionToThrottle, optionalContext);
}
return function (time, delta) {
var sinceLastTime = typeof lastTime === 'undefined' ? delta : time - lastTime;
if (typeof lastTime === 'undefined' || (sinceLastTime >= minimumInterval)) {
lastTime = time;
functionToThrottle(time, sinceLastTime);
}
};
};
/**
* Returns debounce function that gets called only once after a set of repeated calls.
*
* @param {function} functionToDebounce
* @param {number} wait - Time to wait for repeated function calls (milliseconds).
* @param {boolean} immediate - Calls the function immediately regardless of if it should be waiting.
* @returns {function} Debounced function.
*/
module.exports.debounce = function (func, wait, immediate) {
var timeout;
return function () {
var context = this;
var args = arguments;
var later = function () {
timeout = null;
if (!immediate) func.apply(context, args);
};
var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) func.apply(context, args);
};
};
/**
* Mix the properties of source object(s) into a destination object.
*
* @param {object} dest - The object to which properties will be copied.
* @param {...object} source - The object(s) from which properties will be copied.
*/
module.exports.extend = objectAssign;
module.exports.extendDeep = deepAssign;
module.exports.clone = function (obj) {
return JSON.parse(JSON.stringify(obj));
};
/**
* Checks if two values are equal.
* Includes objects and arrays and nested objects and arrays.
* Try to keep this function performant as it will be called often to see if a component
* should be updated.
*
* @param {object} a - First object.
* @param {object} b - Second object.
* @returns {boolean} Whether two objects are deeply equal.
*/
var deepEqual = (function () {
var arrayPool = objectPool.createPool(function () { return []; });
return function (a, b) {
var key;
var keysA;
var keysB;
var i;
var valA;
var valB;
// If not objects or arrays, compare as values.
if (a === undefined || b === undefined || a === null || b === null ||
!(a && b && (a.constructor === Object && b.constructor === Object) ||
(a.constructor === Array && b.constructor === Array))) {
return a === b;
}
// Different number of keys, not equal.
keysA = arrayPool.use();
keysB = arrayPool.use();
keysA.length = 0;
keysB.length = 0;
for (key in a) { keysA.push(key); }
for (key in b) { keysB.push(key); }
if (keysA.length !== keysB.length) {
arrayPool.recycle(keysA);
arrayPool.recycle(keysB);
return false;
}
// Return `false` at the first sign of inequality.
for (i = 0; i < keysA.length; ++i) {
valA = a[keysA[i]];
valB = b[keysA[i]];
// Check nested array and object.
if ((typeof valA === 'object' || typeof valB === 'object') ||
(Array.isArray(valA) && Array.isArray(valB))) {
if (valA === valB) { continue; }
if (!deepEqual(valA, valB)) {
arrayPool.recycle(keysA);
arrayPool.recycle(keysB);
return false;
}
} else if (valA !== valB) {
arrayPool.recycle(keysA);
arrayPool.recycle(keysB);
return false;
}
}
arrayPool.recycle(keysA);
arrayPool.recycle(keysB);
return true;
};
})();
module.exports.deepEqual = deepEqual;
/**
* Computes the difference between two objects.
*
* @param {object} a - First object to compare (e.g., oldData).
* @param {object} b - Second object to compare (e.g., newData).
* @returns {object}
* Difference object where set of keys note which values were not equal, and values are
* `b`'s values.
*/
module.exports.diff = (function () {
var keys = [];
return function (a, b, targetObject) {
var aVal;
var bVal;
var bKey;
var diff;
var key;
var i;
var isComparingObjects;
diff = targetObject || {};
// Collect A keys.
keys.length = 0;
for (key in a) { keys.push(key); }
if (!b) { return diff; }
// Collect B keys.
for (bKey in b) {
if (keys.indexOf(bKey) === -1) {
keys.push(bKey);
}
}
for (i = 0; i < keys.length; i++) {
key = keys[i];
aVal = a[key];
bVal = b[key];
isComparingObjects = aVal && bVal &&
aVal.constructor === Object && bVal.constructor === Object;
if ((isComparingObjects && !deepEqual(aVal, bVal)) ||
(!isComparingObjects && aVal !== bVal)) {
diff[key] = bVal;
}
}
return diff;
};
})();
/**
* Returns whether we should capture this keyboard event for keyboard shortcuts.
* @param {Event} event Event object.
* @returns {Boolean} Whether the key event should be captured.
*/
module.exports.shouldCaptureKeyEvent = function (event) {
if (event.metaKey) { return false; }
return document.activeElement === document.body;
};
/**
* Splits a string into an array based on a delimiter.
*
* @param {string=} [str=''] Source string
* @param {string=} [delimiter=' '] Delimiter to use
* @returns {array} Array of delimited strings
*/
module.exports.splitString = function (str, delimiter) {
if (typeof delimiter === 'undefined') { delimiter = ' '; }
// First collapse the whitespace (or whatever the delimiter is).
var regex = new RegExp(delimiter, 'g');
str = (str || '').replace(regex, delimiter);
// Then split.
return str.split(delimiter);
};
/**
* Extracts data from the element given an object that contains expected keys.
*
* @param {Element} Source element.
* @param {Object} [defaults={}] Object of default key-value pairs.
* @returns {Object}
*/
module.exports.getElData = function (el, defaults) {
defaults = defaults || {};
var data = {};
Object.keys(defaults).forEach(copyAttribute);
function copyAttribute (key) {
if (el.hasAttribute(key)) {
data[key] = el.getAttribute(key);
}
}
return data;
};
/**
* Retrieves querystring value.
* @param {String} name Name of querystring key.
* @return {String} Value
*/
module.exports.getUrlParameter = function (name) {
// eslint-disable-next-line no-useless-escape
name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
var regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
var results = regex.exec(location.search);
return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '));
};
/**
* Detects whether context is within iframe.
*/
module.exports.isIframed = function () {
return window.top !== window.self;
};
/**
* Finds all elements under the element that have the isScene
* property set to true
*/
module.exports.findAllScenes = function (el) {
var matchingElements = [];
var allElements = el.getElementsByTagName('*');
for (var i = 0, n = allElements.length; i < n; i++) {
if (allElements[i].isScene) {
// Element exists with isScene set.
matchingElements.push(allElements[i]);
}
}
return matchingElements;
};
// Must be at bottom to avoid circular dependency.
module.exports.srcLoader = require('./src-loader');
/**
* String split with cached result.
*/
module.exports.split = (function () {
var splitCache = {};
return function (str, delimiter) {
if (!(delimiter in splitCache)) { splitCache[delimiter] = {}; }
if (str in splitCache[delimiter]) { return splitCache[delimiter][str]; }
splitCache[delimiter][str] = str.split(delimiter);
return splitCache[delimiter][str];
};
})();
|
function set_filter_toolbar(select) {
var textarea = select.up('div').down('textarea').readAttribute('id');
var toolbar = textarea + '_toolbar';
var filter = select.getValue();
if (Control.TextArea.ToolBar[filter] != null) {
remove();
if (filter) {
var tb = new Control.TextArea.ToolBar[filter](textarea, {
assets: typeof(Asset) != undefined ? true : false,
preview: true
});
tb.toolbar.container.id = toolbar;
// Allow for Papperclipped Asset Manager extension
if (typeof(Asset) != undefined) {
Event.addBehavior({ 'a.filter_image_button' : Asset.ShowBucket });
};
}
} else {
remove();
}
function remove() {
if ($(toolbar) != null) {
$(toolbar).remove();
}
}
}
document.observe('dom:loaded', function() {
$$('#pages select').each( function(el) {
el.observe('change', function(e) {
set_filter_toolbar(el);
})
set_filter_toolbar(el);
});
}); |
Package.describe({
version: '0.1.2',
summary: "Rig the basics for packmeteor"
});
Package.on_use(function (api) {
api.use('webapp', 'server');
api.use('reload', 'client');
api.use('routepolicy', 'server');
api.use('underscore', 'server');
api.use('autoupdate', 'server', {weak: true});
api.export('Packmeteor');
api.use('deps', 'client');
api.add_files('meteor/packmeteor-client.js', 'client');
api.add_files('meteor/packmeteor-server.js', 'server');
});
|
var browserSync = require('browser-sync');
var changed = require('gulp-changed');
var config = require('../config').images;
var gulp = require('gulp');
var imagemin = require('gulp-imagemin');
gulp.task('images', function() {
return gulp.src(config.src)
.pipe(changed(config.dest)) // Ignore unchanged files
.pipe(imagemin()) // Optimize
.pipe(gulp.dest(config.dest))
.pipe(browserSync.reload({stream:true}));
});
|
import Vue from 'vue'
import Router from 'vue-router'
import Home from '@/pages/home'
import About from '@/pages/about'
import Contact from '@/pages/contact'
import Technology from '@/pages/technology'
import c02 from '@/pages/c02'
import c03 from '@/pages/c03'
import solar from '@/pages/solar'
import factory from '@/pages/factory'
Vue.use(Router)
export default new Router({
routes: [
{
path: '/',
name: 'Home',
component: Home
},
{
path: '/about',
name: 'About',
component: About
},
{
path: '/contact',
name: 'Contact',
component: Contact
},
{
path: '/technology',
name: 'Technology',
component: Technology
},
{
path: '/c02',
name: 'c02',
component: c02
},
{
path: '/c03',
name: 'c03',
component: c03
},
{
path: '/solar',
name: 'solar',
component: solar
},
{
path: '/factory',
name: 'factory',
component: factory
},
]
})
|
/**
* The (inherited) "widget-select" module.
*
* Topics subscribed : "color:add"
* Topics published : "color:preset"
*/
TinyCore.Module.inherit( 'widget-generic', 'widget-select', ['mediator'], function ( _mediator )
{
// The module.
return {
/**
* Topics to automatically subscribe to.
* @type {Object}
*/
topics : {
'color:add' : function ( oTopic )
{
var sNewOptionValue = oTopic.data.text.toLowerCase(),
sNewOption = sNewOptionValue.charAt( 0 ).toUpperCase() + sNewOptionValue.slice( 1 ),
oNewOption = document.createElement( 'option' );
this.logActivity( 'widget-select', '"'+oTopic.name+'" received ('+oTopic.data.text+')' );
oNewOption.value = sNewOptionValue;
oNewOption.text = sNewOption;
this.select.appendChild( oNewOption );
}
},
/**
* Events to automatically add listeners to.
* @type {Object}
*/
events : {
'change select' : function ( eEvent )
{
var oSelectedOption = this.select.options[this.select.selectedIndex],
sText = oSelectedOption.value !== '' ? oSelectedOption.text : '';
this.logActivity( 'widget-select', 'change on select' );
_mediator.publish( 'color:preset', {
value : oSelectedOption.value,
text : sText
} );
}
},
/**
* The select.
* @type {DOM Element}
*/
select : document.getElementById( 'select-input' ),
/**
* This method is called when the module is started.
* @param {Object} oStartData The start data.
*/
onStart : function ( oStartData )
{
this.logActivity( 'widget-select', 'onStart' );
this._super( oStartData );
},
/**
* This method is called when the module is stopped.
*/
onStop : function ()
{
this.logActivity( 'widget-select', 'onStop' );
this._super();
}
};
} );
|
var express = require('express');
var fs = require('fs');
var Mustache = require('mustache');
var jsforce = require('jsforce');
var app = express();
app.listen(9000);
app.get('/', function(req, res) {
var METRICS = [{
reportid: '', username: '', password: '', loginurl: 'https://na1.salesforce.com', chart: 'pie'}, // chart = pie, bar or table
{ reportid: '', username: '', password: '', loginurl: 'https://na1.salesforce.com', chart: 'bar'} ];
function getReportResults(metric, callback) {
var conn = new jsforce.Connection({
loginUrl: metric.loginurl
});
conn.login(metric.username, metric.password, function(err, resp) {
var report = conn.analytics.report(metric.reportid);
report.executeAsync(function(err, instance) {
var pollToComplete = function() {
report.instance(instance.id).retrieve(function(err, result) {
if (result.attributes.status == 'Success')
callback(result);
else
pollToComplete();
});
};
pollToComplete();
});
});
}
var result = [];
var afterResult = function(reportResult) {
reportResult.id = result.length;
reportResult.chart = METRICS[result.length].chart;
result.push(reportResult);
if (result.length < METRICS.length) {
getReportResults(METRICS[result.length], afterResult);
} else {
fs.readFile('./template.mst', function(err, data) {
res.write(Mustache.render(data.toString(), {
data: result,
string: JSON.stringify(result)
}));
res.end();
});
}
};
getReportResults(METRICS[0], afterResult);
});
|
/**
* Created by nickrickenbach on 8/11/15.
*/
var app = angular.module('BLANG', ['ngRoute', 'ngResource', 'ngSanitize', 'angularSpinner']);
app.config(['$routeProvider', '$locationProvider', function ($routeProvider, $locationProvider) {
$routeProvider
.when('/', {
templateUrl: 'views/home.html',
controller: HomeController,
resolve: HomeController.resolve
})
.when('/home', {
templateUrl: 'views/home.html',
controller: HomeController,
resolve: HomeController.resolve
})
.when('/projects', {
templateUrl: 'views/projects.html',
controller: ProjectsController,
resolve: WorkController.resolve
})
.when('/projects/:project', {
templateUrl: 'views/project.html',
controller: ProjectController,
resolve: WorkController.resolve
})
.otherwise({
redirectTo: '/'
});
//$locationProvider.html5Mode(true);
}]);
app.run(['$rootScope', 'usSpinnerService', function ($rootScope, usSpinnerService) {
$rootScope.startSpin = function (_spin) {
usSpinnerService.spin(_spin);
};
$rootScope.stopSpin = function (_spin) {
usSpinnerService.stop(_spin);
};
}]);
app.run(['$route', '$rootScope', '$location', function ($route, $rootScope, $location, $urlRouter) {
$rootScope.$on('$routeChangeStart', function (event, next, current) {
});
}]);
app.directive('workimg',function(){
return {
restrict: 'A',
link: function(scope, element, attrs) {
console.log('found');
element.find('img.bg-img-hide').bind('load', function() {
element.removeClass("inactive");
//TweenMax.to(element,1,{opacity:1});
TweenMax.to(element.parent().parent().find(".spinner"),1,{opacity:0});
$(".site").scroll($rootScope.workScroll);
});
}
};
});
function getResolve(_url) {
return {
datasets : function ($rootScope, $q, $http, $location, $route) {
_url = ($route.current.params.project) ? _url+"&project="+$route.current.params.project : _url;
if (TweenMax) {
// showLoader
TweenMax.to($('#main-overlay'), 0.2, { autoAlpha:1 });
TweenMax.set($('#main-overlay').find('span'), {
marginTop:'0',
opacity:0,
rotationX:90
});
TweenMax.to($('#main-overlay').find('span'), 0.5, {
marginTop:'-65px',
rotationX:0,
opacity:1,
ease:'Cubic.easeInOut',
delay:0.2
});
// start Spinner
$rootScope.startSpin('spinner-main');
var deferred = $q.defer();
TweenMax.to($(".site"),0.5,{scrollTop:0,onComplete:function() {
$http.get(_url).
success(function (data, status, headers, config) {
// hide Loader
TweenMax.to($('#main-overlay'), 0.5, {autoAlpha: 0});
TweenMax.to($('#main-overlay').find('span'), 0.5, {
marginTop: '-130px',
rotationZ: -180,
ease: 'Cubic.easeInOut'
});
deferred.resolve(data);
}).
error(function (data, status, headers, config) {
// hide Loader
TweenMax.to($('#main-overlay'), 0.5, {autoAlpha: 0});
TweenMax.to($('#main-overlay').find('span'), 0.5, {
marginTop: '-130px',
rotationZ: -180,
ease: 'Cubic.easeInOut'
});
deferred.resolve('error')
});
}});
return deferred.promise;
}else {
setTimeout(function () {
getResolve(_url);
}, 200);
}
}
}
}
|
'use strict';
/**
* NodeWithGraph
* =============
*/
const path = require('path');
const inherit = require('inherit');
const Node = require('./node');
module.exports = inherit(Node, {
__constructor(nodePath, makePlatform, cache, graph) {
this.__base(nodePath, makePlatform, cache);
/**
* Построитель графа сборки.
* @type {BuildGraph}
* @name NodeWithGraph.prototype._graph
* @private
*/
this._graph = graph;
},
_initTech(tech) {
const _this = this;
const NodeAdapter = function () {};
NodeAdapter.prototype = _this;
const nodeAdapter = new NodeAdapter();
tech.init(nodeAdapter);
const targets = tech.getTargets();
targets.forEach(target => {
const targetPath = path.join(_this._path, target);
_this._graph.addTarget(targetPath, tech.getName());
});
nodeAdapter.requireSources = sources => _this.requireSources(sources, targets);
nodeAdapter.requireNodeSources = sources => _this.requireNodeSources(sources, targets);
},
requireSources(sources, targets) {
const _this = this;
this._addDepsToGraph(targets, sources, source => path.join(_this._path, _this.unmaskTargetName(source)));
return Node.prototype.requireSources.apply(this, arguments);
},
requireNodeSources(sources, targets) {
Object.keys(sources).forEach(nodeName => {
const nodeSources = sources[nodeName];
this._addDepsToGraph(targets, nodeSources, (source) => {
return path.join(nodeName, this.unmaskNodeTargetName(nodeName, source));
});
});
return Node.prototype.requireNodeSources.apply(this, arguments);
},
_addDepsToGraph(targets, sources, getDepFromPath) {
const _this = this;
targets = targets || [];
targets.forEach(target => {
const targetPath = path.join(_this._path, target);
sources.forEach(source => {
_this._graph.addDep(
targetPath,
getDepFromPath(source)
);
});
});
},
resolveTarget(target) {
this._graph.resolveTarget(path.join(this._path, target));
return Node.prototype.resolveTarget.apply(this, arguments);
},
destruct() {
this.__base();
delete this._graph;
}
});
|
alert('loaded'); |
import React, { Component } from 'react';
import { AppRegistry } from 'react-native';
import App from './src/App';
export default class reactNativeComponentes extends Component {
render() {
return(
<App />
)
}
}
AppRegistry.registerComponent('reactNativeComponentes', () => reactNativeComponentes);
|
import createSvgIcon from './utils/createSvgIcon';
import { jsx as _jsx } from "react/jsx-runtime";
export default createSvgIcon( /*#__PURE__*/_jsx("path", {
d: "M20 8h-3V6.21c0-2.61-1.91-4.94-4.51-5.19C9.51.74 7 3.08 7 6h2c0-1.13.6-2.24 1.64-2.7C12.85 2.31 15 3.9 15 6v2H4v14h16V8zm-2 12H6V10h12v10zm-6-3c1.1 0 2-.9 2-2s-.9-2-2-2-2 .9-2 2 .9 2 2 2z"
}), 'LockOpenSharp'); |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.