Commit 5fa223d6 by Иван Кубота

to QRequire format

parent 643be830
.idea/*
.idea/
node_modules/*
var ObservableSequence = require('observable-sequence'); module.exports =
var DQIndex = require('z-lib-structure-dqIndex'); QRequire('observable-sequence', 'z-lib-structure-dqIndex', 'Core.QObject', function(
ObservableSequence,
var QObject = require('./QObject'); DQIndex,
QObject
/** @class */ ){
var AbstractComponent = QObject.extend('Core', 'AbstractComponent', 'use strict';
{ /** @class */
addChild: function (component) { var AbstractComponent = QObject.extend('Core', 'AbstractComponent',
this._children.push(component); {
return this; addChild: function (component) {
}, this._children.push(component);
return this;
/** },
* Bind to this._children.on('add'...)
* /**
* @param {AbstractComponent} child * Bind to this._children.on('add'...)
* @returns {void} *
*/ * @param {AbstractComponent} child
_onChildAdd: function (child) { * @returns {void}
child.parent = this; */
}, _onChildAdd: function (child) {
child.parent = this;
/** },
* Bind to this._children.on('remove'...)
* /**
* @param {AbstractComponent} child * Bind to this._children.on('remove'...)
* @returns {void} *
*/ * @param {AbstractComponent} child
_onChildRemove: function (child) { * @returns {void}
child.parent = null; */
}, _onChildRemove: function (child) {
child.parent = null;
/** },
* Bind to this._ownComponents.on('add'...)
* /**
* @param {AbstractComponent} child * Bind to this._ownComponents.on('add'...)
* @returns {void} *
*/ * @param {AbstractComponent} child
_onOwnComponentAdd: function (child) { * @returns {void}
child.parent = this; */
}, _onOwnComponentAdd: function (child) {
child.parent = this;
/** },
* Bind to this._ownComponents.on('remove'...)
* /**
* @param {AbstractComponent} child * Bind to this._ownComponents.on('remove'...)
* @returns {void} *
*/ * @param {AbstractComponent} child
_onOwnComponentRemove: function (child) { * @returns {void}
child.parent = null; */
//should not be called _onOwnComponentRemove: function (child) {
}, child.parent = null;
//should not be called
_getAllChildren: function(type){ },
var iterator = this._children.iterator(), item, items = [];
while (item = iterator.next()) { _getAllChildren: function(type){
if (item instanceof type) var iterator = this._children.iterator(), item, items = [];
items.push(item); while (item = iterator.next()) {
} if (item instanceof type)
items.push(item);
iterator = this._ownComponents.iterator(); }
while (item = iterator.next()) {
if (item instanceof type) iterator = this._ownComponents.iterator();
items.push(item); while (item = iterator.next()) {
} if (item instanceof type)
items.push(item);
return items; }
},
return items;
'~destroy': function(){ },
var children = this._getAllChildren(AbstractComponent), i, _i,
child; '~destroy': function(){
for( i = 0, _i = children.length; i < _i; i++ ){ var children = this._getAllChildren(AbstractComponent), i, _i,
child = children[i]; child;
if(typeof child['~destroy'] === 'function') for( i = 0, _i = children.length; i < _i; i++ ){
child['~destroy'](); child = children[i];
if(typeof child['~destroy'] === 'function')
child['~destroy']();
}
this.fire('~destroy');
},
_prop: {
id: null
} }
this.fire('~destroy');
}, },
_prop: {
id: null
}
},
/**
* @constructs AbstractComponent
*/
function () {
/**
* Own Components
*
* @type {AbstractComponent[]}
* @private
*/
this._ownComponents = new ObservableSequence(new DQIndex('id'));
this._ownComponents.on('add', this._onOwnComponentAdd.bind(this));
this._ownComponents.on('remove', this._onOwnComponentRemove.bind(this));
/** /**
* Child Components * @constructs AbstractComponent
*
* @type {AbstractComponent[]}
* @private
*/ */
this._children = new ObservableSequence(new DQIndex('id')); function () {
this._children.on('add', this._onChildAdd.bind(this));
this._children.on('remove', this._onChildRemove.bind(this)); /**
* Own Components
this.parent = null; *
}); * @type {AbstractComponent[]}
* @private
module.exports = AbstractComponent; */
\ No newline at end of file this._ownComponents = new ObservableSequence(new DQIndex('id'));
this._ownComponents.on('add', this._onOwnComponentAdd.bind(this));
this._ownComponents.on('remove', this._onOwnComponentRemove.bind(this));
/**
* Child Components
*
* @type {AbstractComponent[]}
* @private
*/
this._children = new ObservableSequence(new DQIndex('id'));
this._children.on('add', this._onChildAdd.bind(this));
this._children.on('remove', this._onChildRemove.bind(this));
this.parent = null;
});
return AbstractComponent;
});
\ No newline at end of file
...@@ -5,178 +5,182 @@ ...@@ -5,178 +5,182 @@
*/ */
;// QUOKKA 2017 ;// QUOKKA 2017
// By zibx on 5/18/17. // By zibx on 5/18/17.
module.exports =
QRequire('Core.QObject', function(
QObject
) {
var Time = function (val) {
var may = new Date(val),
isValid = !isNaN(may.getDate());
if (isValid) {
may = new Date(may - may.getTimezoneOffset() * 60 * 1000);
this.hours = may.getHours();
this.minutes = may.getMinutes();
this.seconds = may.getSeconds();
} else if (typeof val === 'string') {
var tokens = val.split(':');
var QObject = require('./QObject'); this.hours = tokens[0] | 0;
var Time = function(val){ if (tokens.length > 1) {
var may = new Date(val), this.minutes = tokens[1] | 0;
isValid = !isNaN(may.getDate()); }
if(isValid){ if (tokens.length > 2) {
may = new Date(may-may.getTimezoneOffset()*60*1000); this.seconds = tokens[2] | 0;
this.hours = may.getHours(); }
this.minutes = may.getMinutes(); } else if (val !== void 0) {
this.seconds = may.getSeconds(); this.valid = false;
}else if(typeof val === 'string'){ }
var tokens = val.split(':'); };
Time.prototype = {
hours: 0,
minutes: 0,
seconds: 0,
valid: true,
le: function () {
this.hours = tokens[0]|0; },
if(tokens.length > 1) { ge: function () {
this.minutes = tokens[1] | 0;
}
if(tokens.length > 2) {
this.seconds = tokens[2] | 0;
}
}else if(val !== void 0){
this.valid = false;
}
};
Time.prototype = {
hours: 0,
minutes: 0,
seconds: 0,
valid: true,
le: function(){
},
ge: function(){
},
getSeconds: function(){
return this.seconds + this.minutes * 60 + this.hours * 60 * 60;
}
};
/** @class */ },
var Commission = QObject.extend('Core', 'Commission', { getSeconds: function () {
ctor: function () { return this.seconds + this.minutes * 60 + this.hours * 60 * 60;
}
};
}, /** @class */
calc: function (cfg) { var Commission = QObject.extend('Core', 'Commission', {
!('rules' in cfg) && (cfg.rules = this.get('rules')); ctor: function () {
!('amount' in cfg) && (cfg.amount = this.get('amount'));
!('up' in cfg) && (cfg.up = this.get('up')); },
!('date' in cfg) && (cfg.date = this.get('date')); calc: function (cfg) {
if(!cfg.date){ !('rules' in cfg) && (cfg.rules = this.get('rules'));
cfg.date = new Date(); !('amount' in cfg) && (cfg.amount = this.get('amount'));
cfg.date = new Date((+cfg.date)-cfg.date.getTimezoneOffset()*60*1000); !('up' in cfg) && (cfg.up = this.get('up'));
}else{ !('date' in cfg) && (cfg.date = this.get('date'));
cfg.date = new Date(cfg.date); if (!cfg.date) {
cfg.date = new Date((+cfg.date)+cfg.date.getTimezoneOffset()*60*1000); cfg.date = new Date();
} cfg.date = new Date((+cfg.date) - cfg.date.getTimezoneOffset() * 60 * 1000);
if(cfg.rules && cfg.amount){ } else {
var matched = cfg.rules.filter(function(rule){ cfg.date = new Date(cfg.date);
var fromTime, toTime, fromDate, toDate; cfg.date = new Date((+cfg.date) + cfg.date.getTimezoneOffset() * 60 * 1000);
if('fromTime' in rule){
fromTime = new Time(rule.fromTime);
if('toTime' in rule){
toTime = new Time(rule.toTime);
}else{
toTime = new Time('23:59:59');
}
}else if('toTime' in rule){
fromTime = new Time();
toTime = new Time(rule.toTime);
}
if(
fromTime && fromTime.valid &&
toTime && toTime.valid
){
var date = cfg.date;
var dateSeconds = date.getSeconds() + date.getMinutes() * 60 + date.getHours() * 60 * 60;
if(fromTime.getSeconds() < toTime.getSeconds()){
if(
fromTime.getSeconds() <= dateSeconds &&
toTime.getSeconds() >= dateSeconds
)
return true;
}else{
if(
toTime.getSeconds() >= dateSeconds ||
fromTime.getSeconds() <= dateSeconds
)
return true;
}
return false;
} }
return true; if (cfg.rules && cfg.amount) {
}); var matched = cfg.rules.filter(function (rule) {
if(matched.length){ var fromTime, toTime, fromDate, toDate;
var rule = matched[0], if ('fromTime' in rule) {
result = {}; fromTime = new Time(rule.fromTime);
if ('toTime' in rule) {
toTime = new Time(rule.toTime);
} else {
toTime = new Time('23:59:59');
}
} else if ('toTime' in rule) {
fromTime = new Time();
toTime = new Time(rule.toTime);
}
if (
fromTime && fromTime.valid &&
toTime && toTime.valid
) {
var date = cfg.date;
var dateSeconds = date.getSeconds() + date.getMinutes() * 60 + date.getHours() * 60 * 60;
if (fromTime.getSeconds() < toTime.getSeconds()) {
if (
fromTime.getSeconds() <= dateSeconds &&
toTime.getSeconds() >= dateSeconds
)
return true;
} else {
if (
toTime.getSeconds() >= dateSeconds ||
fromTime.getSeconds() <= dateSeconds
)
return true;
}
return false;
}
return true;
});
if (matched.length) {
var rule = matched[0],
result = {};
if(cfg.up){ if (cfg.up) {
result.commission = cfg.amount*rule.percent/100; result.commission = cfg.amount * rule.percent / 100;
if(rule.min) { if (rule.min) {
if(result.commission < rule.min){ if (result.commission < rule.min) {
console.log('Percent is smaller than min commission ('+[result.commission, rule.min]+')') console.log('Percent is smaller than min commission (' + [result.commission, rule.min] + ')')
result.commission = rule.min; result.commission = rule.min;
} }
} }
if(rule.max){ if (rule.max) {
if(result.commission > rule.max){ if (result.commission > rule.max) {
console.log('Percent is greater than max commission ('+[result.commission, rule.max]+')') console.log('Percent is greater than max commission (' + [result.commission, rule.max] + ')')
result.commission = rule.max; result.commission = rule.max;
} }
} }
result.full = (result.commission + cfg.amount).toFixed(2); result.full = (result.commission + cfg.amount).toFixed(2);
result.commission = result.commission.toFixed(2); result.commission = result.commission.toFixed(2);
result.amount = cfg.amount.toFixed(2); result.amount = cfg.amount.toFixed(2);
}else{ } else {
result.commission = cfg.amount/100*rule.percent; result.commission = cfg.amount / 100 * rule.percent;
if (rule.min) {
if (result.commission < rule.min) {
console.log('Percent is smaller than min commission (' + [result.commission, rule.min] + ')')
result.commission = rule.min;
}
}
if (rule.max) {
if (result.commission > rule.max) {
console.log('Percent is greater than max commission (' + [result.commission, rule.max] + ')')
result.commission = rule.max;
}
}
if(rule.min) {
if(result.commission < rule.min){
console.log('Percent is smaller than min commission ('+[result.commission, rule.min]+')')
result.commission = rule.min;
}
}
if(rule.max){ result.full = (cfg.amount).toFixed(2);
if(result.commission > rule.max){ result.amount = (cfg.amount - result.commission).toFixed(2);
console.log('Percent is greater than max commission ('+[result.commission, rule.max]+')') result.commission = result.commission.toFixed(2);
result.commission = rule.max;
} }
this.set('result', result);
console.log(result)
} }
result.full = (cfg.amount).toFixed(2);
result.amount = (cfg.amount-result.commission).toFixed(2);
result.commission = result.commission.toFixed(2);
} }
this.set('result', result); },
console.log(result) _prop: {
} date: {
set: function (val) {
} this.calc({date: val});
}, }
_prop: { },
date: { rules: {
set: function(val){ set: function (val) {
this.calc({date: val}); this.calc({rules: val});
} }
}, },
rules: { amount: {
set: function(val){ set: function (val, e) {
this.calc({rules: val}); val = parseFloat(val);
} e.value(val);
}, this.calc({amount: val});
amount: { }
set: function(val, e){ },
val = parseFloat(val); result: {},
e.value(val); up: {
this.calc({amount: val}); set: function (val) {
} this.calc({up: val});
}, }
result: {}, }
up: {
set: function(val){
this.calc({up: val});
} }
} });
} return Commission;
}); });
/*var c = new Commission(); /*var c = new Commission();
c.set('rules', [ c.set('rules', [
{ {
...@@ -244,4 +248,4 @@ c.set('amount',400) ...@@ -244,4 +248,4 @@ c.set('amount',400)
c.set('amount',500) c.set('amount',500)
c.set('amount',1000)*/ c.set('amount',1000)*/
module.exports = Commission; //module.exports = Commission;
\ No newline at end of file \ No newline at end of file
var RunAtServerComponent = require('./RunAtServerComponent'); module.exports =
var QObject = require('./QObject'); QRequire('Core.RunAtServerComponent','Core.QObject', 'Core.Variant', function(
var Pipe = require('./Pipe'); RunAtServerComponent,
var Variant = require('./Variant'); QObject,
Variant
) {
'use strict';
var base = RunAtServerComponent.prototype; var base = RunAtServerComponent.prototype;
var QData = {}; var Config = RunAtServerComponent.extend('Core', 'Config', {
ctor: function () {
},
load: function () {
var config = require(this.get('path'));
var config = require('../../platform/config'); config.load(function (data) {
var parsedData;
try {
parsedData = JSON.parse(data);
this._data['qData'] = Variant.deserialize(parsedData);
}
catch (e) {
console.log(e);
throw e;
}
config.load(function(data){ });
var parsedData; },
try { save: function () {
parsedData = JSON.parse(data); config.save(JSON.stringify(QData.serialize(), null, '\t'));
} },
catch (e) { set: function (key, value) {
console.log(e); key = key.indexOf('qData') === -1 ? QObject.joinKey('qData', key) : key;
throw e; var ret = base.set.call(this, key, value);
}
QData = Variant.deserialize(parsedData);
QData._regherughelrgd = true;
});
var Config = RunAtServerComponent.extend('Core', 'Config', {
ctor: function () {
this._data['qData'] = QData;
},
save: function () {
config.save(JSON.stringify(QData.serialize(), null, '\t'));
},
set: function (key, value) {
key = key.indexOf('qData') === -1 ? QObject.joinKey('qData', key) : key;
var ret = base.set.call(this, key, value);
this.save(); this.save();
return ret; return ret;
//QData.set(key, value); //QData.set(key, value);
}, },
get: function (key) { get: function (key) {
key = key.indexOf('qData') === -1 ? QObject.joinKey('qData', key) : key; key = key.indexOf('qData') === -1 ? QObject.joinKey('qData', key) : key;
return base.get.call(this, key, true); return base.get.call(this, key, true);
//QData.get(key); //QData.get(key);
}, },
ref: function (key) { ref: function (key) {
key = key.indexOf('qData') === -1 ? QObject.joinKey('qData', key) : key; key = key.indexOf('qData') === -1 ? QObject.joinKey('qData', key) : key;
var ret = base.ref.call(this, key); var ret = base.ref.call(this, key);
return ret; return ret;
//return QData.ref(key); //return QData.ref(key);
}, },
prop: { prop: {
qData: {} value: 'path',
} path: {
set: function (val, e) {
e.value(val);
this.load();
}
},
qData: {}
}
});
return Config;
}); });
module.exports = Config;
\ No newline at end of file
/** /**
* Created by zibx on 5/9/17. * Created by zibx on 5/9/17.
*/ */
var QObject = require('./QObject'); module.exports =
QRequire('Core.QObject', function(
var DATA = QObject.extend('Core', 'DATA', { QObject
_anything: true, ) {
ctor: function () { 'use strict';
}, var DATA = QObject.extend('Core', 'DATA', {
_prop: { _anything: true,
value: '_val', ctor: function () {
'_val': { },
set: function (val) { _prop: {
this._data = {}; value: '_val',
this.setAll(val); '_val': {
set: function (val) {
this._data = {};
this.setAll(val);
}
}
} }
} });
}
});
module.exports = DATA; return DATA;
\ No newline at end of file });
\ No newline at end of file
var TypeTable = require('./TypeTable'); module.exports =
QRequire('Core.TypeTable', function(
/** TypeTable
* ) {
* @constructor 'use strict';
*/
function Pipe() { /**
this.toRef = void(0); *
this.fn = arguments[arguments.length - 1]; * @constructor
*/
var argumentsLength = arguments.length - 1; function Pipe() {
this.toRef = void(0);
if (arguments.length === 1) { this.fn = arguments[arguments.length - 1];
argumentsLength += 1;
this.fn = function (a) { var argumentsLength = arguments.length - 1;
return a;
if (arguments.length === 1) {
argumentsLength += 1;
this.fn = function (a) {
return a;
}
}
this.inputCache = [];
this.outputCache = void(0);
for (var i = 0; i < argumentsLength; i++) {
var ref = arguments[i];
this.inputCache[i] = ref.get();
this._subscribeToLink(ref, i);
}
var result = this.fn.apply(this, this.inputCache);
this.outputCache = result;
} }
}
/**
this.inputCache = []; *
this.outputCache = void(0); * @type {{to: Pipe.to, _subscribeToLink: Pipe._subscribeToLink}}
*/
for (var i = 0; i < argumentsLength; i++) { Pipe.prototype = {
var ref = arguments[i]; to: function (toRef) {
this.inputCache[i] = ref.get(); this.toRef = toRef;
this._subscribeToLink(ref, i); this.toRef.set(this.outputCache);
} },
_subscribeToLink: function (ref, index) {
var result = this.fn.apply(this, this.inputCache); var self = this;
this.outputCache = result; ref.subscribe(function (val, oldVal) {
} self.inputCache[index] = val;
var result = self.fn.apply(this, self.inputCache);
/** self.outputCache = result;
*
* @type {{to: Pipe.to, _subscribeToLink: Pipe._subscribeToLink}} if (self.toRef)
*/ self.toRef.set(result);
Pipe.prototype = { });
to: function (toRef) { }
this.toRef = toRef; };
this.toRef.set(this.outputCache); /*
}, Pipe.done = function(){
_subscribeToLink: function (ref, index) {
var self = this; };
ref.subscribe(function (val, oldVal) { Pipe.done.prototype = new Pipe();
self.inputCache[index] = val; */
var result = self.fn.apply(this, self.inputCache);
self.outputCache = result; TypeTable.registerType('Core', 'Pipe', Pipe);
return Pipe;
if (self.toRef) });
self.toRef.set(result); \ No newline at end of file
});
}
};
/*
Pipe.done = function(){
};
Pipe.done.prototype = new Pipe();
*/
TypeTable.registerType('Core', 'Pipe', Pipe);
module.exports = Pipe;
\ No newline at end of file
var observable = require('z-observable'); module.exports =
var TypeTable = require('./TypeTable'); QRequire('z-observable','Core.TypeTable', 'Core.Pipe', 'Core.Reference', function(
var Pipe = require('./Pipe'); observable,
var Reference = require('./Reference'); TypeTable,
var index = 0; Pipe,
function QObject() { Reference
this._data = {}; ) {
this.__subscribers = {}; 'use strict';
this.__refs = {};
observable.prototype._init.apply(this); var index = 0;
this.____id = this.__proto__.type + (index++) + '_' + this.createRandomString(12);
} function QObject() {
this._data = {};
var prototype = { this.__subscribers = {};
on: observable.prototype.on, this.__refs = {};
once: observable.prototype.once, observable.prototype._init.apply(this);
fire: observable.prototype.fire, this.____id = this.__proto__.type + (index++) + '_' + this.createRandomString(12);
removableOn: observable.prototype.removableOn,
un: observable.prototype.un,
__checkValue: function (key) {
if (!key || key === 'value') {
if (this._prop.value)
return this._prop.value;
else
return null;
} else {
return key;
}
},
createRandomString: function (length) {
length = length || 12;
var text = "";
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for (var i = 0; i < length; i++)
text += possible.charAt(Math.floor(Math.random() * possible.length));
return text;
},
serialize: function () {
var data = this._data;
var result = {};
for (var key in data)
if (data.hasOwnProperty(key)) {
if (data[key] instanceof QObject)
result[key] = data[key].serialize();
else
result[key] = data[key];
}
return result;
},
get: function (names, soft, returnLastQObject) {
if (!Array.isArray(names)) {
names = names.split('.');
}
if (!names || names.length <= 0) {
return this._get('value');
} }
var ret = this; var prototype = {
var lastQObject = ret; on: observable.prototype.on,
once: observable.prototype.once,
for (var i = 0; i < names.length; i++) { fire: observable.prototype.fire,
if (ret instanceof QObject) { removableOn: observable.prototype.removableOn,
ret = ret._get(names[i]); un: observable.prototype.un,
lastQObject = ret;
} else { __checkValue: function (key) {
ret = ret[names[i]]; if (!key || key === 'value') {
} if (this._prop.value)
return this._prop.value;
if (!ret && i < names.length - 1) { else
if (soft) return null;
return void(0); } else {
else return key;
throw new Error('NullReferenceException: try get `' + names.join('.') + '` and `' + names[i] + '` is undefined'); }
} },
} createRandomString: function (length) {
length = length || 12;
if (returnLastQObject) var text = "";
return {lastQObject: lastQObject, result: ret}; var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for (var i = 0; i < length; i++)
return ret; text += possible.charAt(Math.floor(Math.random() * possible.length));
return text;
}, },
_get: function (key) { serialize: function () {
key = this.__checkValue(key); var data = this._data;
if (!key) return null; var result = {};
for (var key in data)
if (data.hasOwnProperty(key)) {
if (data[key] instanceof QObject)
result[key] = data[key].serialize();
else
result[key] = data[key];
}
return result;
},
get: function (names, soft, returnLastQObject) {
if (!Array.isArray(names)) {
names = names.split('.');
}
if (!names || names.length <= 0) {
return this._get('value');
}
var ret = this;
var lastQObject = ret;
for (var i = 0; i < names.length; i++) {
if (ret instanceof QObject) {
ret = ret._get(names[i]);
lastQObject = ret;
} else {
ret = ret[names[i]];
}
if (!ret && i < names.length - 1) {
if (soft)
return void(0);
else
throw new Error('NullReferenceException: try get `' + names.join('.') + '` and `' + names[i] + '` is undefined');
}
}
if (returnLastQObject)
return {lastQObject: lastQObject, result: ret};
return ret;
},
_get: function (key) {
key = this.__checkValue(key);
if (!key) return null;
var ret = void(0);
var property = this._prop[key];
if (property) {
var getter = property.get;
if ("get" in property) {
if (getter)
ret = getter.call(this);
else
throw new Error("Property '" + key + "' hes no getter");
}
else
ret = this._data[key];
} else {
ret = this._data[key];
}
return ret
},
/**
*
* @param names
* @param value
* @returns {*}
*/
set: function (names, value) {
names = names.slice(0);
if (value instanceof Pipe) {
value.to(this.ref(names));
return;
}
if (!Array.isArray(names)) {
names = names.split('.');
}
if (!names || names.length <= 0) {
return this._set('value', value);
}
if (names.length === 1) {
return this._set(names[0], value);
}
var objToSetFor = this.get(names[0]);
if (objToSetFor instanceof QObject) {
var setted = objToSetFor.set(names.slice(1), value);
//objToSetFor.set(names.slice(1), value);
} else {
var origin = names[0];
names = names.slice(1);
var nextObj = objToSetFor;
while (!(objToSetFor instanceof QObject) && names.length > 1 && objToSetFor) {
objToSetFor = objToSetFor[names[0]];
names = names.slice(1);
}
if (objToSetFor instanceof QObject)
objToSetFor.set(names.slice(1), value);
else if (objToSetFor) {
var oldVal = objToSetFor[names[0]];
objToSetFor[names[0]] = value;
this._propChanged(origin, nextObj);
}
}
//this._propChanged(names[0]);
return this;
},
/**
*
* @param key
* @param value
* @returns {*}
* @private
*/
_set: function (key, value) {
var _data = this._data;
key = this.__checkValue(key);
if (!key) return null;
var oldValue = this._data[key];
var flags = {
oldValue: oldValue,
value: function (newVal) {
flags.useNew = true;
flags.newVal = newVal;
_data[key] = newVal;
}
};
var property = this._prop[key];
if (property) {
var setter = property.set;
if ("set" in property) {
if (setter)
setter.call(this, value, flags);
else
throw new Error("Property '" + key + "' has no setter");
}
}
var newVal = flags.useNew ? flags.newVal : value;
if (newVal !== oldValue) {
_data[key] = newVal;
this._propChanged(key, newVal, oldValue);
}
return this;
},
call: function (fname) {
var method = this._method[fname];
if (!method) {
throw new Error(this.type + ' has no method ' + fname);
}
var args = Array.prototype.slice.call(arguments, 1);
method.apply(this, args);
},
_propChanged: function (key, value, oldValue) {
//var subs = this.__subscribers[key];
var subs = this.__refs[key];
if (subs) {
for (var i = 0; i < subs.length; i++) {
subs[i].resolve(value, oldValue, key);
}
}
},
ref: function (key) {
var self = this;
key = key || 'value';
if (!Array.isArray(key)) {
key = key.split('.');
}
var ref = new Reference(this, key);
var refs = this.__refs;
if (!refs[key[0]]) {
refs[key[0]] = [];
}
refs[key[0]].push(ref);
return ref;
},
setAll: function (values) {
for (var key in values)
if (values.hasOwnProperty(key)) {
this.set(key, values[key]);
}
return this;
},
_prop: {
value: '_value',
_value: {}
},
_method: {}
};
QObject.prototype = prototype;
var ret = void(0); QObject.type = "QObject";
var property = this._prop[key]; QObject.namespace = "Core";
if (property) { QObject.fixKey = function (key) {
var getter = property.get; if (!Array.isArray(key)) {
if ("get" in property) { key = key.split('.');
if (getter)
ret = getter.call(this);
else
throw new Error("Property '" + key + "' hes no getter");
} }
else return key;
ret = this._data[key]; };
} else {
ret = this._data[key];
}
return ret
},
/**
*
* @param names
* @param value
* @returns {*}
*/
set: function (names, value) {
names = names.slice(0);
if (value instanceof Pipe) { QObject.joinKey = function () {
value.to(this.ref(names));
return;
}
if (!Array.isArray(names)) { var arrayProt = Array.prototype;
names = names.split('.');
}
if (!names || names.length <= 0) { var args = arguments;
return this._set('value', value);
}
if (names.length === 1) { args = arrayProt.map.call(args, function (arg) {
return this._set(names[0], value); return QObject.fixKey(arg);
} });
var objToSetFor = this.get(names[0]); return arrayProt.concat.apply([], args);
if (objToSetFor instanceof QObject) {
var setted = objToSetFor.set(names.slice(1), value);
//objToSetFor.set(names.slice(1), value);
} else {
var origin = names[0];
names = names.slice(1);
var nextObj = objToSetFor;
while (!(objToSetFor instanceof QObject) && names.length > 1 && objToSetFor) {
objToSetFor = objToSetFor[names[0]];
names = names.slice(1);
}
if (objToSetFor instanceof QObject)
objToSetFor.set(names.slice(1), value);
else if (objToSetFor) {
var oldVal = objToSetFor[names[0]];
objToSetFor[names[0]] = value;
this._propChanged(origin, nextObj);
}
}
//this._propChanged(names[0]);
return this;
},
/**
*
* @param key
* @param value
* @returns {*}
* @private
*/
_set: function (key, value) {
var _data = this._data;
key = this.__checkValue(key);
if (!key) return null;
var oldValue = this._data[key];
var flags = {
oldValue: oldValue,
value: function (newVal) {
flags.useNew = true;
flags.newVal = newVal;
_data[key] = newVal;
}
}; };
var property = this._prop[key]; QObject.extend = function (namespace, newName, proto, ctor) {
if (property) {
var setter = property.set;
if ("set" in property) {
if (setter)
setter.call(this, value, flags);
else
throw new Error("Property '" + key + "' has no setter");
}
}
var newVal = flags.useNew ? flags.newVal : value;
proto = proto || {};
if (newVal !== oldValue) { if (proto.ctor && ctor)
throw new Error('Constructor duplication');
_data[key] = newVal; // Default constructor
this._propChanged(key, newVal, oldValue); ctor = proto.ctor || ctor || function () {
} };
return this;
},
call: function (fname) {
var method = this._method[fname];
if (!method) {
throw new Error(this.type + ' has no method ' + fname);
}
var args = Array.prototype.slice.call(arguments, 1); proto._prop = proto._prop || {};
proto._method = proto._method || {};
method.apply(this, args); var parentConstructor = TypeTable.getType(this.namespace, this.type);
}, var parentPrototype = Object.create(parentConstructor.prototype);
_propChanged: function (key, value, oldValue) {
//var subs = this.__subscribers[key];
var subs = this.__refs[key];
if (subs) {
for (var i = 0; i < subs.length; i++) {
subs[i].resolve(value, oldValue, key);
}
}
},
ref: function (key) {
var self = this;
key = key || 'value';
if (!Array.isArray(key)) {
key = key.split('.');
}
var ref = new Reference(this, key);
var refs = this.__refs; proto.__proto__ = parentPrototype;
if (!refs[key[0]]) {
refs[key[0]] = [];
}
refs[key[0]].push(ref);
// Force parent constructor call
var newCtor = function (cfg) {
parentConstructor.apply(this);
var me = ctor.call(this);
if (me)
return me;
if (cfg)
this.setAll(cfg);
};
return ref; Object.defineProperty(newCtor, "name", {value: newName});
},
setAll: function (values) {
for (var key in values)
if (values.hasOwnProperty(key)) {
this.set(key, values[key]);
}
return this;
},
_prop: {
value: '_value',
_value: {}
},
_method: {}
};
QObject.prototype = prototype;
QObject.type = "QObject";
QObject.namespace = "Core";
QObject.fixKey = function (key) {
if (!Array.isArray(key)) {
key = key.split('.');
}
return key;
};
QObject.joinKey = function () {
var arrayProt = Array.prototype;
var args = arguments;
args = arrayProt.map.call(args, function(arg){
return QObject.fixKey(arg);
});
return arrayProt.concat.apply([], args); // "Merge" props
}; proto._prop.__proto__ = parentConstructor.prototype._prop;
proto._method.__proto__ = parentConstructor.prototype._method;
proto.type = newName;
proto.namespace = namespace;
newCtor.parent = parentConstructor;
QObject.extend = function (namespace, newName, proto, ctor) { // Make new class
newCtor.prototype = proto;
newCtor.extend = this.extend;
proto = proto || {}; newCtor.namespace = namespace;
newCtor.type = newName;
if (proto.ctor && ctor) TypeTable.registerType(namespace, newName, newCtor);
throw new Error('Constructor duplication');
// Default constructor return newCtor;
ctor = proto.ctor || ctor || function () {
}; };
proto._prop = proto._prop || {}; TypeTable.registerType("Core", "QObject", QObject);
proto._method = proto._method || {}; return QObject;
});
var parentConstructor = TypeTable.getType(this.namespace, this.type);
var parentPrototype = Object.create(parentConstructor.prototype);
proto.__proto__ = parentPrototype;
// Force parent constructor call
var newCtor = function (cfg) {
parentConstructor.apply(this);
var me = ctor.call(this);
if (me)
return me;
if (cfg)
this.setAll(cfg);
};
Object.defineProperty(newCtor, "name", {value: newName});
// "Merge" props
proto._prop.__proto__ = parentConstructor.prototype._prop;
proto._method.__proto__ = parentConstructor.prototype._method;
proto.type = newName;
proto.namespace = namespace;
newCtor.parent = parentConstructor;
// Make new class
newCtor.prototype = proto;
newCtor.extend = this.extend;
newCtor.namespace = namespace;
newCtor.type = newName;
TypeTable.registerType(namespace, newName, newCtor);
return newCtor;
};
TypeTable.registerType("Core", "QObject", QObject);
module.exports = QObject;
\ No newline at end of file
var QObject; module.exports =
QRequire('Core.TypeTable', function(
TypeTable
) {
'use strict';
function Reference(obj, key, callback) { var QObject;
if (!QObject) function Reference(obj, key, callback) {
QObject = require("./QObject");
this.obj = obj; if (!QObject)
this.callback = callback; QRequire('Core.QObject', function (obj) {
QObject = obj;
var names = key; });
this.key = key;
this.path = key;
if (names.length > 1) {
this.type = 'chain';
this.createNextRef();
} else {
names[0] = obj.__checkValue(names[0]);
}
return this; this.obj = obj;
} this.callback = callback;
Reference.prototype = var names = key;
{ this.key = key;
oldVal: void 0,
destroyNext: function () {
if (this._nextRef) {
var index = this._nextRef.obj.__refs[this._nextRef.path[0]].indexOf(this._nextRef);
if (index >= 0) this.path = key;
this._nextRef.obj.__refs[this._nextRef.path[0]].splice(index, 1);
this._nextRef.destroyNext(); if (names.length > 1) {
this._nextRef.callback = void(0); this.type = 'chain';
delete this._nextRef; this.createNextRef();
} } else {
}, names[0] = obj.__checkValue(names[0]);
createNextRef: function () {
var self = this;
var names = this.path;
var obj = this.obj;
var nextName = names[0];
nextName = obj.__checkValue(nextName);
var nextObj = obj.get(nextName);
if (nextObj && nextObj instanceof QObject) {
var nextRef = nextObj.ref(names.slice(1));
nextRef.oldVal = nextObj.get(names.slice(1), true);
nextRef._uberRef = this;
nextRef._mainRef = this._mainRef || this;
nextRef.type = 'chain';
self._nextRef = nextRef;
nextRef.subscribe(function (val, oldVal) {
self.destroyNext();
self.createNextRef();
self.resolve(val, oldVal);
});
}
},
get: function () {
return this.obj.get(this.key, true);
},
getOld: function (val, key) {
if(!val)
return val;
if(val instanceof QObject)
return val.get(this.key, true);
else {
var result = val;
for(var i = 0, _i = this.key.length; i < _i; i++){
if(!result)
break;
if(result instanceof QObject)
result = result.get([this.key[i]], true);
else
result = result[this.key[i]];
}
return result;
}
},
set: function (value) {
this.obj.set(this.key, value);
},
subscribe: function (callback) {
this.callback = callback;
},
resolve: function (val, oldVal, key) {
var cb = this.callback;
if (this.type === "chain") {
val = this.get();
var goldVal = this.getOld(oldVal, key);
var ref = this._uberRef || this;
cb = ref.callback;
}
//console.log('CHANGE', this.key.join('.'), val, oldVal, this.oldVal, goldVal);
if (cb && val !== this.oldVal) {
this.oldVal = val;
cb(val, oldVal);
} }
return this;
} }
};
module.exports = Reference; Reference.prototype =
{
oldVal: void 0,
destroyNext: function () {
if (this._nextRef) {
var index = this._nextRef.obj.__refs[this._nextRef.path[0]].indexOf(this._nextRef);
if (index >= 0)
this._nextRef.obj.__refs[this._nextRef.path[0]].splice(index, 1);
this._nextRef.destroyNext();
this._nextRef.callback = void(0);
delete this._nextRef;
}
},
createNextRef: function () {
var self = this;
var names = this.path;
var obj = this.obj;
var nextName = names[0];
nextName = obj.__checkValue(nextName);
var nextObj = obj.get(nextName);
if (nextObj && nextObj instanceof QObject) {
var nextRef = nextObj.ref(names.slice(1));
nextRef.oldVal = nextObj.get(names.slice(1), true);
nextRef._uberRef = this;
nextRef._mainRef = this._mainRef || this;
nextRef.type = 'chain';
self._nextRef = nextRef;
nextRef.subscribe(function (val, oldVal) {
self.destroyNext();
self.createNextRef();
self.resolve(val, oldVal);
});
}
},
get: function () {
return this.obj.get(this.key, true);
},
getOld: function (val, key) {
if (!val)
return val;
if (val instanceof QObject)
return val.get(this.key, true);
else {
var result = val;
for (var i = 0, _i = this.key.length; i < _i; i++) {
if (!result)
break;
if (result instanceof QObject)
result = result.get([this.key[i]], true);
else
result = result[this.key[i]];
}
return result;
}
},
set: function (value) {
this.obj.set(this.key, value);
},
subscribe: function (callback) {
this.callback = callback;
},
resolve: function (val, oldVal, key) {
var cb = this.callback;
if (this.type === "chain") {
val = this.get();
var goldVal = this.getOld(oldVal, key);
var ref = this._uberRef || this;
cb = ref.callback;
}
//console.log('CHANGE', this.key.join('.'), val, oldVal, this.oldVal, goldVal);
if (cb && val !== this.oldVal) {
this.oldVal = val;
cb(val, oldVal);
}
}
};
TypeTable.registerType('Core', 'Reference', Reference);
return Reference;
});
\ No newline at end of file
var AbstractComponent = require('./AbstractComponent'); module.exports =
var QObject = require('./QObject'); QRequire('Core.AbstractComponent', 'Core.QObject','Core.Pipe', function(
var Pipe = require('./Pipe'); AbstractComponent,
var console = {log: function(){}}; QObject,
var base = AbstractComponent.prototype; Pipe
) {
/** @class */ 'use strict';
var RunAtServerComponent = AbstractComponent.extend('Core', 'RunAtServerComponent', {
ctor: function () { var console = {
this.socket = void(0); log: function () {
this.listeners = {}; }
this._sync = false; };
var base = AbstractComponent.prototype;
if (typeof io !== "undefined") {
this.__side = 'client'; /** @class */
this.socket = io(void 0, this); var RunAtServerComponent = AbstractComponent.extend('Core', 'RunAtServerComponent', {
this.appName = ((((((Q || {}).UI || {}).Navigation || {}).NavigationManager || {}).Application || {}).current || {}).name; ctor: function () {
this._initSocket(); this.socket = void(0);
this.listeners = {};
} else { this._sync = false;
this.__side = 'server';
} if (typeof io !== "undefined") {
}, this.__side = 'client';
'~destroy': function(){ this.socket = io(void 0, this);
if(this.socket) { this.appName = ((((((Q || {}).UI || {}).Navigation || {}).NavigationManager || {}).Application || {}).current || {}).name;
this.socket.emit('~destroy'); this._initSocket();
this.socket['~destroy']();
} } else {
}, this.__side = 'server';
}
_initSocket: function () { },
if (!this.socket) '~destroy': function () {
return; if (this.socket) {
this.socket.emit('~destroy');
var socket = this.socket; this.socket['~destroy']();
var self = this; }
},
socket.on('set', function (data) {
self._sync = true; _initSocket: function () {
self.set(data.key, data.value, true); if (!this.socket)
self._sync = false; return;
});
socket.on('call', function (data) { var socket = this.socket;
self.call.apply(self, data.args); var self = this;
});
socket.on('sync', function (data) { socket.on('set', function (data) {
self.call.apply(self, data.args); self._sync = true;
}); self.set(data.key, data.value, true);
socket.on('resolve', function (data) { self._sync = false;
self._sync = true; });
self.set(data.key, data.data); socket.on('call', function (data) {
console.log('resolve', data.key, self.__refs[data.key[0]], self.____id, data, self); self.call.apply(self, data.args);
/*self.__refs[data.key[0]].forEach(function (r) { });
r.resolve(data.data); socket.on('sync', function (data) {
});*/ self.call.apply(self, data.args);
self._sync = false; });
}); socket.on('resolve', function (data) {
socket.on('ref', function (data) { self._sync = true;
var ref = self.ref(data.key); self.set(data.key, data.data);
ref.subscribe(function (result) { console.log('resolve', data.key, self.__refs[data.key[0]], self.____id, data, self);
socket.emit('resolve', {key: data.key, data: result}) /*self.__refs[data.key[0]].forEach(function (r) {
}); r.resolve(data.data);
socket.emit('resolve', {key: data.key, data: ref.get()}) });*/
}); self._sync = false;
});
socket.on('ref', function (data) {
var ref = self.ref(data.key);
ref.subscribe(function (result) {
socket.emit('resolve', {key: data.key, data: result})
});
socket.emit('resolve', {key: data.key, data: ref.get()})
});
socket.on('RPC', function (data) {
var fn = self['#' + data.fn], out;
if (!fn)
out = {error: true, val: 'No function `' + data.fn + '`'};
else {
try {
out = {error: false, val: fn.apply(self, data.args)};
} catch (e) {
out = {error: true, val: e.message + '\n' + e.stack};
}
}
socket.emit('responseRPC', {id: data.id, data: out});
});
socket.on('responseRPC', function (data) {
var cbs = self.___RPCcallbacks;
if (cbs) {
if (cbs[data.id]) {
var val = data.data;
if (val.error)
throw new Error(val.val);
else
cbs[data.id].call(self, val.val);
}
}
});
if (this.__side === 'client') {
socket.on('fireClient', function (data) {
self.fire.apply(self, data);
});
socket.emit('start', {namespace: this.namespace, type: this.type, appName: this.appName});
} else {
socket.on('~destroy', function () {
self['~destroy'] && self['~destroy']();
self.fire('~destroy');
});
}
},
fireClient: function () {
this.socket.emit('fireClient', [].slice.call(arguments));
},
_connectSocket: function (socket) {
this.socket = socket;
this._initSocket();
this.setAll(this._data);
},
_RPC: function (name, args) {
args = [].slice.call(args);
var cb,
cbs = this.___RPCcallbacks = this.___RPCcallbacks || {};
if (!('___RPCID' in this))
this.___RPCID = 0;
this.___RPCID++;
if (args.length && typeof args[args.length - 1] === 'function') {
cb = args.pop();
cbs[this.___RPCID] = cb;
}
this.socket.emit('RPC', {
fn: name,
args: args,
id: this.___RPCID
});
},
ref: function (key) {
var ref = base.ref.call(this, key);
if (this.__side === 'client') {
this.socket.emit('ref', {key: key});
//this.listeners[key] = ref;
}
return ref;
},
set: function (key, value, silent) {
var data = {};
var toSetVal = value;
var ret = base.set.call(this, key, value);
socket.on('RPC', function (data) { data[key] = toSetVal instanceof QObject ? toSetVal.serialize() : toSetVal;
var fn = self['#'+data.fn], out; if (this.socket && !this._sync) {
if(!fn) this.socket.emit('set', {key: key, value: data[key]});
out = {error: true, val: 'No function `'+ data.fn +'`'};
else {
try{
out = {error: false, val: fn.apply(self, data.args)};
}catch(e){
out = {error: true, val: e.message + '\n'+e.stack};
} }
}
socket.emit('responseRPC', {id: data.id, data: out}); return ret;
}); },
socket.on('responseRPC', function (data) { call: function () {
var cbs = self.___RPCcallbacks; if (this.__side === 'client') {
if(cbs){ this.socket.emit('call', {args: Array.from(arguments)});
if(cbs[data.id]){ }
var val = data.data; if (this.__side === 'server') {
if(val.error) base.call.apply(this, arguments);
throw new Error(val.val);
else
cbs[data.id].call(self, val.val);
} }
} }
}); });
if (this.__side === 'client') { return RunAtServerComponent;
socket.on('fireClient', function(data){ });
self.fire.apply(self, data); \ No newline at end of file
});
socket.emit('start', {namespace: this.namespace, type: this.type, appName: this.appName});
}else{
socket.on('~destroy', function(){
self['~destroy'] && self['~destroy']();
self.fire('~destroy');
});
}
},
fireClient: function(){
this.socket.emit('fireClient', [].slice.call(arguments));
},
_connectSocket: function (socket) {
this.socket = socket;
this._initSocket();
this.setAll(this._data);
},
_RPC: function(name, args){
args = [].slice.call(args);
var cb,
cbs = this.___RPCcallbacks = this.___RPCcallbacks || {};
if(!('___RPCID' in this))
this.___RPCID = 0;
this.___RPCID++;
if(args.length && typeof args[args.length - 1] === 'function'){
cb = args.pop();
cbs[this.___RPCID] = cb;
}
this.socket.emit('RPC', {
fn: name,
args: args,
id: this.___RPCID
});
},
ref: function (key) {
var ref = base.ref.call(this, key);
if (this.__side === 'client') {
this.socket.emit('ref', {key: key});
//this.listeners[key] = ref;
}
return ref;
},
set: function (key, value, silent) {
var data = {};
var toSetVal = value;
var ret = base.set.call(this, key, value);
data[key] = toSetVal instanceof QObject ? toSetVal.serialize() : toSetVal;
if (this.socket && !this._sync) {
this.socket.emit('set', {key: key, value: data[key]});
}
return ret;
},
call: function () {
if (this.__side === 'client') {
this.socket.emit('call', {args: Array.from(arguments)});
}
if (this.__side === 'server') {
base.call.apply(this, arguments);
}
}
});
module.exports = RunAtServerComponent;
\ No newline at end of file
var RunAtServerComponent = require('./RunAtServerComponent'); module.exports =
var Pipe = require('./Pipe'); QRequire('Core.RunAtServerComponent', 'Core.Pipe', 'Core.Variant', 'Core.Config', function(
var Variant = require('./Variant'); RunAtServerComponent,
var Config = require('./Config'); Pipe,
Variant,
Config
){
'use strict';
var config = new Config();
var config = new Config(); var base = RunAtServerComponent.prototype;
var singleton;
var Store = RunAtServerComponent.extend('Core', 'Store', {
_anything: true,
link: function (selfProp, configProp) {
var me = this;
this.set(selfProp, new Pipe(config.ref(configProp), function (a) {
console.log('------------------------->>>>>>>>>>>>-----', me.____id);
return a;
}));
config.set(configProp, new Pipe(this.ref(selfProp), function (a) {
//config.save();
console.log('----------------------------------------------------', me.____id);
return a;
}));
},
save: function () {
config.save();
},
getAppConfigKey: function () {
return 'applications.' + this.appName;
},
set: function (key, value) {
var base = RunAtServerComponent.prototype; var ret = base.set.call(this, key, value);
var singleton;
var Store = RunAtServerComponent.extend('Core', 'Store', {
_anything: true,
link: function (selfProp, configProp) {
var me = this;
this.set(selfProp, new Pipe(config.ref(configProp), function (a) {
console.log('------------------------->>>>>>>>>>>>-----', me.____id);
return a;
}));
config.set(configProp, new Pipe(this.ref(selfProp), function (a) {
//config.save();
console.log('----------------------------------------------------', me.____id);
return a;
}));
},
save: function () {
config.save();
},
getAppConfigKey: function () {
return 'applications.' + this.appName;
},
set: function (key, value) {
var ret = base.set.call(this, key, value); console.log(key);
console.log(key); if (key.indexOf('config') === 0) {
console.log('shit');
config.set(this.getAppConfigKey(), this.get('config'));
if (this.appName === 'confTool') {
//config.set('applications.confTool.resources', this.get('config.resources'));
//config.set('applications.confTool.settings', this.get('config.settings'));
this.set('globalResources', config.get('applications.confTool.resources'));
}
}
if (key.indexOf('config') === 0) { if (key.indexOf('globalResources') === 0)
console.log('shit'); config.set('applications.confTool.resources', this.get('globalResources'));
config.set(this.getAppConfigKey(), this.get('config'));
if (this.appName === 'confTool') {
//config.set('applications.confTool.resources', this.get('config.resources'));
//config.set('applications.confTool.settings', this.get('config.settings'));
this.set('globalResources', config.get('applications.confTool.resources'));
}
}
if (key.indexOf('globalResources') === 0) if (key.indexOf('system') === 0)
config.set('applications.confTool.resources', this.get('globalResources')); config.set('applications.confTool.settings', this.get('system'));
if (key.indexOf('system') === 0) return ret;
config.set('applications.confTool.settings', this.get('system')); },
ctor: function () {
return ret; singleton = this;
},
ctor: function () {
singleton = this; this.appName = Store.appName;
this.appName = Store.appName; this.link('globalResources', 'applications.confTool.resources');
this.link('system', 'applications.confTool.settings');
this.link('globalResources', 'applications.confTool.resources'); this.link('config', this.getAppConfigKey());
this.link('system', 'applications.confTool.settings');
this.link('config', this.getAppConfigKey()); //this.set('resources', config.get('applications.confTool.resources'));
//this.set('system', config.get('applications.confTool.settings'));
},
_prop: {
resources: {},
settings: {},
system: {}
}
});
return Store;
});
//this.set('resources', config.get('applications.confTool.resources'));
//this.set('system', config.get('applications.confTool.settings'));
},
_prop: {
resources: {},
settings: {},
system: {}
}
});
module.exports = Store;
\ No newline at end of file
var QObject = require('./QObject'); module.exports =
var AbstractComponent = require('./AbstractComponent'); QRequire('Core.QObject', 'Core.AbstractComponent', function(
QObject,
AbstractComponent
) {
'use strict';
/** @class */
var Timer = QObject.extend('Core', 'Timer', {
ctor: function () {
this.set('counter', 0);
},
start: function () {
if (this.interval) return;
var self = this; /** @class */
var interval = this.get('interval'); var Timer = QObject.extend('Core', 'Timer', {
this.interval = setInterval(function () { ctor: function () {
self.set('counter', self.get('counter')+1); this.set('counter', 0);
self.fire('tick', self._data.counter); },
}, interval); start: function () {
}, if (this.interval) return;
stop: function () {
clearInterval(this.interval); var self = this;
this.interval = void(0); var interval = this.get('interval');
}, this.interval = setInterval(function () {
_prop: { self.set('counter', self.get('counter') + 1);
value: 'counter', self.fire('tick', self._data.counter);
counter: {}, }, interval);
interval: { },
set: function(val,e){ stop: function () {
if(this.get('enabled')) { clearInterval(this.interval);
e.value(val); this.interval = void(0);
this.start(); },
_prop: {
value: 'counter',
counter: {},
interval: {
set: function (val, e) {
if (this.get('enabled')) {
e.value(val);
this.start();
}
}
},
enabled: {
set: function (val, e) {
e.value(val);
if (val)
this.start();
else
this.stop();
}
} }
} }
}, });
enabled: {
set: function(val, e){
e.value(val);
if(val)
this.start();
else
this.stop();
}
}
}
});
module.exports = Timer; return Timer;
\ No newline at end of file });
\ No newline at end of file
function Node(name) {
this.children = {};
this.name = name || "";
this.namespace = name || "";
this.ctor = null;
}
Node.prototype = {
findOne: function (path) {
if (path.length <= 0)
return this;
var targetChild = this.children[path[0]];
if (!targetChild)
return void(0);
return targetChild.findOne(path.splice(1));
},
findAll: function (name) {
var ret = [];
for (var key in this.children)
if (this.children.hasOwnProperty(key)) {
if (this.children[key].name == name)
ret.push(this.children[key]);
ret = ret.concat(this.children[key].findAll(name))
}
return ret;
}
};
var table = new Node();
var TypeTable = {
registerType: function (namespace, name, ctor) {
var path = namespace.split('.');
if (!ctor) {
ctor = name;
name = path.splice(-1)[0];
}
ctor.namespace = namespace;
ctor.type = name;
var currentNode = table;
for (var i = 0; i < path.length; i++) {
if (!currentNode.children[path[i]]) {
currentNode.children[path[i]] = new Node(path[i]);
}
currentNode = currentNode.children[path[i]];
}
var typeNode = new Node(name);
typeNode.ctor = ctor;
typeNode.namespace = path.join('.');
currentNode.children[name] = typeNode;
(function () {
var pointer = this.Q = this.Q || {};
var targetNode =
path.reduce(function (pointer, name) {
pointer = pointer[name] = pointer[name] || {};
return pointer;
}, pointer);
targetNode[name] = ctor;
}).call(null);
},
search: function (namespace, name) {
namespace = namespace.split('.');
if (!name)
name = namespace.splice(-1)[0];
var ns = namespace.length > 0 ? table.findOne(namespace) : table;
var results = ns.findAll(name);
return results;
},
getType: function (namespace, name) {
namespace = namespace.split('.');
if (!name)
name = namespace.splice(-1)[0];
var ns = namespace.length > 0 ? table.findOne(namespace) : table;
if (!ns) {
throw new Error("Can't find " + name + " in " + namespace + '\n\r'+ console.log(table));
}
var results = ns.findAll(name);
//TODO add exception handling
if (results.length > 0)
return results[0].ctor;
}
};
TypeTable.registerType('Core', 'TypeTable', TypeTable);
module.exports = TypeTable;
\ No newline at end of file
var QObject = require('./QObject'); module.exports =
QRequire('Core.QObject', function(
QObject
) {
'use strict';
var base = QObject.prototype; var base = QObject.prototype;
var Variant = QObject.extend('Core', 'Variant', { var Variant = QObject.extend('Core', 'Variant', {
_set: function (key, value) { _set: function (key, value) {
if (!this._prop[key]) if (!this._prop[key])
this._prop[key] = {}; this._prop[key] = {};
return base._set.call(this, key, value); return base._set.call(this, key, value);
}
});
Variant.deserialize = function (jsonObj) {
if (typeof jsonObj === 'object') {
var res = new Variant();
for (var key in jsonObj)
if (jsonObj.hasOwnProperty(key)) {
res.set(key, Variant.deserialize(jsonObj[key]));
} }
});
return res; Variant.deserialize = function (jsonObj) {
} else { if (typeof jsonObj === 'object') {
return jsonObj; var res = new Variant();
} for (var key in jsonObj)
if (jsonObj.hasOwnProperty(key)) {
res.set(key, Variant.deserialize(jsonObj[key]));
}
}; return res;
} else {
return jsonObj;
}
module.exports = Variant; };
\ No newline at end of file return Variant;
});
var UIComponent = require('./UIComponent'); module.exports =
QRequire('UI.UIComponent', function(
var ContentContainer = UIComponent.extend('UI', 'ContentContainer'); UIComponent
) {
module.exports = ContentContainer; 'use strict';
\ No newline at end of file return UIComponent.extend('UI', 'ContentContainer');
});
/** /**
* Created by ravenor on 13.07.16. * Created by ravenor on 13.07.16.
*/ */
module.exports =
QRequire('UI.UIComponent', 'UI.ContentContainer', function(
UIComponent,
ContentContainer
) {
'use strict';
var UIComponent = require('../UIComponent'); return UIComponent.extend('UI.Controls', 'Border', {
var ContentContainer = require('../ContentContainer'); ctor: function () {
this._ownComponents.push(new ContentContainer());
this.el.style.overflow = 'visible';
this._contentContainer.setAll({
pureCss: 'position: absolute; top: 0; bottom: 0; right: 0; left: 0; width:auto; height: auto'
});
},
_prop: {
margin: {
set: function (value) {
var parts = value.split(/\s{1,}/g);
module.exports = UIComponent.extend('UI.Controls', 'Border', { var css = '';
ctor: function () {
this._ownComponents.push(new ContentContainer());
this.el.style.overflow='visible';
this._contentContainer.setAll({
pureCss: 'position: absolute; top: 0; bottom: 0; right: 0; left: 0; width:auto; height: auto'
});
},
_prop: {
margin: {
set: function (value) {
var parts = value.split(/\s{1,}/g);
var css = ''; if (parts.length === 4) {
css = 'position: absolute; top: ' + parts[0] + '; bottom: ' + parts[2] + '; right:' + parts[1] + '; left: ' + parts[3];
} else if (parts.length === 3) {
css = 'position: absolute; top: ' + parts[0] + '; bottom: ' + parts[2] + '; right:' + parts[1] + '; left: ' + parts[1];
} else if (parts.length === 2) {
css = 'position: absolute; top: ' + parts[0] + '; bottom: ' + parts[0] + '; right:' + parts[1] + '; left: ' + parts[1];
} else if (parts.length === 1) {
css = 'position: absolute; top: ' + parts[0] + '; bottom: ' + parts[0] + '; right:' + parts[0] + '; left: ' + parts[0];
}
if (parts.length === 4) { this._contentContainer.set('pureCss', css);
css = 'position: absolute; top: ' + parts[0] + '; bottom: ' + parts[2] + '; right:' + parts[1] + '; left: ' + parts[3]; }
} else if (parts.length === 3) { },
css = 'position: absolute; top: ' + parts[0] + '; bottom: ' + parts[2] + '; right:' + parts[1] + '; left: ' + parts[1]; borderRadius: {
} else if (parts.length === 2) { set: function (value) {
css = 'position: absolute; top: ' + parts[0] + '; bottom: ' + parts[0] + '; right:' + parts[1] + '; left: ' + parts[1]; this._contentContainer.el.style.borderRadius = value;
} else if (parts.length === 1) {
css = 'position: absolute; top: ' + parts[0] + '; bottom: ' + parts[0] + '; right:' + parts[0] + '; left: ' + parts[0];
} }
this._contentContainer.set('pureCss', css);
}
},
borderRadius: {
set: function (value) {
this._contentContainer.el.style.borderRadius = value;
} }
} }
} });
}); });
\ No newline at end of file
...@@ -2,72 +2,77 @@ ...@@ -2,72 +2,77 @@
* Created by ravenor on 13.07.16. * Created by ravenor on 13.07.16.
*/ */
var UIComponent = require('../UIComponent'); module.exports =
QRequire('UI.UIComponent', function(
UIComponent
) {
'use strict';
return UIComponent.extend('UI.Controls', 'Button', {
ctor: function () {
this.set("width", "100px");
this.set("height", "30px");
this.set("value", "Button");
},
createEl: function () {
var self = this;
this.el = document.createElement('button');
this.el.className = 'Q-UI-Button';
this.el.setAttribute('type', 'button');
module.exports = UIComponent.extend('UI.Controls', 'Button', { var buttonText = document.createElement('span');
createEl: function () { this.el.appendChild(buttonText);
var self = this; this.el.addEventListener('click', function (event) {
this.el = document.createElement('button'); self.fire('click', event);
this.el.className = 'Q-UI-Button'; });
this.el.setAttribute('type', 'button'); this.el.addEventListener('mousedown', function (event) {
self.el.classList.add('Over');
});
this.el.addEventListener('mouseup', function (event) {
self.el.classList.remove('Over');
});
var buttonText = document.createElement('span'); this.buttonText = buttonText;
this.el.appendChild(buttonText); },
this.el.addEventListener('click', function (event) { _tabProtocol: function (delegate) {
self.fire('click', event); if (delegate)
}); return true;
this.el.addEventListener('mousedown', function (event) { this.el.classList.add('Focused');
self.el.classList.add('Over'); this.el.focus();
}); },
this.el.addEventListener('mouseup', function (event) { _tabProtocolLeave: function () {
self.el.classList.remove('Over'); this.el.classList.remove('Focused');
}); },
_prop: {
caption: {
set: function (val) {
this.buttonText.innerText = (val + '').replace(/_/g, String.fromCharCode(160));
}
},
direction: {
set: function (val) {
this.removeClass(this.el, 'Q-UI-Button_left');
this.removeClass(this.el, 'Q-UI-Button_right');
this.buttonText = buttonText; if (val === 'left')
}, this.addClass(this.el, 'Q-UI-Button_left');
_tabProtocol: function (delegate) {
if(delegate)
return true;
this.el.classList.add('Focused');
this.el.focus();
},
_tabProtocolLeave: function(){
this.el.classList.remove('Focused');
},
_prop: {
caption: {
set: function (val) {
this.buttonText.innerText = (val+'').replace(/_/g, String.fromCharCode(160));
}
},
direction: {
set: function(val){
this.removeClass(this.el,'Q-UI-Button_left');
this.removeClass(this.el,'Q-UI-Button_right');
if(val === 'left')
this.addClass(this.el,'Q-UI-Button_left');
if(val === 'right') if (val === 'right')
this.addClass(this.el,'Q-UI-Button_right'); this.addClass(this.el, 'Q-UI-Button_right');
} }
},
filled: {
set: function (val) {
this.removeClass(this.el, 'Q-UI-Button_filled');
},
filled: {
set: function(val){
this.removeClass(this.el,'Q-UI-Button_filled');
if(val === true) if (val === true)
this.addClass(this.el,'Q-UI-Button_filled'); this.addClass(this.el, 'Q-UI-Button_filled');
}
},
value: 'caption'
} }
}, });
value: 'caption' });
} \ No newline at end of file
}, function () {
this.set("width", "100px");
this.set("height", "30px");
this.set("value", "Button");
});
...@@ -6,36 +6,41 @@ ...@@ -6,36 +6,41 @@
;// QUOKKA 2017 ;// QUOKKA 2017
// By zibx on 5/29/17. // By zibx on 5/29/17.
module.exports = (function () { module.exports =
'use strict'; QRequire('UI.UIComponent', function(
var UIComponent = require('../UIComponent'); UIComponent
) {
'use strict';
return UIComponent.extend('UI.Controls', 'Canvas', {
createEl: function () {
var self = this;
this.el = document.createElement('canvas');
this.ctx = this.el.getContext('2d');
this.el.className = 'Q-UI-Canvas';
return UIComponent.extend('UI.Controls', 'Canvas', { this.el.addEventListener('click', function (event) {
createEl: function () { self.fire('click', event);
var self = this; });
this.el = document.createElement('canvas');
this.ctx = this.el.getContext('2d');
this.el.className = 'Q-UI-Canvas';
this.el.addEventListener('click', function (event) { },
self.fire('click', event); dot: function (obj) {
}); this.ctx.fillRect(obj.x - 1, obj.y - 1, 2, 2);
},
}, _prop: {
dot: function(obj){ width: {
this.ctx.fillRect(obj.x-1, obj.y-1, 2, 2); set: function (val) {
}, val += '';
_prop: { if (val.indexOf('%') === -1 && val.indexOf('px') === -1)
width: {set: function(val){ this.el.width = val;
val+=''; }
if(val.indexOf('%')===-1 && val.indexOf('px')===-1) },
this.el.width = val; height: {
}}, set: function (val) {
height: {set: function(val){ val += '';
val+=''; if (val.indexOf('%') === -1 && val.indexOf('px') === -1)
if(val.indexOf('%')===-1 && val.indexOf('px')===-1) this.el.height = val;
this.el.height = val; }
}} }
} }
}); });
})(); });
\ No newline at end of file \ No newline at end of file
var UIComponent = require('../UIComponent'); module.exports =
QRequire('UI.UIComponent', function(
module.exports = UIComponent.extend('UI.Controls', 'CheckBox', { UIComponent
_prop: { ) {
checked: { 'use strict';
get: function () { return UIComponent.extend('UI.Controls', 'CheckBox', {
return !!this.input.checked; _prop: {
}, checked: {
set: function (value, flags) { get: function () {
var newValue = value ==='false' || value === '0' ? false: value; return !!this.input.checked;
if(newValue !== value) },
flags.value(newValue); set: function (value, flags) {
this.input.checked = newValue; var newValue = value === 'false' || value === '0' ? false : value;
if (newValue !== value)
flags.value(newValue);
this.input.checked = newValue;
}
},
label: {
set: function (value) {
this.span.innerText = value;
},
get: function () {
}
},
value: 'checked'
} }
}, }, function () {
label: { var self = this;
set: function(value){ var label = document.createElement('label');
this.span.innerText = value;
}, var input = this.input = document.createElement('input');
get: function(){} input.type = 'checkbox';
},
value: 'checked'
}
}, function () {
var self = this;
var label = document.createElement('label');
var input = this.input = document.createElement('input'); this.span = document.createElement('span');
input.type = 'checkbox';
this.span = document.createElement('span');
label.appendChild(input); label.appendChild(input);
label.appendChild(this.span); label.appendChild(this.span);
label.className = 'Q-UI-CheckBox'; label.className = 'Q-UI-CheckBox';
input.addEventListener('change', function () { input.addEventListener('change', function () {
self._propChanged('checked', self.get('value')); self._propChanged('checked', self.get('value'));
}); });
this.el.appendChild(label); this.el.appendChild(label);
}); });
});
\ No newline at end of file
var UIComponent = require('../UIComponent'); module.exports =
QRequire('UI.UIComponent', function(
module.exports = UIComponent.extend('UI.Controls', 'ComboBox', { UIComponent
ctor: function () { ) {
}, 'use strict';
createEl: function () { return UIComponent.extend('UI.Controls', 'ComboBox', {
ctor: function () {
var _self = this; },
/* createEl: function () {
<div class="select-wrapper">
<button class="select-trigger">utc +3</button> var _self = this;
</div> /*
*/ <div class="select-wrapper">
<button class="select-trigger">utc +3</button>
var el = this.el = UIComponent.createElementCss('div', {}, 'select-wrapper'); </div>
*/
this.el.draggable = false;
var input = this.input = UIComponent.createElementCss('button', {}, 'select-trigger'); var el = this.el = UIComponent.createElementCss('div', {}, 'select-wrapper');
this.el.appendChild(input);
this.el.draggable = false;
var controls = var input = this.input = UIComponent.createElementCss('button', {}, 'select-trigger');
this.controls = this.el.appendChild(input);
UIComponent.createElementCss('div', {}, 'app-screen-controls');
var controls =
var dropDown = this.controls =
this.dropDown = UIComponent.createElementCss('div', {}, 'app-screen-controls');
UIComponent.createElementCss('div', {}, 'select-options-wrapper');
controls.appendChild(dropDown); var dropDown =
this.dropDown =
var title = UIComponent.createElementCss('div', {}, 'select-options-wrapper');
this.titleEl = controls.appendChild(dropDown);
UIComponent.createElementCss('span',{},'select-options-title');
dropDown.appendChild(title); var title =
this.titleEl =
var list = UIComponent.createElementCss('span', {}, 'select-options-title');
this.list = dropDown.appendChild(title);
UIComponent.createElementCss('ul',{},'select-options');
var list =
dropDown.appendChild(list); this.list =
UIComponent.createElementCss('ul', {}, 'select-options');
var realActive =
this.realActive = dropDown.appendChild(list);
UIComponent.createElementCss('ul', {
background: 'rgba(0,0,0,0.5)', var realActive =
position: 'absolute', this.realActive =
top:'150px', UIComponent.createElementCss('ul', {
height: '150px' background: 'rgba(0,0,0,0.5)',
},'select-options'); position: 'absolute',
top: '150px',
dropDown.appendChild(realActive); height: '150px'
realActive.addEventListener('click', function(){ }, 'select-options');
document.body.removeChild(controls);
_self.set('value',_self.items[_self.lastActive].key); dropDown.appendChild(realActive);
}); realActive.addEventListener('click', function () {
document.body.removeChild(controls);
var activeLi = UIComponent.createElementCss('li',{},'active'); _self.set('value', _self.items[_self.lastActive].key);
realActive.appendChild(activeLi); });
var activeLi = UIComponent.createElementCss('li', {}, 'active');
this.lastActive = -1; realActive.appendChild(activeLi);
var setActive = function(){
var num = Math.round(list.scrollTop/150);
if(num !== _self.lastActive){ this.lastActive = -1;
if(_self.lastActive>-1) { var setActive = function () {
list.childNodes[_self.lastActive+1].classList.remove('active'); var num = Math.round(list.scrollTop / 150);
list.childNodes[_self.lastActive+1].innerText = _self.items[_self.lastActive].val; if (num !== _self.lastActive) {
if (_self.lastActive > -1) {
list.childNodes[_self.lastActive + 1].classList.remove('active');
list.childNodes[_self.lastActive + 1].innerText = _self.items[_self.lastActive].val;
}
list.childNodes[num + 1].classList.add('active');
list.childNodes[num + 1].innerHTML = '&nbsp;';
activeLi.innerText = _self.items[num].val;
_self.lastActive = num;
list.scrollTop = num * 150;
}
};
input.addEventListener('click', function () {
document.body.appendChild(controls);
list.scrollTop = _self.lastActive * 150;
});
setTimeout(setActive, 10);
controls.addEventListener('wheel', function (e) {
if (e.deltaY > 0)
list.scrollTop += 150;
else
list.scrollTop -= 150;
setActive();
e.preventDefault();
e.stopPropagation();
//console.log(e)
});
/*
this.back = UIComponent.createElementCss('div', {
background: '#ddd',
height: height - pad * 2 + 'px',
left: height / 2 + 'px',
right: height / 2 + 'px',
top: pad + 'px',
position: 'absolute'
});
/*
var mouseMoveListener = function (e) {
_self._getInfo();
update(e);
};
var update = function (e) {
var x = e.clientX - left;
_self.updateValuePercent((x - height / 2) / (width - height));
};
var width, left;
this.el.addEventListener('mousedown', function (e, name, el) {
_self._getInfo();
var bound = _self.el.getBoundingClientRect();
width = bound.width;
left = bound.left;
update(e);
e.preventDefault();
document.addEventListener('mousemove', mouseMoveListener);
});
document.addEventListener('mouseup', function (e, name, el) {
document.removeEventListener('mousemove', mouseMoveListener);
});
*/
},
redraw: function (val) {
var list = this.list,
i, arr = [];
for (i in val) {
arr.push({key: i, val: val[i]});
} }
arr.sort();
list.childNodes[num+1].classList.add('active'); this.items = arr;
list.childNodes[num+1].innerHTML = '&nbsp;';
activeLi.innerText = _self.items[num].val; list.innerHTML = '<li class="active">&nbsp;</li>' + arr.map(function (el) {
_self.lastActive = num; return '<li>' + el.val + '</li>';
list.scrollTop = num*150; }).join('') + '<li class="active">&nbsp;</li>';
} this.itemHeight = 150; //(full-height)/(count-1)
}; },
input.addEventListener('click', function () { _prop: {
document.body.appendChild(controls); value: '_value',
_value: {
list.scrollTop = _self.lastActive*150; set: function (val, e) {
});
setTimeout(setActive, 10); this.input.innerText = (this.get('items') || {})[val] + '';
}
controls.addEventListener('wheel', function(e){ },
if(e.deltaY>0) items: {
list.scrollTop += 150; set: function (val, e) {
else if (typeof val === 'string') {
list.scrollTop -= 150; try {
setActive(); val = (new Function('', 'return ' + val))();
e.preventDefault(); e.value(val);
e.stopPropagation(); this.redraw(val);
} catch (e) {
//console.log(e) console.log('Invalid JSON ' + val);
}); }
setTimeout(function () {
this.set('value', this.get('value'));
/* }.bind(this), 1);
this.back = UIComponent.createElementCss('div', { } else {
background: '#ddd', this.redraw(val);
height: height - pad * 2 + 'px', }
left: height / 2 + 'px',
right: height / 2 + 'px',
top: pad + 'px', //debugger;
position: 'absolute' }
}); },
label: {
/* set: function (val) {
var mouseMoveListener = function (e) { this.titleEl.innerText = val;
_self._getInfo();
update(e);
};
var update = function (e) {
var x = e.clientX - left;
_self.updateValuePercent((x - height / 2) / (width - height));
};
var width, left;
this.el.addEventListener('mousedown', function (e, name, el) {
_self._getInfo();
var bound = _self.el.getBoundingClientRect();
width = bound.width;
left = bound.left;
update(e);
e.preventDefault();
document.addEventListener('mousemove', mouseMoveListener);
});
document.addEventListener('mouseup', function (e, name, el) {
document.removeEventListener('mousemove', mouseMoveListener);
});
*/
},
redraw: function (val) {
var list = this.list,
i, arr = [];
for(i in val){
arr.push({key: i, val: val[i]});
}
arr.sort();
this.items = arr;
list.innerHTML = '<li class="active">&nbsp;</li>'+arr.map(function(el){
return '<li>'+ el.val +'</li>';
}).join('')+'<li class="active">&nbsp;</li>';
this.itemHeight = 150; //(full-height)/(count-1)
},
_prop: {
value: '_value',
_value: {
set: function (val, e) {
this.input.innerText = (this.get('items')||{})[val]+'';
}
},
items: {
set: function (val, e) {
if(typeof val === 'string'){
try{
val = (new Function('','return '+val))();
e.value(val);
this.redraw(val);
}catch(e){
console.log('Invalid JSON '+val);
} }
setTimeout(function(){
this.set('value', this.get('value'));
}.bind(this),1);
}else{
this.redraw(val);
} }
//debugger;
} }
}, });
label: { });
set: function (val) { \ No newline at end of file
this.titleEl.innerText = val;
}
}
}
});
var UIComponent = require('../UIComponent'); module.exports =
QRequire('UI.UIComponent', 'observable-sequence', 'z-lib-structure-dequeue', function(
var ObservableSequence = require('observable-sequence'); UIComponent,
var dequeue = require('z-lib-structure-dequeue'); ObservableSequence,
dequeue
module.exports = UIComponent.extend('UI.Controls', 'ContainerComponent', { ) {
/** 'use strict';
* return UIComponent.extend('UI.Controls', 'ContainerComponent', {
* @param {} item /**
* @param {} prevItem *
* @param {} nextItem * @param {} item
* @param {} index * @param {} prevItem
* @returns {} * @param {} nextItem
*/ * @param {} index
_itemAddEventHandler: function (item, prevItem, nextItem, index) { * @returns {}
var self = this; */
var newComp = this._wrapItem(item); _itemAddEventHandler: function (item, prevItem, nextItem, index) {
var children = this._contentContainer ? this._contentContainer._children : this._children;
this._handleChildren(newComp, index, index);
newComp.on('click', function () {
var backgroundColor = self.get('selectionColor') || '#ffa834';
newComp.set('background', backgroundColor);
var currentIndex = self.get('selectedIndex');
self.fire('itemClick', self.get('itemSource').get(index));
if (currentIndex === index)
return;
if (currentIndex > -1)
children.get(currentIndex).set('background', '');
self.set('selectedItem', self.get('itemSource').get(index));
self.set('selectedIndex', index);
self.fire('selectionChanged', self.get('itemSource').get(index));
});
},
/**
*
* @param {} item
* @param {} prevItem
* @param {} nextItem
* @param {} index
* @returns {}
*/
_itemRemoveEventHandler: function (item, prevItem, nextItem, index) {
var children = this._contentContainer ? this._contentContainer._children : this._children;
children.splice(index, 1);
},
/**
* Wrap object in ItemTemplate
*
* @param {Object} item
* @returns {}
*/
_wrapItem: function (item) {
var template = this.get('itemTemplate');
var newComp = new template();
if ((typeof item !== 'object') || Array.isArray(item)) {
newComp.set('value', item);
} else {
for (var key in item)
if (item.hasOwnProperty(key))
newComp.set(key, item[key]);
}
return newComp;
},
_handleChildren: function (newComp, index) {
this.addChild(newComp);
},
_rebuildChildren: function (items) {
var self = this;
var children = this._contentContainer ? this._contentContainer._children : this._children;
while(children.length)
children.pop();
if (items) {
items.forEach(function (item, i, array) {
var newComp = self._wrapItem(item);
var index = children.length;
self._handleChildren(newComp, i, index);
});
}
},
_prop: {
value: 'itemSource',
selectionColor: {}, //qiwi color ffa834
selectedIndex: {
set: function (val) {
this.set('selectedItem', this.get('itemSource').get(val));
this.fire('selectionChanged', this.get('itemSource').get(val));
}
},
selectedItem: {
//set: null
},
itemSource: {
set: function (value, e) {
//TODO unsubscribe methods
var self = this; var self = this;
var val = value; var newComp = this._wrapItem(item);
if (!(value instanceof ObservableSequence) && value) { var children = this._contentContainer ? this._contentContainer._children : this._children;
if(e.oldValue instanceof ObservableSequence){
value = e.oldValue; this._handleChildren(newComp, index, index);
while(value.length)
value.pop(); newComp.on('click', function () {
var backgroundColor = self.get('selectionColor') || '#ffa834';
}else { newComp.set('background', backgroundColor);
value = new ObservableSequence(new dequeue());
var currentIndex = self.get('selectedIndex');
value.on('add', this._itemAddEventHandler.bind(this));
value.on('remove', this._itemRemoveEventHandler.bind(this)); self.fire('itemClick', self.get('itemSource').get(index));
}
if (currentIndex === index)
val.forEach(function (v) { return;
value.push(v);
if (currentIndex > -1)
children.get(currentIndex).set('background', '');
self.set('selectedItem', self.get('itemSource').get(index));
self.set('selectedIndex', index);
self.fire('selectionChanged', self.get('itemSource').get(index));
});
},
/**
*
* @param {} item
* @param {} prevItem
* @param {} nextItem
* @param {} index
* @returns {}
*/
_itemRemoveEventHandler: function (item, prevItem, nextItem, index) {
var children = this._contentContainer ? this._contentContainer._children : this._children;
children.splice(index, 1);
},
/**
* Wrap object in ItemTemplate
*
* @param {Object} item
* @returns {}
*/
_wrapItem: function (item) {
var template = this.get('itemTemplate');
var newComp = new template();
if ((typeof item !== 'object') || Array.isArray(item)) {
newComp.set('value', item);
} else {
for (var key in item)
if (item.hasOwnProperty(key))
newComp.set(key, item[key]);
}
return newComp;
},
_handleChildren: function (newComp, index) {
this.addChild(newComp);
},
_rebuildChildren: function (items) {
var self = this;
var children = this._contentContainer ? this._contentContainer._children : this._children;
while (children.length)
children.pop();
if (items) {
items.forEach(function (item, i, array) {
var newComp = self._wrapItem(item);
var index = children.length;
self._handleChildren(newComp, i, index);
}); });
e.value(value);
} }
},
//this._rebuildChildren(value); _prop: {
} value: 'itemSource',
}, selectionColor: {}, //qiwi color ffa834
itemTemplate: { selectedIndex: {
set: function (val, e) { set: function (val) {
if (typeof val === 'string') { this.set('selectedItem', this.get('itemSource').get(val));
var template = Q.Core.TypeTable.getType(val); this.fire('selectionChanged', this.get('itemSource').get(val));
if (template) { }
val = template; },
} else { selectedItem: {
throw new Error('Unknown template `' + val + '`') //set: null
},
itemSource: {
set: function (value, e) {
//TODO unsubscribe methods
var self = this;
var val = value;
if (!(value instanceof ObservableSequence) && value) {
if (e.oldValue instanceof ObservableSequence) {
value = e.oldValue;
while (value.length)
value.pop();
} else {
value = new ObservableSequence(new dequeue());
value.on('add', this._itemAddEventHandler.bind(this));
value.on('remove', this._itemRemoveEventHandler.bind(this));
}
val.forEach(function (v) {
value.push(v);
});
e.value(value);
}
//this._rebuildChildren(value);
}
},
itemTemplate: {
set: function (val, e) {
if (typeof val === 'string') {
var template = Q.Core.TypeTable.getType(val);
if (template) {
val = template;
} else {
throw new Error('Unknown template `' + val + '`')
}
}
e.value(this._data.itemTemplate = val);
this._rebuildChildren(this.get('itemSource'));
} }
} }
e.value(this._data.itemTemplate = val);
this._rebuildChildren(this.get('itemSource'));
} }
} });
} });
}); \ No newline at end of file
\ No newline at end of file
var UIComponent = require('../UIComponent'); module.exports =
QRequire('UI.UIComponent', 'UI.ContentContainer', function(
module.exports = UIComponent.extend('UI.Controls', 'FlexSizeComponent', { UIComponent,
_prop: { ContentContainer
value: 'flexDefenition', ) {
flexDefinition: { 'use strict';
set: function (value) {
var flexDefinition = {parts: [], starCount: 0, flexLength: 0, fixLength: 0}; return UIComponent.extend('UI.Controls', 'FlexSizeComponent', {
var stringParts = value.split(' '); _prop: {
value: 'flexDefenition',
for (var i = 0; i < stringParts.length; i++) { flexDefinition: {
var fPart = stringParts[i]; set: function (value) {
var flexDefinition = {parts: [], starCount: 0, flexLength: 0, fixLength: 0};
if (fPart.length === 0) continue; var stringParts = value.split(' ');
var newPart = {part: 0, flex: true}; for (var i = 0; i < stringParts.length; i++) {
var fPart = stringParts[i];
var parsedFloat = parseFloat(fPart);
if (fPart[fPart.length - 1] === '*') { if (fPart.length === 0) continue;
newPart.flex = true;
var newPart = {part: 0, flex: true};
if (!parsedFloat) {
flexDefinition.starCount += 1; var parsedFloat = parseFloat(fPart);
} else { if (fPart[fPart.length - 1] === '*') {
newPart.part = parsedFloat; newPart.flex = true;
flexDefinition.flexLength += parsedFloat;
if (!parsedFloat) {
flexDefinition.starCount += 1;
} else {
newPart.part = parsedFloat;
flexDefinition.flexLength += parsedFloat;
}
} else {
newPart.flex = false;
newPart.part = parsedFloat;
flexDefinition.fixLength += parsedFloat;
}
flexDefinition.parts.push(newPart);
} }
this._flexDefinition = flexDefinition;
} else { this.updateLayout();
newPart.flex = false;
newPart.part = parsedFloat;
flexDefinition.fixLength += parsedFloat;
} }
flexDefinition.parts.push(newPart);
} }
this._flexDefinition = flexDefinition;
this.updateLayout();
} }
} });
} });
}); \ No newline at end of file
\ No newline at end of file
...@@ -2,188 +2,194 @@ ...@@ -2,188 +2,194 @@
* Created by ravenor on 13.07.16. * Created by ravenor on 13.07.16.
*/ */
var UIComponent = require('../UIComponent'); module.exports =
QRequire('UI.UIComponent', 'UI.ContentContainer', function(
module.exports = UIComponent.extend('UI.Controls', 'GeoMap', { UIComponent,
createEl: function () { ContentContainer
var self = this; ) {
'use strict';
this.id = "8249t7cjnap8otmw89yuao4867ta209";
return UIComponent.extend('UI.Controls', 'GeoMap', {
this.el = document.createElement('div'); createEl: function () {
this.el.style.width = '100%'; var self = this;
this.el.style.height = '100%';
this.el.id = this.id; this.id = "8249t7cjnap8otmw89yuao4867ta209";
this.set('home', [55.76, 37.64]); this.el = document.createElement('div');
this.set('zoom', 11); this.el.style.width = '100%';
this.el.style.height = '100%';
var script = document.createElement("script"); this.el.id = this.id;
script.src = 'https://api-maps.yandex.ru/2.1/?lang=en_US';
document.head.appendChild(script); this.set('home', [55.76, 37.64]);
this.set('zoom', 11);
script.addEventListener('load', function () {
ymaps.ready(function () { var script = document.createElement("script");
self._renderEl(); script.src = 'https://api-maps.yandex.ru/2.1/?lang=en_US';
self.set('ready', true); document.head.appendChild(script);
window.m = self.ymap; script.addEventListener('load', function () {
}); ymaps.ready(function () {
}); self._renderEl();
self.set('ready', true);
}, window.m = self.ymap;
});
_renderEl: function () { });
var self = this;
self.mapApi = ymaps; },
var center = self.get('center');
_renderEl: function () {
self.ymap = new ymaps.Map(self.id, { var self = this;
center: center || [55.7526, 37.6152],
zoom: self.get('zoom'), self.mapApi = ymaps;
// controls: ['zoomControl', 'searchControl'] var center = self.get('center');
controls: ['zoomControl']
}); self.ymap = new ymaps.Map(self.id, {
center: center || [55.7526, 37.6152],
self.pins = new ymaps.GeoObjectCollection(null, { zoom: self.get('zoom'),
preset: 'islands#blueCircleDotIconWithCaption' // controls: ['zoomControl', 'searchControl']
}); controls: ['zoomControl']
self.home = new ymaps.GeoObjectCollection(null, { });
preset: 'islands#redCircleDotIconWithCaption'
}); self.pins = new ymaps.GeoObjectCollection(null, {
preset: 'islands#blueCircleDotIconWithCaption'
/*self._createHome(); });
self._createPins();*/ self.home = new ymaps.GeoObjectCollection(null, {
self.ymap.geoObjects.add(self.pins).add(self.home); preset: 'islands#redCircleDotIconWithCaption'
});
self.ymap.events.add('boundschange', function () { /*self._createHome();
if (!self._handlingCenterEvent) { self._createPins();*/
var center = self.ymap.getCenter(); self.ymap.geoObjects.add(self.pins).add(self.home);
self.set('center', center);
}
}); self.ymap.events.add('boundschange', function () {
}, if (!self._handlingCenterEvent) {
var center = self.ymap.getCenter();
makeRoute: function (from, to) { self.set('center', center);
if (!this.mapApi) return; }
});
var self = this; },
self.ymap.geoObjects.remove(this.route); makeRoute: function (from, to) {
if (!this.mapApi) return;
var self = this;
self.ymap.geoObjects.remove(this.route);
self.mapApi.route(
[from, to],
{routingMode: 'masstransit', multiRoute: true}
).done(function (route) {
//self.mapApi.route({referencePoints:[from,to],params:{routingMode: 'masstransit'}}).then(function(route){
self.route = route;
self.ymap.geoObjects.add(self.route);
// Was binded one more time in every method call
// route.events.add('activeroutechange',self._updateMoveList);
self._updateMoveList();
});
},
_updateMoveList: function () {
var way, segments, moveList = [],
tempRoute = this.route.getActiveRoute();
for (var i = 0; i < tempRoute.getPaths().getLength(); i++) {
way = tempRoute.getPaths().get(i);
segments = way.getSegments();
for (var j = 0; j < segments.getLength(); j++) {
var segment = segments.get(j);
moveList.push(segment.properties.get('text'));
}
}
self.mapApi.route( this.set('moveList', moveList);
[from, to], },
{routingMode: 'masstransit', multiRoute: true}
).done(function (route) {
//self.mapApi.route({referencePoints:[from,to],params:{routingMode: 'masstransit'}}).then(function(route){
self.route = route;
self.ymap.geoObjects.add(self.route);
// Was binded one more time in every method call _createHome: function () {
// route.events.add('activeroutechange',self._updateMoveList); var homeData = this.get('home');
self._updateMoveList(); //
}); if (homeData && this.home) {
}, this.home.add(
new ymaps.Placemark(homeData, {iconCaption: 'You are here'})
_updateMoveList: function () { );
var way, segments, moveList = [],
tempRoute = this.route.getActiveRoute();
for (var i = 0; i < tempRoute.getPaths().getLength(); i++) {
way = tempRoute.getPaths().get(i);
segments = way.getSegments();
for (var j = 0; j < segments.getLength(); j++) {
var segment = segments.get(j);
moveList.push(segment.properties.get('text'));
}
}
this.set('moveList', moveList);
},
_createHome: function () {
var homeData = this.get('home');
//
if (homeData && this.home) {
this.home.add(
new ymaps.Placemark(homeData, {iconCaption: 'You are here'})
);
}
},
_removeHome: function () {
if (this.home)
this.home.removeAll();
},
_createPins: function (pinsData) {
var self = this;
pinsData = pinsData || this.get('pins');
//
if (pinsData && this.pins) {
for (var i = 0; i < pinsData.length; i++) {
var p = pinsData[i];
self.pins.add(
new ymaps.Placemark(p.coords, {
iconCaption: p.name
})
);
}
}
},
_removePins: function () {
if (this.pins)
this.pins.removeAll();
},
_prop: {
ready: {},
zoom: {
set: function (value) {
if (this.ymap)
this.ymap.setZoom(value, {duration: 200});
return value;
}
},
pins: {
set: function (value) {
if (this.mapApi) {
this._removePins();
this._createPins(value);
} }
}
}, },
home: {
set: function (value) { _removeHome: function () {
if (this.mapApi) { if (this.home)
this._removeHome(this); this.home.removeAll();
this._createHome(this); },
}
} _createPins: function (pinsData) {
}, var self = this;
moveList: {
set: function () { pinsData = pinsData || this.get('pins');
} //
}, if (pinsData && this.pins) {
for (var i = 0; i < pinsData.length; i++) {
center: { var p = pinsData[i];
set: function (value) { self.pins.add(
if (this.mapApi) { new ymaps.Placemark(p.coords, {
this._handlingCenterEvent = true; iconCaption: p.name
this.ymap.setCenter(value); })
this._handlingCenterEvent = false; );
}
} }
},
_removePins: function () {
if (this.pins)
this.pins.removeAll();
},
_prop: {
ready: {},
zoom: {
set: function (value) {
if (this.ymap)
this.ymap.setZoom(value, {duration: 200});
return value;
}
},
pins: {
set: function (value) {
if (this.mapApi) {
this._removePins();
this._createPins(value);
}
}
},
home: {
set: function (value) {
if (this.mapApi) {
this._removeHome(this);
this._createHome(this);
}
}
},
moveList: {
set: function () {
}
},
center: {
set: function (value) {
if (this.mapApi) {
this._handlingCenterEvent = true;
this.ymap.setCenter(value);
this._handlingCenterEvent = false;
}
}
},
value: 'center'
} }
}, });
});
value: 'center' \ No newline at end of file
}
});
var UIComponent = require('../UIComponent'); module.exports =
QRequire('UI.UIComponent', 'UI.ContentContainer', function(
UIComponent,
ContentContainer
) {
'use strict';
module.exports = UIComponent.extend('UI.Controls', 'GovnoControl', { return UIComponent.extend('UI.Controls', 'GovnoControl', {
createEl: function () { createEl: function () {
var self = this; var self = this;
this.el = document.createElement('div'); this.el = document.createElement('div');
this.el.id = 'GovnoControlTable'; this.el.id = 'GovnoControlTable';
this.el.style.width = '500px'; this.el.style.width = '500px';
this.el.style.height = '300px'; this.el.style.height = '300px';
setTimeout(function () { setTimeout(function () {
self.govnotable = $('#GovnoControlTable').editTable({ self.govnotable = $('#GovnoControlTable').editTable({
data: [['date', new Date().toLocaleDateString()], ['amount', '500'], ['comission', '5']], data: [['date', new Date().toLocaleDateString()], ['amount', '500'], ['comission', '5']],
first_row: false, first_row: false,
headerCols: [ headerCols: [
'Key', 'Key',
'Value' 'Value'
] ]
}); });
$('#GovnoControlTable').on('keyup', 'input', function () { $('#GovnoControlTable').on('keyup', 'input', function () {
self.set('data', self.get('data')); self.set('data', self.get('data'));
}); });
}, 100); }, 100);
}, },
_prop: { _prop: {
data: { data: {
get: function () { get: function () {
var tdata = this.govnotable ? this.govnotable.getData() : []; var tdata = this.govnotable ? this.govnotable.getData() : [];
var data = {}; var data = {};
for (var i = 0; i < tdata.length; i++) { for (var i = 0; i < tdata.length; i++) {
var record = tdata[i]; var record = tdata[i];
data[record[0]] = record[1]; data[record[0]] = record[1];
} }
return data; return data;
}
}
} }
} });
} });
}); \ No newline at end of file
\ No newline at end of file
var UIComponent = require('../UIComponent'); module.exports =
var Border = require('./Border'); QRequire('UI.UIComponent', 'UI.Border', function(
UIComponent,
Border
) {
'use strict';
var propNames = ['width', 'height', 'top', 'left'];
var base = Border.prototype; var propNames = ['width', 'height', 'top', 'left'];
module.exports = Border.extend('UI.Controls', 'Grid', { var base = Border.prototype;
ctor: function () {
this._cache = {};
this.setAll({
rows: 1,
columns: 1
});
},
createEl: function () {
base.createEl.apply(this, arguments);
var self = this;
this.el.addEventListener('resize', function () {
self.updateLayout();
});
},
addChild: function (child) {
var self = this;
this._calcChild(child);
for (var i = 0; i < propNames.length; i++) { return Border.extend('UI.Controls', 'Grid', {
var pName = propNames[i]; ctor: function () {
(function (name) { this._cache = {};
child.ref(pName).subscribe(function (value) { this.setAll({
if (propNames.indexOf(name) === -1) return; rows: 1,
columns: 1
if (self._cache[child.id + name] !== value) { });
self._calcChild(child); },
} createEl: function () {
base.createEl.apply(this, arguments);
var self = this;
this.el.addEventListener('resize', function () {
self.updateLayout();
}); });
})(pName); },
} addChild: function (child) {
var self = this;
this._calcChild(child);
base.addChild.call(this, child); for (var i = 0; i < propNames.length; i++) {
}, var pName = propNames[i];
_calcChild: function (cmp) { (function (name) {
var rows = this._data.rows; child.ref(pName).subscribe(function (value) {
var cols = this._data.columns; if (propNames.indexOf(name) === -1) return;
var width = cmp.get('width'); if (self._cache[child.id + name] !== value) {
var height = cmp.get('height'); self._calcChild(child);
var top = cmp.get('top') || 0; }
var left = cmp.get('left') || 0; });
})(pName);
}
cmp.el.style.position = 'absolute'; base.addChild.call(this, child);
this._setToComponent(cmp, 'left', ((100 / cols) * left) + '%'); },
this._setToComponent(cmp, 'width', ((100 / cols) * width) + '%'); _calcChild: function (cmp) {
this._setToComponent(cmp, 'top', ((100 / rows) * top) + '%'); var rows = this._data.rows;
this._setToComponent(cmp, 'height', ((100 / rows) * height) + '%'); var cols = this._data.columns;
},
_setToComponent: function (cmp, pName, pValue) { var width = cmp.get('width');
cmp.set(pName, pValue); var height = cmp.get('height');
this._cache[cmp.id + pName] = pValue; var top = cmp.get('top') || 0;
}, var left = cmp.get('left') || 0;
_prop: {
rows: {}, cmp.el.style.position = 'absolute';
columns: {}, this._setToComponent(cmp, 'left', ((100 / cols) * left) + '%');
} this._setToComponent(cmp, 'width', ((100 / cols) * width) + '%');
}); this._setToComponent(cmp, 'top', ((100 / rows) * top) + '%');
\ No newline at end of file this._setToComponent(cmp, 'height', ((100 / rows) * height) + '%');
},
_setToComponent: function (cmp, pName, pValue) {
cmp.set(pName, pValue);
this._cache[cmp.id + pName] = pValue;
},
_prop: {
rows: {},
columns: {},
}
});
});
\ No newline at end of file
var UIComponent = require('../UIComponent'); module.exports =
var FlexSizeComponent = require('./FlexSizeComponent'); QRequire('UI.UIComponent', 'UI.Border','UI.FlexSizeComponent', function(
var Border = require('./Border'); UIComponent,
Border,
FlexSizeComponent
) {
'use strict';
return FlexSizeComponent.extend('UI.Controls', 'HBox', {
ctor: function () {
this.set('height', '100%');
},
_createEl: function () {
FlexSizeComponent.prototype._createEl.apply(this, arguments);
var self = this;
this.el.addEventListener('resize', function () {
self.updateLayout();
});
},
updateLayout: function () {
var self = this;
var children = this._children;
module.exports = FlexSizeComponent.extend('UI.Controls', 'HBox', { clearTimeout(this.updateTimeout);
ctor: function () { this.updateTimeout = setTimeout(function () {
this.set('height', '100%'); var fDef = self._flexDefinition || {parts: [], starCount: 0, flexLength: 0, fixLength: 0};
}, var starCount = fDef.starCount;
_createEl: function () { if (fDef.parts.length === 0)
FlexSizeComponent.prototype._createEl.apply(this, arguments); starCount = children.length;
var self = this;
this.el.addEventListener('resize', function () {
self.updateLayout();
});
},
updateLayout: function () {
var self = this;
var children = this._children;
clearTimeout(this.updateTimeout); var freeWidth = 100 - 100 * (fDef.fixLength / self.el.clientWidth);
this.updateTimeout = setTimeout(function () {
var fDef = self._flexDefinition || {parts: [], starCount: 0, flexLength: 0, fixLength: 0};
var starCount = fDef.starCount;
if (fDef.parts.length === 0)
starCount = children.length;
var freeWidth = 100 - 100 * (fDef.fixLength / self.el.clientWidth); for (var i = 0, length = children.length; i < length; i++) {
var fPart = fDef.parts[i];
for (var i = 0, length = children.length; i < length; i++) { var width = freeWidth / starCount + '%';
var fPart = fDef.parts[i]; if (fPart) {
var width = freeWidth / starCount + '%'; if (fPart.flex && fPart.part > 0) // 25*
if (fPart) { width = freeWidth * (fPart.part / fDef.flexLength) + '%';
if (fPart.flex && fPart.part > 0) // 25* if (!fPart.flex) { // 25
width = freeWidth * (fPart.part / fDef.flexLength) + '%'; width = fPart.part + 'px';
if (!fPart.flex) { // 25 }
width = fPart.part + 'px'; } else {
width = freeWidth / starCount + '%';
} }
} else { children.get(i).set('width', width);
width = freeWidth / starCount + '%';
}
children.get(i).set('width', width);
} }
}, 0); }, 0);
FlexSizeComponent.prototype.updateLayout.call(this); FlexSizeComponent.prototype.updateLayout.call(this);
}, },
addChild: function (child) { addChild: function (child) {
var div = new Border({ var div = new Border({
pureCss: 'float: left;', pureCss: 'float: left;',
height: '100%' height: '100%'
}); });
div.addChild(child); div.addChild(child);
this._children.push(div); this._children.push(div);
this.updateLayout(); this.updateLayout();
} }
});
}); });
\ No newline at end of file
...@@ -2,10 +2,14 @@ ...@@ -2,10 +2,14 @@
* Created by ravenor on 13.07.16. * Created by ravenor on 13.07.16.
*/ */
var Label = require('./Label'); QRequire('UI.Label', function(
Label
) {
'use strict';
module.exports = Label.extend('UI.Controls', 'Header', { return Label.extend('UI.Controls', 'Header', {
ctor: function () { ctor: function () {
this.set("fontSize", '36px'); this.set("fontSize", '36px');
} }
});
}); });
\ No newline at end of file
var UIComponent = require('../UIComponent'); QRequire('UI.UIComponent', function(
UIComponent
) {
'use strict';
module.exports = UIComponent.extend('UI.Controls', 'IFrame', { return UIComponent.extend('UI.Controls', 'IFrame', {
createEl: function () { createEl: function () {
this.el = document.createElement('iframe'); this.el = document.createElement('iframe');
}, },
_prop: { _prop: {
value: 'source', value: 'source',
source: { source: {
set: function (value) { set: function (value) {
this.el.src = value; this.el.src = value;
}
} }
} }
} });
}); });
\ No newline at end of file
var UIComponent = require('../UIComponent'); QRequire('UI.UIComponent', function(
UIComponent
) {
'use strict';
module.exports = UIComponent.extend('UI.Controls', 'Image', { return UIComponent.extend('UI.Controls', 'Image', {
createEl: function () { createEl: function () {
this.el = document.createElement('div'); this.el = document.createElement('div');
this.elStyle = this.el.style; this.elStyle = this.el.style;
this.elStyle.backgroundPosition = 'center'; this.elStyle.backgroundPosition = 'center';
this.elStyle.backgroundRepeat = 'no-repeat'; this.elStyle.backgroundRepeat = 'no-repeat';
},
_prop: {
value: 'source',
source: {
set: function (value) {
this.elStyle.backgroundImage = 'url(' + value + ')';
}
}, },
stretch: { _prop: {
set: function (value) { value: 'source',
switch (value) { source: {
case 'none': set: function (value) {
this.elStyle.backgroundSize = 'auto auto'; this.elStyle.backgroundImage = 'url(' + value + ')';
break;
case 'fill':
this.elStyle.backgroundSize = '100% 100%';
break;
case 'uniform':
this.elStyle.backgroundSize = 'contain';
break;
case 'uniformToFill':
this.elStyle.backgroundSize = 'cover';
break;
default:
this.elStyle.backgroundSize = 'auto auto';
} }
} },
}, stretch: {
} set: function (value) {
switch (value) {
case 'none':
this.elStyle.backgroundSize = 'auto auto';
break;
case 'fill':
this.elStyle.backgroundSize = '100% 100%';
break;
case 'uniform':
this.elStyle.backgroundSize = 'contain';
break;
case 'uniformToFill':
this.elStyle.backgroundSize = 'cover';
break;
default:
this.elStyle.backgroundSize = 'auto auto';
}
}
},
}
});
}); });
\ No newline at end of file
var UIComponent = require('./../UIComponent'); QRequire('UI.UIComponent', function(
UIComponent
) {
'use strict';
module.exports = UIComponent.extend('UI.Controls', 'ItemTemplate', { return UIComponent.extend('UI.Controls', 'ItemTemplate', {
ctor: function () { ctor: function () {
var self = this; var self = this;
this.el.addEventListener('click', function (e) { this.el.addEventListener('click', function (e) {
self.fire('click', e); self.fire('click', e);
}); });
}, },
_prop: { _prop: {
value: '_value', value: '_value',
_value: {} _value: {}
} }
});
}); });
\ No newline at end of file
...@@ -6,21 +6,24 @@ ...@@ -6,21 +6,24 @@
;// QUOKKA 2017 ;// QUOKKA 2017
// By zibx on 5/23/17. // By zibx on 5/23/17.
module.exports = (function () { QRequire('UI.UIComponent', function(
UIComponent
) {
'use strict'; 'use strict';
var layouts = { var layouts = {
none: [], none: [],
'ru': [ 'ru': [
['йцукенгшщзхъ'], ['йцукенгшщзхъ'],
['фывапролджэ'], ['фывапролджэ'],
['ячсмитьбю', {"text":"", "cls": "del", action: 'backspace'}], ['ячсмитьбю', {"text": "", "cls": "del", action: 'backspace'}],
[{"text":" ", "value": " ", "width": "408", "cls": "space"}] [{"text": " ", "value": " ", "width": "408", "cls": "space"}]
], ],
'en': [ 'en': [
['qwertyuiop'], ['qwertyuiop'],
['asdfghjkl'], ['asdfghjkl'],
['zxcvbnm', {"text":"", "cls": "del", action: 'backspace'}], ['zxcvbnm', {"text": "", "cls": "del", action: 'backspace'}],
[{"text":" ", "value": " ", "width": "408", "cls": "space"}] [{"text": " ", "value": " ", "width": "408", "cls": "space"}]
] ]
}; };
var big = function (name) { var big = function (name) {
...@@ -29,7 +32,7 @@ module.exports = (function () { ...@@ -29,7 +32,7 @@ module.exports = (function () {
newLayout = layout.map(function (row) { newLayout = layout.map(function (row) {
return row.map(function (item) { return row.map(function (item) {
if(typeof item === 'string') if (typeof item === 'string')
return item.toUpperCase(); return item.toUpperCase();
else else
return item; return item;
...@@ -41,7 +44,6 @@ module.exports = (function () { ...@@ -41,7 +44,6 @@ module.exports = (function () {
big('ru'); big('ru');
big('en'); big('en');
var UIComponent = require('../UIComponent');
var counter = 0; var counter = 0;
var keyStorage = {}; var keyStorage = {};
var Key = function (cfg) { var Key = function (cfg) {
...@@ -49,10 +51,12 @@ module.exports = (function () { ...@@ -49,10 +51,12 @@ module.exports = (function () {
this.el = document.createElement('div'); this.el = document.createElement('div');
this.el.innerText = this.text; this.el.innerText = this.text;
var cls = ['']; var cls = [''];
if(cfg.cls) if (cfg.cls)
cls = cls.concat(cfg.cls); cls = cls.concat(cfg.cls);
this.el.className = cls.map(function(name){return 'kb-btn'+(name?'--'+name:'')}).join(' '); this.el.className = cls.map(function (name) {
return 'kb-btn' + (name ? '--' + name : '')
}).join(' ');
this.id = counter; this.id = counter;
this.el.setAttribute('data-val', this.id); this.el.setAttribute('data-val', this.id);
counter++; counter++;
...@@ -67,44 +71,44 @@ module.exports = (function () { ...@@ -67,44 +71,44 @@ module.exports = (function () {
var layoutsCache = {}; var layoutsCache = {};
var simpleKey = function (cfg) { var simpleKey = function (cfg) {
return new Key({text: cfg, value: cfg}); return new Key({text: cfg, value: cfg});
}; };
return UIComponent.extend('UI.Controls', 'Keyboard', { return UIComponent.extend('UI.Controls', 'Keyboard', {
_tabProtocol: function(delegate){ _tabProtocol: function (delegate) {
if(delegate){ if (delegate) {
this.delegate = delegate; this.delegate = delegate;
var _self = this; var _self = this;
delegate.layout = function(val){ delegate.layout = function (val) {
_self.set('layout', val); _self.set('layout', val);
}; };
return false; return false;
}else{ } else {
this.delegate.skip(); this.delegate.skip();
} }
}, },
ctor: function(){ ctor: function () {
var origin, var origin,
_self = this; _self = this;
var currentKey; var currentKey;
var up = function(e){ var up = function (e) {
window.removeEventListener('mouseup', up); window.removeEventListener('mouseup', up);
/*if(e.target === origin){ /*if(e.target === origin){
}*/ }*/
var val = origin.getAttribute('data-val'), var val = origin.getAttribute('data-val'),
key = keyStorage[val]; key = keyStorage[val];
currentKey.el.classList.remove('Over'); currentKey.el.classList.remove('Over');
if(key === currentKey){ if (key === currentKey) {
_self.delegate.send({e: e, key: key.text, action: key.action}); _self.delegate.send({e: e, key: key.text, action: key.action});
console.log(key) console.log(key)
} }
e.preventDefault(); e.preventDefault();
}; };
this.el.addEventListener('mousedown', function(e){ this.el.addEventListener('mousedown', function (e) {
origin = e.target; origin = e.target;
var val = origin.getAttribute('data-val'); var val = origin.getAttribute('data-val');
if(val) { if (val) {
currentKey = keyStorage[val]; currentKey = keyStorage[val];
currentKey.el.classList.add('Over'); currentKey.el.classList.add('Over');
} }
...@@ -112,34 +116,34 @@ module.exports = (function () { ...@@ -112,34 +116,34 @@ module.exports = (function () {
window.addEventListener('mouseup', up); window.addEventListener('mouseup', up);
}); });
window.addEventListener('keydown', function(e){ window.addEventListener('keydown', function (e) {
console.log(e.key, e.key.length,e.which,e); console.log(e.key, e.key.length, e.which, e);
if(e.which === 9) { if (e.which === 9) {
if(e.shiftKey){ if (e.shiftKey) {
_self.delegate.prev(); _self.delegate.prev();
}else { } else {
_self.delegate.next(); _self.delegate.next();
} }
e.preventDefault(); e.preventDefault();
e.stopPropagation(); e.stopPropagation();
} }
}); });
window.addEventListener('keypress', function(e){ window.addEventListener('keypress', function (e) {
_self.delegate.send({e: e, key: e.key}); _self.delegate.send({e: e, key: e.key});
e.preventDefault(); e.preventDefault();
e.stopPropagation(); e.stopPropagation();
}); });
}, },
lastLayoutName: void 0, lastLayoutName: void 0,
changeLayout: function(){ changeLayout: function () {
var lastLayoutName = this.lastLayoutName, var lastLayoutName = this.lastLayoutName,
layoutName = this.get('layout'), layoutName = this.get('layout'),
layoutConfig, rows, layout; layoutConfig, rows, layout;
if(lastLayoutName === layoutName) if (lastLayoutName === layoutName)
return; return;
if(!layoutsCache[layoutName]){ // if not cached if (!layoutsCache[layoutName]) { // if not cached
layoutConfig = layouts[layoutName]; // get config layoutConfig = layouts[layoutName]; // get config
...@@ -176,12 +180,12 @@ module.exports = (function () { ...@@ -176,12 +180,12 @@ module.exports = (function () {
rows.forEach(function (row) { // add rows elements to layout element rows.forEach(function (row) { // add rows elements to layout element
layout.el.appendChild(row.el); layout.el.appendChild(row.el);
}); });
}else{ } else {
layout = layoutsCache[layoutName]; layout = layoutsCache[layoutName];
} }
this.el.appendChild(layout.el); this.el.appendChild(layout.el);
if(lastLayoutName){ if (lastLayoutName) {
this.el.removeChild(layoutsCache[lastLayoutName].el); this.el.removeChild(layoutsCache[lastLayoutName].el);
} }
...@@ -189,10 +193,10 @@ module.exports = (function () { ...@@ -189,10 +193,10 @@ module.exports = (function () {
}, },
_prop: { _prop: {
layout: { layout: {
set: function(value, e){ set: function (value, e) {
if(!layouts[value]){ if (!layouts[value]) {
value = e.oldValue; value = e.oldValue;
console.log('Incorrect keyboard layout `'+ value +'`, switched back to `'+ e.oldValue +'`'); console.log('Incorrect keyboard layout `' + value + '`, switched back to `' + e.oldValue + '`');
} }
e.value(value); e.value(value);
this.changeLayout(); this.changeLayout();
...@@ -200,4 +204,4 @@ module.exports = (function () { ...@@ -200,4 +204,4 @@ module.exports = (function () {
} }
} }
}); });
})(); });
\ No newline at end of file \ No newline at end of file
...@@ -2,20 +2,26 @@ ...@@ -2,20 +2,26 @@
* Created by ravenor on 13.07.16. * Created by ravenor on 13.07.16.
*/ */
var UIComponent = require('../UIComponent'); module.exports =
QRequire('UI.UIComponent', function(
UIComponent
) {
'use strict';
module.exports = UIComponent.extend('UI.Controls', 'Label', { return UIComponent.extend('UI.Controls', 'Label', {
_prop: { ctor: function () {
value: 'text', this.set("width", "auto");
text: { this.set("height", "auto");
set: function (val) { this.set("pureCss", 'overflow: visible');
},
_prop: {
value: 'text',
text: {
set: function (val) {
this.el.innerHTML = val === void 0 ? '' : val; this.el.innerHTML = val === void 0 ? '' : val;
}
}
} }
} });
} });
}, function () { \ No newline at end of file
this.set("width", "auto");
this.set("height", "auto");
this.set("pureCss", 'overflow: visible');
});
\ No newline at end of file
var UIComponent = require('../UIComponent'); QRequire('UI.UIComponent', 'UI.ContainerComponent', function(
var ContainerComponent = require('./ContainerComponent'); UIComponent,
ContainerComponent
) {
'use strict';
var base = UIComponent.prototype; var base = UIComponent.prototype;
module.exports = ContainerComponent.extend('UI.Controls', 'ListBox', { return ContainerComponent.extend('UI.Controls', 'ListBox', {
ctor: function () { ctor: function () {
this.setAll({ this.setAll({
scroll: 'vertical', scroll: 'vertical',
height: '100%' height: '100%'
}); });
}, },
_formatChild: function (childComp) { _formatChild: function (childComp) {
var childNode = childComp.el; var childNode = childComp.el;
childNode.style.position = 'relative'; childNode.style.position = 'relative';
if (this._data.orientation === 'horizontal') { if (this._data.orientation === 'horizontal') {
childNode.style.float = 'left'; childNode.style.float = 'left';
childNode.style.clear = 'none'; childNode.style.clear = 'none';
} }
if (this._data.orientation === 'vertical') { if (this._data.orientation === 'vertical') {
childNode.style.float = 'none'; childNode.style.float = 'none';
childNode.style.clear = 'both'; childNode.style.clear = 'both';
} }
}, },
_handleChildren: function (childComp, index) { _handleChildren: function (childComp, index) {
var self = this; var self = this;
this._formatChild(childComp); this._formatChild(childComp);
var childNode = childComp.el; var childNode = childComp.el;
/* /*
childNode.addEventListener('click', function () { childNode.addEventListener('click', function () {
self.set('selectedIndex', index); self.set('selectedIndex', index);
self.fire('select', index); self.fire('select', index);
}); });
childNode.addEventListener('mouseover', function () { childNode.addEventListener('mouseover', function () {
if (self.get('hoverMode')) { if (self.get('hoverMode')) {
self.set('selectedIndex', index); self.set('selectedIndex', index);
} }
}); });
*/ */
}, },
_prop: { _prop: {
hoverMode: {}, hoverMode: {},
orientation: { orientation: {
set: function (value) { set: function (value) {
var iterator = this._children.iterator(), item; var iterator = this._children.iterator(), item;
while (item = iterator.next()) { while (item = iterator.next()) {
this._formatChild(item); this._formatChild(item);
}
} }
} }
} }
} });
}); });
\ No newline at end of file
/** /**
* Created by zibx on 5/9/17. * Created by zibx on 5/9/17.
*/ */
var UIComponent = require('../UIComponent'); QRequire('UI.UIComponent', function(
UIComponent
) {
'use strict';
module.exports = UIComponent.extend('UI.Controls', 'TextArea', { return UIComponent.extend('UI.Controls', 'TextArea', {
_prop: { _prop: {
value: 'text', value: 'text',
text: { text: {
get: function () { get: function () {
return this.input.value; return this.input.value;
},
set: function (value) {
this.input.value = value;
}
},
label: {
set: function (val) {
this.label.innerText = val;
}
}, },
set: function (value) {
this.input.value = value;
}
},
label: {
set: function (val) {
this.label.innerText = val;
}
},
fontSize: { fontSize: {
set: function (value) { set: function (value) {
this.input.style.fontSize = value; this.input.style.fontSize = value;
this.input.style.lineHeight = value; this.input.style.lineHeight = value;
} }
}, },
color: { color: {
set: function (value) { set: function (value) {
this.input.style.color = value; this.input.style.color = value;
} }
}, },
focused: { focused: {
set: function (val) { set: function (val) {
this.removeClass(this.el, 'Q-UI-TextArea_focused'); this.removeClass(this.el, 'Q-UI-TextArea_focused');
if (val === true) if (val === true)
this.addClass(this.el, 'Q-UI-TextArea_focused'); this.addClass(this.el, 'Q-UI-TextArea_focused');
}
} }
} }
} }, function () {
}, function () { var self = this;
var self = this; var input = document.createElement('textarea');
var input = document.createElement('textarea'); this.el.className = 'Q-UI-TextArea';
this.el.className = 'Q-UI-TextArea'; input.style['box-sizing'] = 'border-box';
input.style['box-sizing'] = 'border-box'; input.style['width'] = '100%';
input.style['width'] = '100%'; input.style['height'] = '100%';
input.style['height'] = '100%'; input.addEventListener('keyup', function () {
input.addEventListener('keyup', function () { self._propChanged('text', self.get('value'));
self._propChanged('text', self.get('value')); });
});
input.type = 'text'; input.type = 'text';
this.input = input; this.input = input;
var label = this.label = document.createElement('span'); var label = this.label = document.createElement('span');
label.className = 'Q-UI-TextArea__label'; label.className = 'Q-UI-TextArea__label';
this.el.appendChild(input); this.el.appendChild(input);
this.el.appendChild(label); this.el.appendChild(label);
self.set('width', '400px'); self.set('width', '400px');
self.set('height', '400px'); self.set('height', '400px');
}); });
});
\ No newline at end of file
var UIComponent = require('../UIComponent'); QRequire('UI.UIComponent', function(
UIComponent
var height = 20; ) {
var pad = height / 8; 'use strict';
module.exports = UIComponent.extend('UI.Controls', 'Slider', { var height = 20;
ctor: function () { var pad = height / 8;
this.set('from', 0);
this.set('to', 100); return UIComponent.extend('UI.Controls', 'Slider', {
this.set('step', 1); ctor: function () {
this.set('value', 50); this.set('from', 0);
}, this.set('to', 100);
createEl: function () { this.set('step', 1);
var _self = this; this.set('value', 50);
var el = this.el = UIComponent.createElementCss('div', {
position: 'relative',
height: height + 'px',
minHeight: height +'px'
});
this.el.draggable = false;
this.back = UIComponent.createElementCss('div', {
background: '#ddd',
height: height - pad * 2 + 'px',
left: height / 2 + 'px',
right: height / 2 + 'px',
top: pad + 'px',
position: 'absolute'
});
this.left = UIComponent.createElementCss('div', {
background: '#e00',
height: height - pad * 2 + 'px',
left: height / 2 + 'px',
right: height / 2 + 'px',
top: pad + 'px',
position: 'absolute'
});
this.right = UIComponent.createElementCss('div', {});
this.drag = UIComponent.createElementCss('div', {
background: '#e00',
width: (height - 2) + 'px',
height: (height - 2) + 'px',
top: '1px',
//'margin-left': -(height / 2) +'px',
//background: '#FF0',
left: '50%',
position: 'absolute',
cursor: 'pointer',
'border-radius': height / 2 + 'px',
'box-shadow': '0 0 1px #000'
});
this.el.appendChild(this.back);
this.el.appendChild(this.left);
this.el.appendChild(this.right);
this.el.appendChild(this.drag);
this.left.draggable = false;
this.drag.draggable = false;
this.right.draggable = false;
this.back.draggable = false;
var mouseMoveListener = function (e) {
_self._getInfo();
update(e);
};
var update = function (e) {
var x = e.clientX - left;
_self.updateValuePercent((x - height / 2) / (width - height));
};
var width, left;
this.el.addEventListener('mousedown', function (e, name, el) {
_self._getInfo();
var bound = _self.el.getBoundingClientRect();
width = bound.width;
left = bound.left;
update(e);
e.preventDefault();
document.addEventListener('mousemove', mouseMoveListener);
});
document.addEventListener('mouseup', function (e, name, el) {
document.removeEventListener('mousemove', mouseMoveListener);
});
},
updateLayout: function () {
this._getInfo();
this.set('value', this.get('value'));
},
updateValuePercent: function (val) {
this._getInfo;
this.set('value', val * (this._data.to - this._data.from) + this._data.from);
},
_getInfo: function (e) {
var self = this;
return this.info = {
from: self.get('from'),
to: self.get('to'),
step: self.get('step'),
width: this.el.clientWidth,
left: e && e.target.offsetLeft,
x: e && e.clientX,
y: e && e.clientY
};
},
_prop: {
value: '_value',
_value: {
set: function (val, e) {
this._getInfo();
val = val || 0;
var info = this.info || this._getInfo();
var wid, pos,
step = info.step - 0, from = info.from - 0, to = info.to - 0, delta = to - from;
val < from && (val = from);
val > to && (val = to);
if (step)
val = Math.round(val / step) * step;
wid = (val - from) / delta * (info.width - height);
this.drag.style.left = wid + 'px';
this.left.style.width = wid + 'px';
e.value(val);
}
}, },
from: { createEl: function () {
set: function (val) { var _self = this;
this._getInfo(); var el = this.el = UIComponent.createElementCss('div', {
this.updateLayout(); position: 'relative',
} height: height + 'px',
minHeight: height + 'px'
});
this.el.draggable = false;
this.back = UIComponent.createElementCss('div', {
background: '#ddd',
height: height - pad * 2 + 'px',
left: height / 2 + 'px',
right: height / 2 + 'px',
top: pad + 'px',
position: 'absolute'
});
this.left = UIComponent.createElementCss('div', {
background: '#e00',
height: height - pad * 2 + 'px',
left: height / 2 + 'px',
right: height / 2 + 'px',
top: pad + 'px',
position: 'absolute'
});
this.right = UIComponent.createElementCss('div', {});
this.drag = UIComponent.createElementCss('div', {
background: '#e00',
width: (height - 2) + 'px',
height: (height - 2) + 'px',
top: '1px',
//'margin-left': -(height / 2) +'px',
//background: '#FF0',
left: '50%',
position: 'absolute',
cursor: 'pointer',
'border-radius': height / 2 + 'px',
'box-shadow': '0 0 1px #000'
});
this.el.appendChild(this.back);
this.el.appendChild(this.left);
this.el.appendChild(this.right);
this.el.appendChild(this.drag);
this.left.draggable = false;
this.drag.draggable = false;
this.right.draggable = false;
this.back.draggable = false;
var mouseMoveListener = function (e) {
_self._getInfo();
update(e);
};
var update = function (e) {
var x = e.clientX - left;
_self.updateValuePercent((x - height / 2) / (width - height));
};
var width, left;
this.el.addEventListener('mousedown', function (e, name, el) {
_self._getInfo();
var bound = _self.el.getBoundingClientRect();
width = bound.width;
left = bound.left;
update(e);
e.preventDefault();
document.addEventListener('mousemove', mouseMoveListener);
});
document.addEventListener('mouseup', function (e, name, el) {
document.removeEventListener('mousemove', mouseMoveListener);
});
}, },
to: { updateLayout: function () {
set: function (val) { this._getInfo();
this._getInfo(); this.set('value', this.get('value'));
this.updateLayout();
}
}, },
step: { updateValuePercent: function (val) {
set: function (val) { this._getInfo;
this._getInfo(); this.set('value', val * (this._data.to - this._data.from) + this._data.from);
this.updateLayout();
}
}, },
fillColor: {
set: function (val) { _getInfo: function (e) {
this.left.style.background = val;//('left,drag', {background: val}); var self = this;
this.drag.style.background = val; return this.info = {
from: self.get('from'),
to: self.get('to'),
step: self.get('step'),
width: this.el.clientWidth,
left: e && e.target.offsetLeft,
x: e && e.clientX,
y: e && e.clientY
};
},
_prop: {
value: '_value',
_value: {
set: function (val, e) {
this._getInfo();
val = val || 0;
var info = this.info || this._getInfo();
var wid, pos,
step = info.step - 0, from = info.from - 0, to = info.to - 0, delta = to - from;
val < from && (val = from);
val > to && (val = to);
if (step)
val = Math.round(val / step) * step;
wid = (val - from) / delta * (info.width - height);
this.drag.style.left = wid + 'px';
this.left.style.width = wid + 'px';
e.value(val);
}
},
from: {
set: function (val) {
this._getInfo();
this.updateLayout();
}
},
to: {
set: function (val) {
this._getInfo();
this.updateLayout();
}
},
step: {
set: function (val) {
this._getInfo();
this.updateLayout();
}
},
fillColor: {
set: function (val) {
this.left.style.background = val;//('left,drag', {background: val});
this.drag.style.background = val;
}
} }
}
} }
}); });
});
\ No newline at end of file
var UIComponent = require('../UIComponent'); QRequire('UI.UIComponent', function(
UIComponent
) {
'use strict';
module.exports = UIComponent.extend('UI.Controls', 'TextArea', { return UIComponent.extend('UI.Controls', 'TextArea', {
_prop: { _prop: {
value: 'text', value: 'text',
text: { text: {
get: function () { get: function () {
return this.input.value; return this.input.value;
},
set: function (value) {
this.input.value = value;
}
},
label: {
set: function (val) {
this.label.innerText = val;
}
}, },
set: function (value) {
this.input.value = value;
}
},
label: {
set: function (val) {
this.label.innerText = val;
}
},
fontSize: { fontSize: {
set: function (value) { set: function (value) {
this.input.style.fontSize = value; this.input.style.fontSize = value;
this.input.style.lineHeight = value; this.input.style.lineHeight = value;
} }
}, },
color: { color: {
set: function (value) { set: function (value) {
this.input.style.color = value; this.input.style.color = value;
} }
}, },
focused: { focused: {
set: function (val) { set: function (val) {
this.removeClass(this.el, 'Q-UI-TextArea_focused'); this.removeClass(this.el, 'Q-UI-TextArea_focused');
if (val === true) if (val === true)
this.addClass(this.el, 'Q-UI-TextArea_focused'); this.addClass(this.el, 'Q-UI-TextArea_focused');
}
} }
} }
} }, function () {
}, function () { var self = this;
var self = this; var input = document.createElement('textarea');
var input = document.createElement('textarea'); this.el.className = 'Q-UI-TextArea';
this.el.className = 'Q-UI-TextArea'; input.style['box-sizing'] = 'border-box';
input.style['box-sizing'] = 'border-box'; input.style['width'] = '100%';
input.style['width'] = '100%'; input.style['height'] = '100%';
input.style['height'] = '100%'; input.addEventListener('keyup', function () {
input.addEventListener('keyup', function () { self._propChanged('text', self.get('value'));
self._propChanged('text', self.get('value')); });
});
input.type = 'text'; input.type = 'text';
this.input = input; this.input = input;
var label = this.label = document.createElement('span'); var label = this.label = document.createElement('span');
label.className = 'Q-UI-TextArea__label'; label.className = 'Q-UI-TextArea__label';
this.el.appendChild(input); this.el.appendChild(input);
this.el.appendChild(label); this.el.appendChild(label);
self.set('width', '400px');
self.set('height', '400px');
});
self.set('width', '400px'); });
self.set('height', '400px'); \ No newline at end of file
});
var UIComponent = require('../UIComponent'); QRequire('UI.UIComponent', function(
UIComponent
module.exports = UIComponent.extend('UI.Controls', 'TextBox', { ) {
ctor: function () { 'use strict';
var self = this;
var input = document.createElement('input'); return UIComponent.extend('UI.Controls', 'TextBox', {
ctor: function () {
this.el.className = 'Q-UI-TextBox'; var self = this;
var input = document.createElement('input');
input.style['box-sizing'] = 'border-box';
input.style['width'] = '100%'; this.el.className = 'Q-UI-TextBox';
input.addEventListener('keyup', function () {
self._propChanged('text', self.get('value')); input.style['box-sizing'] = 'border-box';
}); input.style['width'] = '100%';
input.addEventListener('keyup', function () {
input.type = 'text'; self._propChanged('text', self.get('value'));
});
this.input = input;
var label = this.label = document.createElement('span'); input.type = 'text';
label.className = 'Q-UI-TextBox__label';
this.input = input;
this.el.appendChild(input); var label = this.label = document.createElement('span');
this.el.appendChild(label); label.className = 'Q-UI-TextBox__label';
this.set('padding', '0 40px'); this.el.appendChild(input);
this.el.appendChild(label);
this.on('click', function(){
self.delegate.activate(self); this.set('padding', '0 40px');
});
}, this.on('click', function () {
self.delegate.activate(self);
_tabProtocolReceive: function(info){ });
if(info.action === 'backspace'){
this.input.value = this.input.value.substr(0,this.input.value.length-1);
}else
this.input.value += info.key;
},
_tabProtocol: function (delegate) {
if(delegate) {
this.delegate = delegate;
return true;
}
this.el.classList.add('Focused');
var input = this.input;
setTimeout(function(){
input.focus();
},5);
this.delegate.layout && this.delegate.layout(this.get('layout'));
},
_tabProtocolLeave: function(){
this.el.classList.remove('Focused');
this.delegate.layout && this.delegate.layout('none');
},
_prop: {
value: 'text',
text: {
get: function () {
return this.input.value;
},
set: function (value) {
this.input.value = value;
}
}, },
placeholder: {
get: function () { _tabProtocolReceive: function (info) {
return this.input.placeholder; if (info.action === 'backspace') {
}, this.input.value = this.input.value.substr(0, this.input.value.length - 1);
set: function (placeholder) { } else
this.input.placeholder = placeholder; this.input.value += info.key;
}
}, },
color: { _tabProtocol: function (delegate) {
get: function () { if (delegate) {
return this.input.style.color; this.delegate = delegate;
}, return true;
set: function (value) {
this.input.style.color = value;
} }
}, this.el.classList.add('Focused');
var input = this.input;
setTimeout(function () {
input.focus();
}, 5);
this.delegate.layout && this.delegate.layout(this.get('layout'));
label: {
set: function(val){
this.label.innerText = val;
}
}, },
_tabProtocolLeave: function () {
this.el.classList.remove('Focused');
this.delegate.layout && this.delegate.layout('none');
},
_prop: {
value: 'text',
text: {
get: function () {
return this.input.value;
},
set: function (value) {
this.input.value = value;
}
},
placeholder: {
get: function () {
return this.input.placeholder;
},
set: function (placeholder) {
this.input.placeholder = placeholder;
}
},
color: {
get: function () {
return this.input.style.color;
},
set: function (value) {
this.input.style.color = value;
}
},
label: {
set: function (val) {
this.label.innerText = val;
}
},
focused: { focused: {
set: function(val){ set: function (val) {
this.removeClass(this.el,'Q-UI-TextBox_focused'); this.removeClass(this.el, 'Q-UI-TextBox_focused');
if(val === true)
this.addClass(this.el,'Q-UI-TextBox_focused');
if (val === true)
this.addClass(this.el, 'Q-UI-TextBox_focused');
}
} }
}
} }
}); });
});
\ No newline at end of file
var UIComponent = require('../UIComponent'); module.exports =
var FlexSizeComponent = require('./FlexSizeComponent'); QRequire('UI.UIComponent', 'UI.Border','UI.FlexSizeComponent', function(
var Border = require('./Border'); UIComponent,
Border,
FlexSizeComponent
) {
'use strict';
return FlexSizeComponent.extend('UI.Controls', 'VBox', {
ctor: function () {
this.set('height', '100%');
},
_createEl: function () {
FlexSizeComponent.prototype._createEl.apply(this, arguments);
var self = this;
this.el.addEventListener('resize', function () {
self.updateLayout();
});
},
updateLayout: function () {
var self = this;
var children = this._children;
module.exports = FlexSizeComponent.extend('UI.Controls', 'VBox', { clearTimeout(this.updateTimeout);
ctor: function () { this.updateTimeout = setTimeout(function () {
this.set('height', '100%'); var fDef = self._flexDefinition || {parts: [], starCount: 0, flexLength: 0, fixLength: 0};
}, var starCount = fDef.starCount;
_createEl: function () { if (fDef.parts.length === 0)
FlexSizeComponent.prototype._createEl.apply(this, arguments); starCount = children.length;
var self = this; var freeHeight = 100 - 100 * (fDef.fixLength / self.el.clientHeight);
this.el.addEventListener('resize', function () { for (var i = 0, length = children.length; i < length; i++) {
self.updateLayout(); var fPart = fDef.parts[i];
}); var height = freeHeight / starCount + '%';
}, if (fPart) {
updateLayout: function () { if (fPart.flex && fPart.part > 0) // 25*
var self = this; height = freeHeight * (fPart.part / fDef.flexLength) + '%';
var children = this._children; if (!fPart.flex) { // 25
height = fPart.part + 'px';
clearTimeout(this.updateTimeout); }
this.updateTimeout = setTimeout(function () { } else {
var fDef = self._flexDefinition || {parts: [], starCount: 0, flexLength: 0, fixLength: 0}; height = freeHeight / starCount + '%';
var starCount = fDef.starCount; }
if (fDef.parts.length === 0) children.get(i).set('height', height);
starCount = children.length;
var freeHeight = 100 - 100 * (fDef.fixLength / self.el.clientHeight);
for (var i = 0, length = children.length; i < length; i++) {
var fPart = fDef.parts[i];
var height = freeHeight / starCount + '%';
if (fPart) {
if (fPart.flex && fPart.part > 0) // 25*
height = freeHeight * (fPart.part / fDef.flexLength) + '%';
if (!fPart.flex) { // 25
height = fPart.part + 'px';
} }
} else { }, 0);
height = freeHeight / starCount + '%'; FlexSizeComponent.prototype.updateLayout.call(this);
} },
children.get(i).set('height', height); addChild: function (child) {
var div = new Border({
width: '100%'
});
div.addChild(child);
this._children.push(div);
this.updateLayout();
} }
}, 0);
FlexSizeComponent.prototype.updateLayout.call(this);
},
addChild: function (child) {
var div = new Border({
width: '100%'
}); });
div.addChild(child); });
this._children.push(div); \ No newline at end of file
this.updateLayout();
}
});
\ No newline at end of file
var UIComponent = require('../UIComponent'); QRequire('UI.UIComponent', function(
UIComponent
) {
'use strict';
module.exports = UIComponent.extend('UI.Controls', 'Video', { return UIComponent.extend('UI.Controls', 'Video', {
updateLayout: function () { updateLayout: function () {
this.set('value', this.get('value')); this.set('value', this.get('value'));
}, },
ctor: function () { ctor: function () {
this.set('value', 'https://www.w3schools.com/html/mov_bbb.mp4'); this.set('value', 'https://www.w3schools.com/html/mov_bbb.mp4');
}, },
play: function () { play: function () {
this.el.play(); this.el.play();
}, },
stop: function () { stop: function () {
this.el.pause(); this.el.pause();
}, },
pause: function () { pause: function () {
this.el.pause(); this.el.pause();
}, },
createEl: function () { createEl: function () {
var self = this; var self = this;
this.el = document.createElement('video'); this.el = document.createElement('video');
this.el.addEventListener('timeupdate', function (event) { this.el.addEventListener('timeupdate', function (event) {
self.updating = true; self.updating = true;
self.set('time', self.el.currentTime); self.set('time', self.el.currentTime);
self.updating = false; self.updating = false;
}); });
this.el.addEventListener('volumechange', function (event) { this.el.addEventListener('volumechange', function (event) {
self.updating = true; self.updating = true;
self.set('volume', self.el.volume); self.set('volume', self.el.volume);
self.updating = false; self.updating = false;
}); });
this.el.addEventListener('durationchange', function (event) { this.el.addEventListener('durationchange', function (event) {
self.set('duration', self.el.duration); self.set('duration', self.el.duration);
}); });
this.el.addEventListener('click', function () { this.el.addEventListener('click', function () {
self.fire('click'); self.fire('click');
}); });
},
_prop: {
time: {
set: function (value) {
if (!this.updating) {
this.el.currentTime = value;
}
}
}, },
duration: {}, _prop: {
volume: { time: {
description: 'Current volume', set: function (value) {
get: function () { if (!this.updating) {
return this.el.volume * 100; this.el.currentTime = value;
}
}
}, },
set: function (value) { duration: {},
if (!this.updating) volume: {
this.el.volume = value / 100; description: 'Current volume',
} get: function () {
}, return this.el.volume * 100;
controls: { },
get: function () { set: function (value) {
return this.el.controls; if (!this.updating)
this.el.volume = value / 100;
}
}, },
set: function (value) { controls: {
this.el.controls = value; get: function () {
} return this.el.controls;
}, },
muted: { set: function (value) {
get: function () { this.el.controls = value;
return this.el.muted; }
}, },
set: function (value) { muted: {
this.el.muted = value; get: function () {
} return this.el.muted;
}, },
fullscreen: { set: function (value) {
get: function () { this.el.muted = value;
return !!(document.fullscreenElement); }
}, },
set: function (value) { fullscreen: {
if (value) { get: function () {
var el = this.el; return !!(document.fullscreenElement);
if (el.requestFullscreen) { },
el.requestFullscreen(); set: function (value) {
} else if (el.mozRequestFullScreen) { if (value) {
el.mozRequestFullScreen(); var el = this.el;
} else if (el.webkitRequestFullScreen) { if (el.requestFullscreen) {
el.webkitRequestFullScreen(); el.requestFullscreen();
} } else if (el.mozRequestFullScreen) {
} else { el.mozRequestFullScreen();
var doc = UIComponent.document; } else if (el.webkitRequestFullScreen) {
if (doc.exitFullscreen) { el.webkitRequestFullScreen();
doc.exitFullscreen(); }
} else if (doc.cancelFullscreen) { } else {
doc.cancelFullscreen(); var doc = UIComponent.document;
} else if (doc.mozCancelFullScreen) { if (doc.exitFullscreen) {
doc.mozCancelFullScreen(); doc.exitFullscreen();
} else if (doc.cancelFullscreen) {
doc.cancelFullscreen();
} else if (doc.mozCancelFullScreen) {
doc.mozCancelFullScreen();
}
} }
} }
} },
}, autoplay: {
autoplay: { set: function (value) {
set: function (value) { if (value)
if (value) this.play();
this.play(); }
} },
}, loop: {
loop: { set: function (value) {
set: function (value) { this.el.loop = value;
this.el.loop = value; }
} },
}, value: 'source',
value: 'source', source: {
source: { set: function (value) {
set: function (value) { this.stop();
this.stop(); this.el.src = value;
this.el.src = value;
if (this.get('autoplay')) { if (this.get('autoplay')) {
this.play(); this.play();
}
} }
} }
} }
} });
}); });
\ No newline at end of file
var UIComponent = require('../UIComponent'); QRequire('UI.UIComponent', 'UI.ContainerComponent', function(
var ContainerComponent = require('./ContainerComponent'); UIComponent
) {
'use strict';
var base = UIComponent.prototype; var base = UIComponent.prototype;
module.exports = ContainerComponent.extend('UI.Controls', 'WrapPanel', { return ContainerComponent.extend('UI.Controls', 'WrapPanel', {
updateLayout: function () { updateLayout: function () {
var self = this; var self = this;
setTimeout(function () { setTimeout(function () {
var iterator = self._children.iterator(), item; var iterator = self._children.iterator(), item;
while (item = iterator.next()) { while (item = iterator.next()) {
if (item instanceof UIComponent) { if (item instanceof UIComponent) {
item.set('width', self.get('itemWidth')); item.set('width', self.get('itemWidth'));
}
} }
} }, 0);
}, 0);
base.updateLayout.call(this); base.updateLayout.call(this);
}, },
_handleChildren: function (childComp, index) { _handleChildren: function (childComp, index) {
var self = this; var self = this;
var childNode = childComp.el; var childNode = childComp.el;
childComp.set('width', this.get('itemWidth')); childComp.set('width', this.get('itemWidth'));
//TODO rewrite to native properties //TODO rewrite to native properties
childNode.style.float = 'left'; childNode.style.float = 'left';
childNode.style.position = 'relative'; childNode.style.position = 'relative';
childNode.style.overflow = 'hidden'; childNode.style.overflow = 'hidden';
childNode.addEventListener('click', function () { childNode.addEventListener('click', function () {
self.set('selectedIndex', index); self.set('selectedIndex', index);
self.fire('itemClick', self.get('selectedItem'), index); self.fire('itemClick', self.get('selectedItem'), index);
}); });
}, },
_prop: { _prop: {
itemWidth: { itemWidth: {
set: function () { set: function () {
this.updateLayout(); this.updateLayout();
}
} }
} }
} });
}); });
\ No newline at end of file
/** /**
* Created by zibx on 5/6/17. * Created by zibx on 5/6/17.
*/ */
var UIComponent = require('../UIComponent'); module.exports =
var ContentContainer = require('../ContentContainer'); QRequire('UI.UIComponent', function(
var dict = {}; UIComponent
('button,canvas,center,div,' + ) {
'h1,h2,h3,h4,h5,h6,' + 'use strict';
'li,ol,span,sub,sup,' +
'table,tbody,td,th,thead,tr,marquee')
.split(',')
.forEach(function (name) {
dict[name] = UIComponent.extend('UI.HTML', name, {
ctor: function () {
//this._ownComponents.push(new ContentContainer());
this.el = document.createElement(name);
this.el.classList.add(this.baseCls);
},
_prop: {
value: 'text',
text: {
set: function (val) {
//if (!this.textNode) {
// this.textNode = new exports['textNode'];
// this._ownComponents.push(this.textNode);
//}
//this.textNode.set('value', val);
if (!this.textNode) { return ('button,canvas,center,div,' +
this.textNode = document.createTextNode(''); 'h1,h2,h3,h4,h5,h6,' +
this.el.appendChild(this.textNode); 'li,ol,span,sub,sup,' +
} 'table,tbody,td,th,thead,tr,marquee')
this.textNode.nodeValue = val; .split(',')
.map(function (name) {
return UIComponent.extend('UI.HTML', name, {
ctor: function () {
this.el = document.createElement(name);
this.el.classList.add(this.baseCls);
},
_prop: {
value: 'text',
text: {
set: function (val) {
if (!this.textNode) {
this.textNode = document.createTextNode('');
this.el.appendChild(this.textNode);
}
this.textNode.nodeValue = val;
}
},
html: {
set: function (val) {
this.el.innerHTML = val;
}
}
} }
}, });
html: {
set: function(val){
this.el.innerHTML = val;
}
}
}
});
}); });
module.exports = dict; });
\ No newline at end of file \ No newline at end of file
...@@ -5,19 +5,17 @@ ...@@ -5,19 +5,17 @@
*/ */
;// QUOKKA 2017 ;// QUOKKA 2017
// By zibx on 5/22/17. // By zibx on 5/22/17.
module.exports =
QRequire('UI.UIComponent', 'Core.QObject', function(
UIComponent,
QObject
) {
'use strict';
module.exports = (function () {
var UIComponent = require('../UIComponent');
var svgNS = 'http://www.w3.org/2000/svg'; var svgNS = 'http://www.w3.org/2000/svg';
var TypeTable =
typeof Q != "undefined"
? Q.Core.TypeTable
: require("../../Core/TypeTable");
var QObject = TypeTable.getType('Core', "QObject");
return UIComponent.extend('UI.Controls', 'SVG', { return UIComponent.extend('UI.Controls', 'SVG', {
ctor: function(){ ctor: function () {
var self = this; var self = this;
var buttonSVG = this.svg = document.createElementNS(svgNS, 'svg'); var buttonSVG = this.svg = document.createElementNS(svgNS, 'svg');
...@@ -34,20 +32,20 @@ module.exports = (function () { ...@@ -34,20 +32,20 @@ module.exports = (function () {
this.el.addEventListener('click', function (event) { this.el.addEventListener('click', function (event) {
self.fire('click', event); self.fire('click', event);
}); });
var private = new QObject({added: false}); var _private = new QObject({added: false});
this.on('drawed', function(){ this.on('drawed', function () {
private.set(['added'], true); _private.set(['added'], true);
}); });
new Pipe( new Pipe(
this.ref('viewBox'), this.ref('viewBox'),
this.ref('path'), this.ref('path'),
private.ref('added'), _private.ref('added'),
this.recalculate.bind(this) this.recalculate.bind(this)
); );
this.pathsCache = {} this.pathsCache = {}
}, },
recalculate: function(vb, paths, added){ recalculate: function (vb, paths, added) {
if(vb && paths && added){ if (vb && paths && added) {
!Array.isArray(paths) && (paths = [paths]); !Array.isArray(paths) && (paths = [paths]);
var cache = this.pathsCache; var cache = this.pathsCache;
var used = {}, var used = {},
...@@ -59,16 +57,16 @@ module.exports = (function () { ...@@ -59,16 +57,16 @@ module.exports = (function () {
}, },
vbs = vb.split(' ').map(Number); vbs = vb.split(' ').map(Number);
vbs = {left: vbs[0], top: vbs[1], right: vbs[2], bottom: vbs[3], dx: 0, dy: 0}; vbs = {left: vbs[0], top: vbs[1], right: vbs[2], bottom: vbs[3], dx: 0, dy: 0};
vbs.dx = vbs.right-vbs.left; vbs.dx = vbs.right - vbs.left;
vbs.dy = vbs.bottom-vbs.top; vbs.dy = vbs.bottom - vbs.top;
paths.forEach(function(path){ paths.forEach(function (path) {
var s = false; var s = false;
path = path.replace(/([0-9]+(\.[0-9]+)?)/g, function(a, val){ path = path.replace(/([0-9]+(\.[0-9]+)?)/g, function (a, val) {
s = !s; s = !s;
return (val - vbs[s?'left':'top'])/vbs[s?'dx':'dy']*clientSize[s?'dx':'dy']; return (val - vbs[s ? 'left' : 'top']) / vbs[s ? 'dx' : 'dy'] * clientSize[s ? 'dx' : 'dy'];
}); });
if(!(path in cache)) { if (!(path in cache)) {
var p = cache[path] = document.createElementNS(svgNS, 'path'); var p = cache[path] = document.createElementNS(svgNS, 'path');
p.setAttributeNS(null, 'd', path); p.setAttributeNS(null, 'd', path);
svg.appendChild(p); svg.appendChild(p);
...@@ -76,8 +74,8 @@ module.exports = (function () { ...@@ -76,8 +74,8 @@ module.exports = (function () {
used[path] = true; used[path] = true;
}); });
for(var i in cache){ for (var i in cache) {
if(!(i in used)){ if (!(i in used)) {
svg.removeChild(cache[i]); svg.removeChild(cache[i]);
delete cache[i]; delete cache[i];
} }
...@@ -90,7 +88,7 @@ module.exports = (function () { ...@@ -90,7 +88,7 @@ module.exports = (function () {
value: 'caption', value: 'caption',
caption: { caption: {
set: function (val) { set: function (val) {
this.buttonText.innerText = (val+'').replace(/_/g, String.fromCharCode(160)); this.buttonText.innerText = (val + '').replace(/_/g, String.fromCharCode(160));
} }
}, },
viewBox: {}, viewBox: {},
...@@ -98,4 +96,4 @@ module.exports = (function () { ...@@ -98,4 +96,4 @@ module.exports = (function () {
} }
}); });
})(); });
\ No newline at end of file \ No newline at end of file
var TypeTable = module.exports = QRequire('Core.QObject', function(
typeof Q != "undefined" QObject
? Q.Core.TypeTable ) {
: require("../../Core/TypeTable"); 'use strict';
var QObject = TypeTable.getType('Core', "QObject"); return QObject.extend('UI.Navigation', 'AbstractAnimation', {
ctor: function () {
this.set('duration', 300);
this.set('startCss', '');
this.set('endCss', '');
},
play: function (target, callback) {
var self = this;
target.set('pureCss', this.get('startCss'));
var AbstractAnimation = QObject.extend('UI.Navigation', 'AbstractAnimation', { setTimeout(function () {
ctor: function () { target.set('pureCss', 'transition: all ' + self.get('duration') / 1000 + 's');
this.set('duration', 300); target.set('pureCss', self.get('endCss') + ';transition: all ' + self.get('duration') / 1000 + 's');
this.set('startCss', ''); }, 0);
this.set('endCss', ''); setTimeout(function () {
}, if (callback) callback();
play: function (target, callback) { }, this.get('duration'));
var self = this; },
target.set('pureCss', this.get('startCss')); playReverse: function (target, callback) {
var self = this;
setTimeout(function () { target.set('pureCss', this.get('endCss') + ';transition: all ' + this.get('duration') / 1000 + 's');
target.set('pureCss', 'transition: all ' + self.get('duration') / 1000 + 's'); setTimeout(function () {
target.set('pureCss', self.get('endCss') + ';transition: all ' + self.get('duration') / 1000 + 's'); target.set('pureCss', self.get('startCss') + ';transition: all ' + self.get('duration') / 1000 + 's');
}, 0); }, 0);
setTimeout(function () { setTimeout(function () {
if (callback) callback(); if (callback) callback();
}, this.get('duration')); }, this.get('duration'));
}, },
playReverse: function (target, callback) { _prop: {
var self = this; duration: {},
target.set('pureCss', this.get('endCss') + ';transition: all ' + this.get('duration') / 1000 + 's'); startCss: {},
setTimeout(function () { endCss: {}
target.set('pureCss', self.get('startCss') + ';transition: all ' + self.get('duration') / 1000 + 's'); }
}, 0); });
setTimeout(function () { });
if (callback) callback(); \ No newline at end of file
}, this.get('duration'));
},
_prop: {
duration: {},
startCss: {},
endCss: {}
}
});
module.exports = AbstractAnimation;
\ No newline at end of file
var AbstractAnimation = require('./AbstractAnimation'); module.exports = QRequire(
var SwipeInAnimation = require('./SwipeInAnimation'); 'Core.QObject',
var SwipeOutAnimation = require('./SwipeOutAnimation'); 'Navigation.AbstractAnimation',
'Navigation.SwipeInAnimation',
var ScaleInAnimation = require('./ScaleInAnimation'); 'Navigation.SwipeOutAnimation',
'Navigation.ScaleInAnimation',
var TypeTable = function(
typeof Q != "undefined" QObject,
? Q.Core.TypeTable AbstractAnimation,
: require("../../Core/TypeTable"); SwipeInAnimation,
SwipeOutAnimation,
var QObject = TypeTable.getType('Core', "QObject"); ScaleInAnimation
) {
function getViewport() { 'use strict';
return document.getElementById('viewport');
} function getViewport() {
return document.getElementById('viewport');
}
function webGet(url, callback) { function webGet(url, callback) {
var xmlhttp = new XMLHttpRequest(); var xmlhttp = new XMLHttpRequest();
xmlhttp.open('GET', url, true); xmlhttp.open('GET', url, true);
xmlhttp.onreadystatechange = function () { xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState === 4) { if (xmlhttp.readyState === 4) {
if (xmlhttp.status === 200) { if (xmlhttp.status === 200) {
callback(null, xmlhttp.responseText) callback(null, xmlhttp.responseText)
} }
}
};
xmlhttp.send(null);
} }
};
xmlhttp.send(null);
}
/** @class */
var NavigationManager = QObject.extend('UI.Navigation', 'NavigationManager', {});
NavigationManager.defaultAnimation = new ScaleInAnimation();
NavigationManager.applicationStack = [];
NavigationManager.busy = false;
var Application = function (src, name) {
this.navigationStack = [];
this.el = document.createElement('div');
this.el.classList.add('Application');
this.el.style.height = '100%';
this.el.style.width = '100%';
this.fadeInAnimation = new SwipeOutAnimation();
this.fadeOutAnimation = new SwipeInAnimation();
this.currentPage = void(0);
this.name = name;
if (src)
this.setSource(src);
};
Application.prototype = {
setSource: function (src) {
var newSrc = '(function(){';
newSrc += src;
newSrc += ' return _AppNamespace })()';
var ns = eval(newSrc);
this.namespace = ns;
},
canGoBack: function () {
return this.navigationStack.length > 1;
},
navigate: function (to, cfg) {
if (this.busy) return;
this.busy = true;
var self = this;
cfg = cfg || {};
var viewport = this.el;
var targetPageCtor = TypeTable.getType(this.namespace, to);
if (targetPageCtor) {
var nextPage = new targetPageCtor();
var fadeOutAnim = cfg.fadeOut || nextPage.get('fadeOutAnimation') || this.fadeOutAnimation;
var currentPage = this.navigationStack[0];
if (!currentPage) {
viewport.appendChild(nextPage.el);
//fadeOutAnim.play(nextPage, function () {
nextPage.load(true);
self.busy = false;
self.currentPage = nextPage;
nextPage.updateLayout();
!cfg.silent && NavigationManager.fire('pageChanged', nextPage);
//});
} else {
var fadeInAnim = cfg.fadeIn || currentPage.get('fadeInAnimation') || this.fadeInAnimation;
fadeInAnim.play(currentPage); /** @class */
fadeOutAnim.play(nextPage, function () { var NavigationManager = QObject.extend('UI.Navigation', 'NavigationManager', {});
viewport.removeChild(currentPage.el);
nextPage.load(true); NavigationManager.defaultAnimation = new ScaleInAnimation();
self.busy = false; NavigationManager.applicationStack = [];
self.currentPage = nextPage; NavigationManager.busy = false;
nextPage.updateLayout();
!cfg.silent && NavigationManager.fire('pageChanged', nextPage); var Application = function (src, name) {
this.navigationStack = [];
this.el = document.createElement('div');
this.el.classList.add('Application');
this.el.style.height = '100%';
this.el.style.width = '100%';
this.fadeInAnimation = new SwipeOutAnimation();
this.fadeOutAnimation = new SwipeInAnimation();
this.currentPage = void(0);
this.name = name;
if (src)
this.setSource(src);
};
Application.prototype = {
setSource: function (src) {
var newSrc = '(function(){';
newSrc += src;
newSrc += ' return _AppNamespace })()';
var ns = eval(newSrc);
this.namespace = ns;
},
canGoBack: function () {
return this.navigationStack.length > 1;
},
navigate: function (to, cfg) {
if (this.busy) return;
this.busy = true;
var self = this;
cfg = cfg || {};
var viewport = this.el;
var targetPageCtor = TypeTable.getType(this.namespace, to);
if (targetPageCtor) {
var nextPage = new targetPageCtor();
var fadeOutAnim = cfg.fadeOut || nextPage.get('fadeOutAnimation') || this.fadeOutAnimation;
var currentPage = this.navigationStack[0];
if (!currentPage) {
viewport.appendChild(nextPage.el);
//fadeOutAnim.play(nextPage, function () {
nextPage.load(true);
self.busy = false;
self.currentPage = nextPage;
nextPage.updateLayout();
!cfg.silent && NavigationManager.fire('pageChanged', nextPage);
//});
} else {
var fadeInAnim = cfg.fadeIn || currentPage.get('fadeInAnimation') || this.fadeInAnimation;
fadeInAnim.play(currentPage);
fadeOutAnim.play(nextPage, function () {
viewport.removeChild(currentPage.el);
nextPage.load(true);
self.busy = false;
self.currentPage = nextPage;
nextPage.updateLayout();
!cfg.silent && NavigationManager.fire('pageChanged', nextPage);
});
viewport.appendChild(nextPage.el);
}
this.navigationStack.unshift(nextPage);
} else {
console.error('Page ' + [this.namespace, to].join('.') + ' does not exists');
this.busy = false;
}
},
back: function (cfg) {
if (this.canGoBack()) {
if (this.busy) return;
this.busy = true;
var self = this,
getTheHellOutOfHere = false;
var currentPage = this.navigationStack.shift();
var backPage = this.navigationStack[0];
cfg = cfg || {};
var fadeOutAnim = cfg.fadeOut || currentPage.get('fadeOutAnimation') || this.fadeOutAnimation;
var fadeInAnim = cfg.fadeIn || backPage.get('fadeInAnimation') || this.fadeInAnimation;
if (typeof currentPage['~beforeDestroy'] === 'function') {
if (currentPage['~beforeDestroy']() === false) {
getTheHellOutOfHere = true;
self.busy = false;
return false;
}
}
var viewport = this.el;
viewport.appendChild(backPage.el);
fadeInAnim.playReverse(backPage);
fadeOutAnim.playReverse(currentPage, function () {
viewport.removeChild(currentPage.el);
typeof currentPage['~destroy'] === 'function' && currentPage['~destroy']();
backPage.load(true);
self.busy = false;
self.currentPage = backPage;
backPage.updateLayout();
NavigationManager.fire('pageChanged', backPage);
});
}
},
'~destroy': function () {
this.navigationStack.forEach(function (page) {
typeof page['~destroy'] === 'function' && page['~destroy']();
}); });
viewport.appendChild(nextPage.el);
} }
this.navigationStack.unshift(nextPage);
}else{
console.error('Page '+ [this.namespace, to].join('.')+' does not exists');
this.busy = false;
} }
}, ;
back: function (cfg) { Application.current = void(0);
if (this.canGoBack()) {
if (this.busy) return;
this.busy = true;
var self = this,
getTheHellOutOfHere = false;
var currentPage = this.navigationStack.shift();
var backPage = this.navigationStack[0];
cfg = cfg || {};
var fadeOutAnim = cfg.fadeOut || currentPage.get('fadeOutAnimation') || this.fadeOutAnimation;
var fadeInAnim = cfg.fadeIn || backPage.get('fadeInAnimation') || this.fadeInAnimation;
if( typeof currentPage['~beforeDestroy'] === 'function' ){
if(currentPage['~beforeDestroy']() === false) {
getTheHellOutOfHere = true;
self.busy = false;
return false;
}
}
var viewport = this.el;
viewport.appendChild(backPage.el);
fadeInAnim.playReverse(backPage);
fadeOutAnim.playReverse(currentPage, function () {
viewport.removeChild(currentPage.el);
typeof currentPage['~destroy'] === 'function' && currentPage['~destroy']();
backPage.load(true);
self.busy = false;
self.currentPage = backPage;
backPage.updateLayout();
NavigationManager.fire('pageChanged', backPage);
});
}
},
'~destroy': function(){
this.navigationStack.forEach(function(page){
typeof page['~destroy'] === 'function' && page['~destroy']();
});
}
}
;
Application.current = void(0);
NavigationManager.load = function (appName, cb) {
var app = appName;
if (app.slice(0, -3) !== '.qs') {
app += '.qs';
}
webGet('/Apps/' + app, function (err, data) {
console.log(data);
if(cb) {
return cb(new Application(data, appName));
}
if (NavigationManager.busy) return;
NavigationManager.busy = true;
var app = new Application(data, appName); NavigationManager.load = function (appName, cb) {
var app = appName;
if (app.slice(0, -3) !== '.qs') {
Application.current = app; app += '.qs';
var viewport = getViewport();
app.navigate('main');
var anim = NavigationManager.defaultAnimation;
viewport.appendChild(app.el);
anim.play(app, function () {
if (NavigationManager.applicationStack.length > 0) {
var prevApp = NavigationManager.applicationStack[0];
getViewport().removeChild(prevApp.el);
} }
NavigationManager.applicationStack.unshift(app); webGet('/Apps/' + app, function (err, data) {
NavigationManager.busy = false; console.log(data);
NavigationManager.fire('loaded', app); if (cb) {
}); return cb(new Application(data, appName));
}
if (NavigationManager.busy) return;
NavigationManager.busy = true;
var app = new Application(data, appName);
Application.current = app;
var viewport = getViewport();
app.navigate('main');
var anim = NavigationManager.defaultAnimation;
viewport.appendChild(app.el);
anim.play(app, function () {
if (NavigationManager.applicationStack.length > 0) {
var prevApp = NavigationManager.applicationStack[0];
getViewport().removeChild(prevApp.el);
}
NavigationManager.applicationStack.unshift(app);
NavigationManager.busy = false;
NavigationManager.fire('loaded', app);
});
}); });
}; };
NavigationManager.on = Q.Core.QObject.prototype.on; NavigationManager.on = Q.Core.QObject.prototype.on;
NavigationManager.fire = Q.Core.QObject.prototype.fire; NavigationManager.fire = Q.Core.QObject.prototype.fire;
NavigationManager.eventList = {}; NavigationManager.eventList = {};
NavigationManager.navigate = function (to, cfg) { NavigationManager.navigate = function (to, cfg) {
if (NavigationManager.busy) return; if (NavigationManager.busy) return;
Application.current.navigate(to, cfg); Application.current.navigate(to, cfg);
}; };
NavigationManager.canGoBack = function () { NavigationManager.canGoBack = function () {
return NavigationManager.applicationStack.length > 1; return NavigationManager.applicationStack.length > 1;
}; };
NavigationManager.back = function (cfg) { NavigationManager.back = function (cfg) {
if (Application.current.canGoBack()) { if (Application.current.canGoBack()) {
Application.current.back(cfg); Application.current.back(cfg);
} else { } else {
if (NavigationManager.canGoBack()) { if (NavigationManager.canGoBack()) {
if (NavigationManager.busy) return; if (NavigationManager.busy) return;
NavigationManager.busy = true; NavigationManager.busy = true;
var currentApp = NavigationManager.applicationStack.shift(); var currentApp = NavigationManager.applicationStack.shift();
var backApp = NavigationManager.applicationStack[0]; var backApp = NavigationManager.applicationStack[0];
var viewport = getViewport(); var viewport = getViewport();
viewport.insertBefore(backApp.el, currentApp.el); viewport.insertBefore(backApp.el, currentApp.el);
NavigationManager.defaultAnimation.playReverse(currentApp, function () { NavigationManager.defaultAnimation.playReverse(currentApp, function () {
typeof currentApp['~destroy'] === 'function' && currentApp['~destroy'](); typeof currentApp['~destroy'] === 'function' && currentApp['~destroy']();
Application.current = backApp; Application.current = backApp;
viewport.removeChild(currentApp.el); viewport.removeChild(currentApp.el);
NavigationManager.busy = false; NavigationManager.busy = false;
backApp.currentPage.updateLayout(); backApp.currentPage.updateLayout();
NavigationManager.fire('pageChanged', backApp.currentPage); NavigationManager.fire('pageChanged', backApp.currentPage);
}); });
} }
} }
}; };
NavigationManager.Application = Application; NavigationManager.Application = Application;
module.exports = NavigationManager; return NavigationManager;
\ No newline at end of file });
\ No newline at end of file
var AbstractAnimation = require('./AbstractAnimation'); module.exports = QRequire(
'Navigation.AbstractAnimation',
var TypeTable = function(
typeof Q != "undefined" AbstractAnimation
? Q.Core.TypeTable ) {
: require("../../Core/TypeTable"); 'use strict';
var QObject = TypeTable.getType('Core', "QObject"); return AbstractAnimation.extend('UI.Navigation', 'ScaleInAnimation', {
module.exports = AbstractAnimation.extend('UI.Navigation', 'ScaleInAnimation', { play: function (newPage, callback) {
newPage.el.style.transform = 'scale(0.2)';
play: function (newPage, callback) { newPage.el.style.opacity = '0';
newPage.el.style.transform = 'scale(0.2)'; setTimeout(function () {
newPage.el.style.opacity = '0'; newPage.el.style.transition = 'all 0.3s';
setTimeout(function () { newPage.el.style.transform = 'scale(1)';
newPage.el.style.transition = 'all 0.3s'; newPage.el.style.opacity = '1';
newPage.el.style.transform = 'scale(1)'; }, 20);
newPage.el.style.opacity = '1';
}, 20); setTimeout(function () {
if (callback)
setTimeout(function () { callback()
if (callback) }, 320);
callback() },
}, 320);
}, playReverse: function (newPage, callback) {
newPage.el.style.transform = 'scale(1)';
playReverse: function (newPage, callback) { newPage.el.style.opacity = '1';
newPage.el.style.transform = 'scale(1)';
newPage.el.style.opacity = '1'; setTimeout(function () {
newPage.el.style.transition = 'all 0.3s';
setTimeout(function () { newPage.el.style.transform = 'scale(0.2)';
newPage.el.style.transition = 'all 0.3s'; newPage.el.style.opacity = '0';
newPage.el.style.transform = 'scale(0.2)'; }, 20);
newPage.el.style.opacity = '0';
}, 20); setTimeout(function () {
newPage.el.style.transition = 'all 0s';
setTimeout(function () { if (callback)
newPage.el.style.transition = 'all 0s'; callback()
if (callback) }, 320);
callback() }
}, 320); });
} });
}); \ No newline at end of file
\ No newline at end of file
var AbstractAnimation = require('./AbstractAnimation'); module.exports = QRequire(
'Navigation.AbstractAnimation',
var TypeTable = function(
typeof Q != "undefined" AbstractAnimation
? Q.Core.TypeTable ) {
: require("../../Core/TypeTable"); 'use strict';
var QObject = TypeTable.getType('Core', "QObject"); return AbstractAnimation.extend('UI.Navigation', 'ScaleInAnimation', {
module.exports = AbstractAnimation.extend('UI.Navigation', 'ScaleInAnimation', { play: function (newPage, callback) {
newPage.el.style.transform = 'scale(1)';
play: function (newPage, callback) { setTimeout(function () {
newPage.el.style.transform = 'scale(1)'; newPage.el.style.transition = 'all 0.3s';
setTimeout(function () { newPage.el.style.left = '0%';
newPage.el.style.transition = 'all 0.3s'; }, 20);
newPage.el.style.left = '0%';
}, 20); setTimeout(function () {
newPage.el.style.transform = 'scale(1)';
setTimeout(function () { if (callback)
newPage.el.style.transform = 'scale(1)'; callback()
if (callback) }, 320);
callback() },
}, 320);
}, playReverse: function (newPage, callback) {
newPage.el.style.transform = 'scale(1)';
playReverse: function (newPage, callback) {
newPage.el.style.transform = 'scale(1)'; setTimeout(function () {
newPage.el.style.transition = 'all 0.3s';
setTimeout(function () { newPage.el.style.transform = 'scale(1)';
newPage.el.style.transition = 'all 0.3s'; }, 20);
newPage.el.style.transform = 'scale(1)';
}, 20); setTimeout(function () {
newPage.el.style.transition = 'all 0s';
setTimeout(function () { if (callback)
newPage.el.style.transition = 'all 0s'; callback()
if (callback) }, 320);
callback() }
}, 320); });
} });
}); \ No newline at end of file
\ No newline at end of file
var AbstractAnimation = require('./AbstractAnimation'); module.exports = QRequire(
'Navigation.AbstractAnimation',
var TypeTable = function(
typeof Q != "undefined" AbstractAnimation
? Q.Core.TypeTable ) {
: require("../../Core/TypeTable"); 'use strict';
var QObject = TypeTable.getType('Core', "QObject"); return AbstractAnimation.extend('UI.Navigation', 'SwipeInAnimation', {
module.exports = AbstractAnimation.extend('UI.Navigation', 'SwipeInAnimation', { play: function (newPage, callback) {
newPage.el.style.left = '100%';
play: function (newPage, callback) { setTimeout(function () {
newPage.el.style.left = '100%'; newPage.el.style.transition = 'all 0.3s';
setTimeout(function () { newPage.el.style.left = '0%';
newPage.el.style.transition = 'all 0.3s'; }, 20);
newPage.el.style.left = '0%';
}, 20); setTimeout(function () {
newPage.el.style.transition = 'all 0s';
setTimeout(function () { if (callback)
newPage.el.style.transition = 'all 0s'; callback()
if (callback) }, 320);
callback() },
}, 320);
}, playReverse: function (newPage, callback) {
newPage.el.style.left = '0%';
playReverse: function (newPage, callback) {
newPage.el.style.left = '0%'; setTimeout(function () {
newPage.el.style.transition = 'all 0.3s';
setTimeout(function () { newPage.el.style.left = '100%';
newPage.el.style.transition = 'all 0.3s'; }, 20);
newPage.el.style.left = '100%';
}, 20); setTimeout(function () {
newPage.el.style.transition = 'all 0s';
setTimeout(function () { if (callback)
newPage.el.style.transition = 'all 0s'; callback()
if (callback) }, 320);
callback() }
}, 320); });
} });
}); \ No newline at end of file
\ No newline at end of file
var AbstractAnimation = require('./AbstractAnimation'); module.exports = QRequire(
'Navigation.AbstractAnimation',
var TypeTable = function(
typeof Q != "undefined" AbstractAnimation
? Q.Core.TypeTable ) {
: require("../../Core/TypeTable"); 'use strict';
var QObject = TypeTable.getType('Core', "QObject"); return AbstractAnimation.extend('UI.Navigation', 'SwipeOutAnimation', {
module.exports = AbstractAnimation.extend('UI.Navigation', 'SwipeOutAnimation', { play: function (newPage, callback) {
newPage.el.style.left = '0%';
play: function (newPage, callback) {
newPage.el.style.left = '0%'; setTimeout(function () {
newPage.el.style.transition = 'all 0.3s';
setTimeout(function () { newPage.el.style.left = '-100%';
newPage.el.style.transition = 'all 0.3s'; }, 20);
newPage.el.style.left = '-100%';
}, 20); setTimeout(function () {
newPage.el.style.transition = 'all 0s';
setTimeout(function () { if (callback)
newPage.el.style.transition = 'all 0s'; callback()
if (callback) }, 320);
callback() },
}, 320);
}, playReverse: function (newPage, callback) {
newPage.el.style.left = '-100%';
playReverse: function (newPage, callback) {
newPage.el.style.left = '-100%'; setTimeout(function () {
newPage.el.style.transition = 'all 0.3s';
setTimeout(function () { newPage.el.style.left = '0%';
newPage.el.style.transition = 'all 0.3s'; }, 20);
newPage.el.style.left = '0%';
}, 20); setTimeout(function () {
newPage.el.style.transition = 'all 0s';
setTimeout(function () { if (callback)
newPage.el.style.transition = 'all 0s'; callback()
if (callback) }, 320);
callback() }
}, 320); });
} });
}); \ No newline at end of file
\ No newline at end of file
var TypeTable = module.exports = QRequire('UI.UIComponent', function(
typeof Q != "undefined" UIComponent
? Q.Core.TypeTable ) {
: require("../Core/TypeTable"); 'use strict';
return UIComponent.extend('UI', 'Page', {
load: function (parent) {
if (!parent) {
this.getVieport().appendChild(this.el);
}
this.updateLayout();
this.fire('loaded');
this.fire('drawed');
var UIComponent = require('./UIComponent'); //setInterval(function () {
if (!parent) {
this.tab = this.__shadowProtocol({type: 'tab'}).delegate;
}
//}.bind(this),1000);
module.exports = UIComponent.extend('UI', 'Page', {
load: function (parent) {
if (!parent) {
this.getVieport().appendChild(this.el);
}
this.updateLayout();
this.fire('loaded');
this.fire('drawed');
//setInterval(function () { //this.bubble({type: 'tab', direction: 1, me: this});
if (!parent) { },
this.tab = this.__shadowProtocol({type: 'tab'}).delegate; _prop: {
value: 'title',
title: {
set: function (value) {
document.title = value;
},
get: function () {
return document.title;
}
},
dataContext: null
} }
//}.bind(this),1000);
//this.bubble({type: 'tab', direction: 1, me: this});
}, },
_prop: { function () {
value: 'title', this.setAll({
title: { height: '100%',
set: function (value) { width: '100%',
document.title = value; //scroll: 'vertical',
}, pureCss: "position: absolute; top:0; bottom: 0; left: 0; right: 0; background-size: cover;"
get: function () { });
return document.title;
}
},
dataContext: null
}
},
function () {
this.setAll({
height: '100%',
width: '100%',
//scroll: 'vertical',
pureCss: "position: absolute; top:0; bottom: 0; left: 0; right: 0; background-size: cover;"
}); });
}); });
\ No newline at end of file
var AbstractComponent = require('./AbstractComponent'); module.exports =
var cache = {}, QRequire('Core.AbstractComponent', function(
cssCache = {}, AbstractComponent
style; ) {
var Style = AbstractComponent.extend('Core', 'Style', { 'use strict';
_anything: true, var cache = {},
_onChildAdd: function (child) { cssCache = {},
style;
var Style = AbstractComponent.extend('UI', 'Style', {
_anything: true,
_onChildAdd: function (child) {
child.ref('cls').subscribe(function (val, oldVal) { child.ref('cls').subscribe(function (val, oldVal) {
}); });
}, },
_propChanged: function (key, value, oldValue) { _propChanged: function (key, value, oldValue) {
// OVERHACK // OVERHACK
var subs = this.__refs[key]; var subs = this.__refs[key];
if (subs) if (subs)
for (var i = 0; i < subs.length; i++) { for (var i = 0; i < subs.length; i++) {
subs[i].resolve(value, oldValue); subs[i].resolve(value, oldValue);
} }
var cls = cache[key] || (cache[key] = this.getBaseCls(key)); var cls = cache[key] || (cache[key] = this.getBaseCls(key));
if(!cssCache[cls]) if (!cssCache[cls])
cssCache[cls] = {}; cssCache[cls] = {};
this.setCss(cls, cssCache[cls], value); this.setCss(cls, cssCache[cls], value);
}, },
addRule: function (cls, style) { addRule: function (cls, style) {
var id, rule; var id, rule;
if(!(style.sheet||{}).insertRule) { if (!(style.sheet || {}).insertRule) {
id = (style.styleSheet || style.sheet).addRule(cls, ''); id = (style.styleSheet || style.sheet).addRule(cls, '');
}else { } else {
id = style.sheet.insertRule(cls + "{}"); id = style.sheet.insertRule(cls + "{}");
} }
return (style.styleSheet || style.sheet).rules[id]; return (style.styleSheet || style.sheet).rules[id];
}, },
setCss: function (baseCls, store, val) { setCss: function (baseCls, store, val) {
var cls; var cls;
if(val.cls && val.cls !== '.'){ if (val.cls && val.cls !== '.') {
cls = val.cls cls = val.cls
.split('.') .split('.')
.filter(String) .filter(String)
.concat(baseCls) .concat(baseCls)
.map(function(el){return '.'+el;}) .map(function (el) {
.join(''); return '.' + el;
})
.join('');
}else{ } else {
cls = '.'+baseCls; cls = '.' + baseCls;
} }
var ss = cssCache[cls] = cssCache[cls] || {}; var ss = cssCache[cls] = cssCache[cls] || {};
if(!style) { if (!style) {
style = document.createElement('style'); style = document.createElement('style');
style.type = 'text/css'; style.type = 'text/css';
document.getElementsByTagName('head')[0].appendChild(style); document.getElementsByTagName('head')[0].appendChild(style);
} }
!ss.rule && (ss.rule = this.addRule(cls, style)); !ss.rule && (ss.rule = this.addRule(cls, style));
var rule = ss.rule; var rule = ss.rule;
for(var i in val){ for (var i in val) {
if(i!=='cls' && store[i] !== val[i]){ if (i !== 'cls' && store[i] !== val[i]) {
store[i] = rule.style[i] = val[i]; store[i] = rule.style[i] = val[i];
}
}
},
getBaseCls: function (key) {
var cls = Q.Core.TypeTable.search(key);
if (!cls)
throw new Error('Unknown cls `' + key + '`');
return 'Q-UI-' + cls[0].ctor.type;
} }
} });
}, return Style;
getBaseCls: function (key) { });
var cls = Q.Core.TypeTable.search(key); \ No newline at end of file
if(!cls)
throw new Error ('Unknown cls `'+key+'`');
return 'Q-UI-'+cls[0].ctor.type;
}
});
var UIComponent = require('../UI/UIComponent');
var Style2 = UIComponent.extend('Core', 'Style2', {
//_anything: true,
_onChildAdd: function (child) {
debugger;
}
});
\ No newline at end of file
var TypeTable = module.exports =
typeof Q != "undefined" QRequire('Core.QObject', 'Core.AbstractComponent', function(
? Q.Core.TypeTable QObject,
: require("../Core/TypeTable"); AbstractComponent
) {
var QObject = TypeTable.getType('Core', "QObject"); 'use strict';
var AbstractComponent = TypeTable.getType('Core', "AbstractComponent");
var base = AbstractComponent.prototype;
var base = AbstractComponent.prototype; var trim = function (text) {
var trim = function (text) { return text.trim();
return text.trim(); };
}; var UIComponent = AbstractComponent.extend('UI', 'UIComponent', {
var UIComponent = AbstractComponent.extend('UI', 'UIComponent', { ctor: function () {
ctor: function () { this.createEl();
this.createEl(); this.setAll({
this.setAll({ "pureCss": "position: relative; overflow: visible;",
"pureCss": "position: relative; overflow: visible;", width: '100%',
width: '100%', height: '100%'
height: '100%' });
}); this._contentContainer = void(0);
this._contentContainer = void(0); this.baseCls = "Q-UI-" + this.type;
this.baseCls = "Q-UI-" + this.type; this.el.classList.add(this.baseCls);
this.el.classList.add(this.baseCls); var _self = this;
var _self = this;
this.on('drawed', function () {
this.on('drawed', function(){ _self._getAllChildren(UIComponent).forEach(function (item) {
_self._getAllChildren(UIComponent).forEach(function(item){ item.fire('drawed');
item.fire('drawed'); });
}); });
});
this.on('__shadowProtocol', this.__shadowProtocol); this.on('__shadowProtocol', this.__shadowProtocol);
},
getVieport: function () {
return document.getElementById('viewport');
},
removeClass: function (el, name) {
el.className = ((' ' + el.className + ' ').replace(' ' + name + ' ', ' ')).trim();
},
addClass: function (el, name) {
!this.hasClass(el, name) && (el.className += ' ' + name);
},
hasClass: function (el, name) {
return (' ' + el.className + ' ').indexOf(' ' + name + ' ') > -1;
},
/**
*
*/
updateLayout: function () {
this._getAllChildren(UIComponent).forEach(function(item){
item.updateLayout();
});
},
/**
* @override
*/
_onChildAdd: function (child, prev, next) {
base._onChildAdd.call(this, child);
var insertInto;
if (this._contentContainer) {
insertInto = this._contentContainer.el;
} else {
insertInto = this.el;
}
//insert to DOM or _contentContainer
if (child.el) {
if (!next) {
insertInto.appendChild(child.el);
} else {
insertInto.insertBefore(child.el, next.el);
}
child.renderTo = insertInto;
child.fire('addToParent');
}
if (child instanceof UIComponent)
child.updateLayout();
},
_onChildRemove: function (child) {
child.parent = null;
var removeFrom;
if (this._contentContainer) {
removeFrom = this._contentContainer.el;
} else {
removeFrom = this.el;
}
removeFrom.removeChild(child.el);
},
/**
* @override
*/
_onOwnComponentAdd: function (child) {
base._onOwnComponentAdd.call(this, child);
if (child instanceof TypeTable.getType('UI', 'ContentContainer')) {
this._contentContainer = child;
}
// Add to DOM
if (child.el) {
child.renderTo = this.el;
this.el.appendChild(child.el);
child.fire('addToParent');
}
},
/**
*
*/
createEl: function () {
var self = this;
if (!this.el) {
this.el = document.createElement('div');
this.el.style.overflow = 'hidden';
this.el.style.position = 'relative';
}
this.el.addEventListener('click', function () {
self.fire('click');
});
},
_method: {
red: function () {
var self = this;
self.set("pureCss", "background:red");
}
},
__getShadowDelegate: function(what){
var _self = this;
return this.sd || (this.sd =
{
what: what,
activate: function(me){
_self.__shadowProtocol(what, me);
}, },
deactivate: function(me){ getVieport: function () {
me = me || _self.sd.getLast(); return document.getElementById('viewport');
me && _self.__shadowProtocol(what, me, true);
}, },
next: function(me){ removeClass: function (el, name) {
this.what.direction = 'next'; el.className = ((' ' + el.className + ' ').replace(' ' + name + ' ', ' ')).trim();
_self.__shadowProtocol(this.what);
}, },
prev: function(me){ addClass: function (el, name) {
this.what.direction = 'prev'; !this.hasClass(el, name) && (el.className += ' ' + name);
_self.__shadowProtocol(this.what);
}, },
skip: function(){ hasClass: function (el, name) {
_self.__shadowProtocol(this.what); return (' ' + el.className + ' ').indexOf(' ' + name + ' ') > -1;
}, },
send: function(){
var last = _self['_'+what.type+'ProtocolLast']; /**
if(!last){ *
document.activeElement.click(); */
last = _self['_'+what.type+'ProtocolLast']; updateLayout: function () {
this._getAllChildren(UIComponent).forEach(function (item) {
item.updateLayout();
});
},
/**
* @override
*/
_onChildAdd: function (child, prev, next) {
base._onChildAdd.call(this, child);
var insertInto;
if (this._contentContainer) {
insertInto = this._contentContainer.el;
} else {
insertInto = this.el;
} }
if(last && last.match){
var fn = last.match['_'+what.type+'ProtocolReceive']; //insert to DOM or _contentContainer
if(fn) if (child.el) {
fn.apply(last.match, arguments); if (!next) {
insertInto.appendChild(child.el);
} else {
insertInto.insertBefore(child.el, next.el);
}
child.renderTo = insertInto;
child.fire('addToParent');
} }
if (child instanceof UIComponent)
child.updateLayout();
}, },
collect: function(what){
_self.___shadowProtocol(what, this); _onChildRemove: function (child) {
child.parent = null;
var removeFrom;
if (this._contentContainer) {
removeFrom = this._contentContainer.el;
} else {
removeFrom = this.el;
}
removeFrom.removeChild(child.el);
}, },
getLast: function(){
return _self[what.method+'Last']; /**
* @override
*/
_onOwnComponentAdd: function (child) {
base._onOwnComponentAdd.call(this, child);
if (child instanceof TypeTable.getType('UI', 'ContentContainer')) {
this._contentContainer = child;
}
// Add to DOM
if (child.el) {
child.renderTo = this.el;
this.el.appendChild(child.el);
child.fire('addToParent');
}
}, },
setLast: function(val){
return _self[what.method+'Last'] = val; /**
} *
}); */
}, createEl: function () {
__shadowProtocol: function (what, actor, loose) { var self = this;
var whot = Object.create(what); if (!this.el) {
whot.chain = []; this.el = document.createElement('div');
whot.match = void 0; this.el.style.overflow = 'hidden';
var i, _i, chain, lastChain, who, this.el.style.position = 'relative';
_self = this, }
delegate = this.__getShadowDelegate(whot); this.el.addEventListener('click', function () {
what.delegate = delegate; self.fire('click');
what.chain = []; });
what.initiator = this; },
what.method = '_'+what.type+'Protocol';
_method: {
if(!('direction' in what)){ red: function () {
what.direction = 'next'; var self = this;
} self.set("pureCss", "background:red");
}
delegate.collect(what); },
//this.___shadowProtocol(what, delegate);
chain = what.chain; __getShadowDelegate: function (what) {
if(!chain.length) var _self = this;
return what; return this.sd || (this.sd =
{
lastChain = delegate.getLast();//this[what.method+'Last']; what: what,
if(actor){ activate: function (me) {
who = actor; _self.__shadowProtocol(what, me);
}else { },
_i = chain.length; deactivate: function (me) {
if (what.direction === 'next') { me = me || _self.sd.getLast();
for (i = 0; i < _i; i++) { me && _self.__shadowProtocol(what, me, true);
if (!lastChain) { },
who = chain[i]; next: function (me) {
break; this.what.direction = 'next';
_self.__shadowProtocol(this.what);
},
prev: function (me) {
this.what.direction = 'prev';
_self.__shadowProtocol(this.what);
},
skip: function () {
_self.__shadowProtocol(this.what);
},
send: function () {
var last = _self['_' + what.type + 'ProtocolLast'];
if (!last) {
document.activeElement.click();
last = _self['_' + what.type + 'ProtocolLast'];
}
if (last && last.match) {
var fn = last.match['_' + what.type + 'ProtocolReceive'];
if (fn)
fn.apply(last.match, arguments);
}
},
collect: function (what) {
_self.___shadowProtocol(what, this);
},
getLast: function () {
return _self[what.method + 'Last'];
},
setLast: function (val) {
return _self[what.method + 'Last'] = val;
}
});
},
__shadowProtocol: function (what, actor, loose) {
var whot = Object.create(what);
whot.chain = [];
whot.match = void 0;
var i, _i, chain, lastChain, who,
_self = this,
delegate = this.__getShadowDelegate(whot);
what.delegate = delegate;
what.chain = [];
what.initiator = this;
what.method = '_' + what.type + 'Protocol';
if (!('direction' in what)) {
what.direction = 'next';
}
delegate.collect(what);
//this.___shadowProtocol(what, delegate);
chain = what.chain;
if (!chain.length)
return what;
lastChain = delegate.getLast();//this[what.method+'Last'];
if (actor) {
who = actor;
} else {
_i = chain.length;
if (what.direction === 'next') {
for (i = 0; i < _i; i++) {
if (!lastChain) {
who = chain[i];
break;
} else {
if (lastChain.match === chain[i]) {
who = chain[(i + 1) % _i];
break;
}
}
}
} else { } else {
if (lastChain.match === chain[i]) { for (i = _i - 1; i >= 0; i--) {
who = chain[(i + 1) % _i]; if (!lastChain) {
break; who = chain[i];
break;
} else {
if (lastChain.match === chain[i]) {
who = chain[(i - 1 + _i) % _i];
break;
}
}
} }
} }
} }
} else { if (lastChain !== who) {
for (i = _i - 1; i >= 0; i--) { // if component give it's permissions to leave
if (!lastChain) { if (
who = chain[i]; what.force || !lastChain || !lastChain.match[what.method + 'Leave'] ||
break; lastChain.match[what.method + 'Leave']() !== false
} else { ) {
if (lastChain.match === chain[i]) { if (!loose) {
who = chain[(i - 1 + _i) % _i]; what.match = who;
break; delegate.setLast(what);
who[what.method]();
} }
} }
} }
} return what;
}
if(lastChain !== who){
// if component give it's permissions to leave
if(
what.force ||
!lastChain ||
!lastChain.match[what.method+'Leave'] ||
lastChain.match[what.method+'Leave']() !== false
) {
if(!loose) {
what.match = who;
delegate.setLast(what);
who[what.method]();
}
}
}
return what;
},
___shadowProtocol: function (what, delegate) {
var method = what.method,
children, i, _i, child;
if(typeof this[method] === 'function' && this[method](delegate)) {
what.chain = what.chain.concat(this);
}
children = this._getAllChildren(UIComponent);
for (i = 0, _i = children.length; i < _i; i++) {
child = children[i];
child.___shadowProtocol(what, delegate);
}
return what;
},
_shadowProtocol: function(protocol){
var name = '_'+protocol+ 'ProtocolLast';
if(!this[name])
return false;
return this[name].match;
},
/**
*
*/
_prop: {
cls: {
set: function (val, e) {
var el = this._contentContainer ? this._contentContainer.el : this.el;
e.oldValue && e.oldValue
.split('.')
.map(trim)
.filter(String)
.forEach(function (name) {
el.classList.remove(name);
});
val && val
.split('.')
.map(trim)
.filter(String)
.forEach(function (name) {
el.classList.add(name);
});
}, },
get: function () { ___shadowProtocol: function (what, delegate) {
return ([this.baseCls].concat( var method = what.method,
(this._data.cls||'') children, i, _i, child;
.split('.')
.map(trim) if (typeof this[method] === 'function' && this[method](delegate)) {
.filter(String)) what.chain = what.chain.concat(this);
.map(function (el) {
return '.'+el;
}).join(''))
}
},
fontSize: {
set: function (value) {
var el = this._contentContainer ? this._contentContainer.el : this.el;
el.style.fontSize = value;
}
},
padding: {
set: function (value) {
var el = this._contentContainer ? this._contentContainer.el : this.el;
el.style.padding = value;
}
},
margin: {
set: function (value) {
var el = this._contentContainer ? this._contentContainer.el : this.el;
el.style.margin = value;
}
},
scroll: {
set: function (value) {
if (this._contentContainer)
this._contentContainer.set('scroll', value);
switch (value) {
case 'horizontal':
this.el.style.overflowX = 'auto';
this.el.style.overflowY = 'visible';
break;
case 'vertical':
this.el.style.overflowX = 'visible';
this.el.style.overflowY = 'auto';
break;
case 'both':
this.el.style.overflowX = 'auto';
this.el.style.overflowY = 'auto';
break;
default:
this.el.style.overflow = 'visible';
break;
}
}
},
height: {
set: function (height) {
height = '' + height || 'auto';
this.el.style.height = height.trim();
}
},
width: {
set: function (width) {
width = '' + width || 'auto';
this.el.style.width = width.trim();
}
},
left: {
set: function (left) {
left = '' + left || 'auto';
this.el.style.left = left.trim();
}
},
right: {
set: function (right) {
right = '' + right || 'auto';
this.el.style.right = right.trim();
}
},
top: {
set: function (top) {
top = '' + top || 'auto';
this.el.style.top = top.trim();
}
},
bottom: {
set: function (bottom) {
bottom = '' + bottom || 'auto';
this.el.style.bottom = bottom.trim();
}
},
background: {
set: function (value) {
this.el.style.background = value;
}
},
color: {
set: function (value) {
this.el.style.color = value;
}
},
position: {
set: function (value) {
this.el.style.position = value;
}
},
pureCss: {
set: function (value) {
var rules = value.split(';');
for (var i = 0; i < rules.length; i++) {
var rule = rules[i];
var parts = rule.split(':');
this.el.style[parts[0].trim()] = parts[1];
} }
}
}, children = this._getAllChildren(UIComponent);
visibility: { for (i = 0, _i = children.length; i < _i; i++) {
set: function (val) { child = children[i];
switch (val) { child.___shadowProtocol(what, delegate);
case 'visible':
this.el.style.display = '';
this.el.style.opacity = 1;
break;
case 'flex':
this.el.style.display = 'flex';
this.el.style.opacity = 1;
break;
case 'hidden':
this.el.style.display = '';
this.el.style.opacity = 0;
break;
case 'collapsed':
this.el.style.display = 'none';
break;
} }
} return what;
}, },
_shadowProtocol: function (protocol) {
var name = '_' + protocol + 'ProtocolLast';
if (!this[name])
return false;
return this[name].match;
},
/**
*
*/
_prop: {
cls: {
set: function (val, e) {
var el = this._contentContainer ? this._contentContainer.el : this.el;
e.oldValue && e.oldValue
.split('.')
.map(trim)
.filter(String)
.forEach(function (name) {
el.classList.remove(name);
});
val && val
.split('.')
.map(trim)
.filter(String)
.forEach(function (name) {
el.classList.add(name);
});
},
get: function () {
return ([this.baseCls].concat(
(this._data.cls || '')
.split('.')
.map(trim)
.filter(String))
.map(function (el) {
return '.' + el;
}).join(''))
}
},
fontSize: {
set: function (value) {
var el = this._contentContainer ? this._contentContainer.el : this.el;
el.style.fontSize = value;
}
},
padding: {
set: function (value) {
var el = this._contentContainer ? this._contentContainer.el : this.el;
el.style.padding = value;
}
},
margin: {
set: function (value) {
var el = this._contentContainer ? this._contentContainer.el : this.el;
el.style.margin = value;
}
},
scroll: {
set: function (value) {
if (this._contentContainer)
this._contentContainer.set('scroll', value);
switch (value) {
case 'horizontal':
this.el.style.overflowX = 'auto';
this.el.style.overflowY = 'visible';
break;
case 'vertical':
this.el.style.overflowX = 'visible';
this.el.style.overflowY = 'auto';
break;
case 'both':
this.el.style.overflowX = 'auto';
this.el.style.overflowY = 'auto';
break;
default:
this.el.style.overflow = 'visible';
break;
}
}
},
height: {
set: function (height) {
height = '' + height || 'auto';
this.el.style.height = height.trim();
}
},
width: {
set: function (width) {
width = '' + width || 'auto';
this.el.style.width = width.trim();
}
},
left: {
set: function (left) {
left = '' + left || 'auto';
this.el.style.left = left.trim();
}
},
right: {
set: function (right) {
right = '' + right || 'auto';
this.el.style.right = right.trim();
}
},
top: {
set: function (top) {
top = '' + top || 'auto';
this.el.style.top = top.trim();
}
},
bottom: {
set: function (bottom) {
bottom = '' + bottom || 'auto';
this.el.style.bottom = bottom.trim();
}
},
background: {
set: function (value) {
this.el.style.background = value;
}
},
color: {
set: function (value) {
this.el.style.color = value;
}
},
position: {
set: function (value) {
this.el.style.position = value;
}
},
pureCss: {
set: function (value) {
var rules = value.split(';');
for (var i = 0; i < rules.length; i++) {
var rule = rules[i];
var parts = rule.split(':');
this.el.style[parts[0].trim()] = parts[1];
}
}
},
visibility: {
set: function (val) {
switch (val) {
case 'visible':
this.el.style.display = '';
this.el.style.opacity = 1;
break;
case 'flex':
this.el.style.display = 'flex';
this.el.style.opacity = 1;
break;
case 'hidden':
this.el.style.display = '';
this.el.style.opacity = 0;
break;
case 'collapsed':
this.el.style.display = 'none';
break;
}
}
},
} }
}); });
UIComponent.createElementCss = function (name, css, className) { UIComponent.createElementCss = function (name, css, className) {
var el = document.createElement(name); var el = document.createElement(name);
if (className) if (className)
el.className = className; el.className = className;
for (var key in css) for (var key in css)
if (css.hasOwnProperty(key)) { if (css.hasOwnProperty(key)) {
el.style[key] = css[key]; el.style[key] = css[key];
} }
return el; return el;
}; };
module.exports = UIComponent; return UIComponent;
});
module.exports = { module.exports = {
TypeTable: require('./Core/TypeTable'),
dir: __dirname dir: __dirname
}; };
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment