text
stringlengths 2
1.05M
|
|---|
/*
SPDX-License-Identifier: Apache-2.0
*/
'use strict';
const storycontract = require('./lib/storycontract.js');
module.exports.contracts = [storycontract];
|
/*
Copyright 2019-present OmiseGO Pte Ltd
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. */
import balanceReducer from '../balanceReducer';
describe('balanceReducer', () => {
it('should return the initial state', () => {
const newState = balanceReducer(undefined, { type: '@@INIT' });
expect(newState).toEqual({ rootchain: [], childchain: [] });
});
it('should handle balance success', () => {
const action = {
type: 'BALANCE/GET/SUCCESS',
payload: { rootchain: ['toto'], childchain: ['toto'] }
}
const newState = balanceReducer(undefined, action);
expect(newState).toEqual(action.payload);
});
});
|
'use strict';
const beans = require('../../testutil/configureForTest').get('beans');
const sinon = require('sinon').createSandbox();
const expect = require('must-dist');
const wikiService = beans.get('wikiService');
const groupsAndMembersService = beans.get('groupsAndMembersService');
const activitiesService = beans.get('activitiesService');
const dashboardService = beans.get('dashboardService');
describe('Dashboard Service', () => {
const NOT_FOUND = 'notfound';
const CRASH_ACTIVITY = 'crash activity';
let member;
let activity1;
let activity2;
beforeEach(() => {
member = {membername: 'membername'};
activity1 = {activity: 1};
activity2 = {activity: 2};
sinon.stub(groupsAndMembersService, 'getMemberWithHisGroups').callsFake((nickname, callback) => {
if (nickname === NOT_FOUND) {
return callback(null, null);
}
if (nickname === CRASH_ACTIVITY) {
return callback(null, CRASH_ACTIVITY);
}
callback(null, member);
});
sinon.stub(activitiesService, 'getUpcomingActivitiesOfMemberAndHisGroups').callsFake((mem, callback) => {
if (mem === CRASH_ACTIVITY) {
return callback(new Error());
}
callback(null, [activity1, activity2]);
});
});
afterEach(() => {
sinon.restore();
});
it('collects information from other Services when no subscribed groups exist', done => {
dashboardService.dataForDashboard('nick', (err, result) => {
expect(result.member).to.equal(member);
expect(result.activities).to.contain(activity1);
expect(result.activities).to.contain(activity2);
expect(result.postsByGroup).to.be.empty();
expect(result.changesByGroup).to.be.empty();
done(err);
});
});
it('handles the error when no member for nickname found', done => {
dashboardService.dataForDashboard(NOT_FOUND, err => {
expect(err).to.exist();
done();
});
});
it('handles the error when searching activities fails', done => {
dashboardService.dataForDashboard(CRASH_ACTIVITY, err => {
expect(err).to.exist();
done();
});
});
describe('wiki', () => {
const CRASH_BLOG = 'crash blogs';
const CRASH_CHANGE = 'crash changes';
const blogs = ['blog1', 'blog2'];
const changedFiles = ['change1', 'change2'];
beforeEach(() => {
sinon.stub(wikiService, 'getBlogpostsForGroup').callsFake((groupid, callback) => {
if (groupid === CRASH_BLOG) {
return callback(new Error());
}
callback(null, blogs);
});
sinon.stub(wikiService, 'listChangedFilesinDirectory').callsFake((groupid, callback) => {
if (groupid === CRASH_CHANGE) {
return callback(new Error());
}
callback(null, changedFiles);
});
});
it('collects wiki information', done => {
member.subscribedGroups = [
{id: 'group'}
];
dashboardService.dataForDashboard('nick', (err, result) => {
expect(result.postsByGroup).to.have.keys(['group']);
expect(result.postsByGroup.group).to.contain('blog1');
expect(result.postsByGroup.group).to.contain('blog2');
expect(result.changesByGroup).to.have.keys(['group']);
expect(result.changesByGroup.group).to.contain('change1');
expect(result.changesByGroup.group).to.contain('change2');
done(err);
});
});
it('handles the error when searching blogposts crashes', done => {
member.subscribedGroups = [
{id: CRASH_BLOG}
];
dashboardService.dataForDashboard('nick', err => {
expect(err).to.exist();
done();
});
});
it('handles the error when searching wiki changes crashes', done => {
member.subscribedGroups = [
{id: CRASH_CHANGE}
];
dashboardService.dataForDashboard('nick', err => {
expect(err).to.exist();
done();
});
});
});
describe('partitions groups to columns by height', () => {
it('for less than three groups', () => {
const group1 = {id: 1};
const group2 = {id: 2};
const groups = [ group1, group2 ];
const linesPerGroup = {1: 5, 2: 2};
const result = dashboardService.groupsByColumns(groups, linesPerGroup);
expect(result).to.have.length(3);
expect(result[0]).to.contain(group1);
expect(result[1]).to.contain(group2);
expect(result[2]).to.be.empty();
});
it('for three groups of equal height', () => {
const group1 = {id: 1};
const group2 = {id: 2};
const group3 = {id: 3};
const groups = [ group1, group2, group3 ];
const linesPerGroup = {1: 2, 2: 2, 3: 2};
const result = dashboardService.groupsByColumns(groups, linesPerGroup);
expect(result).to.have.length(3);
expect(result[0]).to.contain(group1);
expect(result[1]).to.contain(group2);
expect(result[2]).to.contain(group3);
});
it('for three groups of different height (case 1)', () => {
const group1 = {id: 1};
const group2 = {id: 2};
const group3 = {id: 3};
const groups = [ group1, group2, group3 ];
const linesPerGroup = {1: 3, 2: 2, 3: 1};
const result = dashboardService.groupsByColumns(groups, linesPerGroup);
expect(result).to.have.length(3);
expect(result[0]).to.contain(group1);
expect(result[1]).to.contain(group2);
expect(result[2]).to.contain(group3);
});
it('for three groups of different height (case 2)', () => {
const group1 = {id: 1};
const group2 = {id: 2};
const group3 = {id: 3};
const groups = [ group1, group2, group3 ];
const linesPerGroup = {1: 1, 2: 2, 3: 3};
const result = dashboardService.groupsByColumns(groups, linesPerGroup);
expect(result).to.have.length(3);
expect(result[0]).to.contain(group1);
expect(result[0]).to.contain(group2);
expect(result[1]).to.contain(group3);
expect(result[2]).to.be.empty();
});
});
});
|
var searchData=
[
['slo_277',['SLO',['../classmysite_1_1core_1_1models_1_1slo__models_1_1_s_l_o.html',1,'mysite::core::models::slo_models']]],
['sloinreport_278',['SLOInReport',['../classmysite_1_1core_1_1models_1_1slo__models_1_1_s_l_o_in_report.html',1,'mysite::core::models::slo_models']]],
['slostatus_279',['SLOStatus',['../classmysite_1_1core_1_1models_1_1data__models_1_1_s_l_o_status.html',1,'mysite::core::models::data_models']]],
['slostostakeholder_280',['SLOsToStakeholder',['../classmysite_1_1core_1_1models_1_1slo__models_1_1_s_l_os_to_stakeholder.html',1,'mysite::core::models::slo_models']]]
];
|
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////////
goog.module('tink.aead.exports');
const AeadConfig = goog.require('tink.aead.AeadConfig');
const AeadKeyTemplates = goog.require('tink.aead.AeadKeyTemplates');
const AeadWrapper = goog.require('tink.aead.AeadWrapper');
const AesCtrHmacAeadKeyManager = goog.require('tink.aead.AesCtrHmacAeadKeyManager');
const AesGcmKeyManager = goog.require('tink.aead.AesGcmKeyManager');
goog.exportSymbol('tink.aead.AeadConfig', AeadConfig);
goog.exportProperty(
AeadKeyTemplates, 'aes128CtrHmacSha256',
AeadKeyTemplates.aes128CtrHmacSha256);
goog.exportProperty(
AeadKeyTemplates, 'aes256CtrHmacSha256',
AeadKeyTemplates.aes256CtrHmacSha256);
goog.exportProperty(AeadKeyTemplates, 'aes128Gcm', AeadKeyTemplates.aes128Gcm);
goog.exportProperty(AeadKeyTemplates, 'aes256Gcm', AeadKeyTemplates.aes256Gcm);
goog.exportProperty(
AeadKeyTemplates, 'aes256GcmNoPrefix', AeadKeyTemplates.aes256GcmNoPrefix);
goog.exportSymbol('tink.aead.AeadKeyTemplates', AeadKeyTemplates);
goog.exportSymbol('tink.aead.AeadWrapper', AeadWrapper);
goog.exportSymbol(
'tink.aead.AesCtrHmacAeadKeyManager', AesCtrHmacAeadKeyManager);
goog.exportSymbol('tink.aead.AesGcmKeyManager', AesGcmKeyManager);
|
var data=[['20120731',5.156],
['20120801',5.479],
['20120802',6.038],
['20120803',6.650],
['20120806',7.321],
['20120807',8.062],
['20120813',8.379],
['20120814',8.038],
['20120815',8.150],
['20120816',8.126],
['20120817',7.974],
['20120820',8.779],
['20120821',8.474],
['20120822',8.168],
['20120823',7.915],
['20120824',7.891],
['20120827',7.097],
['20120828',7.285],
['20120829',7.362],
['20120830',7.421],
['20120831',7.832],
['20120903',7.844],
['20120904',8.150],
['20120905',7.750],
['20120906',7.621],
['20120907',8.015],
['20120910',8.232],
['20120911',7.874],
['20120912',7.921],
['20120913',7.415],
['20120914',7.432],
['20120917',7.244],
['20120918',7.097],
['20120919',7.162],
['20120920',6.726],
['20120921',6.479],
['20120924',6.538],
['20120925',6.615],
['20120926',6.615],
['20120927',6.662],
['20120928',6.650],
['20121008',6.774],
['20121009',6.997],
['20121010',7.238],
['20121011',6.803],
['20121012',6.832],
['20121015',6.615],
['20121016',6.638],
['20121017',6.891],
['20121018',6.956],
['20121019',6.944],
['20121022',6.932],
['20121023',6.868],
['20121024',6.615],
['20121025',6.397],
['20121026',6.144],
['20121029',6.174],
['20121030',6.221],
['20121031',6.174],
['20121101',6.344],
['20121102',6.432],
['20121105',6.397],
['20121106',6.256],
['20121107',6.321],
['20121108',6.026],
['20121109',6.026],
['20121112',6.079],
['20121113',5.903],
['20121114',6.503],
['20121115',6.656],
['20121116',6.303],
['20121119',6.709],
['20121120',7.144],
['20121121',7.168],
['20121122',6.944],
['20121123',6.944],
['20121126',6.809],
['20121127',6.138],
['20121128',6.179],
['20121129',6.162],
['20121130',6.162],
['20121203',6.262],
['20121204',6.432],
['20121205',6.668],
['20121206',6.615],
['20121207',6.756],
['20121210',7.062],
['20121211',6.809],
['20121212',7.062],
['20121213',6.821],
['20121214',7.203],
['20121217',7.162],
['20121218',6.979],
['20121219',7.085],
['20121220',7.350],
['20121221',7.738],
['20121224',7.721],
['20121225',8.232],
['20121226',9.062],
['20121227',8.821],
['20121228',8.921],
['20121231',8.832],
['20130104',8.950],
['20130107',8.862],
['20130108',8.862],
['20130109',8.568],
['20130110',8.509],
['20130111',8.774],
['20130114',9.215],
['20130115',9.197],
['20130116',8.891],
['20130117',8.768],
['20130118',8.821],
['20130121',9.068],
['20130122',8.597],
['20130123',8.432],
['20130124',8.121],
['20130125',8.044],
['20130128',8.291],
['20130129',8.362],
['20130130',8.797],
['20130131',8.621],
['20130201',8.421],
['20130204',8.226],
['20130205',8.462],
['20130206',8.379],
['20130207',8.432],
['20130208',8.609],
['20130218',8.803],
['20130219',8.444],
['20130220',8.550],
['20130221',8.238],
['20130222',8.250],
['20130225',8.350],
['20130226',8.350],
['20130227',8.303],
['20130228',8.362],
['20130301',8.656],
['20130304',8.291],
['20130305',8.368],
['20130306',8.626],
['20130307',8.762],
['20130308',8.509],
['20130311',8.538],
['20130312',8.079],
['20130313',7.732],
['20130314',7.750],
['20130315',7.721],
['20130318',7.503],
['20130319',7.597],
['20130320',7.826],
['20130321',7.891],
['20130322',7.803],
['20130325',7.862],
['20130326',7.638],
['20130327',7.615],
['20130328',7.238],
['20130329',7.156],
['20130401',7.256],
['20130402',7.132],
['20130403',7.144],
['20130408',7.091],
['20130409',7.185],
['20130410',7.285],
['20130411',7.303],
['20130412',7.085],
['20130415',6.862],
['20130416',6.938],
['20130417',6.974],
['20130418',7.132],
['20130419',7.250],
['20130422',7.197],
['20130423',6.738],
['20130424',6.844],
['20130425',6.809],
['20130426',6.191],
['20130502',6.244],
['20130503',6.262],
['20130506',6.509],
['20130507',6.638],
['20130508',6.626],
['20130509',6.421],
['20130510',6.632],
['20130513',6.579],
['20130514',6.332],
['20130515',6.397],
['20130516',7.044],
['20130517',7.115],
['20130520',7.156],
['20130521',7.274],
['20130522',7.097],
['20130523',7.038],
['20130524',7.203],
['20130527',7.526],
['20130528',7.362],
['20130529',7.438],
['20130530',7.315],
['20130531',7.244],
['20130603',7.056],
['20130604',6.997],
['20130605',7.038],
['20130606',6.791],
['20130607',6.603],
['20130613',6.250],
['20130614',6.415],
['20130617',6.309],
['20130618',6.309],
['20130619',6.479],
['20130620',6.221],
['20130621',6.050],
['20130624',5.568],
['20130625',5.421],
['20130626',5.515],
['20130627',5.750],
['20130628',5.685],
['20130701',5.679],
['20130702',5.744],
['20130703',5.615],
['20130704',5.668],
['20130705',5.579],
['20130708',5.079],
['20130709',5.115],
['20130710',5.344],
['20130711',5.521],
['20130712',5.650],
['20130715',5.885],
['20130716',5.774],
['20130717',5.574],
['20130718',5.591],
['20130719',5.291],
['20130722',5.474],
['20130723',5.609],
['20130724',5.503],
['20130725',6.056],
['20130726',5.956],
['20130729',5.585],
['20130730',5.691],
['20130731',5.803],
['20130801',5.850],
['20130802',5.821],
['20130805',5.915],
['20130806',6.315],
['20130807',6.126],
['20130808',6.168],
['20130809',6.256],
['20130812',6.391],
['20130813',6.344],
['20130814',6.244],
['20130815',6.074],
['20130816',5.885],
['20130819',5.979],
['20130820',5.921],
['20130821',6.062],
['20130822',6.121],
['20130823',5.968],
['20130826',6.168],
['20130827',6.144],
['20130828',6.150],
['20130829',5.997],
['20130830',5.950],
['20130902',6.038],
['20130903',6.056],
['20130904',6.162],
['20130905',6.021],
['20130906',6.021],
['20130909',6.079],
['20130910',6.185],
['20130911',6.279],
['20130912',6.138],
['20130913',6.079],
['20130916',6.215],
['20130917',6.379],
['20130918',6.274],
['20130923',6.374],
['20130924',6.538],
['20130925',6.444],
['20130926',6.203],
['20130927',6.062],
['20130930',6.074],
['20131008',6.203],
['20131009',6.150],
['20131010',5.968],
['20131011',6.074],
['20131014',6.144],
['20131015',6.332],
['20131016',6.497],
['20131017',6.703],
['20131018',6.468],
['20131021',6.615],
['20131022',6.656],
['20131023',6.185],
['20131024',6.203],
['20131025',5.950],
['20131028',5.538],
['20131029',5.350],
['20131030',5.462],
['20131031',5.432],
['20131101',5.526],
['20131104',5.532],
['20131105',5.556],
['20131106',5.526],
['20131107',5.379],
['20131108',5.491],
['20131111',5.538],
['20131112',5.656],
['20131113',5.521],
['20131114',5.703],
['20131115',5.779],
['20131118',5.844],
['20131119',5.803],
['20131120',5.832],
['20131121',5.785],
['20131122',5.785],
['20131125',5.744],
['20131126',5.785],
['20131127',5.950],
['20131128',5.962],
['20131129',6.079],
['20131202',5.491],
['20131203',5.603],
['20131204',5.691],
['20131205',5.797],
['20131206',5.744],
['20131209',5.944],
['20131210',5.997],
['20131211',5.932],
['20131212',6.132],
['20131213',6.026],
['20131216',5.926],
['20131217',5.915],
['20131218',6.068],
['20131219',5.921],
['20131220',5.668],
['20131223',5.626],
['20131224',5.674],
['20131225',5.791],
['20131226',5.562],
['20131227',5.697],
['20131230',5.938],
['20131231',5.926],
['20140102',5.932],
['20140103',5.932],
['20140106',5.609],
['20140107',5.662],
['20140108',5.685],
['20140109',5.491],
['20140110',5.268],
['20140113',5.309],
['20140114',5.385],
['20140115',5.426],
['20140116',5.597],
['20140117',5.750],
['20140120',5.615],
['20140121',5.703],
['20140122',5.821],
['20140123',5.744],
['20140124',5.744],
['20140127',5.644],
['20140128',5.503],
['20140129',5.579],
['20140130',5.503],
['20140207',5.650],
['20140210',5.821],
['20140211',5.915],
['20140212',5.938],
['20140213',5.791],
['20140214',6.050],
['20140217',6.179],
['20140218',6.085],
['20140219',6.103],
['20140220',6.244],
['20140221',6.097],
['20140224',6.026],
['20140225',5.821],
['20140226',5.915],
['20140227',5.879],
['20140228',6.032],
['20140303',6.197],
['20140304',6.303],
['20140305',6.226],
['20140306',6.450],
['20140307',6.421],
['20140310',6.221],
['20140311',6.450],
['20140312',6.503],
['20140313',6.368],
['20140314',6.315],
['20140317',6.444],
['20140318',6.332],
['20140319',6.715],
['20140320',6.685],
['20140321',6.579],
['20140324',7.244],
['20140325',7.068],
['20140326',7.044],
['20140327',6.797],
['20140328',6.132],
['20140331',6.091],
['20140401',6.197],
['20140402',6.262],
['20140403',6.091],
['20140404',6.162],
['20140408',6.115],
['20140409',6.203],
['20140410',6.268],
['20140411',6.344],
['20140414',6.562],
['20140415',6.597],
['20140416',6.809],
['20140417',6.597],
['20140418',6.397],
['20140421',6.326],
['20140422',6.521],
['20140423',6.144],
['20140424',6.250],
['20140425',6.409],
['20140428',6.385],
['20140429',6.562],
['20140430',6.503],
['20140505',6.615],
['20140506',6.544],
['20140507',6.650],
['20140508',6.756],
['20140509',6.574],
['20140512',6.856],
['20140513',6.785],
['20140514',6.609],
['20140515',6.379],
['20140516',6.279],
['20140519',6.315],
['20140520',6.179],
['20140521',6.274],
['20140522',6.350],
['20140523',6.374],
['20140526',6.403],
['20140527',6.262],
['20140528',6.421],
['20140529',6.338],
['20140530',6.468],
['20140603',6.691],
['20140604',6.685],
['20140605',6.656],
['20140606',6.574],
['20140609',6.479],
['20140610',6.515],
['20140611',6.556],
['20140612',6.609],
['20140613',6.632],
['20140616',6.697],
['20140617',6.547],
['20140618',6.765],
['20140619',6.465],
['20140620',6.541],
['20140623',6.712],
['20140624',6.788],
['20140625',6.794],
['20140626',6.853],
['20140627',6.912],
['20140630',6.900],
['20140701',6.918],
['20140702',6.906],
['20140703',7.047],
['20140704',7.006],
['20140707',7.000],
['20140708',7.124],
['20140709',6.829],
['20140710',6.865],
['20140711',7.065],
['20140714',7.106],
['20140715',7.053],
['20140716',7.229],
['20140717',7.135],
['20140718',7.059],
['20140721',6.941],
['20140722',7.018],
['20140723',6.794],
['20140724',6.800],
['20140725',6.912],
['20140728',7.006],
['20140729',7.065],
['20140730',7.100],
['20140731',7.100],
['20140801',7.012],
['20140804',7.082],
['20140805',7.253],
['20140806',7.388],
['20140807',7.512],
['20140808',7.447],
['20140811',7.459],
['20140812',7.376],
['20140813',7.435],
['20140814',7.347],
['20140815',7.341],
['20140818',7.524],
['20140819',7.394],
['20140820',7.512],
['20140821',7.529],
['20140822',7.718],
['20140825',7.418],
['20140826',7.235],
['20140827',7.259],
['20140828',7.124],
['20140829',7.265],
['20140901',7.394],
['20140902',7.465],
['20140903',7.747],
['20140904',7.824],
['20140905',7.941],
['20140909',7.829],
['20140910',7.835],
['20140911',7.735],
['20140912',7.818],
['20140915',7.900],
['20140916',7.688],
['20140917',7.794],
['20140918',7.965],
['20140919',7.935],
['20140922',7.753],
['20140923',7.859],
['20140924',8.024],
['20140925',7.959],
['20140926',8.176],
['20140929',8.435],
['20140930',8.341],
['20141008',8.347],
['20141009',8.247],
['20141010',8.259],
['20141013',8.159],
['20141014',8.459],
['20141015',8.476],
['20141016',9.100],
['20141017',9.118],
['20141020',9.165],
['20141021',8.718],
['20141022',8.541],
['20141023',8.318],
['20141024',8.329],
['20141027',8.553],
['20141028',8.800],
['20141029',8.800],
['20141030',8.812],
['20141031',8.724],
['20141103',9.012],
['20141104',8.759],
['20141105',8.865],
['20141106',9.153],
['20141107',8.924],
['20141110',9.018],
['20141111',8.382],
['20141112',8.518],
['20141113',8.665],
['20141114',8.476],
['20141117',8.582],
['20141118',8.471],
['20141119',8.629],
['20141120',8.600],
['20141121',8.647],
['20141124',8.694],
['20141125',8.935],
['20141126',8.859],
['20141127',8.888],
['20141128',8.788],
['20141201',8.588],
['20141202',8.729],
['20141203',8.847],
['20141204',8.912],
['20141205',8.394],
['20141208',8.229],
['20141209',7.876],
['20141210',8.141],
['20141211',8.247],
['20141212',8.376],
['20141215',8.471],
['20141216',8.965],
['20141217',9.106],
['20141218',9.306],
['20141219',9.247],
['20141222',9.118],
['20141223',9.082],
['20141224',9.371],
['20141225',9.318],
['20141226',9.424],
['20141229',9.129],
['20141230',8.529],
['20141231',8.959],
['20150105',8.829],
['20150106',8.859],
['20150107',8.806],
['20150108',8.712],
['20150109',8.729],
['20150112',8.600],
['20150113',8.706],
['20150114',8.588],
['20150115',8.582],
['20150116',8.588],
['20150119',8.035],
['20150120',8.265],
['20150121',8.606],
['20150122',8.794],
['20150123',8.594],
['20150126',8.682],
['20150127',8.847],
['20150128',8.688],
['20150129',8.906],
['20150130',8.682],
['20150202',8.541],
['20150203',8.724],
['20150204',8.706],
['20150205',8.600],
['20150206',8.418],
['20150209',8.553],
['20150210',8.594],
['20150211',8.641],
['20150212',8.671],
['20150213',8.782],
['20150216',9.071],
['20150217',8.941],
['20150507',9.841],
['20150508',10.829],
['20150511',11.141],
['20150512',11.376],
['20150513',12.400],
['20150514',11.924],
['20150515',11.388],
['20150518',11.776],
['20150519',11.894],
['20150520',12.082],
['20150521',13.294],
['20150522',13.971],
['20150525',14.600],
['20150526',14.906],
['20150527',15.147],
['20150528',13.635],
['20150529',13.424],
['20150601',14.194],
['20150602',14.841],
['20150603',14.700],
['20150604',14.747],
['20150605',14.835],
['20150608',15.376],
['20150609',16.012],
['20150610',16.041],
['20150611',15.838],
['20150612',16.097],
['20150615',15.491],
['20150616',14.303],
['20150617',14.962],
['20150618',14.562],
['20150619',13.103],
['20150623',12.774],
['20150624',13.156],
['20150625',12.409],
['20150626',11.168],
['20150629',10.738],
['20150630',11.815],
['20150701',11.238],
['20150702',10.679],
['20150703',9.609],
['20150706',8.644],
['20150707',7.779],
['20150708',7.479],
['20150709',8.232],
['20150710',9.056],
['20150713',9.962],
['20150714',9.638],
['20150715',8.674],
['20150716',9.044],
['20150717',9.950],
['20150720',10.244],
['20150721',10.238],
['20150722',10.185],
['20150723',10.709],
['20150724',11.203],
['20150727',10.079],
['20150728',9.068],
['20150729',9.915],
['20150730',9.838],
['20150731',9.156],
['20150803',8.497],
['20150804',9.179],
['20150805',9.038],
['20150806',8.968],
['20150807',9.456],
['20150810',10.403],
['20150811',11.444],
['20150812',12.532],
['20150813',12.532],
['20150814',12.768],
['20150817',13.003],
['20150818',12.915],
['20150819',13.032],
['20150820',13.021],
['20150821',11.779],
['20150824',11.721],
['20150825',10.544],
['20150826',9.485],
['20150827',9.174],
['20150828',9.944],
['20150831',10.268],
['20150901',10.503],
['20150902',9.985],
['20150907',9.326],
['20150908',10.062],
['20150909',10.374],
['20150910',10.150],
['20150911',10.191],
['20150914',9.168],
['20150915',8.250],
['20150916',9.079],
['20150917',9.362],
['20150918',9.526],
['20150921',9.668],
['20150922',10.638],
['20150923',11.703],
['20150924',10.532],
['20150925',9.479],
['20150928',8.838],
['20150929',8.574],
['20150930',8.444],
['20151008',8.691],
['20151009',8.885],
['20151012',9.297],
['20151013',9.432],
['20151014',8.974],
['20151015',9.326],
['20151016',9.685],
['20151019',9.368],
['20151020',9.926],
['20151021',9.074],
['20151022',9.715],
['20151023',10.515],
['20151026',10.415],
['20151027',10.909],
['20151028',10.609],
['20151029',10.279],
['20151030',10.309],
['20151102',10.179],
['20151103',9.885],
['20151104',10.503],
['20151105',10.562],
['20151106',11.015],
['20151109',11.244],
['20151110',11.091],
['20151111',11.832],
['20151112',12.091],
['20151113',11.950],
['20151116',12.209],
['20151117',11.974],
['20151118',11.503],
['20151119',11.709],
['20151120',11.909],
['20151123',11.815],
['20151124',12.021],
['20151125',12.574],
['20151126',12.768],
['20151127',11.850],
['20151130',12.844],
['20151201',12.897],
['20151202',12.532],
['20151203',12.621],
['20151204',12.703],
['20151207',13.156],
['20151208',13.626],
['20151209',13.397],
['20151210',13.385],
['20151211',13.950],
['20160216',13.591],
['20160217',13.150],
['20160218',14.468],
['20160219',14.926],
['20160222',15.162],
['20160726',13.643],
['20160727',12.278],
['20160728',11.055],
['20160729',10.902],
['20160801',10.737],
['20160802',10.937],
['20160803',10.766],
['20160804',10.949],
['20160805',10.890],
['20160808',10.996],
['20160809',11.037],
['20160810',11.125],
['20160811',10.796],
['20160812',10.743],
['20160815',10.890],
['20160816',11.072],
['20160817',11.731],
['20160818',12.102],
['20160819',12.155],
['20160822',11.396],
['20160823',11.484],
['20160824',11.402],
['20160825',12.272],
['20160826',12.296],
['20160829',12.184],
['20160830',12.308],
['20160831',12.249],
['20160901',12.890],
['20160902',13.084],
['20160905',12.949],
['20160906',13.214],
['20160907',13.184],
['20160908',13.037],
['20160909',13.055],
['20160912',12.661],
['20160913',12.866],
['20160914',13.155],
['20160919',13.337],
['20160920',13.202],
['20160921',13.566],
['20160922',13.802],
['20160923',13.625],
['20160926',13.190],
['20160927',12.990],
['20160928',13.184],
['20160929',13.314],
['20160930',13.178],
['20161010',13.625],
['20161011',13.737],
['20161012',13.725],
['20161013',14.061],
['20161014',13.914],
['20161017',13.625],
['20161018',13.919],
['20161019',14.908],
['20161020',14.725],
['20161021',14.978],
['20161024',14.684],
['20161025',15.019],
['20161026',14.696],
['20161027',15.272],
['20161028',15.272],
['20161031',15.514],
['20161101',15.772],
['20161102',15.749],
['20161103',16.266],
['20161104',16.931],
['20161107',16.684],
['20161108',16.802],
['20161109',16.584],
['20161110',16.802],
['20161111',16.608],
['20161114',16.284],
['20161115',16.755],
['20161116',17.161],
['20161117',17.125],
['20161118',16.755],
['20161121',16.555],
['20161122',17.178],
['20161123',16.855],
['20161124',16.466],
['20161125',16.331],
['20161128',15.861],
['20161129',15.690],
['20161130',15.766],
['20161201',17.078],
['20161202',16.725],
['20161205',16.402],
['20161206',17.449],
['20161207',17.431],
['20161208',17.496],
['20161209',18.037],
['20161212',16.861],
['20161213',18.549],
['20161214',20.408],
['20161215',19.790],
['20161216',19.596],
['20161219',19.237],
['20161220',18.514],
['20161221',18.825],
['20161222',18.308],
['20161223',18.325],
['20161226',18.425],
['20161227',18.837],
['20161228',19.919],
['20161229',19.278],
['20161230',18.972],
['20170103',18.925],
['20170104',20.214],
['20170105',19.831],
['20170106',19.978],
['20170109',20.566],
['20170110',20.919],
['20170111',20.572],
['20170112',20.778],
['20170113',19.890],
['20170116',18.802],
['20170117',19.319],
['20170118',19.237],
['20170119',19.290],
['20170120',19.931],
['20170123',19.843],
['20170124',19.831],
['20170125',20.266],
['20170126',20.284],
['20170203',18.255],
['20170206',16.684],
['20170207',16.790],
['20170208',16.866],
['20170209',16.866],
['20170210',16.031],
['20170213',16.155],
['20170214',15.566],
['20170215',15.584],
['20170216',15.484],
['20170217',14.925],
['20170220',15.166],
['20170221',15.102],
['20170222',14.990],
['20170223',14.861],
['20170224',15.025],
['20170227',15.255],
['20170228',15.019],
['20170301',14.896],
['20170302',14.308],
['20170303',13.949],
['20170306',14.972],
['20170307',14.449],
['20170308',14.390],
['20170309',14.455],
['20170310',13.984],
['20170313',14.155],
['20170314',13.890],
['20170315',14.119],
['20170316',14.096],
['20170317',13.937],
['20170320',13.943],
['20170321',13.825],
['20170322',13.584],
['20170323',13.484],
['20170324',14.025],
['20170327',13.825],
['20170328',13.849],
['20170329',15.214],
['20170330',14.590],
['20170331',14.708],
['20170405',16.178],
['20170406',15.914],
['20170407',16.196],
['20170410',16.831],
['20170411',17.302],
['20170412',15.572],
['20170413',15.855],
['20170414',15.443],
['20170417',14.990],
['20170418',15.355],
['20170419',15.978],
['20170420',15.978],
['20170421',15.861],
['20170424',15.272],
['20170425',15.708],
['20170426',15.525],
['20170427',15.072],
['20170428',14.731],
['20170502',15.178],
['20170503',14.684],
['20170504',14.996],
['20170505',15.672],
['20170508',14.437],
['20170509',13.802],
['20170510',12.761],
['20170511',12.696],
['20170512',12.537],
['20170515',13.625],
['20170516',13.908],
['20170517',14.272],
['20170518',14.002],
['20170519',14.108],
['20170522',13.772],
['20170523',13.461],
['20170524',13.525],
['20170525',13.996],
['20170526',14.149],
['20170531',14.214],
['20170601',13.419],
['20170602',13.743],
['20170605',13.737],
['20170606',13.461],
['20170607',13.802],
['20170608',13.661],
['20170609',13.572],
['20170612',13.465],
['20170613',13.565],
['20170614',13.359],
['20170615',13.359],
['20170616',13.553],
['20170619',13.547],
['20170620',13.612],
['20170621',13.641],
['20170622',13.518],
['20170623',13.518],
['20170626',13.782],
['20170627',13.706],
['20170628',13.665],
['20170629',13.676],
['20170630',13.771],
['20170703',13.829],
['20170704',13.988],
['20170705',14.494],
['20170706',14.371],
['20170707',14.312],
['20170710',14.441],
['20170711',14.053],
['20170712',14.676],
['20170713',14.706],
['20170714',15.171],
['20170717',14.988],
['20170718',15.324],
['20170719',15.400],
['20170720',15.318],
['20170721',15.288],
['20170724',15.171],
['20170725',15.429],
['20170726',15.435],
['20170727',15.394],
['20170728',15.288],
['20170731',15.288],
['20170801',15.259],
['20170802',15.129],
['20170803',16.124],
['20170804',15.659],
['20170807',15.718],
['20170808',15.847],
['20170809',15.771],
['20170810',15.812],
['20170811',16.318],
['20170814',16.494],
['20170815',16.418],
['20170816',16.347],
['20170817',16.271],
['20170818',16.053],
['20170821',15.994],
['20170822',16.324],
['20170823',16.218],
['20170824',16.229],
['20170825',16.312],
['20170828',16.306],
['20170829',16.229],
['20170830',15.982],
['20170831',15.876],
['20170901',15.694],
['20170904',15.565],
['20170905',15.665],
['20170906',15.788],
['20170907',16.029],
['20170908',16.129],
['20170911',15.953],
['20170912',15.918],
['20170913',15.724],
['20170914',15.635],
['20170915',15.629],
['20170918',15.847],
['20170919',15.676],
['20170920',15.712],
['20170921',16.512],
['20170922',16.759],
['20170925',16.582],
['20170926',16.406],
['20170927',16.535],
['20170928',16.341],
['20170929',16.347],
['20171009',16.441],
['20171010',16.376],
['20171011',16.406],
['20171012',16.147],
['20171013',16.188],
['20171016',15.524],
['20171017',15.459],
['20171018',15.465],
['20171019',15.406],
['20171020',15.424],
['20171023',15.712],
['20171024',15.541],
['20171025',15.994],
['20171026',15.994],
['20171027',15.835],
['20171030',15.641],
['20171031',15.553],
['20171101',15.582],
['20171102',15.559],
['20171103',15.406],
['20171106',15.347],
['20171107',16.882],
['20171108',16.229],
['20171109',16.065],
['20171110',15.676],
['20171113',15.782],
['20171114',15.488],
['20171115',15.382],
['20171116',15.435],
['20171117',15.506],
['20171120',15.465],
['20171121',15.282],
['20171122',15.288],
['20171123',15.188],
['20171124',15.065],
['20171127',15.029],
['20171128',15.065],
['20171129',14.865],
['20171130',14.735],
['20171201',14.541],
['20171204',14.576],
['20171205',14.682],
['20171206',14.712],
['20171207',14.782],
['20171208',14.794],
['20171211',14.806],
['20171212',14.659],
['20171213',15.176],
['20171214',15.088],
['20171215',14.700],
['20171218',14.665],
['20171219',14.618],
['20171220',14.318],
['20171221',14.229],
['20171222',14.329],
['20171225',14.253],
['20171226',14.235],
['20171227',14.247],
['20171228',14.188],
['20171229',14.176],
['20180102',14.229],
['20180103',14.441],
['20180104',14.253],
['20180105',14.241],
['20180108',14.229],
['20180109',14.412],
['20180110',14.376],
['20180111',14.359],
['20180112',14.382],
['20180115',14.265],
['20180116',14.259],
['20180117',14.312],
['20180118',14.306],
['20180119',14.371],
['20180122',14.312],
['20180123',14.259],
['20180124',14.229],
['20180125',15.200],
['20180126',14.588],
['20180129',14.318],
['20180130',14.288],
['20180131',14.159],
['20180201',14.100],
['20180202',13.935],
['20180205',13.876],
['20180206',13.788],
['20180207',13.859],
['20180208',13.824],
['20180209',13.747],
['20180212',13.747],
['20180213',13.771],
['20180214',13.800],
['20180222',13.847],
['20180223',13.947],
['20180226',13.935],
['20180227',13.800],
['20180228',13.794],
['20180301',13.759],
['20180302',13.541],
['20180305',13.682],
['20180306',13.635],
['20180307',13.612],
['20180308',13.559],
['20180309',13.759],
['20180312',13.929],
['20180313',13.853],
['20180314',13.841],
['20180315',13.753],
['20180316',13.612],
['20180319',13.747],
['20180320',13.659],
['20180321',13.676],
['20180322',13.676],
['20180323',13.694],
['20180326',13.747],
['20180327',13.853],
['20180328',13.653],
['20180329',13.594],
['20180330',13.553],
['20180402',13.559],
['20180403',13.524],
['20180404',13.494],
['20180409',13.500],
['20180410',13.482],
['20180411',14.182],
['20180412',14.376],
['20180413',13.700],
['20180416',13.682],
['20180417',13.641],
['20180418',13.688],
['20180419',13.606],
['20180420',13.447],
['20180423',14.047],
['20180424',14.935],
['20180425',15.559],
['20180426',16.459],
['20180427',17.288],
['20180502',18.994],
['20180503',19.288],
['20180504',19.053],
['20180507',19.571],
['20180508',18.818],
['20180509',19.112],
['20180510',19.288],
['20180511',19.318],
['20180514',18.571],
['20180515',18.629],
['20180516',18.412],
['20180517',16.571],
['20180518',14.912],
['20180521',13.418],
['20180522',12.076],
['20180523',10.871],
['20180524',9.782],
['20180525',9.318],
['20180528',9.794],
['20180529',10.776],
['20180530',11.853],
['20180531',12.053],
['20180601',10.847],
['20180604',10.847],
['20180605',11.065],
['20180606',10.918],
['20180607',10.959],
['20180608',10.524],
['20180611',9.980],
['20180612',10.980],
['20180613',12.080],
['20180614',11.080],
['20180615',10.580],
['20180619',9.760],
['20180620',10.740],
['20180621',11.810],
['20180622',12.990],
['20180625',13.650],
['20180626',13.420],
['20180627',12.860],
['20180628',11.860],
['20180629',12.470],
['20180702',11.780],
['20180703',11.400],
['20180704',12.540],
['20180705',12.090],
['20180706',11.660],
['20180709',11.900],
['20180710',12.220],
['20180711',11.490],
['20180712',11.630],
['20180713',11.710],
['20180716',11.240],
['20180717',11.310],
['20180718',10.850],
['20180719',10.330],
['20180720',10.400],
['20180723',10.260],
['20180724',10.550],
['20180725',10.560],
['20180726',10.640],
['20180727',10.210],
['20180730',9.850],
['20180731',10.000],
['20180801',9.710],
['20180802',9.110],
['20180803',8.670],
['20180806',8.180],
['20180807',8.270],
['20180808',7.760],
['20180809',8.540],
['20180810',9.390],
['20180813',9.480],
['20180814',8.970],
['20180815',8.680],
['20180816',8.420],
['20180817',8.160],
['20180820',8.980],
['20180821',9.010],
['20180822',9.200],
['20180823',8.940],
['20180824',8.730],
['20180827',8.900],
['20180828',8.800],
['20180829',8.730],
['20180830',8.510],
['20180831',8.300],
['20180903',8.510],
['20180904',8.480],
['20180905',8.260],
['20180906',8.300],
['20180907',8.360],
['20180910',8.130],
['20180911',8.250],
['20180912',8.390],
['20180913',8.320],
['20180914',8.100],
['20180917',7.910],
['20180918',8.050],
['20180919',8.090],
['20180920',8.150],
['20180921',8.400],
['20180925',8.220],
['20180926',9.040],
['20180927',8.820],
['20180928',8.620],
['20181008',8.260],
['20181009',8.270],
['20181010',8.190],
['20181011',7.370],
['20181012',7.080],
['20181015',7.150],
['20181016',7.000],
['20181017',7.150],
['20181018',6.810],
['20181019',6.980],
['20181022',7.290],
['20181023',7.420],
['20181024',7.310],
['20181025',7.150],
['20181026',7.090],
['20181029',7.060],
['20181030',7.100],
['20181031',7.140],
['20181101',7.190],
['20181102',7.340],
['20181105',7.470],
['20181106',7.230],
['20181107',7.320],
['20181108',7.350],
['20181109',7.210],
['20181112',7.340],
['20181113',7.630],
['20181114',7.610],
['20181115',7.770],
['20181116',7.770],
['20181119',8.180],
['20181120',7.660],
['20181121',7.730],
['20181122',7.710],
['20181123',7.360],
['20181126',7.250],
['20181127',7.140],
['20181128',7.140],
['20181129',6.850],
['20181130',6.910],
['20181203',7.100],
['20181204',7.140],
['20181205',7.040],
['20181206',6.910],
['20181207',7.600],
['20181210',7.250],
['20181211',7.980],
['20181212',8.780],
['20181213',8.410],
['20181214',7.890],
['20181217',8.050],
['20181218',7.730],
['20181219',7.570],
['20181220',7.610],
['20181221',7.330],
['20181224',7.320],
['20181225',7.210],
['20181226',7.520],
['20181227',7.240],
['20181228',7.390],
['20190102',7.410],
['20190103',7.020],
['20190104',7.180],
['20190107',7.330],
['20190108',7.270],
['20190109',7.270],
['20190110',7.460],
['20190111',7.650],
['20190114',7.630],
['20190115',7.810],
['20190116',7.740],
['20190117',7.460],
['20190118',7.270],
['20190121',7.320],
['20190122',7.210],
['20190123',7.160],
['20190124',7.190],
['20190125',7.230],
['20190128',7.080],
['20190129',6.970],
['20190130',6.810],
['20190131',6.540],
['20190201',6.780],
['20190211',6.970],
['20190212',7.060],
['20190213',7.160],
['20190214',7.160],
['20190215',7.260],
['20190218',7.420],
['20190219',7.390],
['20190220',7.400],
['20190221',7.260],
['20190222',7.460],
['20190225',7.820],
['20190226',7.750],
['20190227',7.830],
['20190228',7.880],
['20190301',7.800],
['20190304',7.850],
['20190305',8.090],
['20190306',8.210],
['20190307',8.370],
['20190308',7.680],
['20190311',8.070],
['20190312',8.240],
['20190313',8.170],
['20190314',7.900],
['20190315',8.160],
['20190318',8.520],
['20190319',8.380],
['20190320',8.310],
['20190321',8.440],
['20190322',8.670],
['20190325',8.350],
['20190326',8.440],
['20190327',8.650],
['20190328',8.930],
['20190329',9.550],
['20190401',10.010],
['20190402',9.550],
['20190403',9.350],
['20190404',9.430],
['20190408',9.160],
['20190409',9.280],
['20190410',9.090],
['20190411',9.000],
['20190412',8.950],
['20190415',8.970],
['20190416',9.110],
['20190417',9.140],
['20190418',9.060],
['20190419',9.120],
['20190422',9.280],
['20190423',9.540],
['20190424',9.070],
['20190425',8.280],
['20190426',7.950],
['20190429',7.440],
['20190430',7.530],
['20190506',6.880],
['20190507',7.010],
['20190508',7.000],
['20190509',6.950],
['20190510',7.170],
['20190513',7.160],
['20190514',7.090],
['20190515',7.220],
['20190516',7.210],
['20190517',6.880],
['20190520',6.860],
['20190521',7.070],
['20190522',7.050],
['20190523',6.920],
['20190524',6.900],
['20190527',7.010],
['20190528',6.980],
['20190529',7.030],
['20190530',6.990],
['20190531',6.960],
['20190701',7.030]];
var source='wstock.net';
|
import React from 'react';
import Relay from 'react-relay';
import addTaskMutation from './addTaskMutation';
import removeTaskMutation from './removeTaskMutation';
import editTaskMutation from './editTaskMutation';
const ENTER_KEY_CODE = 13;
const ESC_KEY_CODE = 27;
class TasksMain extends React.Component {
constructor( props )
{
super( props );
this.state = {
viewer: this.props.viewer,
tasks: this.props.viewer.tasks,
isEditing: false,
text: '',
};
this._onNewTaskSave = this._onNewTaskSave.bind(this);
this._handleTextInputCancel = this._handleTextInputCancel.bind(this);
this._commitChanges = this._commitChanges.bind(this);
this._onDeleteTask = this._onDeleteTask.bind(this);
}
_onNewTaskSave = (text) => {
this.props.relay.commitUpdate(
new addTaskMutation({ viewer: this.props.viewer, text: this.state.text }),
this._commitChanges(),
);
};
_onDeleteTask = () => {
this.props.relay.commitUpdate(
new removeTaskMutation({viewer: this.props.viewer, tasks: this.props.tasks})
);
}
/*_onTextInputSave = (text) => {
const { relay, task } = this.props;
this.setEditMode(false);
relay.commitUpdate(
new RenameTodoMutation({ task, text })
);
};*/
_setEditMode(isEditing) {
this.setState({ isEditing });
}
_renderTasks() {
return this.props.viewer.tasks.edges.map(edge => (
<div
key={edge.node.id}
viewer={this.props.viewer}
task={edge.node}>
</div>
));
}
onKeyDown = (e) => {
if (this._handleTextInputCancel && e.keyCode === ESC_KEY_CODE) {
this._handleTextInputCancel();
} else if (e.keyCode === ENTER_KEY_CODE) {
this._onNewTaskSave();
}
};
onChange = (e) => {
this.setState({ text: e.target.value });
};
onBlur = () => {
if (this.props.commitOnBlur) {
this._onNewTaskSave();
}
};
_commitChanges() {
const newText = this.state.text.trim();
if (newText !== '') {
this.setState({ text: '' });
}
}
/*else if (newText !== '') {
this.props.onSave(newText);
this.setState({text: ''}) */
/*_handleTextInputSave = (text) => {
this._setEditMode(false);
this.props.relay.commitUpdate(
new RenameTodoMutation({tasks: this.props.todo, text})
);*/
_handleTextInputCancel = () => {
this._setEditMode(false);
};
render () {
console.log(this.state.text)
console.log(this.props.viewer)
console.log(this.props.viewer.tasks)
const { viewer, children, relay, text } = this.props;
return (
<div>
<button onClick={this._onNewTaskSave}>Add new task!</button>
<button>Edit task</button>
<button onClick={this._onDeleteTask}>Delete task</button>
<br />
<br />
<input
//{...this.props}
placeholder="add a new task here"
onKeyDown={this.onKeyDown}
onChange={this.onChange}
onBlur={this.onBlur}
value={this.state.text}
/>
<br />
<br />
<div>
I am a list of tasks:
<br />
<br />
{this._renderTasks()}
</div>
<div>
TOTAL COUNT (TASKS):
</div>
</div>
)
}
}
export default Relay.createContainer( TasksMain, {
fragments: {
viewer: () => Relay.QL`
fragment on User {
tasks (
first: 2147483647
)
{
edges
},
${addTaskMutation.getFragment('viewer')}
}`
},
});
/* {this.renderTasks()} */
|
var event = angular.module('event', ['ui.bootstrap', 'videoService'])
event.controller('EventCtrl', function($scope, $document, $uibModal, $routeParams, $location, getVideo) {
$scope.likeOptions = {
like : function(likeCount){
likes = parseInt(likeCount) + 1
$scope.videoData.likes = likes
}
}
$scope.commentOptions = {
showCommentBox : false,
newComment : "",
addComment : function(){
$scope.videoData.commentsArr.push({
user : 'user' + Math.ceil(Math.random(3, 100)),
comment : this.newComment
})
this.newComment = ""
this.showCommentBox = !this.showCommentBox
}
}
$scope.followOptions = {
text : 'Follow channel',
follow : function(){
this.text = this.text == 'Follow channel' ? 'Following' : 'Follow channel'
}
}
$scope.getEventData = function(){
getVideo($routeParams.id).then(function(result){
$scope.videoData = result.data
$scope.currentUrl = $location.absUrl()
console.log($scope.videoData)
})
}
})
|
import React, { useEffect } from 'react'
import { withGoogleMap, withScriptjs, GoogleMap, Marker } from 'react-google-maps'
import mapIcon from '../images/mapIcon2.svg'
import focusIcon from '../images/mapIcon3.svg'
const mapStyles = [
{
featureType: 'administrative.land_parcel',
elementType: 'labels',
stylers: [
{
visibility: 'off'
}
]
},
{
featureType: 'administrative.locality',
stylers: [
{
visibility: 'off'
}
]
},
{
featureType: 'administrative.neighborhood',
stylers: [
{
visibility: 'off'
}
]
},
{
featureType: 'poi',
elementType: 'labels.text',
stylers: [
{
visibility: 'off'
}
]
},
{
featureType: 'poi.attraction',
stylers: [
{
visibility: 'off'
}
]
},
{
featureType: 'poi.business',
stylers: [
{
visibility: 'off'
}
]
},
{
featureType: 'poi.government',
stylers: [
{
visibility: 'off'
}
]
},
{
featureType: 'poi.medical',
stylers: [
{
visibility: 'off'
}
]
},
{
featureType: 'road',
elementType: 'labels.icon',
stylers: [
{
visibility: 'off'
}
]
},
{
featureType: 'road.local',
elementType: 'labels',
stylers: [
{
visibility: 'simplified'
}
]
},
{
featureType: 'transit',
stylers: [
{
visibility: 'off'
}
]
}
]
const defaultMapOptions = {
disableDefaultUI: true,
styles: mapStyles
}
const HappyHourMap = ({ happyHours, focused }) => {
const center = { lat: 33.819, lng: -84.388 }
const zoom = 11
const [markers, setMarkers] = React.useState([])
const onClickHandler = id => {
const element = document.getElementById(id)
element.scrollIntoView({ inline: 'center' })
}
useEffect(() => {
if (happyHours.length > 0) {
const points = happyHours.map(m => (
<Marker
key={m.id}
position={{ lat: m.location.lat, lng: m.location.lon }}
icon={focused === m.id ? focusIcon : mapIcon}
labelVisible={false}
onClick={() => onClickHandler(m.id)}
zIndex={focused === m.id ? 10000 : 100}
/>
))
setMarkers(points)
} else {
setMarkers([])
}
}, [happyHours, focused])
return (
<GoogleMap defaultZoom={zoom} defaultCenter={center} options={defaultMapOptions}>
{markers}
</GoogleMap>
)
}
export default withScriptjs(withGoogleMap(HappyHourMap))
|
import React, { useState } from 'react';
import './App.css';
import StripeSampleFooter from './StripeSampleFooter';
import TopNavigationBar from './TopNavigationBar';
import { Redirect } from 'react-router-dom';
function Login(props) {
const [email, setEmail] = useState('');
const [customer, setCustomer] = useState(null);
const handleSubmit = (evt) => {
evt.preventDefault();
return fetch('/create-customer', {
method: 'post',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
email: email,
}),
})
.then((response) => {
return response.json();
})
.then((result) => {
setCustomer(result.customer);
});
};
if (customer) {
return (
<Redirect
to={{
pathname: '/prices',
state: { customer: customer },
}}
/>
);
} else {
return (
<div>
<div className="antialiased p-6">
<TopNavigationBar loggedIn={false} />
<div className="flex justify-center">
<div className="w-full max-w-sm m-6">
<div className="pasha-image-stack">
<img
src="https://picsum.photos/280/320?random=1"
alt="picsum generated"
width="140"
height="160"
/>
<img
src="https://picsum.photos/280/320?random=2"
alt="picsum generated"
width="140"
height="160"
/>
<img
src="https://picsum.photos/280/320?random=3"
alt="picsum generated"
width="140"
height="160"
/>
<img
src="https://picsum.photos/280/320?random=4"
alt="picsum generated"
width="140"
height="160"
/>
</div>
<div className="text-pasha font-semibold text-xl mb-4">
Unlimited photo hosting, and more. Cancel anytime.
</div>
<form id="signup-form" onSubmit={handleSubmit}>
<div className="w-full mb-2">
<input
className="appearance-none border-2 border-gray-200 rounded-md w-full py-2 px-4 text-gray-700 leading-tight focus:outline-none focus:bg-white focus:border-pasha"
id="email"
type="text"
value={email}
onChange={(e) => setEmail(e.target.value)}
placeholder="Email address"
required
/>
</div>
<button
id="email-submit"
className="w-full bg-pasha hover:bg-red-200 hover:shadow-outline rounded-md hover:text-pasha hover:border hover:border-black focus:shadow-outline text-white focus:bg-white focus:text-pasha font-light py-2 px-4 rounded"
type="submit"
>
<div id="loading" className="hidden">
Signing up...
</div>
<span id="button-text">Sign up</span>
</button>
</form>
</div>
</div>
</div>
<StripeSampleFooter />
</div>
);
}
}
export default Login;
|
var falafel=require("falafel"),test=require("../");test("array",function(e){e.plan(5);var n="("+function(){var e=[1,2,[3,4]],n=[5,6];g([e,n])}+")()",t=falafel(n,function(e){"ArrayExpression"===e.type&&e.update("fn("+e.source()+")")}),r=[[3,4],[1,2,[3,4]],[5,6],[[1,2,[3,4]],[5,6]]];Function(["fn","g"],t)(function(n){return e.same(r.shift(),n),n},function(n){e.same(n,[[1,2,[3,4]],[5,6]])})});
|
/*
* @Author: 谢树宏
* @Date: 2022-01-27 15:32:44
* @LastEditors: 谢树宏
* @LastEditTime: 2022-01-27 15:48:33
* @FilePath: /electron-mp-ci/script/common/winConfig.js
*/
if (process.platform === 'darwin') module.exports = {}
else
module.exports = {
icon: './resource/icon_app.ico',
target: [
{
target: 'nsis'
}
],
sign: async (config) => {
//应用签名逻辑后文详细介绍
}
}
|
/**
* Created by Wolke on 06.06.2017.
*/
let Command = require('../../structures/command');
const regs = {user: /<?(?:@|@!)([0-9]+)>/};
const utils = require('../../structures/utilities');
const searcher = require('../../structures/searcher');
class Ship extends Command {
constructor({t}) {
super();
this.cat = 'fun';
this.cmd = 'ship';
this.needGuild = true;
this.t = t;
this.help = {
short: 'help.ship.short',
usage: 'help.ship.usage',
example: 'help.ship.example'
}
}
async run(msg) {
let msgSplit = msg.content.trim().split(' ').map(c => c.trim()).filter(c => c !== '').splice(1);
// console.log(msgSplit);
if (msgSplit.length === 0) {
return msg.channel.createMessage(this.t('ship.single', {
lngs: msg.lang,
user: msg.member.nick ? msg.member.nick : msg.author.username
}));
}
let targets = {t1: msg.member, t2: undefined};
for (let i = 0; i < msgSplit.length; i++) {
if (regs.user.test(msgSplit[i])) {
let id = "";
if (msgSplit[i].startsWith('<@!')) {
id = msgSplit[i].substring(3);
} else {
id = msgSplit[i].substring(2);
}
id = id.substring(0, id.length - 1);
if (targets.t2 === undefined) {
targets.t2 = msg.channel.guild.members.find(m => m.user.id === id);
} else {
targets.t1 = msg.channel.guild.members.find(m => m.user.id === id);
}
} else {
let users = utils.searchUser(msg.channel.guild.members, msgSplit[i]);
let pick = await searcher.userSearchMenu(msg, [msgSplit[i]], this.t);
if (pick === -1) {
return msg.channel.createMessage(this.t('generic.cancelled-command', {lngs: msg.lang}));
}
if (pick === -2) {
return msg.channel.createMessage(this.t('search.no-results', {lngs: msg.lang}));
}
if (pick > -1) {
let targetUser = users[pick];
if (targets.t2 === undefined) {
targets.t2 = targetUser
} else {
targets.t1 = targetUser
}
}
}
}
if (!targets.t2) {
return msg.channel.createMessage(this.t('ship.single', {
lngs: msg.lang,
user: msg.member.nick ? msg.member.nick : msg.author.username
}));
}
if (targets.t1.user.id === targets.t2.user.id) {
return msg.channel.createMessage(this.t('ship.single', {
lngs: msg.lang,
user: msg.member.nick ? msg.member.nick : msg.author.username
}));
}
let shipname = this.getShipname(targets);
return msg.channel.createMessage(this.t('ship.success', {lngs: msg.lang, shipname}))
}
getShipname(targets) {
let firstTarget = Math.floor(Math.random() * 100) > 49;
let name = "";
let t1Name = targets.t1.nick ? targets.t1.nick : targets.t1.user.username;
let t2Name = targets.t2.nick ? targets.t2.nick : targets.t2.user.username;
if (firstTarget) {
name = t1Name.substring(0, Math.floor(t1Name.length / 2));
name += t2Name.substring(Math.floor(t2Name.length / 2));
} else {
name = t2Name.substring(0, Math.floor(t2Name.length / 2));
name += t1Name.substring(Math.floor(t1Name.length / 2));
}
return name;
}
}
module.exports = Ship;
|
//
// users.js: A Node.js Module for for management of a NewsWatcher user settings and news newsFilters CRUD operations.
// There is middleware that makes sure a user is logged in so they can only get their profile.
// A profile is really associated with a user and never goes away,
// so there is no post as it is already there and a delete is also not needed
//
"use strict";
var express = require('express');
var bcrypt = require('bcryptjs');
var async = require('async');
var joi = require('joi'); // For data validation
var authHelper = require('./authHelper');
var ObjectId = require('mongodb').ObjectID;
var router = express.Router();
//
// Create a User in the Collection for NewsWatcher.
// Does not require session authentication at this point as this is the registration step.
//
router.post('/', function postUser(req, res, next) {
// Password must be 7 to 15 characters in length and contain at least one numeric digit and a special character
var schema = {
displayName: joi.string().alphanum().min(3).max(50).required(),
email: joi.string().email().min(7).max(50).required(),
password: joi.string().regex(/^(?=.*[0-9])(?=.*[!@#$%^&*])[a-zA-Z0-9!@#$%^&*]{7,15}$/).required()
};
joi.validate(req.body, schema, function (err) {
if (err) {
let err = new Error('Invalid field: display name 3 to 50 alpanumeric, valid email, password 7 to 15 (one number, one special character)');
err.status = 400;
return next(err);
}
req.db.collection.findOne({ type: 'USER_TYPE', email: req.body.email }, function (err, doc) {
if (err) {
err.status = 400;
return next(err);
}
if (doc) {
let err = new Error('Email account already registered');
err.status = 403;
return next(err);
}
var xferUser = {
type: 'USER_TYPE',
displayName: req.body.displayName,
email: req.body.email,
passwordHash: null,
date: Date.now(),
completed: false,
settings: {
requireWIFI: true,
enableAlerts: false
},
newsFilters: [{
name: 'Technology Companies',
keyWords: ['Apple', 'Microsoft', 'IBM', 'Amazon', 'Google', 'Intel'],
enableAlert: false,
alertFrequency: 0,
enableAutoDelete: false,
deleteTime: 0,
timeOfLastScan: 0,
newsStories: []
}],
savedStories: []
};
bcrypt.hash(req.body.password, 10, function getHash(err, hash) {
if (err) {
err.status = 400;
return next(err);
}
xferUser.passwordHash = hash;
req.db.collection.insertOne(xferUser, function createUser(err, result) {
if (err) {
err.status = 400;
return next(err);
}
req.node2.send({ msg: 'REFRESH_STORIES', doc: result.ops[0] });
res.status(201).json(result.ops[0]);
});
});
});
});
});
//
// Delete a User in the Collection for NewsWatcher.
//
router.delete('/:id', authHelper.checkAuth, function (req, res, next) {
// Verify that the passed in id to delete is the same as that in the auth token
if (req.params.id != req.auth.userId) {
let err = new Error('Invalid request for account deletion');
err.status = 401;
return next(err);
}
// MongoDB should do the work of queuing this up and retrying if there is a conflict, According to their documentation.
// This actually requires a write lock on their part.
req.db.collection.findOneAndDelete({ type: 'USER_TYPE', _id: ObjectId(req.auth.userId) }, function (err, result) {
if (err) {
console.log("+++POSSIBLE USER DELETION CONTENTION ERROR?+++ err:", err);
err.status = 409;
return next(err);
} else if (result.ok != 1) {
console.log("+++POSSIBLE USER DELETION CONTENTION ERROR?+++ result:", result);
let err = new Error('Account deletion failure');
err.status = 409;
return next(err);
}
res.status(200).json({ msg: "User Deleted" });
});
});
//
// Get a NewsWatcher user
//
router.get('/:id', authHelper.checkAuth, function (req, res, next) {
// Verify that the passed in id to delete is the same as that in the auth token
if (req.params.id != req.auth.userId) {
let err = new Error('Invalid request for account fetch');
err.status = 401;
return next(err);
}
req.db.collection.findOne({ type: 'USER_TYPE', _id: ObjectId(req.auth.userId) }, function (err, doc) {
if (err) {
err.status = 400;
return next(err);
}
var xferProfile = {
email: doc.email,
displayName: doc.displayName,
date: doc.date,
settings: doc.settings,
newsFilters: doc.newsFilters,
savedStories: doc.savedStories
};
res.header("Cache-Control", "no-cache, no-store, must-revalidate");
res.header("Pragma", "no-cache");
res.header("Expires", 0);
res.status(200).json(xferProfile);
});
});
//
// Update a user profile. For example, they have edited their newsFilters.
//
router.put('/:id', authHelper.checkAuth, function (req, res, next) {
// Verify that the passed in id is the same as that in the auth token
if (req.params.id != req.auth.userId) {
let err = new Error('Invalid request for account update');
err.status = 401;
return next(err);
}
// Limit the number of newsFilters
if (req.body.newsFilters.length > process.env.MAX_FILTERS) {
let err = new Error('Too many news newsFilters');
err.status = 403;
return next(err);
}
// clear out leading and trailing spaces
for (var i = 0; i < req.body.newsFilters.length; i++) {
if ("keyWords" in req.body.newsFilters[i] && req.body.newsFilters[i].keyWords[0] != "") {
for (var j = 0; j < req.body.newsFilters[i].keyWords.length; j++) {
req.body.newsFilters[i].keyWords[j] = req.body.newsFilters[i].keyWords[j].trim();
}
}
}
// Validate the newsFilters
var schema = {
name: joi.string().min(1).max(30).regex(/^[-_ a-zA-Z0-9]+$/).required(),
keyWords: joi.array().max(10).items(joi.string().max(20)).required(),
enableAlert: joi.boolean(),
alertFrequency: joi.number().min(0),
enableAutoDelete: joi.boolean(),
deleteTime: joi.date(),
timeOfLastScan: joi.date(),
newsStories: joi.array(),
keywordsStr: joi.string().min(1).max(100)
};
async.eachSeries(req.body.newsFilters, function (filter, innercallback) {
joi.validate(filter, schema, function (err) {
innercallback(err);
});
}, function (err) {
if (err) {
err.status = 400;
return next(err);
} else {
// MongoDB implements optomistic concurrency for us.
// We were not holding on to the document anyway, so we just do a quick read and replace of just those properties and not the complete document.
// It matters if news stories were updated in the mean time (i.e. user sat there taking their time updating their news profile)
// because we will force that to update as part of this operation.
// We need the {returnOriginal: false}, so a test could verify what happened, otherwise the defualt is to return the origional.
req.db.collection.findOneAndUpdate({ type: 'USER_TYPE', _id: ObjectId(req.auth.userId) },
{ $set: { settings: { requireWIFI: req.body.requireWIFI, enableAlerts: req.body.enableAlerts }, newsFilters: req.body.newsFilters } },
{ returnOriginal: false },
function (err, result) {
if (err) {
console.log("+++POSSIBLE USER PUT CONTENTION ERROR?+++ err:", err);
err.status = 400;
return next(err);
} else if (result.ok != 1) {
console.log("+++POSSIBLE USER PUT CONTENTION ERROR?+++ result:", result);
let err = new Error('User PUT failure');
err.status = 409;
return next(err);
}
req.node2.send({ msg: 'REFRESH_STORIES', doc: result.value });
res.status(200).json(result.value);
});
}
});
});
//
// Move a story to the save folder.
// We can't move a story there that is already there. We compare the link to tell.
// There is a limit to how many can be saved.
//
router.post('/:id/savedstories', authHelper.checkAuth, function (req, res, next) {
// Verify that the passed in id to delete is the same as that in the auth token
if (req.params.id != req.auth.userId) {
let err = new Error('Invalid request for saving story');
err.status = 401;
return next(err);
}
// Validate the body
var schema = {
contentSnippet: joi.string().max(300).required(),
date: joi.date().required(),
hours: joi.string().max(20),
imageUrl: joi.string().max(300).required(),
keep: joi.boolean().required(),
link: joi.string().max(300).required(),
source: joi.string().max(50).required(),
storyID: joi.string().max(100).required(),
title: joi.string().max(200).required()
};
joi.validate(req.body, schema, function (err) {
if (err) {
err.status = 400;
return next(err);
}
// This uses the MongoDB operators to test the savedStories array to make sure:
// A. Story is not aready in there.
// B. We limit the number of saved stories to 30
// We could add to the query operators -> "savedStories": { $ne: req.body }
// But, we cannot differentiate between the failures we report back to the user.
// We can just let addToSet take care of the comparison and silently fail as the user does not need to know if the story was really already there
// Not allowed at free tier!!!req.db.collection.findOneAndUpdate({ type: 'USER_TYPE', _id: ObjectId(req.auth.userId), $where: 'this.savedStories.length<29' },
req.db.collection.findOneAndUpdate({ type: 'USER_TYPE', _id: ObjectId(req.auth.userId) },
{ $addToSet: { savedStories: req.body } },
{ returnOriginal: true },
function (err, result) {
if (result && result.value == null) {
let err = new Error('Over the save limit, or story already saved');
err.status = 403;
return next(err);
} else if (err) {
console.log("+++POSSIBLE save story CONTENTION ERROR?+++ err:", err);
err.status = 409;
return next(err);
} else if (result.ok != 1) {
console.log("+++POSSIBLE save story CONTENTION ERROR?+++ result:", result);
let err = new Error('Story save failure');
err.status = 409;
return next(err);
}
res.status(200).json(result.value);
});
});
});
//
// Delete a story from the save folder.
//
router.delete('/:id/savedstories/:sid', authHelper.checkAuth, function (req, res, next) {
// Verify that the passed in id to delete is the same as that in the auth token
if (req.params.id != req.auth.userId) {
let err = new Error('Invalid request for deletion of saved story');
err.status = 401;
return next(err);
}
req.db.collection.findOneAndUpdate({ type: 'USER_TYPE', _id: ObjectId(req.auth.userId) },
{ $pull: { savedStories: { storyID: req.params.sid } } },
{ returnOriginal: true },
function (err, result) {
if (err) {
console.log("+++POSSIBLE saved story delete CONTENTION ERROR?+++ err:", err);
err.status = 400;
return next(err);
} else if (result.ok != 1) {
console.log("+++POSSIBLE saved story delete CONTENTION ERROR?+++ result:", result);
let err = new Error('Story delete failure');
err.status = 409;
return next(err);
}
res.status(200).json(result.value);
});
});
module.exports = router;
|
var seed = require('math-random-seed')
var tape = require('tape')
var html = require('bel')
var nanomorph = require('./')
if (!module.parent) {
specificTests(nanomorph)
abstractMorph(nanomorph)
} else {
module.exports = abstractMorph
}
function specificTests (morph) {
tape('nanomorph', function (t) {
t.test('should assert input types', function (t) {
t.plan(2)
t.throws(morph, /a/)
t.throws(morph.bind(null, {}), /b/)
})
})
}
function abstractMorph (morph) {
tape('abstract morph', function (t) {
t.test('root level', function (t) {
t.test('should replace a node', function (t) {
t.plan(1)
var a = html`<p>hello world</p>`
var b = html`<div>hello world</div>`
var expected = b.outerHTML
var res = morph(a, b)
t.equal(res.outerHTML, expected, 'result was expected')
})
t.test('should morph a node', function (t) {
t.plan(1)
var a = html`<p>hello world</p>`
var b = html`<p>hello you</p>`
var expected = b.outerHTML
var res = morph(a, b)
t.equal(res.outerHTML, expected, 'result was expected')
})
t.test('should morph a node with namespaced attribute', function (t) {
t.plan(1)
var a = html`<svg><use xlink:href="#heybooboo"></use></svg>`
var b = html`<svg><use xlink:href="#boobear"></use></svg>`
var expected = b.outerHTML
var res = morph(a, b)
t.equal(res.outerHTML, expected, 'result was expected')
})
t.test('should ignore if node is same', function (t) {
t.plan(1)
var a = html`<p>hello world</p>`
var expected = a.outerHTML
var res = morph(a, a)
t.equal(res.outerHTML, expected, 'result was expected')
})
})
t.test('nested', function (t) {
t.test('should replace a node', function (t) {
t.plan(1)
var a = html`<main><p>hello world</p></main>`
var b = html`<main><div>hello world</div></main>`
var expected = b.outerHTML
var res = morph(a, b)
t.equal(res.outerHTML, expected, 'result was expected')
})
t.test('should replace a node', function (t) {
t.plan(1)
var a = html`<main><p>hello world</p></main>`
var b = html`<main><p>hello you</p></main>`
var res = morph(a, b)
var expected = b.outerHTML
t.equal(res.outerHTML, expected, 'result was expected')
})
t.test('should replace a node', function (t) {
t.plan(1)
var a = html`<main><p>hello world</p></main>`
var res = morph(a, a)
var expected = a.outerHTML
t.equal(res.outerHTML, expected, 'result was expected')
})
t.test('should append a node', function (t) {
t.plan(1)
var a = html`<main></main>`
var b = html`<main><p>hello you</p></main>`
var expected = b.outerHTML
var res = morph(a, b)
t.equal(res.outerHTML, expected, 'result was expected')
})
t.test('should remove a node', function (t) {
t.plan(1)
var a = html`<main><p>hello you</p></main>`
var b = html`<main></main>`
var expected = b.outerHTML
var res = morph(a, b)
t.equal(res.outerHTML, expected, 'result was expected')
})
})
t.test('events', function (t) {
t.test('should copy onclick events', function (t) {
t.plan(1)
var a = html`<button onclick=${fail}>OLD</button>`
var b = html`<button>NEW</button>`
var res = morph(a, b)
res.click()
a = html`<button>OLD</button>`
b = html`<button onclick=${pass}>NEW</button>`
res = morph(a, b)
res.click()
function fail (e) {
e.preventDefault()
t.fail('should not be called')
}
function pass (e) {
e.preventDefault()
t.ok('called')
}
})
})
t.test('values', function (t) {
t.test('if new tree has no value and old tree does, remove value', function (t) {
t.plan(4)
var a = html`<input type="text" value="howdy" />`
var b = html`<input type="text" />`
var res = morph(a, b)
t.equal(res.getAttribute('value'), null)
t.equal(res.value, '')
a = html`<input type="text" value="howdy" />`
b = html`<input type="text" value=${null} />`
res = morph(a, b)
t.equal(res.getAttribute('value'), null)
t.equal(res.value, '')
})
t.test('if new tree has value and old tree does too, set value from new tree', function (t) {
t.plan(4)
var a = html`<input type="text" value="howdy" />`
var b = html`<input type="text" value="hi" />`
var res = morph(a, b)
t.equal(res.value, 'hi')
a = html`<input type="text"/>`
a.value = 'howdy'
b = html`<input type="text"/>`
b.value = 'hi'
res = morph(a, b)
t.equal(res.value, 'hi')
a = html`<input type="text" value="howdy"/>`
b = html`<input type="text"/>`
b.value = 'hi'
res = morph(a, b)
t.equal(res.value, 'hi')
a = html`<input type="text"/>`
a.value = 'howdy'
b = html`<input type="text" value="hi"/>`
res = morph(a, b)
t.equal(res.value, 'hi')
})
})
t.test('isSameNode', function (t) {
t.test('should return a if true', function (t) {
t.plan(1)
var a = html`<div>YOLO</div>`
var b = html`<div>FOMO</div>`
b.isSameNode = function (el) {
return true
}
var res = morph(a, b)
t.equal(res.childNodes[0].data, 'YOLO')
})
t.test('should return b if false', function (t) {
t.plan(1)
var a = html`<div>YOLO</div>`
var b = html`<div>FOMO</div>`
b.isSameNode = function (el) {
return false
}
var res = morph(a, b)
t.equal(res.childNodes[0].data, 'FOMO')
})
})
t.test('lists', function (t) {
t.test('should append nodes', function (t) {
t.plan(1)
var a = html`<ul></ul>`
var b = html`<ul><li>1</li><li>2</li><li>3</li><li>4</li><li>5</li></ul>`
var expected = b.outerHTML
var res = morph(a, b)
t.equal(res.outerHTML, expected, 'result was expected')
})
t.test('should remove nodes', function (t) {
t.plan(1)
var a = html`<ul><li>1</li><li>2</li><li>3</li><li>4</li><li>5</li></ul>`
var b = html`<ul></ul>`
var res = morph(a, b)
var expected = b.outerHTML
t.equal(res.outerHTML, expected, 'result was expected')
})
})
t.test('selectables', function (t) {
t.test('should append nodes', function (t) {
t.plan(1)
var a = html`<select></select>`
var b = html`<select><option>1</option><option>2</option><option>3</option><option>4</option></select>`
var expected = b.outerHTML
var res = morph(a, b)
t.equal(res.outerHTML, expected, 'result was expected')
})
t.test('should append nodes (including optgroups)', function (t) {
t.plan(1)
var a = html`<select></select>`
var b = html`<select><optgroup><option>1</option><option>2</option></optgroup><option>3</option><option>4</option></select>`
var expected = b.outerHTML
var res = morph(a, b)
t.equal(res.outerHTML, expected, 'result was expected')
})
t.test('should remove nodes', function (t) {
t.plan(1)
var a = html`<select><option>1</option><option>2</option><option>3</option><option>4</option></select>`
var b = html`<select></select>`
var expected = b.outerHTML
var res = morph(a, b)
t.equal(res.outerHTML, expected, 'result was expected')
})
t.test('should remove nodes (including optgroups)', function (t) {
t.plan(1)
var a = html`<select><optgroup><option>1</option><option>2</option></optgroup><option>3</option><option>4</option></select>`
var b = html`<select></select>`
var expected = b.outerHTML
var res = morph(a, b)
t.equal(res.outerHTML, expected, 'result was expected')
})
t.test('should add selected', function (t) {
t.plan(1)
var a = html`<select><option>1</option><option>2</option></select>`
var b = html`<select><option>1</option><option selected>2</option></select>`
var expected = b.outerHTML
var res = morph(a, b)
t.equal(res.outerHTML, expected, 'result was expected')
})
t.test('should add selected (xhtml)', function (t) {
t.plan(1)
var a = html`<select><option>1</option><option>2</option></select>`
var b = html`<select><option>1</option><option selected="selected">2</option></select>`
var expected = b.outerHTML
var res = morph(a, b)
t.equal(res.outerHTML, expected, 'result was expected')
})
t.test('should switch selected', function (t) {
t.plan(1)
var a = html`<select><option selected="selected">1</option><option>2</option></select>`
var b = html`<select><option>1</option><option selected="selected">2</option></select>`
var expected = b.outerHTML
var res = morph(a, b)
t.equal(res.outerHTML, expected, 'result was expected')
})
})
t.test('should replace nodes', function (t) {
t.plan(1)
var a = html`<ul><li>1</li><li>2</li><li>3</li><li>4</li><li>5</li></ul>`
var b = html`<ul><div>1</div><li>2</li><p>3</p><li>4</li><li>5</li></ul>`
var expected = b.outerHTML
a = morph(a, b)
t.equal(a.outerHTML, expected, 'result was expected')
})
t.test('should replace nodes after multiple iterations', function (t) {
t.plan(2)
var a = html`<ul></ul>`
var b = html`<ul><li>1</li><li>2</li><li>3</li><li>4</li><li>5</li></ul>`
var expected = b.outerHTML
a = morph(a, b)
t.equal(a.outerHTML, expected, 'result was expected')
b = html`<ul><div>1</div><li>2</li><p>3</p><li>4</li><li>5</li></ul>`
expected = b.outerHTML
a = morph(a, b)
t.equal(a.outerHTML, expected, 'result was expected')
})
})
}
tape('use id as a key hint', function (t) {
t.test('append an element', function (t) {
var a = html`<ul>
<li id="a"></li>
<li id="b"></li>
<li id="c"></li>
</ul>`
var b = html`<ul>
<li id="a"></li>
<li id="new"></li>
<li id="b"></li>
<li id="c"></li>
</ul>`
var oldFirst = a.children[0]
var oldSecond = a.children[1]
var oldThird = a.children[2]
var c = nanomorph(a, b)
t.equal(oldFirst, c.children[0], 'first is equal')
t.equal(oldSecond, c.children[2], 'moved second is equal')
t.equal(oldThird, c.children[3], 'moved third is equal')
t.end()
})
t.test('remove an element', function (t) {
var a = html`<ul><li id="a"></li><li id="b"></li><li id="c"></li></ul>`
var b = html`<ul><li id="a"></li><li id="c"></li></ul>`
var oldFirst = a.children[0]
var oldThird = a.children[2]
var c = nanomorph(a, b)
t.equal(c.children[0], oldFirst, 'first is equal')
t.equal(c.children[1], oldThird, 'second untouched')
t.end()
})
})
tape('chaos monkey #1', function (t) {
var a, b
a = html`<div r="r"><div></div></div>`
b = html`<div io="iO" vq="Vq"><div></div></div>`
compare(a, b, t)
t.end()
})
// modeled after
// https://github.com/mafintosh/hypercore/blob/master/test/tree-index.js
var random = seed('choo choo')
var props = null
tape('fuzz tests', function (t) {
var a, b
for (var i = 0; i < 7; i++) {
for (var j = 0; j < 5; j++) {
a = create(i, j, 0)
for (var k = 0; k < 3; k++) {
b = create(i, k, 1)
props = { depth: i, propCount: j, offset: k }
compare(a, b, t, props)
}
}
}
t.end()
})
function create (depth, propCount, offset) {
var chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
var root = document.createElement('div')
var el = root
var _el = null
var str = ''
offset += 100
for (var i = 0; i < depth; i++) {
_el = document.createElement('div')
el.appendChild(_el)
for (var j = 0; j < propCount; j++) {
str = ''
for (var k = propCount; k > 0; --k) {
str += chars[Math.floor(random() * 100) % chars.length]
}
el.setAttribute(str, str)
offset++
}
el = _el
}
return root
}
function compare (a, b, t, props) {
props = props ? JSON.stringify(props) : undefined
var expected = b.cloneNode(true)
var res = nanomorph(a, b)
deepEqualNode(res, expected, t, props)
}
function deepEqualNode (a, b, t, props) {
t.ok(a.isEqualNode(b), props)
for (var i = a.childNodes.length - 1; i >= 0; --i) {
deepEqualNode(a.childNodes[i], a.childNodes[i], t, props)
}
}
|
import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<React.Fragment><path fill="none" d="M0 0h24v24H0V0z" /><g><path d="M13 2.05v3.03c3.39.49 6 3.39 6 6.92 0 .9-.18 1.75-.48 2.54l2.6 1.53c.56-1.24.88-2.62.88-4.07 0-5.18-3.95-9.45-9-9.95zM12 19c-3.87 0-7-3.13-7-7 0-3.53 2.61-6.43 6-6.92V2.05c-5.06.5-9 4.76-9 9.95 0 5.52 4.47 10 9.99 10 3.31 0 6.24-1.61 8.06-4.09l-2.6-1.53A6.95 6.95 0 0 1 12 19z" /></g></React.Fragment>
, 'DataUsageTwoTone');
|
// This module is kind of small, but it will help us keep
// server_events.js simple while breaking some circular
// dependencies that existed when this code was in people.js.
// (We should do bot updates here too.)
import * as activity from "./activity";
import * as compose from "./compose";
import * as gear_menu from "./gear_menu";
import * as message_live_update from "./message_live_update";
import * as narrow_state from "./narrow_state";
import * as people from "./people";
import * as pm_list from "./pm_list";
import * as settings_account from "./settings_account";
import * as settings_config from "./settings_config";
import * as settings_linkifiers from "./settings_linkifiers";
import * as settings_org from "./settings_org";
import * as settings_profile_fields from "./settings_profile_fields";
import * as settings_streams from "./settings_streams";
import * as settings_users from "./settings_users";
export const update_person = function update(person) {
const person_obj = people.get_by_user_id(person.user_id);
if (!person_obj) {
blueslip.error("Got update_person event for unexpected user " + person.user_id);
return;
}
if (Object.prototype.hasOwnProperty.call(person, "new_email")) {
const user_id = person.user_id;
const new_email = person.new_email;
narrow_state.update_email(user_id, new_email);
compose.update_email(user_id, new_email);
if (people.is_my_user_id(person.user_id)) {
page_params.email = new_email;
}
people.update_email(user_id, new_email);
}
if (Object.prototype.hasOwnProperty.call(person, "delivery_email")) {
const delivery_email = person.delivery_email;
if (people.is_my_user_id(person.user_id)) {
settings_account.update_email(delivery_email);
page_params.delivery_email = delivery_email;
}
}
if (Object.prototype.hasOwnProperty.call(person, "full_name")) {
people.set_full_name(person_obj, person.full_name);
settings_users.update_user_data(person.user_id, person);
activity.redraw();
message_live_update.update_user_full_name(person.user_id, person.full_name);
pm_list.update_private_messages();
if (people.is_my_user_id(person.user_id)) {
page_params.full_name = person.full_name;
settings_account.update_full_name(person.full_name);
}
}
if (Object.prototype.hasOwnProperty.call(person, "role")) {
person_obj.is_owner = person.role === settings_config.user_role_values.owner.code;
person_obj.is_admin =
person.role === settings_config.user_role_values.admin.code || person_obj.is_owner;
person_obj.is_guest = person.role === settings_config.user_role_values.guest.code;
settings_users.update_user_data(person.user_id, person);
if (people.is_my_user_id(person.user_id) && page_params.is_owner !== person_obj.is_owner) {
page_params.is_owner = person_obj.is_owner;
settings_org.maybe_disable_widgets();
}
if (people.is_my_user_id(person.user_id) && page_params.is_admin !== person_obj.is_admin) {
page_params.is_admin = person_obj.is_admin;
gear_menu.update_org_settings_menu_item();
settings_linkifiers.maybe_disable_widgets();
settings_org.maybe_disable_widgets();
settings_profile_fields.maybe_disable_widgets();
settings_streams.maybe_disable_widgets();
}
}
if (Object.prototype.hasOwnProperty.call(person, "avatar_url")) {
const url = person.avatar_url;
person_obj.avatar_url = url;
person_obj.avatar_version = person.avatar_version;
if (people.is_my_user_id(person.user_id)) {
page_params.avatar_source = person.avatar_source;
page_params.avatar_url = url;
page_params.avatar_url_medium = person.avatar_url_medium;
$("#user-avatar-upload-widget .image-block").attr("src", person.avatar_url_medium);
}
message_live_update.update_avatar(person_obj.user_id, person.avatar_url);
}
if (Object.prototype.hasOwnProperty.call(person, "custom_profile_field")) {
people.set_custom_profile_field_data(person.user_id, person.custom_profile_field);
}
if (Object.prototype.hasOwnProperty.call(person, "timezone")) {
person_obj.timezone = person.timezone;
}
if (Object.prototype.hasOwnProperty.call(person, "bot_owner_id")) {
person_obj.bot_owner_id = person.bot_owner_id;
}
};
|
/**
* @fileoverview Prevents usage of Function.prototype.bind and arrow functions
* in React component definition.
* @author Daniel Lo Nigro <dan.cx>
*/
'use strict';
// -----------------------------------------------------------------------------
// Requirements
// -----------------------------------------------------------------------------
const rule = require('../../../lib/rules/jsx-no-bind');
const RuleTester = require('eslint').RuleTester;
const parserOptions = {
ecmaVersion: 8,
sourceType: 'module',
ecmaFeatures: {
experimentalObjectRestSpread: true,
jsx: true
}
};
// -----------------------------------------------------------------------------
// Tests
// -----------------------------------------------------------------------------
const ruleTester = new RuleTester({parserOptions});
ruleTester.run('jsx-no-bind', rule, {
valid: [
// Not covered by the rule
{
code: '<div onClick={this._handleClick}></div>',
parser: 'babel-eslint'
},
{
code: '<div meaningOfLife={42}></div>',
parser: 'babel-eslint'
},
{
code: '<div onClick={getHandler()}></div>',
parser: 'babel-eslint'
},
// bind() and arrow functions in refs explicitly ignored
{
code: '<div ref={c => this._input = c}></div>',
options: [{ignoreRefs: true}],
parser: 'babel-eslint'
},
{
code: '<div ref={this._refCallback.bind(this)}></div>',
options: [{ignoreRefs: true}],
parser: 'babel-eslint'
},
// bind() explicitly allowed
{
code: '<div onClick={this._handleClick.bind(this)}></div>',
options: [{allowBind: true}],
parser: 'babel-eslint'
},
// Arrow functions explicitly allowed
{
code: '<div onClick={() => alert("1337")}></div>',
options: [{allowArrowFunctions: true}],
parser: 'babel-eslint'
},
// Redux connect
{
code: `
class Hello extends Component {
render() {
return <div>Hello</div>;
}
}
export default connect()(Hello);
`,
options: [{allowBind: true}],
parser: 'babel-eslint'
},
// Backbone view with a bind
{
code: `
var DocumentRow = Backbone.View.extend({
tagName: "li",
render: function() {
this.onTap.bind(this);
}
});
`,
parser: 'babel-eslint'
},
{
code: `
const foo = {
render: function() {
this.onTap.bind(this);
return true;
}
};
`,
parser: 'babel-eslint'
},
{
code: `
const foo = {
render() {
this.onTap.bind(this);
return true;
}
};
`,
parser: 'babel-eslint'
}
],
invalid: [
// .bind()
{
code: '<div onClick={this._handleClick.bind(this)}></div>',
errors: [{message: 'JSX props should not use .bind()'}],
parser: 'babel-eslint'
},
{
code: '<div onClick={someGlobalFunction.bind(this)}></div>',
errors: [{message: 'JSX props should not use .bind()'}],
parser: 'babel-eslint'
},
{
code: '<div onClick={window.lol.bind(this)}></div>',
errors: [{message: 'JSX props should not use .bind()'}],
parser: 'babel-eslint'
},
{
code: '<div ref={this._refCallback.bind(this)}></div>',
errors: [{message: 'JSX props should not use .bind()'}],
parser: 'babel-eslint'
},
{
code: `
var Hello = createReactClass({
render: function() {
const click = this.someMethod.bind(this);
return <div onClick={click}>Hello {this.state.name}</div>;
}
});
`,
errors: [{message: 'JSX props should not use .bind()'}],
parser: 'babel-eslint'
},
{
code: `
class Hello23 extends React.Component {
render() {
const click = this.someMethod.bind(this);
return <div onClick={click}>Hello {this.state.name}</div>;
}
};
`,
errors: [{message: 'JSX props should not use .bind()'}],
parser: 'babel-eslint'
},
{
code: `
const foo = {
render: function() {
const click = this.onTap.bind(this);
return <div onClick={onClick}>Hello</div>;
}
};
`,
errors: [{message: 'JSX props should not use .bind()'}],
parser: 'babel-eslint'
},
{
code: `
const foo = {
render: ({onClick}) => (
<div onClick={onClick.bind(this)}>Hello</div>
)
};
`,
errors: [{message: 'JSX props should not use .bind()'}],
parser: 'babel-eslint'
},
{
code: `
const foo = {
render() {
const click = this.onTap.bind(this);
return <div onClick={onClick}>Hello</div>;
}
};
`,
errors: [{message: 'JSX props should not use .bind()'}],
parser: 'babel-eslint'
},
// Arrow functions
{
code: '<div onClick={() => alert("1337")}></div>',
errors: [{message: 'JSX props should not use arrow functions'}],
parser: 'babel-eslint'
},
{
code: '<div onClick={() => 42}></div>',
errors: [{message: 'JSX props should not use arrow functions'}],
parser: 'babel-eslint'
},
{
code: '<div onClick={param => { first(); second(); }}></div>',
errors: [{message: 'JSX props should not use arrow functions'}],
parser: 'babel-eslint'
},
{
code: '<div ref={c => this._input = c}></div>',
errors: [{message: 'JSX props should not use arrow functions'}],
parser: 'babel-eslint'
},
// Bind expression
{
code: '<div foo={::this.onChange} />',
errors: [{message: 'JSX props should not use ::'}],
parser: 'babel-eslint'
},
{
code: '<div foo={foo.bar::baz} />',
errors: [{message: 'JSX props should not use ::'}],
parser: 'babel-eslint'
},
{
code: '<div foo={foo::bar} />',
errors: [{message: 'JSX props should not use ::'}],
parser: 'babel-eslint'
}
]
});
|
'use strict';
// --------------- Helpers that build all of the responses -----------------------
function buildSpeechletResponse(title, output, repromptText, shouldEndSession) {
return {
outputSpeech: {
type: 'PlainText',
text: output,
},
card: {
type: 'Simple',
title: `SessionSpeechlet - ${title}`,
content: `SessionSpeechlet - ${output}`,
},
reprompt: {
outputSpeech: {
type: 'PlainText',
text: repromptText,
},
},
shouldEndSession,
};
}
// This is what is re-played on Alexa device.
function buildResponse(sessionAttributes, speechletResponse) {
return {
version: '1.0',
sessionAttributes,
response: speechletResponse,
};
}
// --------------- Functions that control the skill's behavior -----------------------
function getWelcomeResponse(callback) {
// If we wanted to initialize the session to have some attributes we could add those here.
const sessionAttributes = {};
const cardTitle = 'Welcome';
const speechOutput = 'Welcome to NestCam test.';
const repromptText = '';
const shouldEndSession = false;
callback(sessionAttributes,
buildSpeechletResponse(cardTitle, speechOutput, repromptText, shouldEndSession));
}
function handleSessionEndRequest(callback) {
const cardTitle = 'Session Ended';
const speechOutput = 'Thank you for using NestCam. Have a nice day!';
// Setting this to true ends the session and exits the skill.
const shouldEndSession = true;
callback({}, buildSpeechletResponse(cardTitle, speechOutput, null, shouldEndSession));
}
/**
* Turns NestCam streaming On.
*/
function nestcamOn(intent, session, callback) {
const cardTitle = intent.name;
let repromptText = null;
let sessionAttributes = {};
const shouldEndSession = true;
let speechOutput = "Initializing video feed.";
var client = require('graphql-client')({ url: 'https://api.graph.cool/simple/v1/cj7qirvgf02cl0116yr8ks74h' });
client.query(`
mutation {
updateNestCam(
id: "cj9k4unu9pwqh0104z9gkov2l"
isStreaming: true
)
{
id
}
}`, function (req, res) {
if (res.status === 401) {
throw new Error('Not authorized');
}
})
.then(function (body) {
console.log(body);
})
.catch(function (err) {
console.log(err.message);
});
// Setting repromptText to null signifies that we do not want to reprompt the user.
// If the user does not respond or says something that is not understood, the session
// will end.
callback(sessionAttributes,
buildSpeechletResponse(intent.name, speechOutput, repromptText, shouldEndSession));
}
/**
* Turns NestCam streaming Off.
*/
function nestcamOff(intent, session, callback) {
const cardTitle = intent.name;
let repromptText = null;
let sessionAttributes = {};
const shouldEndSession = true;
let speechOutput = "Killing video stream.";
var client = require('graphql-client')({ url: 'https://api.graph.cool/simple/v1/cj7qirvgf02cl0116yr8ks74h' });
client.query(`
mutation {
updateNestCam(
id: "cj9k4unu9pwqh0104z9gkov2l"
isStreaming: false
)
{
id
}
}`, function (req, res) {
if (res.status === 401) {
throw new Error('Not authorized');
}
})
.then(function (body) {
console.log(body);
})
.catch(function (err) {
console.log(err.message);
});
// Setting repromptText to null signifies that we do not want to reprompt the user.
// If the user does not respond or says something that is not understood, the session
// will end.
callback(sessionAttributes,
buildSpeechletResponse(intent.name, speechOutput, repromptText, shouldEndSession));
}
// --------------- Events -----------------------
/**
* Called when the session starts.
*/
function onSessionStarted(sessionStartedRequest, session) {
console.log(`onSessionStarted requestId=${sessionStartedRequest.requestId}, sessionId=${session.sessionId}`);
}
/**
* Called when the user launches the skill without specifying what they want.
*/
function onLaunch(launchRequest, session, callback) {
console.log(`onLaunch requestId=${launchRequest.requestId}, sessionId=${session.sessionId}`);
// Dispatch to your skill's launch.
getWelcomeResponse(callback);
}
/**
* Called when the user specifies an intent for this skill.
*/
function onIntent(intentRequest, session, callback) {
console.log(`onIntent requestId=${intentRequest.requestId}, sessionId=${session.sessionId}`);
const intent = intentRequest.intent;
const intentName = intentRequest.intent.name;
// Dispatch to your skill's intent handlers
if (intentName === 'TurnOnNestcamIntent') {
nestcamOn(intent, session, callback);
} else if (intentName === 'TurnOffNestcamIntent') {
nestcamOff(intent, session, callback);
} else if (intentName === 'AMAZON.HelpIntent') {
getWelcomeResponse(callback);
} else if (intentName === 'AMAZON.StopIntent' || intentName === 'AMAZON.CancelIntent') {
handleSessionEndRequest(callback);
} else {
throw new Error('Invalid intent');
}
}
/**
* Called when the user ends the session.
* Is not called when the skill returns shouldEndSession=true.
*/
function onSessionEnded(sessionEndedRequest, session) {
console.log(`onSessionEnded requestId=${sessionEndedRequest.requestId}, sessionId=${session.sessionId}`);
// Add cleanup logic here
}
// --------------- Main handler -----------------------
// Route the incoming request based on type (LaunchRequest, IntentRequest,
// etc.) The JSON body of the request is provided in the event parameter.
exports.handler = (event, context, callback) => {
try {
console.log(`event.session.application.applicationId=${event.session.application.applicationId}`);
if (event.session.new) {
onSessionStarted({ requestId: event.request.requestId }, event.session);
}
if (event.request.type === 'LaunchRequest') {
onLaunch(event.request,
event.session,
(sessionAttributes, speechletResponse) => {
callback(null, buildResponse(sessionAttributes, speechletResponse));
});
} else if (event.request.type === 'IntentRequest') {
onIntent(event.request,
event.session,
(sessionAttributes, speechletResponse) => {
callback(null, buildResponse(sessionAttributes, speechletResponse));
});
} else if (event.request.type === 'SessionEndedRequest') {
onSessionEnded(event.request, event.session);
callback();
}
} catch (err) {
callback(err);
}
};
|
var tape = require("tape"),
sceneGraph = require("@nathanfaucett/scene_graph"),
transformComponents = require("@nathanfaucett/transform_components"),
camera = require("..");
var Scene = sceneGraph.Scene,
Entity = sceneGraph.Entity,
Transform3D = transformComponents.Transform3D,
Camera = camera.Camera;
tape("Camera", function(assert) {
var scene = Scene.create(),
transform = Transform3D.create(),
camera = Camera.create(),
entity = Entity.create().addComponent(transform, camera);
transform.translate([1, 1, 1]);
scene.addEntity(entity);
assert.deepEquals(camera.getProjection(), [
2.114396572113037, 0, 0, 0,
0, 3.1715948581695557, 0, 0,
0, 0, -1.0000076293945312, -1,
0, 0, -0.1250004768371582, 0
]);
assert.deepEquals(camera.getView(), [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, -1, -1, -1, 1]);
assert.deepEquals(camera.getProjection2D(), [
0.3333333432674408, 0, 0, 0.5, 0, 0
]);
assert.deepEquals(camera.getView2D(), [1, 0, 0, 1, -1, -1]);
var cameraManager = scene.getComponentManager("camera.Camera");
assert.equals(cameraManager.getActive(), camera);
assert.end();
});
|
import i18n from "i18next";
import {initReactI18next} from "react-i18next";
import Backend from "i18next-http-backend";
import LanguageDetector from "i18next-browser-languagedetector";
import languages from "./translations/languages";
i18n
.use(Backend)
.use(LanguageDetector)
.use(initReactI18next)
.init({
fallbackLng: "en-GB",
debug: true,
react: {
useSuspense: false,
},
interpolation: {
escapeValue: false, // not needed for react as it escapes by default
},
resources: languages,
});
export default i18n;
|
import example from './src/app';
import {
AppRegistry,
PushNotificationIOS
} from 'react-native';
class exampleIos extends example {
componentWillMount() {
super.componentWillMount();
PushNotificationIOS.addEventListener('notification', (notification) => this._onNotification(notification));
PushNotificationIOS.addEventListener('localNotification', (notification) => this._onNotification(notification));
}
async componentDidMount() {
super.componentDidMount();
const notification = await PushNotificationIOS.getInitialNotification();
if (notification) {
this.setState({notification: notification.getAlert().title});
}
}
}
console.disableYellowBox = true;
AppRegistry.registerComponent('example', () => exampleIos);
|
const db = require("../db");
const argon2 = require('argon2');
const uuid = require("uuid").v4;
const jwt = require('jsonwebtoken');
require("dotenv").config();
module.exports = async (req, res) => {
if (typeof req.body.class !== "string" || typeof req.body.password !== "string" || typeof req.body.ipaddress !== "string" || (req.body.environment !== "development" && req.body.environment !== "production")) return res.status(400).json({ err: "badRequest" });
const fetchedClass = await db.Class.findOne({
where: {
id: req.body.class
}
});
if (!fetchedClass) return res.status(404).json({ err: "classNotFound" });
try {
if (await argon2.verify(fetchedClass.password, req.body.password)) {
const newSession = await db.Session.create({
id: uuid(),
ip: req.body.ipaddress,
environment: req.body.environment
});
await newSession.addClass(fetchedClass);
var token = jwt.sign({ session: newSession.id }, process.env.SESSION_JWT);
res.status(200).json({ session: token });
} else {
res.status(401).json({ err: "wrongPassword" });
}
} catch (err) {
res.status(500).json({ err: "internalError" });
}
}
|
import firebase from "react-native-firebase";
const analytics = firebase.analytics();
const remoteConfig = firebase.config();
if (__DEV__) {
remoteConfig.enableDeveloperMode();
}
export { analytics, remoteConfig };
|
const merge = require('webpack-merge');
const common = require('./common');
module.exports = merge(common, {
devServer: {
contentBase: './',
},
mode: 'development',
});
|
function getValue(){var inputs=$("#sb input:text:visible"),val="",cb="title";return 2==inputs.length?(val=inputs.eq(0).val(),inputs.eq(0).val()&&inputs.eq(1).val()&&(val+=" "),val+=inputs.eq(1).val()):(val=inputs.val(),$("#sb select:visible[name=search_type]").length&&(cb=$("#sb select:visible[name=search_type]").val())),{text:val,cb:cb}}function setValue(val){var inputs=$("#sb input:text:visible");2==inputs.length?"title"==val.cb?(inputs.eq(0).val(""),inputs.eq(1).val(val.text)):(inputs.eq(1).val(""),inputs.eq(0).val(val.text)):inputs.val(val.text)}function SwitchSearch(){var val=getValue(),advanced=document.getElementById("search_bar_advanced"),simple=document.getElementById("search_bar_simple"),expanded=""==advanced.style.display;advanced.style.display=expanded?"none":"",simple.style.display=expanded?"":"none",document.getElementById("expand_search_link").className=expanded?"expa expand_icon":"expa colapse_icon",document.getElementById("expand_search_link").innerHTML=expanded?"<b></b>Expand":"<b></b>Collapse",$(".search-main").toggleClass("search_b_adv"),setValue(val);var ug_search_cookie_name="ug_search_exp";return expanded?document.cookie=ug_search_cookie_name+"=; expires=Thu, 01 Jan 1970 00:00:01 GMT;":$.cookie(ug_search_cookie_name,"1"),!1}function SwitchAdvancedForm(){var val=getValue();return $(".adv_one_field").toggleClass("dn"),$(".adv_two_fields").toggleClass("dn"),$(".adv_one_field input").attr("disabled",!1),$(".adv_one_field.dn input").attr("disabled",!0),$(".adv_two_fields input").attr("disabled",!1),$(".adv_two_fields.dn input").attr("disabled",!0),setValue(val),!1}function getURLParameter(name){return decodeURIComponent((location.search.match(RegExp("[?|&]"+name+"=(.+?)(&|$)"))||[,null])[1])}function getTabsHistory(){var tabs_history=$.cookie("tabs_history",new Array);try{null!=tabs_history&&tabs_history.length>2&&(tabs_history=JSON.parse(tabs_history)),null==tabs_history&&(tabs_history=new Array)}catch(err){tabs_history=new Array,$.cookie("tabs_history",JSON.stringify(tabs_history),{expires:365,path:"/",domain:"."+ug_serv})}return tabs_history}function renderTabHistoryItem(history_item){$("#history-tooltip .no-tabs").length>0&&$("#history-tooltip .no-tabs").remove(),$("#history-tooltip .history-items").append('<div class="nowrap">'+history_item.artist+' - <a href="'+document.location.protocol+"//tabs."+main_server_name+history_item.url+'">'+history_item.name+(1==history_item.v?"":" (ver "+history_item.v+")")+"</a></div>")}function switch_auth_blocks(enabled_block_names,not_hide_msg){$("#a_layer .a_block").hide();for(var key=0;key<enabled_block_names.length;key++)$("#a_layer ."+enabled_block_names[key]).show();not_hide_msg!==!0&&remove_all_auth_messages()}function remove_all_auth_messages(){$("#a_layer .a_msg").removeClass("success").hide(),$("#a_layer .a_msg ul li").remove(),$("#a_layer input").removeClass("wrong")}function show_auth_message(type,position,text,msg_class){$(".a_msg").show(),"success"==type?$(".a_msg").addClass("success"):($(".a_msg").hasClass("success")&&($(".a_msg").removeClass("success"),$(".a_msg ul li").remove()),$("#a_layer input[name="+msg_class+"]").addClass("wrong")),$(".a_msg li."+msg_class_prefix+msg_class).length>0?$(".a_msg li."+msg_class_prefix+msg_class).html(text):$(".a_msg ul."+position).append("<li class="+msg_class_prefix+msg_class+">"+text+"</li>")}function remove_auth_msg(msg_class){$(".a_msg ul li."+msg_class_prefix+msg_class).remove(),$("#a_layer input[name="+msg_class+"]").removeClass("wrong"),0==$(".a_msg ul li").length&&$(".a_msg").hide()}function get_random_string(string_length){for(var chars="0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz",randomstring="",i=0;i<string_length;i++){var rnum=Math.floor(Math.random()*chars.length);randomstring+=chars.substring(rnum,rnum+1)}return randomstring}function auth_on_sign_in(data){auth_fill_user_info(data),close_auth_layer(),data.user_id&&(window.user_id=data.user_id,window.UGAPP.config.user.id=data.user_id),"function"==typeof window.auth_callback_function?window.auth_callback_function.apply(auth_callback_function,auth_callback_params):"function"==typeof window[auth_callback_function]&&window[auth_callback_function].apply(auth_callback_function,auth_callback_params)}function redirect_after_login(url){window.location=url}function auth_fill_user_info(data){var user_iq=data.iq||"";$("#login_user_guest").hide(),$("#login_user_auth").removeClass("dn"),header_fill_user_info($.cookie("bbuserid"),$.cookie("bbusername"),user_iq)}function check_exist_user_by_param(user_param_name,user_param_value,message_position){$.jsonp({callbackParameter:"callback",url:document.location.protocol+"//www."+main_server_name+"/user/auth/check",data:{action_type:"register",name:user_param_name,value:user_param_value},timeout:1e5,success:function(data){return"error"==data.result?(show_auth_message("error",message_position,user_param_name.charAt(0).toUpperCase()+user_param_name.slice(1)+auth_msg.verify_user_exist,user_param_name),!0):(remove_auth_msg(user_param_name),!1)}})}function send_reset_password_email_to_user(email_to_send,success_msg){$("#a_layer .a_msg").is(":visible")&&!$("#a_layer .a_msg").hasClass("success")||$.jsonp({url:document.location.protocol+"//www."+main_server_name+"/user/security/sendResetPasswordMail",callbackParameter:"callback",data:{email:email_to_send},timeout:4e4,success:function(json){"error"==json.result?(show_auth_message("error","r",auth_msg.verify_email,"email"),ga("send","event","LoginRegister PopUp","LoginRegister SignIn","LoginRegister ForgotPassword False")):(show_auth_message("success","r",success_msg,"email"),ga("send","event","LoginRegister PopUp","LoginRegister SignIn","LoginRegister ForgotPassword Success"))},error:function(){show_auth_message("error","r",auth_msg.something_happens,"email")}})}function send_activation_email_to_user(email_to_send,success_msg){$("#a_layer .a_msg").is(":visible")&&!$("#a_layer .a_msg").hasClass("success")||$.jsonp({url:document.location.protocol+"//www."+main_server_name+"/user/security/sendActivationLetter",callbackParameter:"callback",data:{email:email_to_send},timeout:4e4,success:function(json){"error"==json.result?(show_auth_message("error","r",auth_msg.verify_email,"email"),ga("send","event","LoginRegister PopUp","LoginRegister Activation","Activation Resend False")):(show_auth_message("success","r",success_msg,"email"),ga("send","event","LoginRegister PopUp","LoginRegister Activation","Activation Resend Success"))},error:function(){show_auth_message("error","r",auth_msg.something_happens,"email")}})}function show_auth_layer_on_registration(callback){if(window.register_callback=callback,!ug_load_recaptcha)if(ug_load_recaptcha=!0,"object"!=typeof grecaptcha)$.getScript("https://www.google.com/recaptcha/api.js",function(data,textStatus){});else{var $$recaptcha=document.querySelector(".register .recaptcha2"),sitekey=$$recaptcha.getAttribute("data-sitekey"),size=$$recaptcha.getAttribute("data-size");grecaptcha.render($$recaptcha,{sitekey:sitekey,callback:onUgRegisterRepachaSuccess,size:size})}switch_auth_blocks(new Array("register")),show_auth_layer(auth_callback_function),ga("send","event","LoginRegister PopUp","LoginRegister SignUp","SignUp Show")}function show_auth_layer_for_blocked_users(){show_auth_layer(""),switch_auth_blocks(new Array("a_blocked"))}function show_auth_layer_for_non_activ_users(){""==$("#a_layer .a_block.activ input[name=email]").val()&&$.jsonp({url:document.location.protocol+"//www."+main_server_name+"/user/auth/getEmail",callbackParameter:"callback",timeout:4e4,success:function(json){$("#a_layer .a_block.activ input[name=email]").val(json.email)}}),show_auth_layer(""),$("#a_layer .a_block.activ").addClass("again"),switch_auth_blocks(["activ_none","activ"])}function show_auth_layer_create_username(avatar_path,message,again,url,username){$("#a_layer").show(),switch_auth_blocks(["username_exist","create_username"]),$(".a_block.create_username").attr("data",url),$(".a_block.username_exist font").html(username),""!=avatar_path&&$(".a_block.create_username .log_ico").show().prepend('<img src="'+avatar_path+'" />'),1==again?show_auth_message("error","r",message,"username"):ga("send","event","LoginRegister PopUp","LoginRegister ChangeUsername","ChangeUsername Show")}function show_auth_layer(callback_name){auth_callback_function=callback_name,$("#a_layer").show(),ga("send","event","LoginRegister PopUp","LoginRegister SignIn","LoginRegister Show")}function show_forgot_password(){switch_auth_blocks(["sign_in","forgot"]),ga("send","event","LoginRegister PopUp","LoginRegister SignIn","LoginRegister ForgotPassword Show")}function close_auth_layer(){$("#a_layer").hide(),switch_auth_blocks(["sign_in","sign_up"])}function prepare_auth_layer(){auth_callback_params=[],auth_callback_need_activ=!0}function get_avatar_url(user_id){for(full_user_id=user_id;full_user_id.length<3;)full_user_id="0"+full_user_id;return document.location.protocol+"//"+js_img_domain+"/users/"+full_user_id[full_user_id.length-1]+"/"+full_user_id[full_user_id.length-2]+"/"+full_user_id[full_user_id.length-3]+"/"+user_id+".gif?d=d"}function header_fill_user_info(user_id,user_name,user_iq){var username_header=document.getElementById("username_header"),user_iq_container=document.querySelector(".ug-iq--rating__main-header");username_header.href="http://profile."+main_server_name+"/"+encodeURIComponent(user_name)+"/",username_header.innerHTML='<b class="f-left"></b>'+user_name,user_iq_container.innerHTML=user_iq,user_iq_container.href="/user/activity/iq?user_id="+user_id,document.getElementById("login_user_auth").className="",document.getElementById("login_user_guest").className="dn";var header_login_ava=document.getElementById("header_login_ava");header_login_ava.innerHTML='<img src="'+get_avatar_url(user_id)+'" />'}function onUgRegisterRepachaSuccess(){remove_auth_msg("capcha")}function auth_input_validate($input,not_check_visibility){if(not_check_visibility||$input.parents(".a_block").is(":visible")){var input_name=$input.attr("name");switch(input_name){case"username":var message_position="l";if($("#a_layer .a_block.create_username").is(":visible")&&(message_position="r"),0==$input.val().length)show_auth_message("error",message_position,input_name.charAt(0).toUpperCase()+input_name.slice(1)+auth_msg.verify_empty,input_name);else if($input.val().length<=3&&"none"==$("#a_layer .a_block.sign_in").css("display"))show_auth_message("error",message_position,auth_msg.verify_username,input_name);else if($("#a_layer .a_block.register").is(":visible")||$("#a_layer .a_block.create_username").is(":visible")){var username_regexp=/^[a-zA-Z0-9_-]+$/;username_regexp.test($input.val())?check_exist_user_by_param(input_name,$input.val(),message_position):show_auth_message("error",message_position,auth_msg.verify_not_allowed_symbols,input_name)}else remove_auth_msg(input_name);break;case"email":var email_regexp=/^[a-z0-9_\.\-]*@[a-z0-9\.\-]+\.[a-z]{2,4}$/i,email_val=$input.val();0==$input.val().length?show_auth_message("error",$input.parents(".a_block.register").is(":visible")?"l":"r",input_name.charAt(0).toUpperCase()+input_name.slice(1)+auth_msg.verify_empty,input_name):email_regexp.test(email_val)?$("#a_layer .a_block.register").is(":visible")?check_exist_user_by_param(input_name,$input.val(),"l"):remove_auth_msg(input_name):show_auth_message("error",$input.parents(".a_block.register").is(":visible")?"l":"r",auth_msg.verify_email,input_name);break;case"pass":0==$input.val().length?show_auth_message("error","l","Password"+auth_msg.verify_empty,input_name):remove_auth_msg(input_name);break;case"capcha":grecaptcha.getResponse()||show_auth_message("error","r",auth_msg.verify_capcha,"capcha")}}}function trackMetricaEvent(event_name){if("complete"==document.readyState)try{yaCounter18746557.reachGoal(event_name)}catch(e){}else window.addEventListener("load",function(){trackMetricaEvent(event_name)})}function ratingToggle(event){event.preventDefault(),$(event.currentTarget).hasClass("active")&&($(".js-rating-toggle:not(.active)").toggleClass("active"),$(event.currentTarget).removeClass("active"),$(".js-rating-weekly").toggleClass("hide"),$(".js-rating-all-time").toggleClass("hide"))}function switchElementVisibility(id,show){var element=document.getElementById(id);void 0===show&&(show="none"==element.style.display),show?element.style.display="block":element.style.display="none"}function setSearchTooltipPosition(e){var target=e.currentTarget,rect=target.getBoundingClientRect(),tooltip=target.querySelector(".js-tooltip-content"),action="removeClass";tooltip&&(rect.top<tooltip.offsetHeight&&(action="addClass"),$(tooltip)[action]("bottom"))}function expandActivityFeedItems(){for(i=0;i<activity_feed_expand.length;i++)activity_feed_expand[i].querySelector(".js-activity-feed-trigger").addEventListener("click",function(e){var el_current=$(e.currentTarget),el_parent=$(el_current).closest(".js-activity-feed-expand"),el_stack=el_parent.find(".js-activity-feed-stack");el_current.hasClass("open")||0!=el_stack.children().length?expandGroup(el_current):($.ajax({url:"/main/feedgroups",type:"GET",dataType:"html",data:{timestamp:el_stack.attr("data-timestamp"),type:el_stack.attr("data-type")},success:function(data){el_stack.html(data),expandGroup(el_current)}}),trackMetricaEvent("AUTHOR_FEED_EXPAND_STACK"))})}function expandGroup(el_current){el_current.toggleClass("open"),el_current.parent().toggleClass("open")}jQuery.fn.putCursorAtEnd=function(){return this.each(function(){if($(this).focus(),this.setSelectionRange){var len=2*$(this).val().length;this.setSelectionRange(len,len)}else $(this).val($(this).val());this.scrollTop=999999})},jQuery.autocomplete=function(U,aa,R){function type(){if("title"!=Z.parents("form").find(":input[name=search_type]").val())return!0;if(46==N||N>8&&N<32)return Y.hide();var e=Z.val().toLowerCase();return e!=A&&(A=e,e.length?q(e):Y.hide()),!0}function moveCursor(f){var e=$("li",T).not(".in_artist_title");if(e){W+=f,W<0?W=0:W>=e.size()&&(W=e.size()-1),e.removeClass("ac_over"),$(e[W]).addClass("ac_over");var newSuggestionChunk=$(e[W]).text();Z.val(newSuggestionChunk)}}function pasteSuggestion(){var text=$("li.ac_over",T)[0];return!!text&&(_doPasteSuggestion(text),!0)}function _doPasteSuggestion(text){text&&(text=$(text).text()+" ",A=U.lastSelected=text,Y.html(""),Z.val(text),hideSuggestionsList(),Z.putCursorAtEnd())}function m(){var e={width:$(".searchinp").outerWidth()-2,top:$(".searchinp").offset().top+$(".searchinp").outerHeight(),left:$(".searchinp").offset().left};$(".searchsel").length&&(e.left-=1,e.width+=1,e.top-=1),$(".searchinp").length||(e.left=Z.offset().left,e.width=Z.outerWidth(),e.top=Z.offset().top+Z.outerHeight()),Y.css(e).show()}function z(){X&&clearTimeout(X),X=setTimeout(hideSuggestionsList,200)}function hideSuggestionsList(){X&&clearTimeout(X),Y.is(":visible")&&Y.hide()}function d(f,e){if(e){if(T.innerHTML="",!t||0==e.length)return hideSuggestionsList();$.browser.msie&&Y.append(document.createElement("iframe")),T.appendChild(c(f,e)),m()}else hideSuggestionsList();return!1}function c(p,l){var i,j=document.createElement("ul"),k=!0;aa&&"@"==l[0].substr(-1,1)&&(i=document.createElement("li"),i.innerHTML="In "+R+":",$(i).addClass("in_artist_title"),j.appendChild(i));for(var h=0;h<l.length;h++){if(i=document.createElement("li"),"@"==l[h].substr(-1,1)){var r=p.split(" ");i.selectValue=l[h].substr(0,l[h].length-1);for(var g=i.selectValue.split(" "),e=0;e<r.length;e++)for(var f=0;f<g.length;f++)0===g[f].toLowerCase().indexOf(r[e].toLowerCase())&&(g[f]="<span>"+g[f].slice(0,r[e].length)+"</span>"+g[f].slice(r[e].length));i.innerHTML=g.join(" ")}else aa&&k&&(k=!1,$(i).addClass("not_art")),i.selectValue=i.innerHTML=l[h];j.appendChild(i),$(i).hover(function(){$("li",j).removeClass("ac_over"),$(this).addClass("ac_over"),W=$("li",j).indexOf($(this).get(0))},function(){$(this).removeClass("ac_over")}).click(function(s){s.preventDefault(),s.stopPropagation(),_doPasteSuggestion(this),Z.parents("form").submit()})}return j}function q(f){var e=b(f);if(e)d(f,e);else{var max_results=10,filtered_data=[];if(aa&&Q.artist_suggestion){var regex=new RegExp("\\s("+f+"[^\\s]*)|^("+f+"[^\\s]*)","gi");$.each(Q.artist_suggestion,function(i,suggestion){if(suggestion.match(regex)&&(filtered_data.push(suggestion+"@"),filtered_data.length==max_results))return!1})}var max_gen_js=5;f.length<=max_gen_js?$.ajax({url:document.location.protocol+"//"+js_img_domain+"/article/suggestions/"+f.slice(0,1)+"/"+encodeURI(f.replace(/\s+/g,"_"))+".js",dataType:"json",type:"GET",data:{},success:function(json){json&&json.suggestions&&json.suggestions.length&&(json=json.suggestions,json=filterSugReq(json,f,!0),auto.receiveData("r",filtered_data.concat(json).slice(0,max_results)))},error:function(){auto.receiveData("r",filtered_data)}}):(V.allData.length>0&&(filtered_data=filtered_data.concat(filterSugReq(V.allData,f,!1)).slice(0,max_results)),auto.receiveData("r",filtered_data))}}function filterSugReq(data,filter,need_to_push){need_to_push&&(V.allData=[]);for(var j=0,filtered_data=[],i=0;i<data.length;i++)0==data[i].indexOf(filter)&&(j<=10&&filtered_data.push(data[i]),need_to_push&&V.allData.push(data[i]),j++);return filtered_data}function b(f){if(V.data[f])return V.data[f];for(var e=!1,h=f;h.length>1&&!V.data[h];)h=h.slice(0,-1),V.data[h]&&(e=V.data[h].length<10);if(e){e=V.data[h],h=[];for(var g=0;g<e.length;g++)"@"==e[g].charAt(e[g].length-1)?a(f,e[g])&&(h[h.length]=e[g]):0==e[g].toLowerCase().indexOf(f)&&(h[h.length]=e[g]);return h}return null}function a(f,e){f=f.split(" "),e=" "+e;for(var g=0;g<f.length;g++)if(e.indexOf(" "+f[g])<0)return!1;return!0}var Q=this,Z=$(U).attr("autocomplete","off"),T=document.createElement("div"),Y=$(T);Y.hide().addClass("ac_results").css("position","absolute"),$("body").append(T),U.autocompleter=Q;var X=null,A="",W=-1,V={},t=!0,N=null;V.data={},V.allData=[],Z.keydown(function(e){switch(N=e.keyCode,e.keyCode){case 38:e.preventDefault(),moveCursor(-1);break;case 40:e.preventDefault(),moveCursor(1);break;case 9:e.preventDefault(),pasteSuggestion();break;case 13:pasteSuggestion();break;default:W=-1,X&&clearTimeout(X),X=setTimeout(function(){type()},1)}}).focus(function(){t=!0,aa&&!Q.artist_suggestion&&$.ajax({url:document.location.protocol+"//"+js_img_domain+"/article/artist_suggestions/"+aa.toString().slice(0,1)+"/"+encodeURI(aa.toString())+".json",type:"GET",dataType:"json",data:{},success:function(json){Q.artist_suggestion=json}})}).blur(function(){t=!1,z()}),hideSuggestionsList();this.receiveData=function(f,e){d(f,e),V.data[f]=e}},jQuery.fn.autocomplete=function(a,b){return this.each(function(){window.auto=new jQuery.autocomplete(this,a,b)}),this},jQuery.fn.indexOf=function(a){for(var b=0;b<this.length;b++)if(this[b]==a)return b;return-1},$(document).ready(function(){function url_query(query){query=query.replace(/[\[]/,"\\[").replace(/[\]]/,"\\]");var expr="[\\?&]"+query+"=([^&#]*)",regex=new RegExp(expr),results=regex.exec(window.location.href);return null!==results&&results[1]}var show_menu=1;$(document).bind("click",function(e){show_menu&&$(".selwin").hide(),show_menu=1}),$(".searchsel").click(function(){$(".selwin").toggle(),show_menu=0}),$(".selwin a").bind("click",function(event){$(".selcurr").html('<b class="f-right"></b>'+$(this).text()),$("#w").val($(this).attr("value")),"news"==$(this).attr("value")?$("#search-order").val("date"):$("#search-order").val("");var form=document.querySelector(".js-search-form");"forum"==$(this).attr("value")?(form.action=form.dataset.searchforum,form.querySelector(".search_input").name="SearchForm[search_keyword]"):(form.action=form.dataset.searchsite,form.querySelector(".search_input").name="value"),event.preventDefault()}),$(".search_input").autocomplete(void 0!==artist_id&&artist_id,void 0!==name_art&&name_art),0==$("#a_layer").length&&$("body").append(auth_html);var is_soc_login=url_query("login_via_soc_networks");is_soc_login&&$("#a_layer form").removeClass("a_classic"),function(a){a.placeHeld=function(c,b){var d=this;d.$el=a(c),d.el=c,d.$el.data("placeHeld",d),d.placeholderText=d.$el.attr("placeholder"),d.init=function(){d.options=a.extend({},a.placeHeld.defaultOptions,b),d.$el.bind("blur",d.holdPlace).bind("focus",d.releasePlace).trigger("blur"),d.$el.parents("form").bind("submit",d.clearPlace)},d.holdPlace=function(){var e=d.$el.val();e||d.$el.val(d.placeholderText).addClass(d.options.className)},d.releasePlace=function(){var e=d.$el.val();e==d.placeholderText&&d.$el.val("").removeClass(d.options.className)},d.clearPlace=function(){var e=d.$el.val();e==d.placeholderText&&d.$el.hasClass(d.options.className)&&d.$el.val("")},d.init()},a.placeHeld.defaultOptions={className:"placeheld"},a.fn.placeHeld=function(b){if(!("placeholder"in a("<input>")[0]))return this.each(function(){new a.placeHeld(this,b)})}}(jQuery),$("input[placeholder]").placeHeld({className:"a_ph"}),$("input").live("touchend",function(){$(this).mouseout()}),navigator.userAgent.toLowerCase().indexOf("android")>-1&&$("#a_layer").addClass("a_android"),tabs_history=getTabsHistory();for(var i=0;i<tabs_history.length;i++)renderTabHistoryItem(tabs_history[i]);var tabHistoryTimeout=null;if($(".js-tabs-history").hover(function(){tabHistoryTimeout=setTimeout(function(){$(".js-tabs-history-tooltip").addClass("show")},150)},function(){clearTimeout(tabHistoryTimeout),$(".js-tabs-history-tooltip").removeClass("show")}),$(".js-contrib-msg").live("click",function(){var $parent=$(this).parent().parent();return $parent.animate({opacity:.05},400,function(){$.get("/contribution/award/read",{id:$parent.attr("data-id")}),$parent.remove(),0==$(".js-contrib-msg").length&&$(".js-message-wrapper").remove()}),!1}),$(".js-popup-review").length>0&&(navigator.userAgent.indexOf("Win")!=-1||navigator.userAgent.indexOf("Mac")&&navigator.userAgent.indexOf("iPad")==-1&&navigator.userAgent.indexOf("iPhone")==-1)&&(js_popup_review_top=$(".ar-reviews").first(".update_item").offset().top,$(window).scroll(function(){js_popup_review_top<$(window).scrollTop()?$(".js-popup-review").addClass("open"):$(".js-popup-review").removeClass("open")})),$(".js-ug-alert-cookie").click(function(){$(".js-ug-alert-cookie").addClass("hide")}),$(".js-track-metrica-click").click(function(){var event_name=$(this).attr("data-metrica-click");trackMetricaEvent(event_name)}),""==document.referrer&&"/"==location.pathname&&$.cookie("ug_hats_group",1,{expires:365,path:"/",domain:main_server_name}),$.cookie("__ugVisit","",{expires:-1,path:"/",domain:main_server_name}),user_id>0&&$.cookie("__ugVisit2",Math.floor((new Date).getTime()/1e3),{expires:30,path:"/",domain:main_server_name}),$(".js-remove-artist-follower").click(function(){return $(this).parents(".js-artist-follower").hide(),$.get($(this).attr("href")),!1}),$('.js-tp-link[data-source="search"]').length>0||$('.js-tp-link[data-source="artist"]').length>0){var tooltipTimers={};$('.js-tp-link[data-source="search"], .js-tp-link[data-source="artist"]').on("mouseenter",function(e){var id=$(e.currentTarget).data("id");tooltipTimers[id]?clearTimeout(tooltipTimers[id]):$(e.currentTarget).find(".js-tp-tooltip").removeClass("hide")}),$('.js-tp-link[data-source="search"], .js-tp-link[data-source="artist"]').on("mouseleave",function(e){var id=$(e.currentTarget).data("id");tooltipTimers[id]=setTimeout(function(){$(e.currentTarget).find(".js-tp-tooltip").addClass("hide"),tooltipTimers[id]=null},0)})}}),jQuery.cookie=function(key,value,options){if(arguments.length>1&&(null===value||"object"!=typeof value)){if(options=jQuery.extend({},options),null===value&&(options.expires=-1),"number"==typeof options.expires){var days=options.expires,t=options.expires=new Date;t.setDate(t.getDate()+days)}return document.cookie=[encodeURIComponent(key),"=",options.raw?String(value):encodeURIComponent(String(value)),options.expires?"; expires="+options.expires.toUTCString():"",options.path?"; path="+options.path:"",options.domain?"; domain="+options.domain:"",options.secure?"; secure":""].join("")}options=value||{};var result,decode=options.raw?function(s){return s}:decodeURIComponent;return(result=new RegExp("(?:^|; )"+encodeURIComponent(key)+"=([^;]*)").exec(document.cookie))?decode(result[1]):null};var user_id=null==$.cookie("bbuserid")?0:$.cookie("bbuserid"),user_name=$.cookie("bbusername");!function(a,z){function B(){}function r(C){A=[C]}function i(C){b.insertBefore(C,b.firstChild)}function h(D,E,C){return D&&D.apply(E.context||E,C)}function g(C){return/\?/.test(C)?"&":"?"}function o(Q){function L(S){!I++&&z(function(){F(),H&&(s[R]={s:[S]}),C&&(S=C.apply(Q,[S])),h(Q.success,Q,[S,t]),h(O,Q,[Q,t])},0)}function D(S){!I++&&z(function(){F(),H&&S!=w&&(s[R]=S),h(Q.error,Q,[Q,S]),h(O,Q,[Q,S])},0)}Q=a.extend({},d,Q);var M,O=Q.complete,C=Q.dataFilter,K=Q.callbackParameter,P=Q.callback,E=Q.cache,H=Q.pageCache,G=Q.charset,R=Q.url,J=Q.data,N=Q.timeout,I=0,F=B;return Q.abort=function(){!I++&&F()},h(Q.beforeSend,Q,[Q])===!1||I?Q:(R=R||n,J=J?"string"==typeof J?J:a.param(J,Q.traditional):n,R+=J?g(R)+J:n,K&&(R+=g(R)+encodeURIComponent(K)+"=?"),!E&&!H&&(R+=g(R)+"_"+(new Date).getTime()+"="),R=R.replace(/=\?(&|$)/,"="+P+"$1"),H&&(M=s[R])?M.s?L(M.s[0]):D(M):z(function(T,S,U){function V(W){(T[k]||B)(),W=A,A=void 0,W?L(W[0]):D(m)}I||(U=N>0&&z(function(){D(w)},N),F=function(){U&&clearTimeout(U),T[e]=T[k]=T[y]=T[l]=null,b[x](T),S&&b[x](S)},window[P]=r,T=a(c)[0],T.id=p+f++,G&&(T[q]=G),v.msie?(T.event=k,T.htmlFor=T.id,T[e]=function(){/loaded|complete/.test(T.readyState)&&V()}):(T[l]=T[y]=V,v.opera?(S=a(c)[0]).text="jQuery('#"+T.id+"')[0]."+l+"()":T[j]=j),T.src=R,i(T),S&&i(S))},0),Q)}var A,j="async",q="charset",n="",m="error",p="_jqjsp",u="on",k=u+"click",l=u+m,y=u+"load",e=u+"readystatechange",x="removeChild",c="<script/>",t="success",w="timeout",v=a.browser,b=a("head")[0]||document.documentElement,s={},f=0,d={callback:p,url:location.href};o.setup=function(C){a.extend(d,C)},a.jsonp=o}(jQuery,setTimeout);var auth_msg={verify_user_not_exist:"Incorrect username",verify_sign_in:"Incorrect password",verify_user_exist:" has already been taken",verify_email:"Invalid email address",verify_username:"Username is too short",verify_not_allowed_symbols:"Username contains invalid characters. Please use letters (A-Z) or digits (0-9) only.",verify_empty:" not entered",verify_capcha:"Re-enter text from image",verify_reset_pass:"Please check your email for further instructions",something_happens:"Network error",activ_mail_sended:"Activation email has been sent once more",reset_pass:"Your password has been reset.<br>Check your email for futher instructions"},msg_class_prefix="m",auth_imagehash="",auth_callback_function="",register_callback="",auth_callback_params=new Array,auth_callback_need_activ=!0,ug_load_recaptcha=!1;$(function(){$("#a_layer .sign_in span").live("click",function(){show_forgot_password()}),$("#a_layer .sign_up .create").live("click",function(){show_auth_layer_on_registration(),ga("send","event","LoginRegister PopUp","LoginRegister SignIn","LoginRegister CreateAccount")}),$("#a_layer .shw_pswd").live("click",function(){"display password"==$(this).text()?($(this).text("hide password"),$("#a_layer .a_block.register input[name=pass]").get(0).type="text",ga("send","event","LoginRegister PopUp","LoginRegister SignUp","SignUp DisplayPassword On")):($(this).text("display password"),$("#a_layer .a_block.register input[name=pass]").get(0).type="password",ga("send","event","LoginRegister PopUp","LoginRegister SignUp","SignUp DisplayPassword Off"))}),$("#a_layer .a_block.register .back").live("click",function(){switch_auth_blocks(new Array("sign_in","sign_up"))}),$("#a_layer .a_close").live("click",function(){close_auth_layer(),$("#a_layer .sign_in").is(":visible")?ga("send","event","LoginRegister PopUp","LoginRegister SignIn","LoginRegister Close"):$("#a_layer .register").is(":visible")?ga("send","event","LoginRegister PopUp","LoginRegister SignUp","SignUp Close"):$("#a_layer .activ").is(":visible")?ga("send","event","LoginRegister PopUp","LoginRegister Activation","Activation Close"):$("#a_layer .a_blocked").is(":visible")&&ga("send","event","LoginRegister PopUp","LoginRegister Banned","Banned Close")}),$("a.auth_sign_up").live("click",function(){if(!user_id)return show_auth_layer_on_registration(),!1}),$("a.auth_sign_in").live("click",function(){if(!user_id)return prepare_auth_layer(),callback_name="",$(this).hasClass("auth_continue")&&(callback_name="redirect_after_login",auth_callback_params.push($(this).attr("href"))),show_auth_layer(callback_name),!1}),$("#a_layer .a_block.activ .create").live("click",function(){send_activation_email_to_user($("#a_layer .a_block.activ input[name=email]").val(),auth_msg.activ_mail_sended)}),$("#a_layer .a_block.forgot .create").live("click",function(){send_reset_password_email_to_user($("#a_layer .a_block.forgot input[name=email]").val(),auth_msg.reset_pass)}),$("#a_layer .sign_in input").live("focus",function(){$("#a_layer .a_block.forgot").is(":visible")&&switch_auth_blocks(new Array("sign_in","sign_up"))}),$("#a_layer .a_block.forgot input").live("focus",function(){$("#a_layer .a_block.sign").is(":visible")&&show_forgot_password()}),$("#check").live("change",function(){$(this).is(":checked")?ga("send","event","LoginRegister PopUp","LoginRegister SignUp","SignUp Subscribe On"):ga("send","event","LoginRegister PopUp","LoginRegister SignUp","SignUp Subscribe Off")}),$("#a_layer .a_block.create_username .create").live("click",function(){if(ga("send","event","LoginRegister PopUp","LoginRegister ChangeUsername","SignIn Click"),auth_input_validate($("#a_layer .a_block.create_username input[name=username]")),"none"==$("#a_layer .a_msg").css("display")||$("#a_layer .a_msg").hasClass("success")){var custom_username=$("#a_layer .a_block.create_username input[name=username]").val(),url=document.location.protocol+"//"+main_server_name+"/"+$("#a_layer .a_block.create_username").attr("data")+"?service&again=1&custom_username="+custom_username;social_auth_for_change_username=window.open(url,"ug_auth_popup","width=350px,height=350px,left=500px,top=500px,resizable=yes,scrollbars=no,toolbar=no,menubar=no,location=no,directories=no,status=yes"),social_auth_for_change_username.focus()}}),$("#js-user-logout").live("click",function(){return $.ajax({url:document.location.protocol+"//www."+main_server_name+"/user/auth/logout",type:"GET",xhrFields:{withCredentials:!0},success:function(){location.reload(!1)}}),!1})}),$(function(){$("#a_layer input[name=username]").live("focusout",function(){$(this).val($(this).val().trim()),auth_input_validate($(this),!1)}),$("#a_layer input[name=email]").live("focusout",function(){auth_input_validate($(this),!1)}),$("#a_layer input[name=pass]").live("focusout",function(){auth_input_validate($(this),!1)}),$("#a_layer form").live("submit",function(){if("none"!=$("#a_layer .a_block.sign_in").css("display")&&switch_auth_blocks(new Array("sign_in","sign_up"),!0),$("#a_layer .a_block:visible input").each(function(){auth_input_validate($(this))}),"none"==$("#a_layer .a_msg").css("display")||$("#a_layer .a_msg").hasClass("success")){if(remove_all_auth_messages(),"none"!=$("#a_layer .a_block.sign_in").css("display"))var form_url=document.location.protocol+"//www."+main_server_name+"/user/auth/processSignIn",username=$("#a_layer .a_block.sign_in input[name=username]").val(),data={username:username,password:$("#a_layer .a_block.sign_in input[name=pass]").val()};else if("none"!=$("#a_layer .a_block.register").css("display"))var form_url=document.location.protocol+"//www."+main_server_name+"/user/auth/processSignUp",pass=$("#a_layer .a_block.register input[name=pass]").val(),data={username:$("#a_layer .a_block.register input[name=username]").val(),password:pass,"g-recaptcha-response":grecaptcha.getResponse(),email:$("#a_layer .a_block.register input[name=email]").val(),subscribe_to_newsletter:$("#a_layer .a_block.register input[name=check]").is(":checked")?"true":"false"};$.ajax({url:form_url,type:"POST",
data:data,dataType:"json",timeout:4e4,xhrFields:{withCredentials:!0},success:function(json){if("none"!=$("#a_layer .a_block.sign_in").css("display"))if("error"==json.result)ga("send","event","LoginRegister PopUp","LoginRegister SignIn","LoginRegister SignIn False"),show_auth_layer(auth_callback_function),"password"==json.info?show_auth_message("error","l",auth_msg.verify_sign_in,"pass"):show_auth_message("error","l",auth_msg.verify_user_not_exist,"username");else switch(auth_on_sign_in(json.info),json.info.user_status){case"not_activated":show_auth_layer_for_non_activ_users(),ga("send","event","LoginRegister PopUp","LoginRegister Activation","Activation Show");break;case"blocked":show_auth_layer_for_blocked_users(),ga("send","event","LoginRegister PopUp","LoginRegister Banned","Banned Show");break;default:ga("send","event","LoginRegister PopUp","LoginRegister SignIn","LoginRegister SignIn")}else if("none"!=$("#a_layer .a_block.register").css("display"))if("error"==json.result)switch(ga("send","event","LoginRegister PopUp","LoginRegister SignUp","SignUp Join False"),json.info){case"username_exist":case"username_short":case"username_long":case"username_invalid_symbols":case"username_sensored":show_auth_message("error","l","Username"+auth_msg.verify_user_exist,"username");break;case"email_invalid":case"email_banned":case"email_exist":show_auth_message("error","l",auth_msg.verify_email,"email");break;case"capcha_failed":grecaptcha.reset(),show_auth_message("error","r",auth_msg.verify_capcha,"capcha");break;case"internal_error":close_auth_layer()}else $("#a_layer .a_block.activ input[name=email]").val(json.info.email).removeClass(".a_ph"),ga("send","event","LoginRegister PopUp","LoginRegister SignUp","SignUp Join"),auth_callback_need_activ?(switch_auth_blocks(new Array("register_success","activ")),auth_fill_user_info(json.info),"function"==typeof window.register_callback&&window.register_callback()):auth_on_sign_in()},error:function(){show_auth_message("error","l",auth_msg.something_happens,"username")}})}else $("#a_layer").show();return!1})});var auth_html='\n<div id="a_layer" style="display: none;">\n<div class="shtorki"></div>\n <form action="'+document.location.protocol+"//www."+main_server_name+'/user/auth/processSignUp" method="post" class="a_window">\n <div class="a_close">×</div>\n <div class="a_block sign_in">\n <div class="a_line"></div>\n <h2>Sign in</h2>\n <input type="text" name="username" maxlength="120" placeholder="Username or e-mail" >\n <input type="password" name="pass" maxlength="25" placeholder="Password">\n <div class="span_holder"><span>Forgot username or password?</span></div>\n <input type="submit" value="Sign in" class="sign">\n <div class="soc_login">\n <a href="'+document.location.protocol+"//www."+main_server_name+'/user/auth/oauth?service=facebook" class="fb auth_s"><i><b></b></i>Sign in with Facebook</a>\n <a href="'+document.location.protocol+"//www."+main_server_name+'/user/auth/oauth?service=google" class="gplus auth_g auth_s"><i><b></b></i>Sign in with Google</a>\n <p class="cb">Don\'t worry, we won\'t post anything without asking.</p>\n <div></div>\n <span>or</span>\n </div>\n </div>\n <div class="a_block sign_up">\n <h2>Join Ultimate Guitar</h2>\n <p>You\'re just two steps away from<br>getting access to all the awesome<br>features of Ultimate-Guitar.com</p>\n <input type="button" value="Join Ultimate Guitar" class="create">\n </div>\n <div class="a_block forgot" style="display: none;">\n <h2>Forgot password?</h2>\n <p>Enter the email address you used<br> when joining and we\'ll send you<br> the instructions to reset your password.</p>\n <input type="text" name="email" maxlength="50" placeholder="Email">\n <input type="button" value="Send reset instruction" class="create">\n </div>\n <div class="a_block register" style="display: none;">\n <div class="back">← <span>back</span></div>\n <div class="a_line"></div>\n <h2>Sign up</h2>\n <input type="text" name="username" maxlength="15" placeholder="Username">\n <input type="text" name="email" maxlength="50" placeholder="Email">\n <input type="checkbox" name="check" id="check"><label for="check" class="a_check">Subscribe to UG Weekly Newsletter</label>\n <input type="password" name="pass" maxlength="25" placeholder="Password">\n <span class="shw_pswd">display password</span>\n </div>\n <div class="a_block register" style="display: none;">\n <input name="capcha" type="hidden">\n <div class="g-recaptcha recaptcha2" data-size="compact" data-callback="onUgRegisterRepachaSuccess" data-sitekey="6LfCo_8SAAAAALEMHnlK18j8IemlAdvmxwRnQe2v" style="margin-top: 30px;"></div>\n <input type="submit" value="Join Ultimate Guitar" class="create">\n <p>By clicking Join you agree<br>to the <a href="'+document.location.protocol+'//www.ultimate-guitar.com/about/tos.htm" target="_blank">Terms Of Service</a></p>\n </div>\n <div class="a_block register_success" style="display: none;">\n <span></span>\n <div><h2>Thank You!</h2><br>Registration<br> almost completed</div>\n <p>A confirmation email has been sent.<br>Please check your inbox now and <br>follow the instructions provided in <br>the email.</p>\n </div>\n <div class="a_block activ_none" style="display: none;">\n <span></span>\n <div><h2>Clank!</h2><br>Your account has<br> not been activated.</div>\n </div>\n <div class="a_block activ" style="display: none;">\n <div class="a_line"></div>\n <h2>Account activation</h2>\n <p>If you haven\'t received activation <br>email, please use form below.</p>\n <b style="display: none">Enter your email below,<br> to receive account activation instruction.</b>\n <input type="text" name="email" maxlength="50" placeholder="Email">\n <input type="button" value="Resend activation email" class="create">\n </div>\n <div class="a_block username_exist" style="display: none;">\n <span></span>\n <div><h2>Oops!</h2><br><font></font> username<br>is already in use.</div>\n </div>\n <div class="a_block create_username" style="display: none;" data="">\n <div class="a_line"></div>\n <div class="ov-h cont_ico_t"><div class="log_ico f-left" style="display: none;"><span></span></div><p>Please enter a different username to complete sign in proccess.</p></div>\n <div>\n <input type="text" name="username" maxlength="50" placeholder="New username">\n <input type="button" value="Sign in" class="create">\n </div>\n </div>\n <div class="a_blocked" style="display: none;">\n <span class="angry"></span>\n <div><h2>Clank!</h2><br>Your account<br>is blocked!</div>\n </div>\n <div class="a_msg" style="display: none;">\n <ul class="l">\n </ul>\n <ul class="r">\n </ul>\n </div>\n </form>\n</div>';document.domain=main_server_name;var social_auth_popup_width=450,social_auth_popup_height=550,social_auth_popup;$(function(){$("a.auth_s").live("click",function(){var soc_network_name="Facebook";$(this).attr("class").indexOf("auth_g")!=-1&&(soc_network_name="Google");var login_from="PopUp ";$(this).parent().attr("class").indexOf("s_up")!=-1&&(login_from="Header "),ga("send","event","LoginRegister PopUp","LoginRegister SocialNetworks",login_from+soc_network_name+" Button Click"),void 0!==social_auth_popup&&social_auth_popup.close();var redirect_uri,url=redirect_uri=this.href;url+=url.indexOf("?")>=0?"&":"?",url.indexOf("redirect_uri=")===-1&&(url+="redirect_uri="+encodeURIComponent(redirect_uri)+"&"),url+="js";var centerWidth=(window.screen.width-social_auth_popup_width)/2,centerHeight=(window.screen.height-social_auth_popup_height)/2;return social_auth_popup=window.open(url,"ug_auth_popup","width="+social_auth_popup_width+",height="+social_auth_popup_height+",left="+centerWidth+",top="+centerHeight+",resizable=yes,scrollbars=no,toolbar=no,menubar=no,location=no,directories=no,status=yes"),social_auth_popup.focus(),!1})}),$(function(){$(".js-btn-submit-news").bind("click",function(){return user_id?(ga("send","event","Links","Submit News Story","Click (Authorized)",1,{nonInteraction:1}),!0):(ga("send","event","Links","Submit News Story","Click (Not Authorized)",1,{nonInteraction:1}),prepare_auth_layer(),callback_name="redirect_after_login",auth_callback_params.push($(this).attr("href")),show_auth_layer(callback_name),!1)})}),function(){function CustomEvent(event,params){params=params||{bubbles:!1,cancelable:!1,detail:void 0};var evt=document.createEvent("CustomEvent");return evt.initCustomEvent(event,params.bubbles,params.cancelable,params.detail),evt}return"function"!=typeof window.CustomEvent&&(CustomEvent.prototype=window.Event.prototype,void(window.CustomEvent=CustomEvent))}(),function(window){var FuckAdBlock=function(options){this._options={checkOnLoad:!1,resetOnEnd:!1,loopCheckTime:50,loopMaxNumber:5,baitClass:"pub_300x250 pub_300x250m pub_728x90 text-ad textAd text_ad text_ads text-ads text-ad-links",baitStyle:"width: 1px !important; height: 1px !important; position: absolute !important; left: -10000px !important; top: -1000px !important;",debug:!1},this._var={version:"3.2.0",bait:null,checking:!1,loop:null,loopNumber:0,event:{detected:[],notDetected:[]}},void 0!==options&&this.setOption(options);var self=this,eventCallback=function(){setTimeout(function(){self._options.checkOnLoad===!0&&(self._options.debug===!0&&self._log("onload->eventCallback","A check loading is launched"),null===self._var.bait&&self._creatBait(),setTimeout(function(){self.check()},1))},1)};void 0!==window.addEventListener?window.addEventListener("load",eventCallback,!1):window.attachEvent("onload",eventCallback)};FuckAdBlock.prototype._options=null,FuckAdBlock.prototype._var=null,FuckAdBlock.prototype._bait=null,FuckAdBlock.prototype._log=function(method,message){},FuckAdBlock.prototype.setOption=function(options,value){if(void 0!==value){var key=options;options={},options[key]=value}for(var option in options)this._options[option]=options[option],this._options.debug===!0&&this._log("setOption",'The option "'+option+'" he was assigned to "'+options[option]+'"');return this},FuckAdBlock.prototype._creatBait=function(){var bait=document.createElement("div");bait.setAttribute("class",this._options.baitClass),bait.setAttribute("style",this._options.baitStyle),this._var.bait=window.document.body.appendChild(bait),this._var.bait.offsetParent,this._var.bait.offsetHeight,this._var.bait.offsetLeft,this._var.bait.offsetTop,this._var.bait.offsetWidth,this._var.bait.clientHeight,this._var.bait.clientWidth,this._options.debug===!0&&this._log("_creatBait","Bait has been created")},FuckAdBlock.prototype._destroyBait=function(){window.document.body.removeChild(this._var.bait),this._var.bait=null,this._options.debug===!0&&this._log("_destroyBait","Bait has been removed")},FuckAdBlock.prototype.check=function(loop){if(void 0===loop&&(loop=!0),this._options.debug===!0&&this._log("check","An audit was requested "+(loop===!0?"with a":"without")+" loop"),this._var.checking===!0)return this._options.debug===!0&&this._log("check","A check was canceled because there is already an ongoing"),!1;this._var.checking=!0,null===this._var.bait&&this._creatBait();var self=this;return this._var.loopNumber=0,loop===!0&&(this._var.loop=setInterval(function(){self._checkBait(loop)},this._options.loopCheckTime)),setTimeout(function(){self._checkBait(loop)},1),this._options.debug===!0&&this._log("check","A check is in progress ..."),!0},FuckAdBlock.prototype._checkBait=function(loop){var detected=!1;if(null===this._var.bait&&this._creatBait(),null===window.document.body.getAttribute("abp")&&null!==this._var.bait.offsetParent&&0!=this._var.bait.offsetHeight&&0!=this._var.bait.offsetLeft&&0!=this._var.bait.offsetTop&&0!=this._var.bait.offsetWidth&&0!=this._var.bait.clientHeight&&0!=this._var.bait.clientWidth||(detected=!0),void 0!==window.getComputedStyle){var baitTemp=window.getComputedStyle(this._var.bait,null);"none"!=baitTemp.getPropertyValue("display")&&"hidden"!=baitTemp.getPropertyValue("visibility")||(detected=!0)}this._options.debug===!0&&this._log("_checkBait","A check ("+(this._var.loopNumber+1)+"/"+this._options.loopMaxNumber+" ~"+(1+this._var.loopNumber*this._options.loopCheckTime)+"ms) was conducted and detection is "+(detected===!0?"positive":"negative")),loop===!0&&(this._var.loopNumber++,this._var.loopNumber>=this._options.loopMaxNumber&&this._stopLoop()),detected===!0?(this._stopLoop(),this._destroyBait(),this.emitEvent(!0),loop===!0&&(this._var.checking=!1)):null!==this._var.loop&&loop!==!1||(this._destroyBait(),this.emitEvent(!1),loop===!0&&(this._var.checking=!1))},FuckAdBlock.prototype._stopLoop=function(detected){clearInterval(this._var.loop),this._var.loop=null,this._var.loopNumber=0,this._options.debug===!0&&this._log("_stopLoop","A loop has been stopped")},FuckAdBlock.prototype.emitEvent=function(detected){this._options.debug===!0&&this._log("emitEvent","An event with a "+(detected===!0?"positive":"negative")+" detection was called");var fns=this._var.event[detected===!0?"detected":"notDetected"];for(var i in fns)this._options.debug===!0&&this._log("emitEvent","Call function "+(parseInt(i)+1)+"/"+fns.length),fns.hasOwnProperty(i)&&fns[i]();return this._options.resetOnEnd===!0&&this.clearEvent(),this},FuckAdBlock.prototype.clearEvent=function(){this._var.event.detected=[],this._var.event.notDetected=[],this._options.debug===!0&&this._log("clearEvent","The event list has been cleared")},FuckAdBlock.prototype.on=function(detected,fn){return this._var.event[detected===!0?"detected":"notDetected"].push(fn),this._options.debug===!0&&this._log("on",'A type of event "'+(detected===!0?"detected":"notDetected")+'" was added'),this},FuckAdBlock.prototype.onDetected=function(fn){return this.on(!0,fn)},FuckAdBlock.prototype.onNotDetected=function(fn){return this.on(!1,fn)},window.FuckAdBlock=FuckAdBlock,void 0===window.fuckAdBlock&&(window.fuckAdBlock=new FuckAdBlock({checkOnLoad:!0,resetOnEnd:!0})),window.fuckAdBlock.on(!0,function(){window.dispatchEvent(new CustomEvent("adblock_detected"))}),window.fuckAdBlock.on(!1,function(){window.dispatchEvent(new CustomEvent("adblock_not_detected"))})}(window),window.addEventListener("adblock_detected",function(e){ga("set",{dimension6:"on"})}),window.addEventListener("adblock_not_detected",function(e){ga("set",{dimension6:"off"})});var searchTooltipContainer=document.querySelectorAll(".js-tooltip");if(searchTooltipContainer.length)for(var i=0;i<searchTooltipContainer.length;i++)searchTooltipContainer[i].addEventListener("mouseover",setSearchTooltipPosition);$(document).bind("yacounter18746557inited",function(){var links=$(".for-approval .result-link");links.each(function(){trackMetricaEvent("NOT_APPROVED_TAB_LINK_SHOW")}),links.bind("click",function(e){if(trackMetricaEvent("NOT_APPROVED_TAB_LINK_CLICK"),1===e.which){e.preventDefault();var link=$(this);setTimeout(function(){document.location=link.attr("href")},300)}})}),$(window).bind("adblock_detected",function(){var $criteo=$(".criteo_block"),$native=$("#native_wrapper");if($(".js-ab-regular").addClass("hide"),$(".js-ab-partners").length&&$(".js-ab-partners").removeClass("hide"),$(".js-guitartricks").length&&$(".js-guitartricks").removeClass("hide"),$criteo.length){var script=document.createElement("script");script.onload=function(){$criteo.removeClass("hide"),document.getElementById("cto_160x600")&&Criteo.DisplayAcceptableAdIfAdblocked({zoneid:441358,containerid:"cto_160x600"}),document.getElementById("cto_300x600")&&Criteo.DisplayAcceptableAdIfAdblocked({zoneid:470979,containerid:"cto_300x600",overrideZoneFloor:!1}),document.getElementById("cto_728x90")&&Criteo.DisplayAcceptableAdIfAdblocked({zoneid:470978,containerid:"cto_728x90",overrideZoneFloor:!1}),setTimeout(function(){$native.length&&($("#cto_160x600").length&&$("#cto_160x600").html().length&&!/disable_criteo/.test(window.location.search)||($("#cto_160x600").addClass("hide"),$native.removeClass("hide"),$native.length&&$native.is(":visible")&&1==Math.round(100*Math.random())&&ga("send","event","native","Whole Block","impress")))},1e3)},script.src="//static.criteo.net/js/ld/publishertag.js",document.getElementsByTagName("head")[0].appendChild(script)}}),window.addEventListener("load",function(){var list_links=document.querySelectorAll(".js-h-t-list a"),forum_link=document.querySelector(".js-h-t-forum");if(list_links)for(var i=0;i<list_links.length;i++)list_links[i].addEventListener("click",function(){trackMetricaEvent("H_T_LIST")});forum_link&&forum_link.addEventListener("click",function(){trackMetricaEvent("H_T_FORUM")})}),$(function(){function closeAd(){$(".js-interstitial_overlay, .js-interstitial").addClass("hide")}function trackInterView(id,ug_from,container){try{var img=document.createElement("img");img.setAttribute("src","/components/tracker/inter-show?id="+encodeURIComponent(id)+"&ug_from="+encodeURIComponent(ug_from)+"&cb="+(Math.floor(1e7*Math.random())+1)),img.width="1",img.height="1",container.appendChild(img)}catch(e){}}function setInterCookie(){var d=new Date;d.setTime(d.getTime()+864e5),document.cookie="mojo_takeover=1;expires="+d.toUTCString()+";path=/"}function dec(){var $time_left=$(".js-interstitial_left"),left=$time_left.text();--left?($time_left.text(left),setTimeout(dec,1e3)):closeAd()}if($(".js-interstitial_overlay").length&&!/mojo_takeover/.test(document.cookie)){$(".js-interstitial_close").on("click",closeAd),$(".js-interstitial_overlay, .js-interstitial").removeClass("hide"),setInterCookie();var $inter=$(".js-interstitial");trackInterView($inter.attr("data-id"),$inter.attr("data-from"),$inter[0]),setTimeout(dec,1e3)}}),$(".js-sponsor-top-iq").click(function(){trackMetricaEvent("SPONSOR_IQ_CLICK")}),$(".js-sponsor-top-iq-main-page").click(function(){trackMetricaEvent("SPONSOR_IQ_CLICK_MAIN_PAGE")}),$(".js-contest-takeover").length&&($.get("/user/contest/link?to=tab_show"),trackMetricaEvent("TAKEOVER_TAB_SHOW"),$(".js-takeover-track-event").click(function(e){target=$(this).data("takeover"),trackMetricaEvent("TAKEOVER_"+target.toUpperCase()),$.get("/user/contest/link?to="+target)})),$(".js-sponsor-top-iq").click(function(){trackMetricaEvent("SPONSOR_IQ_CLICK")});var activity_feed_expand=document.querySelectorAll(".js-activity-feed-expand");activity_feed_expand&&expandActivityFeedItems();var metrica_objects=[{selector:".js-author-feed .js-tpa_comment a",action:"click",metrica_name:"AUTHOR_FEED_COMMENT_TPA_CLICK"},{selector:".js-more-stories a",action:"click",metrica_name:"MORE_STORY"},{selector:".js-author-feed a",action:"click",metrica_name:"AUTHOR_FEED_LINK_CLICK"},{selector:".js-special-series",action:"click",metrica_name:"SPECIAL_SERIES"},{selector:".js-hot-discussions-toggle",action:"click",metrica_name:"HOT_DISCUSSIONS_TOGGLE"},{selector:".js-hot-discussions a",action:"click",metrica_name:"HOT_DISCUSSIONS_LINK_CLICK"},{selector:".js-history-toggle",action:"click",metrica_name:"HISTORY_TOGGLE"},{selector:".js-suggest-correction-comment",action:"click",metrica_name:"SUGGEST_CORRECTION_FROM_COMMENT"},{selector:".js-forum-on-artist-user",action:"click",metrica_name:"FORUM_ON_ARTIST_USER"},{selector:".js-forum-on-artist-link",action:"click",metrica_name:"FORUM_ON_ARTIST_LINK"},{selector:".js-forum-on-review-user",action:"click",metrica_name:"FORUM_ON_REVIEW_USER"},{selector:".js-forum-on-review-link",action:"click",metrica_name:"FORUM_ON_REVIEW_LINK"},{selector:".js-wrong-search-link",action:"click",metrica_name:"WRONG_SEARCH_LINK_CLICK"},{selector:".js-submit-tab-btn",action:"click",metrica_name:"SUBMIT_TAB_BTN_CLICK"}];metrica_objects.map(function(item){Array.prototype.slice.call(document.querySelectorAll(item.selector),0).map(function(el){el.addEventListener(item.action,function(){trackMetricaEvent(item.metrica_name)})})}),window.addEventListener("load",function(){document.querySelector(".js-forum-on-review")&&trackMetricaEvent("FORUM_ON_REVIEW_SHOW"),document.querySelector(".js-forum-on-artist")&&trackMetricaEvent("FORUM_ON_ARTIST_SHOW"),document.querySelector(".js-author-feed")&&trackMetricaEvent("AUTHOR_FEED_SHOW"),document.querySelector(".js-wrong-search-link")&&trackMetricaEvent("WRONG_SEARCH_LINK_SHOW")}),"undefined"==typeof window.trackCorrected&&(window.trackCorrected=function(event_name){return!0});
|
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { createStore, applyMiddleware } from 'redux';
import { Router, Route, Switch } from 'react-router-dom';
import App from './components/app';
import reducers from './reducers';
const createStoreWithMiddleware = applyMiddleware()(createStore);
import 'bootstrap/dist/css/bootstrap.css';
import './style/main.scss';
import Projects from './components/projects/projects';
import history from './history';
import Contact from './components/contactpage';
function main() {
ReactDOM.render(
<Provider store={createStoreWithMiddleware(reducers)}>
<Router history={history}>
<Switch>
<Route path="/" exact component={App}/>
<Route path="/Projects" component={Projects}/>
<Route path="/contact" component={Contact} />
</Switch>
</Router>
</Provider>
, document.querySelector('.app-wrapper'));
}
document.addEventListener('DOMContentLoaded', main);
|
import { connect } from 'react-redux'
import Container from './Container'
const mapStateToProps = state => {
return {
state,
loaders: state.loaders,
employees: state.employees.data,
legal_units: state.legal_units,
departments: state.departments,
customers: state.customers,
project: state.projectsData.current,
}
}
const mapDispatchToProps = dispatch => {
return {
dispatch,
}
}
const NewProject = connect(mapStateToProps, mapDispatchToProps)(Container)
export default NewProject
|
import {AddComputerPage} from "./AddComputerPage";
//<reference type ="cypress" />
export class LandingPage{
//const addButton = cy.get('')
constructor(){
cy.xpath("(.//*[normalize-space(text()) and normalize-space(.)='Create'])[1]/following::a[1]").should('be.visible');
}
clickLoginInMainPage(){
cy.xpath("(.//*[normalize-space(text()) and normalize-space(.)='Create'])[1]/following::a[1]").click();
return new AddComputerPage();
}
}
|
// @flow
export const colors = {
brand: '#0079BF',
};
export const grid: number = 8;
|
const urls = {
login: 'https://www.linkedin.com/uas/login',
loginSubmit: 'https://www.linkedin.com/uas/login-submit',
peopleYouMayKnow: 'https://www.linkedin.com/voyager/api/relationships/peopleYouMayKnow',
normInvitations: 'https://www.linkedin.com/voyager/api/growth/normInvitations',
};
const headers = {
loginGET: {
'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
'accept-encoding': 'gzip, deflate, br',
'accept-language': 'en-GB,en-US;q=0.9,en;q=0.8',
'upgrade-insecure-requests': '1',
'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36',
},
loginSubmitPOST: {
'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
'accept-encoding': 'gzip, deflate, br',
'accept-language': 'en-GB,en-US;q=0.9,en;q=0.8',
'cache-control': 'no-cache',
'content-type': 'application/x-www-form-urlencoded',
'origin': 'https://www.linkedin.com',
'pragma': 'no-cache',
'referer': 'https://www.linkedin.com/uas/login',
'upgrade-insecure-requests': '1',
'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36',
},
peopleYouMayKnowGET: {
'accept': 'application/vnd.linkedin.normalized+json',
'accept-encoding': 'gzip, deflate, br',
'accept-language': 'en-GB,en-US;q=0.9,en;q=0.8',
'cache-control': 'no-cache',
'pragma': 'no-cache',
'referer': 'https://www.linkedin.com/mynetwork/',
'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36',
'x-li-lang': 'en_US',
'x-li-track': '{"clientVersion":"1.1.*","osName":"web","timezoneOffset":5.5,"deviceFormFactor":"DESKTOP","mpName":"voyager-web"}',
'x-requested-with': 'XMLHttpRequest',
'x-restli-protocol-version': '2.0.0',
},
normInvitationsPOST: {
'accept': 'text/plain, */*; q=0.01',
'accept-encoding': 'gzip, deflate, br',
'accept-language': 'en-GB,en-US;q=0.9,en;q=0.8',
'cache-control': 'no-cache',
'content-type': 'application/json; charset=UTF-8',
'origin': 'https://www.linkedin.com',
'pragma': 'no-cache',
'referer': 'https://www.linkedin.com/mynetwork/',
'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36',
'x-li-lang': 'en_US',
'x-li-track': '{"clientVersion":"1.1.*","osName":"web","timezoneOffset":5.5,"deviceFormFactor":"DESKTOP","mpName":"voyager-web"}',
'x-requested-with': 'XMLHttpRequest',
'x-restli-protocol-version': '2.0.0',
},
};
module.exports = {
urls,
headers,
fetchingPeoplesCount: 50,
requestInterval: 0,
peopleProfileType: 'com.linkedin.voyager.identity.shared.MiniProfile',
};
|
Clazz.declarePackage ("J.awtjs2d");
c$ = Clazz.declareType (J.awtjs2d, "JSFont");
c$.newFont = Clazz.defineMethod (c$, "newFont",
function (fontFace, isBold, isItalic, fontSize, type) {
fontFace = (fontFace.equals ("Monospaced") ? "Courier" : fontFace.startsWith ("Sans") ? "Sans-Serif" : "Serif");
return (isBold ? "bold " : "") + (isItalic ? "italic " : "") + fontSize + type + " " + fontFace;
}, "~S,~B,~B,~N,~S");
c$.getFontMetrics = Clazz.defineMethod (c$, "getFontMetrics",
function (font, context) {
{
if (context.font != font.font) {
context.font = font.font;
font.font = context.font;
context._fontAscent = Math.ceil(font.fontSize); //pt, not px
// the descent is actually (px - pt)
// but I know of no way of getting access to the drawn height
context._fontDescent = Math.ceil(font.fontSize * 0.25);//approx
}
}return context;
}, "javajs.awt.Font,~O");
c$.getAscent = Clazz.defineMethod (c$, "getAscent",
function (context) {
{
return Math.ceil(context._fontAscent);
}}, "~O");
c$.getDescent = Clazz.defineMethod (c$, "getDescent",
function (context) {
{
return Math.ceil(context._fontDescent);
}}, "~O");
c$.stringWidth = Clazz.defineMethod (c$, "stringWidth",
function (font, context, text) {
{
context.font = font.font;
return Math.ceil(context.measureText(text).width);
}}, "javajs.awt.Font,~O,~S");
|
import React from "react";
import styled from "styled-components";
const FlexDiv = styled.div`
display: flex;
height: fit-content;
flex-direction: column;
justify-content: center;
align-items: center;
margin: 10px;
`;
const Thumbnail = styled.img`
width: 80px;
height: 80px;
border-radius: 50%;
background-color: black;
border: 0;
&:hover {
box-shadow: 1px 1px 10px #3c110d;
}
margin-bottom: 3px;
box-sizing: border-box;
${(props) => (props.selected ? "border:4px solid #2ecc71" : "")}
`;
export default function ChampionThumbnail({
addChampion,
data,
name,
thumbnailSrc,
selected,
}) {
return (
<FlexDiv>
<div
style={{ cursor: "pointer" }}
onClick={() => addChampion(data, selected)}
>
<Thumbnail selected={selected} src={thumbnailSrc} alt={name} />
</div>
<div style={{ fontSize: "1em", whiteSpace: "nowrap" }}>{name}</div>
</FlexDiv>
);
}
|
import * as types from '../actions/types';
const contractBasedFeatures = [
// Used in retrieval of EOS Token information
// https://github.com/greymass/customtokens
'customtokens',
// Used to retrieve USD price feeds
// https://github.com/eostitan/delphioracle
'delphioracle',
// Used in retrieval of Block Producer information
// https://github.com/greymass/producerjson
'producerinfo',
// Used in retrieval of EOS Referendum Proposals
// https://github.com/eoscanada/eosio.forum
'proposals',
// Used in retrieval of EOS Proxies information
// https://github.com/AlohaEOS/eos-proxyinfo
'regproxyinfo',
// BEOS features for exchanging BTS <-> BEOS
'beosexchange',
// REX Smart Contract
// https://github.com/EOSIO/eosio.contracts
'rex',
];
const initialState = {
constants: {},
download: undefined,
init: false,
features: contractBasedFeatures
};
export default function app(state = initialState, action) {
switch (action.type) {
case types.APP_INIT: {
return Object.assign({}, state, {
init: true
});
}
case types.APP_UPDATE_DOWNLOAD_PROGRESS: {
return Object.assign({}, state, {
download: action.payload
});
}
case types.SYSTEM_GETCONSTANTS_SUCCESS: {
return Object.assign({}, state, {
constants: action.payload.data
});
}
case types.SYSTEM_GETCONSTANTS_FAILURE: {
return Object.assign({}, initialState);
}
default: {
return state;
}
}
}
|
import base from './base'
import axios from '@/api/http'
const couple = {
getUserCouple() {
return axios.get(`${base.api}/event`)
},
getCoupleList() {
return axios.get(`${base.api}/orderForm/`)
},
getCoupleRule() {
return axios.get(`${base.api}/coupons`)
},
createCoupleRule(params) {
return axios.post(`${base.api}/coupons/new/`, JSON.stringify(params))
},
fixCoupleRule(params) {
return axios.post(`${base.api}/coupons/fix`, JSON.stringify(params))
},
deleteCoupleRule(params) {
return axios.post(`${base.api}/coupons/delete`, JSON.stringify(params))
},
deleteCoupleRuleAll(params) {
return axios.post(`${base.api}/event/delete`, params)
}
}
export default couple
|
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
* Changes may cause incorrect behavior and will be lost if the code is
* regenerated.
*/
'use strict';
const models = require('./index');
/**
* Eloqua server linked service.
*
* @extends models['LinkedService']
*/
class EloquaLinkedService extends models['LinkedService'] {
/**
* Create a EloquaLinkedService.
* @member {object} endpoint The endpoint of the Eloqua server. (i.e.
* eloqua.example.com)
* @member {object} username The site name and user name of your Eloqua
* account in the form: sitename/username. (i.e. Eloqua/Alice)
* @member {object} [password] The password corresponding to the user name.
* @member {string} [password.type] Polymorphic Discriminator
* @member {object} [useEncryptedEndpoints] Specifies whether the data source
* endpoints are encrypted using HTTPS. The default value is true.
* @member {object} [useHostVerification] Specifies whether to require the
* host name in the server's certificate to match the host name of the server
* when connecting over SSL. The default value is true.
* @member {object} [usePeerVerification] Specifies whether to verify the
* identity of the server when connecting over SSL. The default value is
* true.
* @member {object} [encryptedCredential] The encrypted credential used for
* authentication. Credentials are encrypted using the integration runtime
* credential manager. Type: string (or Expression with resultType string).
*/
constructor() {
super();
}
/**
* Defines the metadata of EloquaLinkedService
*
* @returns {object} metadata of EloquaLinkedService
*
*/
mapper() {
return {
required: false,
serializedName: 'Eloqua',
type: {
name: 'Composite',
className: 'EloquaLinkedService',
modelProperties: {
connectVia: {
required: false,
serializedName: 'connectVia',
type: {
name: 'Composite',
className: 'IntegrationRuntimeReference'
}
},
description: {
required: false,
serializedName: 'description',
type: {
name: 'String'
}
},
type: {
required: true,
serializedName: 'type',
type: {
name: 'String'
}
},
endpoint: {
required: true,
serializedName: 'typeProperties.endpoint',
type: {
name: 'Object'
}
},
username: {
required: true,
serializedName: 'typeProperties.username',
type: {
name: 'Object'
}
},
password: {
required: false,
serializedName: 'typeProperties.password',
type: {
name: 'Composite',
polymorphicDiscriminator: {
serializedName: 'type',
clientName: 'type'
},
uberParent: 'SecretBase',
className: 'SecretBase'
}
},
useEncryptedEndpoints: {
required: false,
serializedName: 'typeProperties.useEncryptedEndpoints',
type: {
name: 'Object'
}
},
useHostVerification: {
required: false,
serializedName: 'typeProperties.useHostVerification',
type: {
name: 'Object'
}
},
usePeerVerification: {
required: false,
serializedName: 'typeProperties.usePeerVerification',
type: {
name: 'Object'
}
},
encryptedCredential: {
required: false,
serializedName: 'typeProperties.encryptedCredential',
type: {
name: 'Object'
}
}
}
}
};
}
}
module.exports = EloquaLinkedService;
|
var ApiGen = ApiGen || {};
ApiGen.elements = [["f","_perform_ldap_auth()"],["c","Example"],["c","Format"],["c","Key"],["c","REST_Controller"]];
|
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
'use strict';
// MODULES //
var bench = require( '@stdlib/bench' );
var isString = require( '@stdlib/assert/is-string' ).isPrimitive;
var fromCodePoint = require( './../../from-code-point' );
var pkg = require( './../package.json' ).name;
var pad = require( './../lib' );
// FUNCTIONS //
/**
* Creates a benchmark function.
*
* @private
* @param {PositiveInteger} len - string length
* @returns {Function} benchmark function
*/
function createBenchmark( len ) {
return benchmark;
/**
* Benchmark function.
*
* @private
* @param {Benchmark} b - benchmark instance
*/
function benchmark( b ) {
var out;
var i;
b.tic();
for ( i = 0; i < b.iterations; i++ ) {
out = pad( fromCodePoint( i%126 ), len );
if ( !isString( out ) ) {
b.fail( 'should return a string' );
}
}
b.toc();
if ( !isString( out ) ) {
b.fail( 'should return a string' );
}
b.pass( 'benchmark finished' );
b.end();
}
}
// MAIN //
/**
* Main execution sequence.
*
* @private
*/
function main() {
var len;
var min;
var max;
var f;
var i;
min = 1; // 10*min
max = 10; // 10*max
for ( i = min; i <= max; i++ ) {
len = 10 * i;
f = createBenchmark( len );
bench( pkg+':len='+len, f );
}
}
main();
|
/**
* Homepage selectors
*/
import { createSelector } from 'reselect';
const selectUser = (state) => state.get('userDetails');
const makeSelectUserLocks = () => {
return createSelector(
selectUser,
(userState) => userState.get('locks')
);
};
export {
selectUser,
makeSelectUserLocks
};
|
/**
* @param {string} ref
* @param {string} path
* @param {string | undefined} title
* @returns
*/
export function transform(ref, path, title) {
title = title ?? path
switch (ref) {
case 'wikipedia':
return `<a href="https://en.wikipedia.org/wiki/${path}">${title}</a>`
case 'wikimo':
return `<a href="https://wiki.mozilla.org/${path}">${title}</a>`
default:
return null
}
}
|
'use strict';
(function () {
angular.module('About', [])
.controller('AboutCtrl', function () {
});
})();
|
'use strict'
const t = require('tap')
const test = t.test
const sget = require('simple-get').concat
const Fastify = require('fastify')
const fs = require('fs')
const path = require('path')
const minifier = require('html-minifier')
const minifierOpts = {
removeComments: true,
removeCommentsFromCDATA: true,
collapseWhitespace: true,
collapseBooleanAttributes: true,
removeAttributeQuotes: true,
removeEmptyAttributes: true
}
test('reply.view with ejs engine and custom templates folder', t => {
t.plan(6)
const fastify = Fastify()
const ejs = require('ejs')
const data = { text: 'text' }
fastify.register(require('../index'), {
engine: {
ejs: ejs
},
templates: 'templates'
})
fastify.get('/', (req, reply) => {
reply.view('index.ejs', data)
})
fastify.listen(0, err => {
t.error(err)
sget({
method: 'GET',
url: 'http://localhost:' + fastify.server.address().port
}, (err, response, body) => {
t.error(err)
t.strictEqual(response.statusCode, 200)
t.strictEqual(response.headers['content-length'], '' + body.length)
t.strictEqual(response.headers['content-type'], 'text/html; charset=utf-8')
t.strictEqual(ejs.render(fs.readFileSync('./templates/index.ejs', 'utf8'), data), body.toString())
fastify.close()
})
})
})
test('reply.view with ejs engine with layout option', t => {
t.plan(6)
const fastify = Fastify()
const ejs = require('ejs')
const data = { text: 'text' }
fastify.register(require('../index'), {
engine: {
ejs: ejs
},
root: path.join(__dirname, '../templates'),
layout: 'layout.html'
})
fastify.get('/', (req, reply) => {
reply.view('index-for-layout.ejs', data)
})
fastify.listen(0, err => {
t.error(err)
sget({
method: 'GET',
url: 'http://localhost:' + fastify.server.address().port
}, (err, response, body) => {
t.error(err)
t.strictEqual(response.statusCode, 200)
t.strictEqual(response.headers['content-length'], '' + body.length)
t.strictEqual(response.headers['content-type'], 'text/html; charset=utf-8')
t.strictEqual(ejs.render(fs.readFileSync('./templates/index.ejs', 'utf8'), data), body.toString())
fastify.close()
})
})
})
test('reply.view with ejs engine and custom ext', t => {
t.plan(6)
const fastify = Fastify()
const ejs = require('ejs')
const data = { text: 'text' }
fastify.register(require('../index'), {
engine: {
ejs: ejs
},
templates: 'templates',
viewExt: 'ejs'
})
fastify.get('/', (req, reply) => {
reply.view('index', data)
})
fastify.listen(0, err => {
t.error(err)
sget({
method: 'GET',
url: 'http://localhost:' + fastify.server.address().port
}, (err, response, body) => {
t.error(err)
t.strictEqual(response.statusCode, 200)
t.strictEqual(response.headers['content-length'], '' + body.length)
t.strictEqual(response.headers['content-type'], 'text/html; charset=utf-8')
t.strictEqual(ejs.render(fs.readFileSync('./templates/index.ejs', 'utf8'), data), body.toString())
fastify.close()
})
})
})
test('reply.view for ejs without data-parameter but defaultContext', t => {
t.plan(6)
const fastify = Fastify()
const ejs = require('ejs')
const data = { text: 'text' }
fastify.register(require('../index'), {
engine: {
ejs: ejs
},
defaultContext: data,
templates: 'templates'
})
fastify.get('/', (req, reply) => {
reply.view('index.ejs')
})
fastify.listen(0, err => {
t.error(err)
sget({
method: 'GET',
url: 'http://localhost:' + fastify.server.address().port
}, (err, response, body) => {
t.error(err)
t.strictEqual(response.statusCode, 200)
t.strictEqual(response.headers['content-length'], '' + body.length)
t.strictEqual(response.headers['content-type'], 'text/html; charset=utf-8')
t.strictEqual(ejs.render(fs.readFileSync('./templates/index.ejs', 'utf8'), data), body.toString())
fastify.close()
})
})
})
test('reply.view for ejs without data-parameter but defaultContext', t => {
t.plan(6)
const fastify = Fastify()
const ejs = require('ejs')
const data = { text: 'text' }
fastify.register(require('../index'), {
engine: {
ejs: ejs
},
defaultContext: data,
templates: 'templates'
})
fastify.get('/', (req, reply) => {
reply.view('index.ejs')
})
fastify.listen(0, err => {
t.error(err)
sget({
method: 'GET',
url: 'http://localhost:' + fastify.server.address().port
}, (err, response, body) => {
t.error(err)
t.strictEqual(response.statusCode, 200)
t.strictEqual(response.headers['content-length'], '' + body.length)
t.strictEqual(response.headers['content-type'], 'text/html; charset=utf-8')
t.strictEqual(ejs.render(fs.readFileSync('./templates/index.ejs', 'utf8'), data), body.toString())
fastify.close()
})
})
})
test('reply.view for ejs without data-parameter and without defaultContext', t => {
t.plan(6)
const fastify = Fastify()
const ejs = require('ejs')
fastify.register(require('../index'), {
engine: {
ejs: ejs
},
templates: 'templates'
})
fastify.get('/', (req, reply) => {
reply.view('index-bare.html')
})
fastify.listen(0, err => {
t.error(err)
sget({
method: 'GET',
url: 'http://localhost:' + fastify.server.address().port
}, (err, response, body) => {
t.error(err)
t.strictEqual(response.statusCode, 200)
t.strictEqual(response.headers['content-length'], '' + body.length)
t.strictEqual(response.headers['content-type'], 'text/html; charset=utf-8')
t.strictEqual(ejs.render(fs.readFileSync('./templates/index-bare.html', 'utf8')), body.toString())
fastify.close()
})
})
})
test('reply.view with ejs engine and full path templates folder', t => {
t.plan(6)
const fastify = Fastify()
const ejs = require('ejs')
const data = { text: 'text' }
fastify.register(require('../index'), {
engine: {
ejs: ejs
},
templates: path.join(__dirname, '../templates')
})
fastify.get('/', (req, reply) => {
reply.view('index.ejs', data)
})
fastify.listen(0, err => {
t.error(err)
sget({
method: 'GET',
url: 'http://localhost:' + fastify.server.address().port
}, (err, response, body) => {
t.error(err)
t.strictEqual(response.statusCode, 200)
t.strictEqual(response.headers['content-length'], '' + body.length)
t.strictEqual(response.headers['content-type'], 'text/html; charset=utf-8')
t.strictEqual(ejs.render(fs.readFileSync('./templates/index.ejs', 'utf8'), data), body.toString())
fastify.close()
})
})
})
test('reply.view with ejs engine', t => {
t.plan(6)
const fastify = Fastify()
const ejs = require('ejs')
const data = { text: 'text' }
fastify.register(require('../index'), {
engine: {
ejs: ejs
}
})
fastify.get('/', (req, reply) => {
reply.view('templates/index.ejs', data)
})
fastify.listen(0, err => {
t.error(err)
sget({
method: 'GET',
url: 'http://localhost:' + fastify.server.address().port
}, (err, response, body) => {
t.error(err)
t.strictEqual(response.statusCode, 200)
t.strictEqual(response.headers['content-length'], '' + body.length)
t.strictEqual(response.headers['content-type'], 'text/html; charset=utf-8')
t.strictEqual(ejs.render(fs.readFileSync('./templates/index.ejs', 'utf8'), data), body.toString())
fastify.close()
})
})
})
test('reply.view with ejs engine and defaultContext', t => {
t.plan(6)
const fastify = Fastify()
const ejs = require('ejs')
const data = { text: 'text' }
fastify.register(require('../index'), {
engine: {
ejs: ejs
},
defaultContext: data
})
fastify.get('/', (req, reply) => {
reply.view('templates/index.ejs', {})
})
fastify.listen(0, err => {
t.error(err)
sget({
method: 'GET',
url: 'http://localhost:' + fastify.server.address().port
}, (err, response, body) => {
t.error(err)
t.strictEqual(response.statusCode, 200)
t.strictEqual(response.headers['content-length'], '' + body.length)
t.strictEqual(response.headers['content-type'], 'text/html; charset=utf-8')
t.strictEqual(ejs.render(fs.readFileSync('./templates/index.ejs', 'utf8'), data), body.toString())
fastify.close()
})
})
})
test('reply.view with ejs engine and html-minifier', t => {
t.plan(6)
const fastify = Fastify()
const ejs = require('ejs')
const data = { text: 'text' }
fastify.register(require('../index'), {
engine: {
ejs: ejs
},
options: {
useHtmlMinifier: minifier,
htmlMinifierOptions: minifierOpts
}
})
fastify.get('/', (req, reply) => {
reply.view('templates/index.ejs', data)
})
fastify.listen(0, err => {
t.error(err)
sget({
method: 'GET',
url: 'http://localhost:' + fastify.server.address().port
}, (err, response, body) => {
t.error(err)
t.strictEqual(response.statusCode, 200)
t.strictEqual(response.headers['content-length'], '' + body.length)
t.strictEqual(response.headers['content-type'], 'text/html; charset=utf-8')
t.strictEqual(minifier.minify(ejs.render(fs.readFileSync('./templates/index.ejs', 'utf8'), data), minifierOpts), body.toString())
fastify.close()
})
})
})
test('reply.view with ejs engine and includeViewExtension property as true', t => {
t.plan(6)
const fastify = Fastify()
const ejs = require('ejs')
const data = { text: 'text' }
fastify.register(require('../index'), {
engine: {
ejs: ejs
},
includeViewExtension: true
})
fastify.get('/', (req, reply) => {
reply.view('templates/index', data)
})
fastify.listen(0, err => {
t.error(err)
sget({
method: 'GET',
url: 'http://localhost:' + fastify.server.address().port
}, (err, response, body) => {
t.error(err)
t.strictEqual(response.statusCode, 200)
t.strictEqual(response.headers['content-length'], '' + body.length)
t.strictEqual(response.headers['content-type'], 'text/html; charset=utf-8')
t.strictEqual(ejs.render(fs.readFileSync('./templates/index.ejs', 'utf8'), data), body.toString())
fastify.close()
})
})
})
test('reply.view with ejs engine, template folder specified, include files (ejs and html) used in template, includeViewExtension property as true', t => {
t.plan(7)
const fastify = Fastify()
const ejs = require('ejs')
const resolve = require('path').resolve
const templatesFolder = 'templates'
const options = {
filename: resolve(templatesFolder), // needed for include files to be resolved in include directive ...
views: [__dirname] // must be put to make tests (with include files) working ...
}
const data = { text: 'text' }
fastify.register(require('../index'), {
engine: {
ejs: ejs
},
includeViewExtension: true,
templates: templatesFolder,
options: options
})
fastify.get('/', (req, reply) => {
reply.type('text/html; charset=utf-8').view('index-linking-other-pages', data) // sample for specifying with type
// reply.view('index-with-includes', data)
})
fastify.listen(0, err => {
t.error(err)
sget({
method: 'GET',
url: 'http://localhost:' + fastify.server.address().port
}, (err, response, body) => {
t.error(err)
t.strictEqual(response.statusCode, 200)
t.strictEqual(response.headers['content-type'], 'text/html; charset=utf-8')
t.strictEqual(response.headers['content-length'], '' + body.length)
let content = null
ejs.renderFile(templatesFolder + '/index-linking-other-pages.ejs', data, options, function (err, str) {
content = str
t.error(err)
t.strictEqual(content.length, body.length)
})
fastify.close()
})
})
})
test('reply.view with ejs engine, templates with folder specified, include files and attributes; home', t => {
t.plan(7)
const fastify = Fastify()
const ejs = require('ejs')
const resolve = require('path').resolve
const templatesFolder = 'templates'
const options = {
filename: resolve(templatesFolder),
views: [__dirname]
}
const data = { text: 'Hello from EJS Templates' }
fastify.register(require('../index'), {
engine: {
ejs: ejs
},
includeViewExtension: true,
templates: templatesFolder,
options: options
})
fastify.get('/', (req, reply) => {
reply.type('text/html; charset=utf-8').view('index', data)
})
fastify.listen(0, err => {
t.error(err)
sget({
method: 'GET',
url: 'http://localhost:' + fastify.server.address().port
}, (err, response, body) => {
t.error(err)
t.strictEqual(response.statusCode, 200)
t.strictEqual(response.headers['content-type'], 'text/html; charset=utf-8')
t.strictEqual(response.headers['content-length'], '' + body.length)
let content = null
ejs.renderFile(templatesFolder + '/index.ejs', data, options, function (err, str) {
content = str
t.error(err)
t.strictEqual(content.length, body.length)
})
fastify.close()
})
})
})
test('reply.view with ejs engine, templates with folder specified, include files and attributes; page with no data', t => {
t.plan(7)
const fastify = Fastify()
const ejs = require('ejs')
const resolve = require('path').resolve
const templatesFolder = 'templates'
const options = {
filename: resolve(templatesFolder),
views: [__dirname]
}
fastify.register(require('../index'), {
engine: {
ejs: ejs
},
includeViewExtension: true,
templates: templatesFolder,
options: options
})
fastify.get('/no-data-test', (req, reply) => {
reply.type('text/html; charset=utf-8').view('index-with-no-data')
})
fastify.listen(0, err => {
t.error(err)
sget({
method: 'GET',
url: 'http://localhost:' + fastify.server.address().port + '/no-data-test'
}, (err, response, body) => {
t.error(err)
t.strictEqual(response.statusCode, 200)
t.strictEqual(response.headers['content-type'], 'text/html; charset=utf-8')
t.strictEqual(response.headers['content-length'], '' + body.length)
let content = null
ejs.renderFile(templatesFolder + '/index-with-no-data.ejs', null, options, function (err, str) {
content = str
t.error(err)
t.strictEqual(content.length, body.length)
})
fastify.close()
})
})
})
test('reply.view with ejs engine, templates with folder specified, include files and attributes; page with includes', t => {
t.plan(7)
const fastify = Fastify()
const ejs = require('ejs')
const resolve = require('path').resolve
const templatesFolder = 'templates'
const options = {
filename: resolve(templatesFolder),
views: [path.join(__dirname, '..')]
}
const data = { text: 'Hello from EJS Templates' }
fastify.register(require('../index'), {
engine: {
ejs: ejs
},
includeViewExtension: true,
templates: templatesFolder,
options: options
})
fastify.get('/include-test', (req, reply) => {
reply.type('text/html; charset=utf-8').view('index-with-includes', data)
})
fastify.listen(0, err => {
t.error(err)
sget({
method: 'GET',
url: 'http://localhost:' + fastify.server.address().port + '/include-test'
}, (err, response, body) => {
t.error(err)
t.strictEqual(response.statusCode, 200)
t.strictEqual(response.headers['content-type'], 'text/html; charset=utf-8')
t.strictEqual(response.headers['content-length'], '' + body.length)
let content = null
ejs.renderFile(templatesFolder + '/index-with-includes.ejs', data, options, function (err, str) {
content = str
t.error(err)
t.strictEqual(content.length, body.length)
})
fastify.close()
})
})
})
test('reply.view with ejs engine, templates with folder specified, include files and attributes; page with one include missing', t => {
t.plan(7)
const fastify = Fastify()
const ejs = require('ejs')
const resolve = require('path').resolve
const templatesFolder = 'templates'
const options = {
filename: resolve(templatesFolder),
views: [__dirname]
}
const data = { text: 'Hello from EJS Templates' }
fastify.register(require('../index'), {
engine: {
ejs: ejs
},
includeViewExtension: true,
templates: templatesFolder,
options: options
})
fastify.get('/include-one-include-missing-test', (req, reply) => {
reply.type('text/html; charset=utf-8').view('index-with-includes-one-missing', data)
})
fastify.listen(0, err => {
t.error(err)
sget({
method: 'GET',
url: 'http://localhost:' + fastify.server.address().port + '/include-one-include-missing-test'
}, (err, response, body) => {
t.error(err)
t.strictEqual(response.statusCode, 500)
t.strictEqual(response.headers['content-type'], 'application/json; charset=utf-8')
t.strictEqual(response.headers['content-length'], '' + body.length)
let content = null
ejs.renderFile(templatesFolder + '/index-with-includes-one-missing.ejs', data, options, function (err, str) {
content = str
t.type(err, Error) // expected Error here ...
t.strictEqual(content, undefined)
})
fastify.close()
})
})
})
test('reply.view with ejs engine, templates with folder specified, include files and attributes; page with one attribute missing', t => {
t.plan(7)
const fastify = Fastify()
const ejs = require('ejs')
const resolve = require('path').resolve
const templatesFolder = 'templates'
const options = {
filename: resolve(templatesFolder),
views: [__dirname]
}
const data = { text: 'Hello from EJS Templates' }
fastify.register(require('../index'), {
engine: {
ejs: ejs
},
includeViewExtension: true,
templates: templatesFolder,
options: options
})
fastify.get('/include-one-attribute-missing-test', (req, reply) => {
reply.type('text/html; charset=utf-8').view('index-with-includes-and-attribute-missing', data)
})
fastify.listen(0, err => {
t.error(err)
sget({
method: 'GET',
url: 'http://localhost:' + fastify.server.address().port + '/include-one-attribute-missing-test'
}, (err, response, body) => {
t.error(err)
t.strictEqual(response.statusCode, 500)
t.strictEqual(response.headers['content-type'], 'application/json; charset=utf-8')
t.strictEqual(response.headers['content-length'], '' + body.length)
let content = null
ejs.renderFile(templatesFolder + '/index-with-includes-and-attribute-missing.ejs', data, options, function (err, str) {
content = str
t.type(err, Error) // expected Error here ...
t.strictEqual(content, undefined)
})
fastify.close()
})
})
})
test('fastify.view with ejs engine and callback in production mode', t => {
t.plan(6)
const fastify = Fastify()
const ejs = require('ejs')
const data = { text: 'text' }
fastify.register(require('../index'), {
engine: {
ejs: ejs
},
production: true
})
fastify.ready(err => {
t.error(err)
fastify.view('templates/index.ejs', data, (err, compiled) => {
t.error(err)
t.strictEqual(ejs.render(fs.readFileSync('./templates/index.ejs', 'utf8'), data), compiled)
fastify.ready(err => {
t.error(err)
fastify.view('templates/index.ejs', data, (err, compiled) => {
t.error(err)
t.strictEqual(ejs.render(fs.readFileSync('./templates/index.ejs', 'utf8'), data), compiled)
fastify.close()
})
})
})
})
})
|
const deepMerge = require('deepmerge')
const semver = require('semver')
/**
* @param {object} config
* @param {string} env
* @param {object} htmlWebpackPluginOptions
*/
function rewireHtmlWebpackPlugin(config, env, htmlWebpackPluginOptions = {}) {
let optionKey = 'options'
const webpack = require('webpack')
if (semver.major(webpack.version) === 5) {
optionKey = 'userOptions'
}
const htmlWebpackPlugin = config.plugins.find(
plugin => plugin.constructor.name === 'HtmlWebpackPlugin'
)
if (!htmlWebpackPlugin) {
throw new Error("Can't find HtmlWebpackPlugin")
}
htmlWebpackPlugin[optionKey] = deepMerge(
htmlWebpackPlugin[optionKey],
htmlWebpackPluginOptions
)
return config
}
module.exports = rewireHtmlWebpackPlugin
|
import React from "react";
import { InputGroup, FormControl, Button } from "react-bootstrap";
const MobileNoCard = (props) => {
return (
<>
<div className="pt-4 zoomeffect">
<InputGroup className="mb-3">
<InputGroup.Prepend>
<InputGroup.Text>+91</InputGroup.Text>
</InputGroup.Prepend>
<FormControl
placeholder={props.mobileNo}
aria-label="Mobile No."
onChange={(e) => props.mobileNoChangeHandler(e)}
/>
<InputGroup.Append>
<Button variant="outline-secondary" onClick={props.sendOtpHandler} style={{boxShadow: "2px 3px 5px #888888"}}>
Send OTP
</Button>
</InputGroup.Append>
</InputGroup>
</div>
</>
);
};
export default MobileNoCard;
|
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _objectSpread2 = _interopRequireDefault(require("@babel/runtime/helpers/objectSpread"));
var _themer = require("../../../../themer");
var _memoizeClassName = _interopRequireDefault(require("../utils/memoizeClassName"));
var _scales = _interopRequireDefault(require("../foundational-styles/scales"));
var _helpers = require("../helpers");
var _shared = require("../shared");
/**
* Disabled styles are all the same for all buttons.
*/
var disabled = _shared.defaultControlStyles.disabled;
/**
* Get button appearance.
* @param {string} appearance - default, primary, minimal.
* @param {string} intent - none, success, warning, danger.
* @return {Object} the appearance of the button.
*/
var getButtonAppearance = function getButtonAppearance(appearance, intent) {
switch (appearance) {
case 'primary':
{
var _getPrimaryButtonStyl = (0, _helpers.getPrimaryButtonStylesForIntent)(intent),
linearGradient = _getPrimaryButtonStyl.linearGradient,
focusColor = _getPrimaryButtonStyl.focusColor;
return _themer.Themer.createButtonAppearance({
disabled: disabled,
base: {
color: 'white',
backgroundColor: 'white',
backgroundImage: linearGradient.base,
boxShadow: "inset 0 0 0 1px ".concat(_scales.default.neutral.N5A, ", inset 0 -1px 1px 0 ").concat(_scales.default.neutral.N2A)
},
hover: {
backgroundImage: linearGradient.hover
},
focus: {
boxShadow: "0 0 0 3px ".concat(focusColor, ", inset 0 0 0 1px ").concat(_scales.default.neutral.N4A, ", inset 0 -1px 1px 0 ").concat(_scales.default.neutral.N5A)
},
active: {
backgroundImage: linearGradient.active,
boxShadow: "inset 0 0 0 1px ".concat(_scales.default.neutral.N4A, ", inset 0 1px 1px 0 ").concat(_scales.default.neutral.N2A)
},
focusAndActive: {
boxShadow: "0 0 0 3px ".concat(focusColor, ", inset 0 0 0 1px ").concat(_scales.default.neutral.N4A, ", inset 0 1px 1px 0 ").concat(_scales.default.neutral.N2A)
}
});
}
case 'minimal':
{
var intentTextColor = (0, _helpers.getTextColorForIntent)(intent, _scales.default.blue.B9);
return _themer.Themer.createButtonAppearance({
disabled: disabled,
base: {
color: intentTextColor,
backgroundColor: 'transparent'
},
hover: {
backgroundColor: _scales.default.neutral.N2A
},
focus: {
boxShadow: "0 0 0 3px ".concat(_scales.default.blue.B5A)
},
active: {
backgroundImage: 'none',
backgroundColor: _scales.default.blue.B3A
},
focusAndActive: {}
});
}
case 'default':
default:
{
var _intentTextColor = (0, _helpers.getTextColorForIntent)(intent);
return _themer.Themer.createButtonAppearance({
disabled: disabled,
base: (0, _objectSpread2.default)({
color: _intentTextColor
}, _shared.defaultControlStyles.base),
hover: _shared.defaultControlStyles.hover,
focus: _shared.defaultControlStyles.focus,
active: _shared.defaultControlStyles.active,
focusAndActive: _shared.defaultControlStyles.focusAndActive
});
}
}
};
/**
* Get the className of a `Button`|`IconButton`.
* @param {string} appearance - default, primary, minimal.
* @param {Intent} intent - none, success, warning, danger.
* @return {string} the appearance class name.
*/
var _default = (0, _memoizeClassName.default)(getButtonAppearance);
exports.default = _default;
//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uLy4uL3NyYy90aGVtZS9zcmMvZGVmYXVsdC10aGVtZS9jb21wb25lbnQtc3BlY2lmaWMvZ2V0QnV0dG9uQ2xhc3NOYW1lLmpzIl0sIm5hbWVzIjpbImRpc2FibGVkIiwiZGVmYXVsdENvbnRyb2xTdHlsZXMiLCJnZXRCdXR0b25BcHBlYXJhbmNlIiwiYXBwZWFyYW5jZSIsImludGVudCIsImxpbmVhckdyYWRpZW50IiwiZm9jdXNDb2xvciIsIlRoZW1lciIsImNyZWF0ZUJ1dHRvbkFwcGVhcmFuY2UiLCJiYXNlIiwiY29sb3IiLCJiYWNrZ3JvdW5kQ29sb3IiLCJiYWNrZ3JvdW5kSW1hZ2UiLCJib3hTaGFkb3ciLCJzY2FsZXMiLCJuZXV0cmFsIiwiTjVBIiwiTjJBIiwiaG92ZXIiLCJmb2N1cyIsIk40QSIsImFjdGl2ZSIsImZvY3VzQW5kQWN0aXZlIiwiaW50ZW50VGV4dENvbG9yIiwiYmx1ZSIsIkI5IiwiQjVBIiwiQjNBIl0sIm1hcHBpbmdzIjoiOzs7Ozs7Ozs7OztBQUFBOztBQUNBOztBQUNBOztBQUNBOztBQUlBOztBQUVBOzs7SUFHUUEsUSxHQUFhQyw0QixDQUFiRCxRO0FBRVI7Ozs7Ozs7QUFNQSxJQUFNRSxtQkFBbUIsR0FBRyxTQUF0QkEsbUJBQXNCLENBQUNDLFVBQUQsRUFBYUMsTUFBYixFQUF3QjtBQUNsRCxVQUFRRCxVQUFSO0FBQ0UsU0FBSyxTQUFMO0FBQWdCO0FBQUEsb0NBQ3lCLDhDQUNyQ0MsTUFEcUMsQ0FEekI7QUFBQSxZQUNOQyxjQURNLHlCQUNOQSxjQURNO0FBQUEsWUFDVUMsVUFEVix5QkFDVUEsVUFEVjs7QUFJZCxlQUFPQyxlQUFPQyxzQkFBUCxDQUE4QjtBQUNuQ1IsVUFBQUEsUUFBUSxFQUFSQSxRQURtQztBQUVuQ1MsVUFBQUEsSUFBSSxFQUFFO0FBQ0pDLFlBQUFBLEtBQUssRUFBRSxPQURIO0FBRUpDLFlBQUFBLGVBQWUsRUFBRSxPQUZiO0FBR0pDLFlBQUFBLGVBQWUsRUFBRVAsY0FBYyxDQUFDSSxJQUg1QjtBQUlKSSxZQUFBQSxTQUFTLDRCQUNQQyxnQkFBT0MsT0FBUCxDQUFlQyxHQURSLGtDQUVlRixnQkFBT0MsT0FBUCxDQUFlRSxHQUY5QjtBQUpMLFdBRjZCO0FBVW5DQyxVQUFBQSxLQUFLLEVBQUU7QUFDTE4sWUFBQUEsZUFBZSxFQUFFUCxjQUFjLENBQUNhO0FBRDNCLFdBVjRCO0FBYW5DQyxVQUFBQSxLQUFLLEVBQUU7QUFDTE4sWUFBQUEsU0FBUyxzQkFBZVAsVUFBZiwrQkFDUFEsZ0JBQU9DLE9BQVAsQ0FBZUssR0FEUixrQ0FFZU4sZ0JBQU9DLE9BQVAsQ0FBZUMsR0FGOUI7QUFESixXQWI0QjtBQWtCbkNLLFVBQUFBLE1BQU0sRUFBRTtBQUNOVCxZQUFBQSxlQUFlLEVBQUVQLGNBQWMsQ0FBQ2dCLE1BRDFCO0FBRU5SLFlBQUFBLFNBQVMsNEJBQ1BDLGdCQUFPQyxPQUFQLENBQWVLLEdBRFIsaUNBRWNOLGdCQUFPQyxPQUFQLENBQWVFLEdBRjdCO0FBRkgsV0FsQjJCO0FBd0JuQ0ssVUFBQUEsY0FBYyxFQUFFO0FBQ2RULFlBQUFBLFNBQVMsc0JBQWVQLFVBQWYsK0JBQ1BRLGdCQUFPQyxPQUFQLENBQWVLLEdBRFIsaUNBRWNOLGdCQUFPQyxPQUFQLENBQWVFLEdBRjdCO0FBREs7QUF4Qm1CLFNBQTlCLENBQVA7QUE4QkQ7O0FBQ0QsU0FBSyxTQUFMO0FBQWdCO0FBQ2QsWUFBTU0sZUFBZSxHQUFHLG9DQUFzQm5CLE1BQXRCLEVBQThCVSxnQkFBT1UsSUFBUCxDQUFZQyxFQUExQyxDQUF4QjtBQUNBLGVBQU9sQixlQUFPQyxzQkFBUCxDQUE4QjtBQUNuQ1IsVUFBQUEsUUFBUSxFQUFSQSxRQURtQztBQUVuQ1MsVUFBQUEsSUFBSSxFQUFFO0FBQ0pDLFlBQUFBLEtBQUssRUFBRWEsZUFESDtBQUVKWixZQUFBQSxlQUFlLEVBQUU7QUFGYixXQUY2QjtBQU1uQ08sVUFBQUEsS0FBSyxFQUFFO0FBQ0xQLFlBQUFBLGVBQWUsRUFBRUcsZ0JBQU9DLE9BQVAsQ0FBZUU7QUFEM0IsV0FONEI7QUFTbkNFLFVBQUFBLEtBQUssRUFBRTtBQUNMTixZQUFBQSxTQUFTLHNCQUFlQyxnQkFBT1UsSUFBUCxDQUFZRSxHQUEzQjtBQURKLFdBVDRCO0FBWW5DTCxVQUFBQSxNQUFNLEVBQUU7QUFDTlQsWUFBQUEsZUFBZSxFQUFFLE1BRFg7QUFFTkQsWUFBQUEsZUFBZSxFQUFFRyxnQkFBT1UsSUFBUCxDQUFZRztBQUZ2QixXQVoyQjtBQWdCbkNMLFVBQUFBLGNBQWMsRUFBRTtBQWhCbUIsU0FBOUIsQ0FBUDtBQWtCRDs7QUFDRCxTQUFLLFNBQUw7QUFDQTtBQUFTO0FBQ1AsWUFBTUMsZ0JBQWUsR0FBRyxvQ0FBc0JuQixNQUF0QixDQUF4Qjs7QUFDQSxlQUFPRyxlQUFPQyxzQkFBUCxDQUE4QjtBQUNuQ1IsVUFBQUEsUUFBUSxFQUFSQSxRQURtQztBQUVuQ1MsVUFBQUEsSUFBSTtBQUNGQyxZQUFBQSxLQUFLLEVBQUVhO0FBREwsYUFFQ3RCLDZCQUFxQlEsSUFGdEIsQ0FGK0I7QUFNbkNTLFVBQUFBLEtBQUssRUFBRWpCLDZCQUFxQmlCLEtBTk87QUFPbkNDLFVBQUFBLEtBQUssRUFBRWxCLDZCQUFxQmtCLEtBUE87QUFRbkNFLFVBQUFBLE1BQU0sRUFBRXBCLDZCQUFxQm9CLE1BUk07QUFTbkNDLFVBQUFBLGNBQWMsRUFBRXJCLDZCQUFxQnFCO0FBVEYsU0FBOUIsQ0FBUDtBQVdEO0FBdkVIO0FBeUVELENBMUVEO0FBNEVBOzs7Ozs7OztlQU1lLCtCQUFpQnBCLG1CQUFqQixDIiwic291cmNlc0NvbnRlbnQiOlsiaW1wb3J0IHsgVGhlbWVyIH0gZnJvbSAnLi4vLi4vLi4vLi4vdGhlbWVyJ1xuaW1wb3J0IG1lbW9pemVDbGFzc05hbWUgZnJvbSAnLi4vdXRpbHMvbWVtb2l6ZUNsYXNzTmFtZSdcbmltcG9ydCBzY2FsZXMgZnJvbSAnLi4vZm91bmRhdGlvbmFsLXN0eWxlcy9zY2FsZXMnXG5pbXBvcnQge1xuICBnZXRUZXh0Q29sb3JGb3JJbnRlbnQsXG4gIGdldFByaW1hcnlCdXR0b25TdHlsZXNGb3JJbnRlbnRcbn0gZnJvbSAnLi4vaGVscGVycydcbmltcG9ydCB7IGRlZmF1bHRDb250cm9sU3R5bGVzIH0gZnJvbSAnLi4vc2hhcmVkJ1xuXG4vKipcbiAqIERpc2FibGVkIHN0eWxlcyBhcmUgYWxsIHRoZSBzYW1lIGZvciBhbGwgYnV0dG9ucy5cbiAqL1xuY29uc3QgeyBkaXNhYmxlZCB9ID0gZGVmYXVsdENvbnRyb2xTdHlsZXNcblxuLyoqXG4gKiBHZXQgYnV0dG9uIGFwcGVhcmFuY2UuXG4gKiBAcGFyYW0ge3N0cmluZ30gYXBwZWFyYW5jZSAtIGRlZmF1bHQsIHByaW1hcnksIG1pbmltYWwuXG4gKiBAcGFyYW0ge3N0cmluZ30gaW50ZW50IC0gbm9uZSwgc3VjY2Vzcywgd2FybmluZywgZGFuZ2VyLlxuICogQHJldHVybiB7T2JqZWN0fSB0aGUgYXBwZWFyYW5jZSBvZiB0aGUgYnV0dG9uLlxuICovXG5jb25zdCBnZXRCdXR0b25BcHBlYXJhbmNlID0gKGFwcGVhcmFuY2UsIGludGVudCkgPT4ge1xuICBzd2l0Y2ggKGFwcGVhcmFuY2UpIHtcbiAgICBjYXNlICdwcmltYXJ5Jzoge1xuICAgICAgY29uc3QgeyBsaW5lYXJHcmFkaWVudCwgZm9jdXNDb2xvciB9ID0gZ2V0UHJpbWFyeUJ1dHRvblN0eWxlc0ZvckludGVudChcbiAgICAgICAgaW50ZW50XG4gICAgICApXG4gICAgICByZXR1cm4gVGhlbWVyLmNyZWF0ZUJ1dHRvbkFwcGVhcmFuY2Uoe1xuICAgICAgICBkaXNhYmxlZCxcbiAgICAgICAgYmFzZToge1xuICAgICAgICAgIGNvbG9yOiAnd2hpdGUnLFxuICAgICAgICAgIGJhY2tncm91bmRDb2xvcjogJ3doaXRlJyxcbiAgICAgICAgICBiYWNrZ3JvdW5kSW1hZ2U6IGxpbmVhckdyYWRpZW50LmJhc2UsXG4gICAgICAgICAgYm94U2hhZG93OiBgaW5zZXQgMCAwIDAgMXB4ICR7XG4gICAgICAgICAgICBzY2FsZXMubmV1dHJhbC5ONUFcbiAgICAgICAgICB9LCBpbnNldCAwIC0xcHggMXB4IDAgJHtzY2FsZXMubmV1dHJhbC5OMkF9YFxuICAgICAgICB9LFxuICAgICAgICBob3Zlcjoge1xuICAgICAgICAgIGJhY2tncm91bmRJbWFnZTogbGluZWFyR3JhZGllbnQuaG92ZXJcbiAgICAgICAgfSxcbiAgICAgICAgZm9jdXM6IHtcbiAgICAgICAgICBib3hTaGFkb3c6IGAwIDAgMCAzcHggJHtmb2N1c0NvbG9yfSwgaW5zZXQgMCAwIDAgMXB4ICR7XG4gICAgICAgICAgICBzY2FsZXMubmV1dHJhbC5ONEFcbiAgICAgICAgICB9LCBpbnNldCAwIC0xcHggMXB4IDAgJHtzY2FsZXMubmV1dHJhbC5ONUF9YFxuICAgICAgICB9LFxuICAgICAgICBhY3RpdmU6IHtcbiAgICAgICAgICBiYWNrZ3JvdW5kSW1hZ2U6IGxpbmVhckdyYWRpZW50LmFjdGl2ZSxcbiAgICAgICAgICBib3hTaGFkb3c6IGBpbnNldCAwIDAgMCAxcHggJHtcbiAgICAgICAgICAgIHNjYWxlcy5uZXV0cmFsLk40QVxuICAgICAgICAgIH0sIGluc2V0IDAgMXB4IDFweCAwICR7c2NhbGVzLm5ldXRyYWwuTjJBfWBcbiAgICAgICAgfSxcbiAgICAgICAgZm9jdXNBbmRBY3RpdmU6IHtcbiAgICAgICAgICBib3hTaGFkb3c6IGAwIDAgMCAzcHggJHtmb2N1c0NvbG9yfSwgaW5zZXQgMCAwIDAgMXB4ICR7XG4gICAgICAgICAgICBzY2FsZXMubmV1dHJhbC5ONEFcbiAgICAgICAgICB9LCBpbnNldCAwIDFweCAxcHggMCAke3NjYWxlcy5uZXV0cmFsLk4yQX1gXG4gICAgICAgIH1cbiAgICAgIH0pXG4gICAgfVxuICAgIGNhc2UgJ21pbmltYWwnOiB7XG4gICAgICBjb25zdCBpbnRlbnRUZXh0Q29sb3IgPSBnZXRUZXh0Q29sb3JGb3JJbnRlbnQoaW50ZW50LCBzY2FsZXMuYmx1ZS5COSlcbiAgICAgIHJldHVybiBUaGVtZXIuY3JlYXRlQnV0dG9uQXBwZWFyYW5jZSh7XG4gICAgICAgIGRpc2FibGVkLFxuICAgICAgICBiYXNlOiB7XG4gICAgICAgICAgY29sb3I6IGludGVudFRleHRDb2xvcixcbiAgICAgICAgICBiYWNrZ3JvdW5kQ29sb3I6ICd0cmFuc3BhcmVudCdcbiAgICAgICAgfSxcbiAgICAgICAgaG92ZXI6IHtcbiAgICAgICAgICBiYWNrZ3JvdW5kQ29sb3I6IHNjYWxlcy5uZXV0cmFsLk4yQVxuICAgICAgICB9LFxuICAgICAgICBmb2N1czoge1xuICAgICAgICAgIGJveFNoYWRvdzogYDAgMCAwIDNweCAke3NjYWxlcy5ibHVlLkI1QX1gXG4gICAgICAgIH0sXG4gICAgICAgIGFjdGl2ZToge1xuICAgICAgICAgIGJhY2tncm91bmRJbWFnZTogJ25vbmUnLFxuICAgICAgICAgIGJhY2tncm91bmRDb2xvcjogc2NhbGVzLmJsdWUuQjNBXG4gICAgICAgIH0sXG4gICAgICAgIGZvY3VzQW5kQWN0aXZlOiB7fVxuICAgICAgfSlcbiAgICB9XG4gICAgY2FzZSAnZGVmYXVsdCc6XG4gICAgZGVmYXVsdDoge1xuICAgICAgY29uc3QgaW50ZW50VGV4dENvbG9yID0gZ2V0VGV4dENvbG9yRm9ySW50ZW50KGludGVudClcbiAgICAgIHJldHVybiBUaGVtZXIuY3JlYXRlQnV0dG9uQXBwZWFyYW5jZSh7XG4gICAgICAgIGRpc2FibGVkLFxuICAgICAgICBiYXNlOiB7XG4gICAgICAgICAgY29sb3I6IGludGVudFRleHRDb2xvcixcbiAgICAgICAgICAuLi5kZWZhdWx0Q29udHJvbFN0eWxlcy5iYXNlXG4gICAgICAgIH0sXG4gICAgICAgIGhvdmVyOiBkZWZhdWx0Q29udHJvbFN0eWxlcy5ob3ZlcixcbiAgICAgICAgZm9jdXM6IGRlZmF1bHRDb250cm9sU3R5bGVzLmZvY3VzLFxuICAgICAgICBhY3RpdmU6IGRlZmF1bHRDb250cm9sU3R5bGVzLmFjdGl2ZSxcbiAgICAgICAgZm9jdXNBbmRBY3RpdmU6IGRlZmF1bHRDb250cm9sU3R5bGVzLmZvY3VzQW5kQWN0aXZlXG4gICAgICB9KVxuICAgIH1cbiAgfVxufVxuXG4vKipcbiAqIEdldCB0aGUgY2xhc3NOYW1lIG9mIGEgYEJ1dHRvbmB8YEljb25CdXR0b25gLlxuICogQHBhcmFtIHtzdHJpbmd9IGFwcGVhcmFuY2UgLSBkZWZhdWx0LCBwcmltYXJ5LCBtaW5pbWFsLlxuICogQHBhcmFtIHtJbnRlbnR9IGludGVudCAtIG5vbmUsIHN1Y2Nlc3MsIHdhcm5pbmcsIGRhbmdlci5cbiAqIEByZXR1cm4ge3N0cmluZ30gdGhlIGFwcGVhcmFuY2UgY2xhc3MgbmFtZS5cbiAqL1xuZXhwb3J0IGRlZmF1bHQgbWVtb2l6ZUNsYXNzTmFtZShnZXRCdXR0b25BcHBlYXJhbmNlKVxuIl19
|
import Head from 'next/head';
import { Box, Container, Grid } from '@mui/material';
import { Vacancy } from '../dashboard/vacancy';
import { StatBy } from '../dashboard/statby';
import { Noti } from '../dashboard/noti';
import { CandidateStat } from '../dashboard/candstat';
import { Alarm } from '../dashboard/alarm';
import { Rate } from '../dashboard/rate';
import { DashboardLayout } from '../dashboard-layout';
import { useDispatch, useSelector } from 'react-redux';
import { changeMenu } from '../../redux/slices/NavBarSlice';
import React, { useEffect } from 'react';
import { useParams, useLocation } from 'react-router-dom';
function ClientsAnalytics() {
const { clientsid, chatid, vacancyid, id } = useParams();
const location = useLocation()
const dispatch = useDispatch();
// useEffect
useEffect(() => {
dispatch(changeMenu({ locationPath: location.pathname, clientsid, chatid, vacancyid, id }));
}, [location]);
return (
<>
<Head>
<title>
Аналитика по кандидатам
</title>
</Head>
<Box
component="main"
sx={{
flexGrow: 1,
mt: -1.4,
width: '90%',
mx: 'auto',
}}
>
<Container maxWidth={false}>
<Box
component="main"
sx={{
flexGrow: 1,
py: 0.6
}}>
<h2>Аналитика</h2>
</Box>
<Grid
container
spacing={3}
>
<Grid
item
lg={3}
sm={3}
xl={3}
xs={5}
>
<Vacancy />
</Grid>
<Grid
item
xl={3}
lg={3}
sm={6}
xs={12}
>
<CandidateStat />
</Grid>
<Grid
item
xl={3}
lg={3}
sm={6}
xs={12}
>
<Noti />
</Grid>
<Grid
item
xl={3}
lg={3}
sm={6}
xs={12}
>
<Alarm />
</Grid>
<Grid
item
lg={8}
md={12}
xl={9}
xs={12}
>
<StatBy />
</Grid>
<Grid
item
lg={4}
md={6}
xl={3}
xs={12}
>
<Rate sx={{ height: '80%' }} />
</Grid>
<Grid
item
lg={4}
md={6}
xl={3}
xs={12}
>
</Grid>
</Grid>
</Container>
</Box>
</>
);
}
ClientsAnalytics.getLayout = (page) => (
<DashboardLayout>
{page}
</DashboardLayout>
);
export default ClientsAnalytics;
|
mycallback( {"ELECTION CODE": "G2010", "EXPENDITURE PURPOSE DESCRIP": "Labels", "BENEFICIARY CANDIDATE OFFICE": "", "PAYEE ZIP": "95841", "MEMO CODE": "X", "PAYEE STATE": "CA", "PAYEE LAST NAME": "", "PAYEE CITY": "Sacramento", "PAYEE SUFFIX": "", "CONDUIT STREET 2": "", "CONDUIT STREET 1": "2523- I St., Apt. #5", "PAYEE FIRST NAME": "", "BACK REFERENCE SCHED NAME": "SB17", "BENEFICIARY COMMITTEE NAME": "", "PAYEE PREFIX": "", "MEMO TEXT/DESCRIPTION": "", "FILER COMMITTEE ID NUMBER": "C00461061", "EXPENDITURE AMOUNT (F3L Bundled)": "64.15", "BENEFICIARY CANDIDATE MIDDLE NAME": "", "BENEFICIARY CANDIDATE LAST NAME": "", "_record_type": "fec.version.v7_0.SB", "PAYEE STREET 2": "", "PAYEE STREET 1": "4614 Madison Avenue", "SEMI-ANNUAL REFUNDED BUNDLED AMT": "", "Reference to SI or SL system code that identifies the Account": "", "CONDUIT CITY": "Sacramento", "ENTITY TYPE": "ORG", "BENEFICIARY CANDIDATE FEC ID": "", "BENEFICIARY COMMITTEE FEC ID": "", "BENEFICIARY CANDIDATE STATE": "", "BENEFICIARY CANDIDATE FIRST NAME": "", "PAYEE MIDDLE NAME": "", "ELECTION OTHER DESCRIPTION": "", "_src_file": "2011/20110504/727407.fec_4.yml", "CONDUIT STATE": "CA", "CATEGORY CODE": "001", "EXPENDITURE PURPOSE CODE": "", "BENEFICIARY CANDIDATE DISTRICT": "", "TRANSACTION ID NUMBER": "EDTB43EXPB7870", "BACK REFERENCE TRAN ID NUMBER": "EXPB7870", "EXPENDITURE DATE": "20101031", "BENEFICIARY CANDIDATE PREFIX": "", "CONDUIT NAME": "Johnston, Conner", "PAYEE ORGANIZATION NAME": "Office Depot", "BENEFICIARY CANDIDATE SUFFIX": "", "CONDUIT ZIP": "95816", "FORM TYPE": "SB17"});
mycallback( {"ELECTION CODE": "G2010", "EXPENDITURE PURPOSE DESCRIP": "Labels", "BENEFICIARY CANDIDATE OFFICE": "", "PAYEE ZIP": "95841", "MEMO CODE": "X", "PAYEE STATE": "CA", "PAYEE LAST NAME": "", "PAYEE CITY": "Sacramento", "PAYEE SUFFIX": "", "CONDUIT STREET 2": "", "CONDUIT STREET 1": "2523- I St., Apt. #5", "PAYEE FIRST NAME": "", "BACK REFERENCE SCHED NAME": "SB17", "BENEFICIARY COMMITTEE NAME": "", "PAYEE PREFIX": "", "MEMO TEXT/DESCRIPTION": "", "FILER COMMITTEE ID NUMBER": "C00461061", "EXPENDITURE AMOUNT (F3L Bundled)": "64.15", "BENEFICIARY CANDIDATE MIDDLE NAME": "", "BENEFICIARY CANDIDATE LAST NAME": "", "_record_type": "fec.version.v7_0.SB", "PAYEE STREET 2": "", "PAYEE STREET 1": "4614 Madison Avenue", "SEMI-ANNUAL REFUNDED BUNDLED AMT": "", "Reference to SI or SL system code that identifies the Account": "", "CONDUIT CITY": "Sacramento", "ENTITY TYPE": "ORG", "BENEFICIARY CANDIDATE FEC ID": "", "BENEFICIARY COMMITTEE FEC ID": "", "BENEFICIARY CANDIDATE STATE": "", "BENEFICIARY CANDIDATE FIRST NAME": "", "PAYEE MIDDLE NAME": "", "ELECTION OTHER DESCRIPTION": "", "_src_file": "2011/20110504/727407.fec_4.yml", "CONDUIT STATE": "CA", "CATEGORY CODE": "001", "EXPENDITURE PURPOSE CODE": "", "BENEFICIARY CANDIDATE DISTRICT": "", "TRANSACTION ID NUMBER": "EDTB43EXPB7870", "BACK REFERENCE TRAN ID NUMBER": "EXPB7870", "EXPENDITURE DATE": "20101031", "BENEFICIARY CANDIDATE PREFIX": "", "CONDUIT NAME": "Johnston, Conner", "PAYEE ORGANIZATION NAME": "Office Depot", "BENEFICIARY CANDIDATE SUFFIX": "", "CONDUIT ZIP": "95816", "FORM TYPE": "SB17"});
|
"use strict";
/**
* @license
* Copyright 2018 Google LLC
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
* =============================================================================
*/
Object.defineProperty(exports, "__esModule", { value: true });
var utils_1 = require("./utils");
/**
* List of all known activation names.
*/
exports.activationOptions = utils_1.stringLiteralArray([
'elu', 'hard_sigmoid', 'linear', 'relu', 'relu6', 'selu', 'sigmoid',
'softmax', 'softplus', 'softsign', 'tanh'
]);
//# sourceMappingURL=activation_config.js.map
|
/**
* This test ensures readers on a secondary are unable to read from unique indexes that temporarily
* violate their uniqueness constraint. When oplog entries are applied in parallel batch writes,
* operations can be applied out-of-order, and reading at an inconsistent state is possible.
*
* For example, take two documents, { _id: 1, x: 1} and { _id: 2, x: 2} with a unique index on 'x'.
* On the primary, two updates take place in this order:
* { _id: 2, x: 3 }
* { _id: 1, x: 2 }
* There is no uniqueness violation here because x: 3 happens before x: 2. If the updates had
* occured in the opposite order, a DuplicateKey error would be returned to the user.
*
* When these operations are applied on a secondary, they split up across one of 16 writer threads,
* hashed on the _id of the document. This guarantees that updates to the same document will occur
* in-order on the same thread.
*
* Take two parallel threads applying the same updates as before:
* Thread 1 Thread 2
* { _id: 1, x: 2 }
* { _id: 2, x: 3 }
*
* If a secondary reader were to access the index entry for x=2 after Thread 1 made its update but
* before Thread 2 made its update, they would find two entries for x=2, which is a violation of the
* uniqueness constraint. When applying operations in parallel like this, we temporarily ignore
* uniqueness violations on indexes, and require readers on secondaries to wait for the parallel
* batch insert to complete, at which point the state of the indexes will be consistent.
*/
(function() {
"use strict";
load("jstests/replsets/libs/secondary_reads_test.js");
const name = "secondaryReadsUniqueIndexes";
const collName = "testColl";
let secondaryReadsTest = new SecondaryReadsTest(name);
let primaryDB = secondaryReadsTest.getPrimaryDB();
let secondaryDB = secondaryReadsTest.getSecondaryDB();
// Setup collection.
primaryDB.runCommand({drop: collName});
assert.commandWorked(primaryDB.runCommand({create: collName}));
// Create a unique index on the collection in the foreground.
assert.commandWorked(primaryDB.runCommand(
{createIndexes: collName, indexes: [{key: {x: 1}, name: "x_1", unique: true}]}));
let replSet = secondaryReadsTest.getReplset();
replSet.awaitReplication();
// We want to do updates with at least as many different documents as there are parallel batch
// writer threads (16). Each iteration increments and decrements a uniquely indexed value, 'x'.
// The goal is that a reader on a secondary might find a case where the unique index constraint
// is ignored, and an index on x maps to two different records.
const nOps = 16;
const nIterations = 50;
const nReaders = 16;
// Do a bunch of reads using the 'x' index on the secondary.
// No errors should be encountered on the secondary.
let readFn = function() {
for (let x = 0; x < TestData.nOps; x++) {
assert.commandWorked(db.runCommand({
find: TestData.collName,
filter: {x: x},
projection: {x: 1},
readConcern: {level: "local"},
}));
// Sleep a bit to make these reader threads less CPU intensive.
sleep(60);
}
};
TestData.nOps = nOps;
TestData.collName = collName;
secondaryReadsTest.startSecondaryReaders(nReaders, readFn);
// Write the initial documents. Ensure they have been replicated.
for (let i = 0; i < nOps; i++) {
assert.commandWorked(
primaryDB.runCommand({insert: collName, documents: [{_id: i, x: i, iter: 0}]}));
}
replSet.awaitReplication();
// Cycle the value of x in the document {_id: i, x: i} between i and i+1 each iteration.
for (let iteration = 0; iteration < nIterations; iteration++) {
let updates = [];
// Reset each document.
for (let i = 0; i < nOps; i++) {
updates[i] = {q: {_id: i}, u: {x: i, iter: iteration}};
}
assert.commandWorked(primaryDB.runCommand({update: collName, updates: updates}));
updates = [];
// Generate updates that increment x on each document backwards by _id to avoid conficts
// when applied in-order. When these updates get applied to the secondary, they may get
// applied out of order by different threads and temporarily violate unique index
// constraints.
for (let i = 0; i < nOps; i++) {
// Start at the end and increment x by 1.
let end = nOps - i - 1;
let nextX = end + 1;
updates[i] = {q: {_id: end}, u: {x: nextX, iter: iteration}};
}
print("iteration " + iteration);
assert.commandWorked(primaryDB.runCommand({update: collName, updates: updates}));
}
replSet.awaitReplication();
secondaryReadsTest.stop();
})();
|
const myArray = ['Hello', 'Welcome', 'Greetings'];
const temp = randomItem(myArray);
const h1 = document.getElementById('Greet');
const message = document.createTextNode(temp);
h1.appendChild(message);
function randomItem(arr) {
return arr[Math.floor(Math.random() * arr.length)];
}
|
var HSA_scrollAreas = new Array();
var HSA_default_imagesPath = "img";
var HSA_default_btnLeftImage = "button-left-trans.png";
var HSA_default_btnRightImage = "button-left-trans.png";
var HSA_default_scrollStep = 5;
var HSA_default_wheelSensitivity = 10;
var HSA_default_scrollbarPosition = 'bottom'; //'top';//'bottom';'inline';
var HSA_default_scrollButtonWidth = 32;
var HSA_default_scrollbarHeight = 32;
var HSA_resizeTimer = 200;
if (window.addEventListener)
window.addEventListener("load", HSA_initScrollbars, false);
else if (window.attachEvent)
window.attachEvent("onload", HSA_initScrollbars);
function HSA_initScrollbars() {
var scrollElements = HSA_getElements("scrollable", "DIV", document, "class");
for (var i = 0; i < scrollElements.length; i++) {
HSA_scrollAreas[i] = new ScrollArea(i, scrollElements[i]);
}
}
function ScrollArea(index, elem) //constructor
{
this.index = index;
this.element = elem;
var attr = this.element.getAttribute("imagesPath");
this.imagesPath = attr ? attr : HSA_default_imagesPath;
attr = this.element.getAttribute("btnLeftImage");
this.btnLeftImage = attr ? attr : HSA_default_btnLeftImage;
attr = this.element.getAttribute("btnRightImage");
this.btnRightImage = attr ? attr : HSA_default_btnRightImage;
attr = Number(this.element.getAttribute("scrollStep"));
this.scrollStep = attr ? attr : HSA_default_scrollStep;
attr = Number(this.element.getAttribute("wheelSensitivity"));
this.wheelSensitivity = attr ? attr : HSA_default_wheelSensitivity;
attr = this.element.getAttribute("scrollbarPosition");
this.scrollbarPosition = attr ? attr : HSA_default_scrollbarPosition;
attr = this.element.getAttribute("scrollButtonWidth");
this.scrollButtonWidth = attr ? attr : HSA_default_scrollButtonWidth;
attr = this.element.getAttribute("scrollbarHeight");
this.scrollbarHeight = attr ? attr : HSA_default_scrollbarHeight;
this.scrolling = false;
this.iOffsetX = 0;
this.scrollWidth = 0;
this.scrollContent = null;
this.scrollbar = null;
this.scrollleft = null;
this.scrollright = null;
this.scrollslider = null;
this.scroll = null;
this.enableScrollbar = false;
this.scrollFactor = 1;
this.scrollingLimit = 0;
this.leftPosition = 0;
//functions declaration
this.init = HSA_init;
this.scrollLeft = HSA_scrollLeft;
this.scrollRight = HSA_scrollRight;
this.createScrollBar = HSA_createScrollBar;
this.scrollIt = HSA_scrollIt;
this.init();
}
function HSA_init() {
this.scrollContent = document.createElement("DIV");
this.scrollContent.style.position = "absolute";
this.scrollContent.style.width = this.element.offsetWidth + "px";
this.scrollContent.style.height = this.element.offsetHeight + "px";
this.scrollContent.innerHTML = this.element.innerHTML;
this.scrollContent.style.overflow = "hidden";
this.element.innerHTML = "";
this.element.style.overflow = "hidden";
this.element.style.display = "block";
this.element.style.visibility = "visible";
this.element.style.position = "relative";
this.element.appendChild(this.scrollContent);
this.scrollContent.className = 'scroll-content';
this.element.index = this.index;
this.element.over = false;
var _this = this;
this.element.onmouseover = function () {
_this.element.over = true;
};
this.element.onmouseout = function () {
_this.element.over = false;
}
if (document.all) {
this.element.onscroll = HSA_handleOnScroll;
this.element.onresize = HSA_handleResize;
} else {
window.onresize = HSA_handleResize;
}
this.createScrollBar();
if (window.addEventListener)
/** DOMMouseScroll is for mozilla. */
this.element.addEventListener('DOMMouseScroll', HSA_handleMouseWheel, false);
/** IE/Opera. */
this.element.onmousewheel = document.onmousewheel = HSA_handleMouseWheel;
}
function HSA_createScrollBar() {
if (this.scrollbar != null) {
this.element.removeChild(this.scrollbar);
this.scrollbar = null;
}
if (this.scrollContent.scrollWidth <= this.scrollContent.offsetWidth)
this.enableScrollbar = false;
else if (this.element.offsetWidth > 2 * this.scrollButtonWidth)
this.enableScrollbar = true;
else
this.enableScrollbar = false;
if (this.scrollContent.scrollWidth - Math.abs(this.scrollContent.scrollLeft) < this.element.offsetWidth)
this.scrollContent.style.left = 0;
if (this.enableScrollbar) {
this.scrollbar = document.createElement("DIV");
this.element.appendChild(this.scrollbar);
this.scrollbar.style.position = "absolute";
this.scrollbar.style.left = "0px";
this.scrollbar.style.width = this.element.offsetWidth + "px";
this.scrollbar.style.height = this.scrollbarHeight + "px";
this.scrollbar.className = 'hscroll-bar';
if (this.scrollbarHeight != this.scrollbar.offsetHeight) {
this.scrollbarHeight = this.scrollbar.offsetWidth;
}
this.scrollbarHeight = this.scrollbar.offsetHeight;
if (this.scrollbarPosition == 'top') {
this.scrollContent.style.top = this.scrollbarHeight + 5 + "px";
this.scrollContent.style.height = this.element.offsetHeight - this.scrollbarHeight - 5 + "px";
} else if (this.scrollbarPosition == 'bottom') {
this.scrollbar.style.top = this.element.offsetHeight - this.scrollbarHeight + "px";
this.scrollContent.style.height = this.element.offsetHeight - this.scrollbarHeight - 5 + "px";
}
//create scroll up button
this.scrollleft = document.createElement("DIV");
this.scrollleft.index = this.index;
this.scrollleft.onmousedown = HSA_handleBtnLeftMouseRight;
this.scrollleft.onmouseup = HSA_handleBtnLeftMouseLeft;
this.scrollleft.onmouseout = HSA_handleBtnLeftMouseOut;
this.scrollleft.style.position = "absolute";
this.scrollleft.style.left = "0px";
this.scrollleft.style.width = this.scrollButtonWidth + "px";
this.scrollleft.style.height = this.scrollbarHeight + "px";
this.scrollleft.innerHTML = '<img src="' + this.imagesPath + '/' + this.btnLeftImage + '" border="0"/>';
this.scrollbar.appendChild(this.scrollleft);
this.scrollleft.className = 'hscroll-left';
if (this.scrollButtonWidth != this.scrollleft.offsetWidth) {
this.scrollButtonWidth = this.scrollleft.offsetWidth;
}
//create scroll down button
this.scrollright = document.createElement("DIV");
this.scrollright.index = this.index;
this.scrollright.onmousedown = HSA_handleBtnRightMouseRight;
this.scrollright.onmouseup = HSA_handleBtnRightMouseLeft;
this.scrollright.onmouseout = HSA_handleBtnRightMouseOut;
this.scrollright.style.position = "absolute";
this.scrollright.style.left = this.scrollbar.offsetWidth - this.scrollButtonWidth + "px";
this.scrollright.style.height = this.scrollbarHeight + "px";
this.scrollright.innerHTML = '<img src="' + this.imagesPath + '/' + this.btnRightImage + '" border="0"/>';
this.scrollbar.appendChild(this.scrollright);
this.scrollright.className = 'hscroll-right';
//create scroll
this.scroll = document.createElement("DIV");
this.scroll.index = this.index;
this.scroll.style.position = "absolute";
this.scroll.style.zIndex = 0;
this.scroll.style.textAlign = "center";
this.scroll.style.left = this.scrollButtonWidth + "px";
this.scroll.style.height = this.scrollbarHeight + "px";
var h = this.scrollbar.offsetWidth - 2 * this.scrollButtonWidth;
this.scroll.style.width = ((h > 0) ? h : 0) + "px";
this.scroll.innerHTML = '';
this.scroll.onclick = HSA_handleScrollbarClick;
this.scrollbar.appendChild(this.scroll);
this.scroll.style.overflow = "hidden";
this.scroll.className = "hscroll-line";
//create slider
this.scrollslider = document.createElement("DIV");
this.scrollslider.index = this.index;
this.scrollslider.style.position = "absolute";
this.scrollslider.style.zIndex = 1000;
this.scrollslider.style.textAlign = "center";
this.scrollslider.innerHTML = '<div id="scrollslider' + this.index + '" style="padding:0;margin:0;"><div class="scroll-bar-left"></div><div class="scroll-bar-right"></div></div>';
this.scrollbar.appendChild(this.scrollslider);
this.subscrollslider = document.getElementById("scrollslider" + this.index);
this.subscrollslider.style.width = Math.round((this.scrollContent.offsetWidth / this.scrollContent.scrollWidth) * (this.scrollbar.offsetWidth - 2 * this.scrollButtonWidth)) + "px";
this.scrollslider.className = "hscroll-slider";
this.scrollWidth = this.scrollbar.offsetWidth - 2 * this.scrollButtonWidth - this.scrollslider.offsetWidth;
this.scrollFactor = (this.scrollContent.scrollWidth - this.scrollContent.offsetWidth) / this.scrollWidth;
this.leftPosition = getRealLeft(this.scrollbar) + this.scrollButtonWidth;
/* this.scrollbarWidth = this.scrollbar.offsetWidth - 2*this.scrollButtonWidth - this.scrollslider.offsetWidth; */
this.scrollslider.style.left = /* 1 / this.scrollFactor * Math.abs(this.scrollContent.offsetTop) +*/ this.scrollButtonWidth + "px";
this.scrollslider.style.height = "100%";
this.scrollslider.onmousedown = HSA_handleSliderMouseDown;
if (document.all)
this.scrollslider.onmouseup = HSA_handleSliderMouseLeft;
} else
this.scrollContent.style.height = this.element.offsetHeight + "px";
}
function HSA_handleBtnLeftMouseRight() {
var sa = HSA_scrollAreas[this.index];
sa.scrolling = true;
sa.scrollLeft();
}
function HSA_handleBtnLeftMouseLeft() {
HSA_scrollAreas[this.index].scrolling = false;
}
function HSA_handleBtnLeftMouseOut() {
HSA_scrollAreas[this.index].scrolling = false;
}
function HSA_handleBtnRightMouseRight() {
var sa = HSA_scrollAreas[this.index];
sa.scrolling = true;
sa.scrollRight();
}
function HSA_handleBtnRightMouseLeft() {
HSA_scrollAreas[this.index].scrolling = false;
}
function HSA_handleBtnRightMouseOut() {
HSA_scrollAreas[this.index].scrolling = false;
}
function HSA_scrollIt() {
this.scrollContent.scrollLeft = this.scrollFactor * ((this.scrollslider.offsetLeft + this.scrollslider.offsetWidth / 2) - this.scrollButtonWidth - this.scrollslider.offsetWidth / 2);
}
function HSA_scrollLeft() {
if (this.scrollingLimit > 0) {
this.scrollingLimit--;
if (this.scrollingLimit == 0) this.scrolling = false;
}
if (!this.scrolling) return;
if (this.scrollContent.scrollLeft - this.scrollStep > 0) {
this.scrollContent.scrollLeft -= this.scrollStep;
this.scrollslider.style.left = 1 / this.scrollFactor * Math.abs(this.scrollContent.scrollLeft) + this.scrollButtonWidth + "px";
} else {
this.scrollContent.scrollLeft = "0";
this.scrollslider.style.left = this.scrollButtonWidth + "px";
return;
}
setTimeout("HSA_Ext_scrollLeft(" + this.index + ")", 30);
}
function HSA_Ext_scrollLeft(index) {
HSA_scrollAreas[index].scrollLeft();
}
function HSA_scrollRight() {
if (this.scrollingLimit > 0) {
this.scrollingLimit--;
if (this.scrollingLimit == 0) this.scrolling = false;
}
if (!this.scrolling) return;
this.scrollContent.scrollLeft += this.scrollStep;
this.scrollslider.style.left = 1 / this.scrollFactor * Math.abs(this.scrollContent.scrollLeft) + this.scrollButtonWidth + "px";
if (this.scrollContent.scrollLeft >= (this.scrollContent.scrollWidth - this.scrollContent.offsetWidth)) {
this.scrollContent.scrollLeft = (this.scrollContent.scrollWidth - this.scrollContent.offsetWidth);
this.scrollslider.style.left = this.scrollbar.offsetWidth - this.scrollButtonWidth - this.scrollslider.offsetWidth + "px";
return;
}
setTimeout("HSA_Ext_scrollRight(" + this.index + ")", 30);
}
function HSA_Ext_scrollRight(index) {
HSA_scrollAreas[index].scrollRight();
}
function HSA_handleMouseMove(evt) {
var sa = HSA_scrollAreas[((document.all && !window.opera) ? this.index : document.documentElement.scrollAreaIndex)];
var posy = 0;
if (!evt) var evt = window.event;
if (evt.pageX)
posy = evt.pageX;
else if (evt.clientX)
posy = evt.clientX;
if (document.all && !window.opera) {
posy += document.documentElement.scrollLeft;
}
var iNewY = posy - sa.iOffsetX - sa.leftPosition;
iNewY += sa.scrollButtonWidth;
if (iNewY < sa.scrollButtonWidth)
iNewY = sa.scrollButtonWidth;
if (iNewY > (sa.scrollbar.offsetWidth - sa.scrollButtonWidth) - sa.scrollslider.offsetWidth)
iNewY = (sa.scrollbar.offsetWidth - sa.scrollButtonWidth) - sa.scrollslider.offsetWidth;
sa.scrollslider.style.left = iNewY + "px";
sa.scrollIt();
}
function HSA_handleSliderMouseDown(evt) {
if (!(document.uniqueID && document.compatMode && !window.XMLHttpRequest)) {
document.onselectstart = function () {
return false;
}
document.onmousedown = function () {
return false;
}
}
var sa = HSA_scrollAreas[this.index];
if (document.all && !window.opera) {
sa.scrollslider.setCapture()
sa.iOffsetX = event.offsetX;
sa.scrollslider.onmousemove = HSA_handleMouseMove;
} else {
if (window.opera) {
sa.iOffsetX = event.offsetX;
} else {
sa.iOffsetX = evt.layerX;
}
document.documentElement.scrollAreaIndex = sa.index;
document.documentElement.addEventListener("mousemove", HSA_handleMouseMove, true);
document.documentElement.addEventListener("mouseup", HSA_handleSliderMouseLeft, true);
}
}
function HSA_handleSliderMouseLeft() {
if (!(document.uniqueID && document.compatMode && !window.XMLHttpRequest)) {
document.onmousedown = null;
document.onselectstart = null;
}
if (document.all && !window.opera) {
var sa = HSA_scrollAreas[this.index];
sa.scrollslider.onmousemove = null;
sa.scrollslider.releaseCapture();
sa.scrollIt();
} else {
var sa = HSA_scrollAreas[document.documentElement.scrollAreaIndex];
document.documentElement.removeEventListener("mousemove", HSA_handleMouseMove, true);
document.documentElement.removeEventListener("mouseup", HSA_handleSliderMouseLeft, true);
sa.scrollIt();
}
}
function HSA_handleResize() {
if (HSA_resizeTimer) {
clearTimeout(HSA_resizeTimer);
HSA_resizeTimer = 0;
}
HSA_resizeTimer = setTimeout("HSA_performResizeEvent()", 100);
}
function HSA_performResizeEvent() {
for (var i = 0; i < HSA_scrollAreas.length; i++)
HSA_scrollAreas[i].createScrollBar();
}
function HSA_handleMouseWheel(event) {
if (this.index != null) {
var sa = HSA_scrollAreas[this.index];
if (sa.scrollbar == null) return;
sa.scrolling = true;
sa.scrollingLimit = sa.wheelSensitivity;
var delta = 0;
if (!event) /* For IE. */
event = window.event;
if (event.wheelDelta) { /* IE/Opera. */
delta = event.wheelDelta / 120;
/*if (window.opera)
delta = -delta;*/
} else if (event.detail) { /** Mozilla case. */
delta = -event.detail / 3;
}
if (delta && sa.element.over) {
if (delta > 0)
sa.scrollLeft();
else
sa.scrollRight();
if (event.preventDefault)
event.preventDefault();
event.returnValue = false;
}
}
}
function HSA_handleSelectStart() {
event.returnValue = false;
}
function HSA_handleScrollbarClick(evt) {
var sa = HSA_scrollAreas[this.index];
var offsetX = (document.all ? event.offsetX : evt.layerX);
if (offsetX < (sa.scrollButtonWidth + sa.scrollslider.offsetWidth / 2))
sa.scrollslider.style.left = sa.scrollButtonWidth + "px";
else if (offsetX > (sa.scrollbar.offsetWidth - sa.scrollButtonWidth - sa.scrollslider.offsetWidth))
sa.scrollslider.style.left = sa.scrollbar.offsetWidth - sa.scrollButtonWidth - sa.scrollslider.offsetWidth + "px";
else {
sa.scrollslider.style.left = offsetX + sa.scrollButtonWidth - sa.scrollslider.offsetWidth / 2 + "px";
}
sa.scrollIt();
}
function HSA_handleOnScroll() {
event.srcElement.doScroll("pageLeft");
}
//--- common functions ----
function HSA_getElements(attrValue, tagName, ownerNode, attrName) //get Elements By Attribute Name
{
if (!tagName) tagName = "*";
if (!ownerNode) ownerNode = document;
if (!attrName) attrName = "name";
var result = [];
var nl = ownerNode.getElementsByTagName(tagName);
for (var i = 0; i < nl.length; i++) {
// if (nl.item(i).getAttribute(attrName) == attrValue)
// result.push(nl.item(i));
if (nl.item(i).className.indexOf(attrValue) != -1)
result.push(nl.item(i));
}
return result;
}
function getRealLeft(elem) {
var nLeft = 0;
if (elem) {
do {
nLeft += elem.offsetLeft - elem.scrollLeft;
elem = elem.offsetParent;
}
while (elem)
}
return nLeft;
}
|
/* ************************************************************************
qooxdoo - the new era of web development
http://qooxdoo.org
Copyright:
2004-2009 1&1 Internet AG, Germany, http://www.1und1.de
License:
MIT: https://opensource.org/licenses/MIT
See the LICENSE file in the project's top-level directory for details.
Authors:
* Thomas Herchenroeder (thron7)
************************************************************************ */
/**
* This is the main application class of your custom application "showcase_i18n"
*
* @tag showcase
*/
qx.Class.define("qxl.demobrowser.demo.showcase.Translation",
{
extend : qx.application.Standalone,
/*
*****************************************************************************
MEMBERS
*****************************************************************************
*/
members :
{
/**
* This method contains the initial application code and gets called
* during startup of the application
* @lint ignoreDeprecated(alert)
*/
main : function()
{
// Call super class
this.base(arguments);
// Enable logging in debug variant
if ((qx.core.Environment.get("qx.debug")))
{
// support native logging capabilities, e.g. Firebug for Firefox
qx.log.appender.Native;
// support additional cross-browser console. Press F7 to toggle visibility
qx.log.appender.Console;
}
var container = new qx.ui.container.Composite(new qx.ui.layout.Grid(8, 8));
this.getRoot().add(container, {top: 20, left: 20});
var part0Label = new qx.ui.basic.Label("<b>Locale and language:</b>");
part0Label.setRich(true);
container.add(part0Label, {row: 0,column: 0, colSpan: 3});
// Choose Locale
var l0 = new qx.ui.basic.Label("Choose Locale:");
l0.setMarginTop(5);
l0.setAlignY('middle');
container.add(l0, {row: 1, column: 0});
var localeManager = qx.locale.Manager.getInstance();
var locales = localeManager.getAvailableLocales().sort();
var currentLocale = localeManager.getLocale();
var select = new qx.ui.form.SelectBox();
select.setAllowGrowY(false);
select.setAlignY('middle');
var defaultListItem = null;
for (var i=0; i<locales.length; i++)
{
var listItem =new qx.ui.form.ListItem(locales[i]);
select.add(listItem);
if ((!defaultListItem && locales[i] == "en") || locales[i] == currentLocale) {
defaultListItem = listItem;
}
}
select.addListener("changeSelection", function(e)
{
var locale = e.getData()[0].getLabel();
qx.locale.Manager.getInstance().setLocale(locale);
});
container.add(select, {row: 1, column: 1});
// Listening on locale change and act on it
// show locale and territory
var l1 = new qx.ui.basic.Label('Locale');
l1.setMarginTop(5);
l1.setWidth(80);
var l2 = new qx.ui.basic.Label('Territory');
l2.setMarginTop(5);
l2.setWidth(80);
var l3 = new qx.ui.basic.Label('Language');
l3.setMarginTop(5);
l3.setWidth(80);
var infoContainer = new qx.ui.container.Composite(new qx.ui.layout.VBox(3));
infoContainer.add(l1);infoContainer.add(l2);infoContainer.add(l3);
container.add(infoContainer, {row: 1, column: 2});
qx.locale.Manager.getInstance().addListener("changeLocale", function()
{
var manager = qx.locale.Manager.getInstance();
l1.setValue('Locale: '+manager.getLocale());
l2.setValue('Territory: ' + manager.getTerritory());
l3.setValue('Language: '+manager.getLanguage());
translateLabels.apply(this);
addTrLabel.setValue("Add translation<br>at runtime for: <b>"+localeManager.getLocale() +"</b>");
}, this);
function translateLabels()
{
// strings here must be present in the .po files in order to get translated.
translation1.setValue(this.tr("Hello World"));
translation1.setToolTipText("Simple Translate: this.tr('Hello World')");
var applesNumber = parseInt(numberOfApples.getSelection()[0].getLabel());
translation2.setValue(this.trn("I have an apple", "I have %1 apples", applesNumber, applesNumber));
translation2.setToolTipText("Singular/Plural Translate: this.trn('I have an apple', I have %1 apples, " + applesNumber + ", applesNumber)");
translation3.setValue(this.trc("The mammal fox that is.", "The quick brown fox"));
translation3.setToolTipText("with .po comment: this.trc('The mammal fox that is.', 'The quick brown fox')");
translation4.setValue(this.marktr("Orange"));
translation4.setToolTipText("Mark the string 'Orange' for later translation so we do not forget it: this.marktr('Orange')");
var messageId = showMessageId.getValue();
if(messageId && messageId.length>0) {
showTrLabel.setValue(localeManager.translate(messageId,[],localeManager.getLocale()));
}
}
var part1Label = new qx.ui.basic.Label("<b>Static translation [found in .po files]. Hover the labels below to see more info.</b>");
part1Label.setRich(true);
part1Label.setMarginTop(15);
container.add(part1Label, {row: 2,column: 0, colSpan: 4});
var column1Header = new qx.ui.basic.Label("<i>MessageId</i>");
column1Header.setRich(true);
container.add(column1Header, {row: 3,column: 1});
var column2Header = new qx.ui.basic.Label("<i>Translated Text</i>");
column2Header.setRich(true);
container.add(column2Header, {row: 3,column: 2});
var translation1MId = new qx.ui.basic.Label("Hello World");
container.add(translation1MId, {row: 4,column: 1});
// Simple Translate
var translation1 = new qx.ui.basic.Label(this.tr("Hello World"));
container.add(translation1, {row: 4,column: 2});
var translation1Info = new qx.ui.basic.Label("Simple messageId translation");
container.add(translation1Info, {row: 4,column: 3});
// Singular/Plural Translate
var appleNumberSelectBoxLabel = new qx.ui.basic.Label("Number of apples:");
appleNumberSelectBoxLabel.setAlignX('right');
appleNumberSelectBoxLabel.setAlignY('bottom');
container.add(appleNumberSelectBoxLabel, {row: 5,column: 0});
var numberOfApples = new qx.ui.form.SelectBox();
for (var i=1; i<5; i++)
{
var tempItem = new qx.ui.form.ListItem(i + "");
numberOfApples.add(tempItem);
}
numberOfApples.setToolTipText("Number of apples");
numberOfApples.setAlignY('top');
numberOfApples.setAlignX('right');
container.add(numberOfApples, {row: 6, column: 0});
var translation2MId = new qx.ui.basic.Label("I have an apple");
translation2MId.setAlignY('middle');
container.add(translation2MId, {row: 5, column: 1, rowSpan: 2});
var translation2 = new qx.ui.basic.Label(this.trn("I have an apple", "I have %1 apples", 1, 1));
translation2.setAlignY('middle');
container.add(translation2, {row: 5, column: 2, rowSpan: 2});
var translation2Info = new qx.ui.basic.Label("Singular/Plural Translate<br>Choose a number from the select box<br>to see plural translation");
translation2Info.setAlignY('middle');
translation2Info.setRich(true);
container.add(translation2Info, {row: 5,column: 3, rowSpan: 2});
numberOfApples.addListener("changeSelection", function(e)
{
translateLabels.apply(this);
});
var translation3MId = new qx.ui.basic.Label("The quick brown fox");
container.add(translation3MId, {row: 7, column: 1});
// Translate with .po comment
var translation3 = new qx.ui.basic.Label(this.trc("The mammal fox that is.", "The quick brown fox"));
translation3.setWidth(140);
container.add(translation3, {row: 7, column: 2});
var translation3Info = new qx.ui.basic.Label("A comment: 'The mammal fox that is.'<br>is added in the .po file");
translation3Info.setRich(true);
container.add(translation3Info, {row: 7,column: 3});
var translation4MId = new qx.ui.basic.Label("Orange");
container.add(translation4MId, {row: 8, column: 1});
// Mark the string "Orange" for later translation so we do not forget it
// also we could grep for marktr calls and get them all for translation
var translation4 = new qx.ui.basic.Label(this.marktr("Orange"));
container.add(translation4, {row: 8, column: 2});
var translation4Info = new qx.ui.basic.Label("Mark the string 'Orange' for later<br>translation so we do not forget it");
translation4Info.setRich(true);
container.add(translation4Info, {row: 8,column: 3});
var part2Label = new qx.ui.basic.Label("<b>Dynamic translation. This is added at runtime.</b>");
part2Label.setRich(true);
part2Label.setMarginTop(15);
container.add(part2Label, {row: 9,column: 0, colSpan: 3});
var addTrLabel = new qx.ui.basic.Label("Add translation<br>at runtime for: <b>" + localeManager.getLocale() +"</b>");
addTrLabel.setRich(true);
addTrLabel.setWidth(120);
container.add(addTrLabel, {row: 10,column: 0});
var inputMessageId = new qx.ui.form.TextField("");
inputMessageId.setToolTipText("MessageId");
container.add(inputMessageId, {row: 10,column: 1});
var inputDTranslation = new qx.ui.form.TextField("");
inputDTranslation.setToolTipText("Translation");
container.add(inputDTranslation, {row: 10,column: 2});
var addTranslationButton = new qx.ui.form.Button("Add Translation");
addTranslationButton.setAllowGrowY(false);
container.add(addTranslationButton, {row: 10,column: 3});
addTranslationButton.addListener("execute", function (e)
{
var map = {};
map[inputMessageId.getValue()] = inputDTranslation.getValue();
localeManager.addTranslation(localeManager.getLocale(),map);
alert(inputDTranslation.getValue() + " has been added for messageId: " + inputMessageId.getValue() + " for locale: " + localeManager.getLocale());
}, this);
var showLabel = new qx.ui.basic.Label("MessageId:");
container.add(showLabel, {row: 11,column: 0});
var showMessageId = new qx.ui.form.TextField("");
showMessageId.setToolTipText("MessageId");
container.add(showMessageId, {row: 11,column: 1});
var showTranslationButton = new qx.ui.form.Button("show Translation");
container.add(showTranslationButton, {row: 11,column: 2});
showTranslationButton.setAllowGrowY(false);
showTranslationButton.addListener("execute", function (e)
{
var messageId = showMessageId.getValue();
showTrLabel.setValue(localeManager.translate(messageId,[],localeManager.getLocale()));
}, this);
var showTrLabel = new qx.ui.basic.Label("tap 'Show Translation' button to translate<br>the messageId in the current selected locale");
showTrLabel.setRich(true);
showTrLabel.setAlignY('middle');
container.add(showTrLabel, {row: 11,column: 3});
var addNewLocaleLabel = new qx.ui.basic.Label("Add new Locale<br> at runtime");
addNewLocaleLabel.setRich(true);
container.add(addNewLocaleLabel, {row: 12,column: 0});
var inputNewLocaleName = new qx.ui.form.TextField("");
inputNewLocaleName.setPlaceholder("en_QX");
inputNewLocaleName.setToolTipText("Locale Name (ex: en_QX)");
container.add(inputNewLocaleName, {row: 12,column: 1});
var addNewLocaleButton = new qx.ui.form.Button("Add new Locale");
addNewLocaleButton.setAllowGrowY(false);
container.add(addNewLocaleButton, {row: 12,column: 2});
addNewLocaleButton.addListener("execute", function (e)
{
var newLocaleName = inputNewLocaleName.getValue();
if(newLocaleName!=null && newLocaleName.length<1)
{
alert("new Locale must not be empty string");
return;
}
var locales = localeManager.getAvailableLocales();
if(locales.indexOf(newLocaleName)!=-1)
{
alert(newLocaleName + " already exists");
}
else
{
localeManager.addTranslation(newLocaleName,{"demo": "demo"});
alert(newLocaleName + " has been added");
select.add(new qx.ui.form.ListItem(newLocaleName));
}
}, this);
if (defaultListItem) {
select.setSelection([defaultListItem]);
}
// data binding between the 2 text fields
inputMessageId.bind("value", showMessageId, "value");
showMessageId.bind("value", inputMessageId, "value");
return;
}
}
});
|
import React, { Component } from "react";
import { Label, Col, Row } from "reactstrap";
import Sidenav from "../SideNav";
import Subjects from "./Subjects";
import Labs from "./Labs";
class Subject extends Component {
constructor(props) {
super(props);
this.state = {
selectedOption: "option1"
};
this.handleOptionChange = this.handleOptionChange.bind(this);
}
handleOptionChange(event) {
this.setState({
selectedOption: event.target.value
});
}
render() {
function RenderComponent({ selectedOption }) {
if (selectedOption === "option1") {
return <Subjects />;
} else {
return <Labs />;
}
}
return (
<div className="page">
<Row className="occupy">
<Col sm="3">
<Sidenav />
</Col>
<Col sm="9">
<div className="container mt-5 show">
<h2 id="addsub"> Add Subjects</h2>
<div className="radio choice mt-5">
<Label>
<input
type="radio"
value="option1"
checked={this.state.selectedOption === "option1"}
onChange={this.handleOptionChange}
/>
Add Theory Subject
</Label>
</div>
<div className="radio choice">
<Label>
<input
type="radio"
value="option2"
checked={this.state.selectedOption === "option2"}
onChange={this.handleOptionChange}
/>
Add Lab
</Label>
</div>
<RenderComponent selectedOption={this.state.selectedOption} />
</div>
</Col>
</Row>
</div>
);
}
}
export default Subject;
|
(() => {
const monaco = "https://cdn.jsdelivr.net/npm/monaco-editor@0.27.0";
requirejs.config({
urlArgs: (_, url) => url.startsWith(monaco) || url.includes("-")
? ""
: "?v={{version}}",
paths: {
vs: `${monaco}/min/vs`,
},
});
window.MonacoEnvironment = {
getWorkerUrl: (_workerId, _label) =>
`data:text/javascript;charset=utf-8,${encodeURIComponent(`
self.MonacoEnvironment = {
baseUrl: "${monaco}/min/"
};
importScripts("${monaco}/min/vs/base/worker/workerMain.js");
`)}`,
};
require(["./index"], main => main());
})();
|
const { getOptions } = require( "loader-utils" );
const { optimize } = require( "svgo" );
/**
* @param {string} source
* @this {LoaderContext}
* @return {string}
*/
module.exports = function svgoLoader( source ) {
const {
plugins = [{ name: "preset-default" }],
...options
} = getOptions( this );
const result = optimize( source, {
...options,
path: this.resourcePath,
plugins
});
if ( result.error ) {
throw result.error;
}
return result.data;
};
|
// protect function from too-many re-entries (recursive)
// protect loops from infinite or too-many re-entries
// Based on jsbin loop protect (https://github.com/jsbin/loop-protect)
/*
before:
====
n = 0;
while(n++ < 100000000) {
doSomething();
}
after:
===
n = 0;
while(n++ < 100000000) {
__guard.enterLoop(uid, row, column);
doSomething();
}
Note: it does not report line number, since we do not map to original line number yet
(maybe use map file or recast later on)
*/
const { CostTable } = require('../gascost')
const generateInside = ({ t, id, line, ch, gas }) => {
return t.blockStatement([
t.expressionStatement(t.callExpression(
t.memberExpression(t.identifier('__guard'), t.identifier('enterFunction')),
[t.stringLiteral(id.name), t.numericLiteral(line), t.numericLiteral(ch)]
)),
t.expressionStatement(t.callExpression(
t.memberExpression(t.identifier('__guard'), t.identifier('usegas')),
[t.numericLiteral(gas)]
))
])
}
const protect = t => path => {
let line = 0; let ch = 0
if (path.node.loc) {
line = path.node.loc.start.line
ch = path.node.loc.start.column
}
const id = path.scope.generateUidIdentifierBasedOnNode(path.node.id)
const inside = generateInside({ t, id, line, ch, gas: CostTable.EnterFunction })
const body = path.get('body')
// It is not possible to re-entry for literal function
if (body.isLiteral()) return
// if we have an expression statement, convert it to a block
if (!t.isBlockStatement(body)) {
try {
body.replaceWith(t.blockStatement([body.node]))
} catch (err) {
body.replaceWith(t.blockStatement([t.returnStatement(body.node)]))
}
} else if (!body.node.body.length) {
return
}
body.unshiftContainer('body', inside)
}
module.exports = ({ types: t }) => {
return {
name: 'function-entry-guard',
visitor: {
FunctionDeclaration: protect(t),
FunctionExpression: protect(t),
ArrowFunctionExpression: protect(t),
ObjectMethod: protect(t),
ClassMethod: protect(t)
}
}
}
|
import Vue from 'vue'
import Router from 'vue-router'
import routes from './routers'
import store from '@/store'
import iView from 'iview'
import {canTurnTo} from '@/libs/util'
import config from '@/config'
Vue.use(Router)
const router = new Router({
routes,
mode: 'history'
})
const turnTo = (to, access, next) => {
if (canTurnTo(to.name, access, routes)) next() // 有权限,可访问
else next({replace: true, name: 'error_401'}) // 无权限,重定向到401页面
}
router.beforeEach((to, from, next) => {
iView.LoadingBar.start()
const userInfo = store.getters.getUserInfo;
var token = "";
if (userInfo) {
token = userInfo.token;
}
if (!token && to.name !== config.loginName) {
// 未登录且要跳转的页面不是登录页
next({
name: config.loginName // 跳转到登录页
})
} else if (!token && to.name === config.loginName) {
// 未登陆且要跳转的页面是登录页
next() // 跳转
} else if (token && to.name === config.loginName) {
// 已登录且要跳转的页面是登录页
next({
name: config.homeName // 跳转到homeName页
})
} else {
if (token) {
// turnTo(to, store.state.user.access, next)
if (to.path === '/wh-law-firm-pc/') {
next({
name: config.homeName
})
} else {
next();
}
} else {
store.commit("setUserInfo", null);
next({
name: config.loginName
})
}
}
})
router.afterEach(to => {
iView.LoadingBar.finish()
window.scrollTo(0, 0)
})
export default router
|
import React,{Fragment,Children} from "react"
import memoize from "memoize-one"
import {shallowEqual} from "recompose"
import ComposedAllTrigger from "./composed-all-trigger"
import UseCached from "./use-cached"
/**
* make component always update (by calling .render), so AllComposedTrigger would be triggered to correctly set allComposed
* but at first clear last composed
*
* Recompose:
* 1. cancel and keep last composed according to props/state/computed/context
* in render:
* 2. append last composed
* 3. compose not composed
* ** The cache mechanism is to use keyed array react elements
* To make everything cacheable, component can customize appendLastComposed to define itself cache policy
* shoul lastComposed be cleared
*
* AtomCollector: is inline conainer and NoChild in Paragraph, Paragraph.nextAvailableSpace would give null for AtomCollector test.
* AtomCollector is just to collect atom without either block or inline layout, so the cache policy is sure as
* ** if not change, cache can always be applicable
* ** AtomCollector should be either all composed, or nothing composed
* ** NoChild also works like AtomCollector from cache perspective
*/
export default A=>{
class Recomposable extends A{
static displayName=`recomposable-${A.displayName}`
constructor(){
super(...arguments)
this.computed.lastComposed=[]
this.computed.composedUUID=Date.now()
}
recomposable_createComposed2Parent(){
return super.createComposed2Parent(...arguments)
}
//cache last composed for next time
createComposed2Parent(){
const composed=this.recomposable_createComposed2Parent(...arguments)
this.computed.lastComposed.push(composed)
return composed
}
//always call render to compose to sync onAllChildrenComposed
shouldComponentUpdate(next){
/**
* composedUUID to identify each compose, so createComposed2Parent can be cached.
*/
this.computed.composedUUID=Date.now()
this.context.mount && this.context.mount(this)
const changed=next.hash!=this.props.hash
if(changed || !this.isAllChildrenComposed()){
//clear last allComposed, so it can be reset
this.computed.allComposed=undefined
}
if(this.context.shouldContinueCompose && !this.context.shouldContinueCompose(this,...arguments)){
return false
}
this.cancelUnusableLastComposed(...arguments)
return true
}
/**
* to remove unusable composed, and keep usable, then append usable to parent in render
* all computed should be synced here
* @param {*} nextProps
* @param {*} nextState
*/
cancelUnusableLastComposed(props){
if(this.isAtom && shallowEqual(props,this.props)){
return
}
this._cancelAllLastComposed()
}
_cancelAllLastComposed(){
this.computed.composed=[]
this.computed.lastComposed=[]
this.computed.allComposed=undefined
}
/**
* * all computed should be synced here again based on cancelUnusableLastComposed
* @return
* number: need render from the index
* true: success, render nothing,
* others: fail, render all
*/
appendLastComposed(){
if(this.isAtom){
this.computed.lastComposed.forEach(a=>this.context.parent.appendComposed(a))
return true
}
}
//last composed + left
render(){
if(this.computed.allComposed || this.computed.lastComposed.length>0){
const appended=this.appendLastComposed()
const children=this.childrenArray(this.props.children)
const tryUseCached=a=>UseCached.create(a,this.context.getComposer)
if(typeof(appended)=="number" && appended>-1){
console.debug(`${this.getComposeType()}[${this.props.id}] used ${appended+1} children caches`)
return (
<Fragment>
{[//keyed array
...children.slice(0,appended+1).map(tryUseCached),
...children.slice(appended+1),
]}
{ComposedAllTrigger.createElement(this)}
</Fragment>
)
}else if(appended===true){
console.debug(`${this.getComposeType()}[${this.props.id}] used all children caches`)
return (
<Fragment>
{children.map(tryUseCached)}
{this.onUseAllCached()}
</Fragment>
)
}
}
console.debug(`${this.getComposeType()}[${this.props.id}] used 0 children caches`)
return super.render()
}
onUseAllCached(){
}
childIdOf(composed,id){
const extract=({props:{"data-content":a,children}})=>(id=a)!=undefined ?
true : Children.toArray(children).findIndex(extract)!=-1;
extract(composed)
if(this.childrenArray(this.props.children).findIndex(a=>a && a.props.id==id)!=-1)
return id
}
childrenNeedRecompose=memoize((b,a)=>{
const next=Children.toArray(b.children)
const current=this.childrenArray(a.children)
const changedIndex=current.findIndex((a1,i,_,$,b1=next[i])=>!(b1?.props.id==a1?.props.id && b1?.props.hash==a1?.props.hash))
if(changedIndex!=-1){
return current.slice(changedIndex).map(a=>a && a.props.id)
}
return Object.assign([],{sizeChanged:current.length!=next.length})
})
}
return Recomposable
}
|
const app = require('../../src/app')
describe('\'measurements\' service', () => {
it('registered the service', () => {
const service = app.service('measurements')
expect(service).toBeTruthy()
})
})
|
$(document).ready(function() {
$("#current_password").keyup(function () {
var current_password = $("#current_password").val();
$.ajax({
type: "post",
url: "/admin/check-current-password",
data: {current_password},
success: function (res) {
if (res == "false"){
$("#checkCurrentpassword").html("<span style='color: red;'>current password is incorrect</span>")
}else if(res == "true"){
$("#checkCurrentpassword").html("<span style='color: green;'>current password is correct</span>")
}
},
error: function () {
alert("errors");
}
});
});
// Make section active or inactive
$( ".updateSectionStatus" ).click( function() {
var status = $( this ).text();
var section_id = $( this ).attr('section_id');
$.ajax({
url: "/admin/update-section-status",
type: "Post",
data: { status, section_id},
success: function (res) {
if (res.status == 0){
$("#section-" + res.section_id).text("Inactive");
}else if( res.status == 1){
$("#section-" + res.section_id).text("Active");
}
},
error: function () {
console.log("errors");
}
});
});
// Make category active or inactive
$( ".updateCategoryStatus" ).click( function() {
var status = $( this ).text();
var category_id = $( this ).attr('category_id');
$.ajax({
url: "/admin/update-category-status",
type: "Post",
data: { status, category_id},
success: function (res) {
if (res.status == 0){
$("#category-" + res.category_id).text("Inactive");
}else if( res.status == 1){
$("#category-" + res.category_id).text("Active");
}
},
error: function () {
console.log("errors");
}
});
});
// Append Category Level
$('#section_id').change(function () {
var section_id = $(this).val();
$.ajax({
type: 'post',
url: '/admin/append-categories-level',
data: { section_id: section_id},
success: function (res) {
$('#appendCategoriesLevel').html(res);
},
error: function () {
alert("Error...");
}
});
});
// Simple jQuery Alert
/*
$('.confirmDelete').click(function () {
var name = $(this).attr('name');
if (confirm("Are you sure that you want to delete this " + name + " ? ")){
return true;
}
return false;
});
*/
// Category Delete using sweet alert
$('.confirmDelete').click(function () {
var record = $(this).attr('record');
var recordId = $(this).attr('recordId');
Swal.fire({
title: 'Are you sure?',
text: "You won't be able to revert this!",
icon: 'warning',
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'Yes, delete it!'
}).then((result) => {
if (result.value) {
window.location.href = "/admin/delete-" + record + "/" + recordId;
}
});
});
// Make product active or inactive
$( ".updateProductStatus" ).click( function() {
var status = $( this ).text();
var product_id = $( this ).attr('product_id');
$.ajax({
url: "/admin/update-product-status",
type: "post",
data: { status: status, product_id: product_id},
success: function (res) {
if (res.status == 0){
$("#product-" + res.product_id).text("Inactive");
}else if( res.status == 1){
$("#product-" + res.product_id).text("Active");
}
},
error: function () {
console.log("errors");
}
});
});
});
|
let url = base_url+"/categorias/";
$(document).ready(function(){
/**
* Procedemos a cargar los datos de la tabla
*/
$('#tabla').DataTable(); // End of DataTable
});
$("#form_add").on('submit', function(e){
e.preventDefault();
$(this).parsley().validate();
if ($(this).parsley().isValid()){
$("#btn_add").prop("disabled",true)
save_data();
}
});
$("#form_edit").on('submit', function(e){
e.preventDefault();
$(this).parsley().validate();
if ($(this).parsley().isValid()){
$("#btn_add").prop("disabled",true)
edit_data();
}
});
function save_data(){
let form = $("#form_add");
let formdata = false;
if (window.FormData) {
formdata = new FormData(form[0]);
}
$.ajax({
type: 'POST',
url: url+'store',
cache: false,
data: formdata ? formdata : form.serialize(),
contentType: false,
processData: false,
dataType: 'json',
success: function (data) {
notification(data.type,data.title,data.msg);
if (data.type == "success") {
setTimeout("reload();", 1500);
}
}
});
}
function edit_data(){
let form = $("#form_edit");
let formdata = false;
if (window.FormData) {
formdata = new FormData(form[0]);
}
$.ajax({
type: 'POST',
url: url+'update',
cache: false,
data: formdata ? formdata : form.serialize(),
contentType: false,
processData: false,
dataType: 'json',
success: function (data) {
notification(data.type,data.title,data.msg);
if (data.type == "success") {
setTimeout("reload();", 1500);
}
}
});
}
$(document).on("click",".eliminar_elemento", function(event)
{
event.preventDefault()
let id_row = $(this).attr("id_detalle");
let dataString = "id=" + id_row;
Swal.fire({
title: 'Alerta!!',
text: "Estas seguro de eliminar este regitro?!",
type: 'error',
target:'#page-top',
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'Aceptar',
cancelButtonText: 'Cancelar',
}).then((result) => {
if (result.value) {
$.ajax({
type: "POST",
url: url+"destroy",
data: dataString,
dataType: 'json',
success: function (data) {
notification(data.type,data.title,data.msg);
if (data.type == "success") {
setTimeout("reload();", 1500);
}
}
});
}
});
});
function reload() {
location.href = url;
}
|
import uuid from 'uuid';
import DBManager from '../managers/DBManager';
const studentSchema = {
id: {
type: String,
hashKey: true
},
firstName: String,
lastName: String,
major: String,
semester: Number,
createdAt: String,
updatedAt: String
};
export default class Student extends DBManager {
id;
firstName;
lastName;
major;
semester;
createdAt;
updatedAt;
constructor(id, firstName, lastName, major, semester, createdAt, updatedAt) {
super(process.env.STUDENT_TABLE_NAME, studentSchema);
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
this.major = major;
this.semester = semester;
this.createdAt = createdAt;
this.updatedAt = updatedAt;
}
toDBFormat() {
return {
...this,
updatedAt: this.updatedAt.toString(),
createdAt: this.createdAt.toString()
};
}
getKey() {
return this.id;
}
// eslint-disable-next-line class-methods-use-this
fromDBResponse(item) {
const {
id,
firstName,
lastName,
major,
semester,
createdAt,
updatedAt,
} = item;
return new Student (
id,
firstName,
lastName,
major,
semester,
createdAt,
updatedAt
);
}
static newStudent(firstName, lastName, major, semester) {
const id = uuid();
return new Student(
id,
firstName,
lastName,
major,
semester,
new Date(),
new Date()
);
}
}
|
"use strict";
exports.__esModule = true;
exports.c_tabs__scroll_button_before_BorderWidth = {
"name": "--pf-c-tabs__scroll-button--before--BorderWidth",
"value": "1px",
"var": "var(--pf-c-tabs__scroll-button--before--BorderWidth)"
};
exports["default"] = exports.c_tabs__scroll_button_before_BorderWidth;
|
/**
* @preserve
* jquery.layout 1.4.4
* $Date: 2014-11-29 08:00:00 (Sat, 29 November 2014) $
* $Rev: 1.0404 $
*
* Copyright (c) 2014 Kevin Dalman (http://jquery-dev.com)
* Based on work by Fabrizio Balliano (http://www.fabrizioballiano.net)
*
* Dual licensed under the GPL (http://www.gnu.org/licenses/gpl.html)
* and MIT (http://www.opensource.org/licenses/mit-license.php) licenses.
*
* SEE: http://layout.jquery-dev.com/LICENSE.txt
*
* Changelog: http://layout.jquery-dev.com/changelog.cfm
*
* Docs: http://layout.jquery-dev.com/documentation.html
* Tips: http://layout.jquery-dev.com/tips.html
* Help: http://groups.google.com/group/jquery-ui-layout
*/
//<div class="ui-layout-east">东</div>
//<div class="ui-layout-south">南</div>
//<div class="ui-layout-west">西</div>
//<div class="ui-layout-north">北</div>
//<div class="ui-layout-center">中</div>
//<script>
//$('body').layout({});
//</script>
/* JavaDoc Info: http://code.google.com/closure/compiler/docs/js-for-compiler.html
* {!Object} non-nullable type (never NULL)
* {?string} nullable type (sometimes NULL) - default for {Object}
* {number=} optional parameter
* {*} ALL types
*/
/* TODO for jQ 2.x
* check $.fn.disableSelection - this is in jQuery UI 1.9.x
*/
// NOTE: For best readability, view with a fixed-width font and tabs equal to 4-chars
;(function ($) {
// alias Math methods - used a lot!
var min = Math.min
, max = Math.max
, round = Math.floor
, isStr = function (v) { return $.type(v) === "string"; }
/**
* @param {!Object} Instance
* @param {Array.<string>} a_fn
*/
, runPluginCallbacks = function (Instance, a_fn) {
if ($.isArray(a_fn))
for (var i=0, c=a_fn.length; i<c; i++) {
var fn = a_fn[i];
try {
if (isStr(fn)) // 'name' of a function
fn = eval(fn);
if ($.isFunction(fn))
g(fn)( Instance );
} catch (ex) {}
}
function g(f) {
return f;
} // compiler hack
}
;
/*
* GENERIC $.layout METHODS - used by all layouts
*/
$.layout = {
version: "1.4.4"
, revision: 1.0404 // eg: ver 1.4.4 = rev 1.0404 - major(n+).minor(nn)+patch(nn+)
// $.layout.browser REPLACES $.browser
, browser: {} // set below
// *PREDEFINED* EFFECTS & DEFAULTS
// MUST list effect here - OR MUST set an fxSettings option (can be an empty hash: {})
, effects: {
// Pane Open/Close Animations
slide: {
all: { duration: "fast" } // eg: duration: 1000, easing: "easeOutBounce"
, north: { direction: "up" }
, south: { direction: "down" }
, east: { direction: "right"}
, west: { direction: "left" }
}
, drop: {
all: { duration: "slow" }
, north: { direction: "up" }
, south: { direction: "down" }
, east: { direction: "right"}
, west: { direction: "left" }
}
, scale: {
all: { duration: "fast" }
}
// these are not recommended, but can be used
, blind: {}
, clip: {}
, explode: {}
, fade: {}
, fold: {}
, puff: {}
// Pane Resize Animations
, size: {
all: { easing: "swing" }
}
}
// INTERNAL CONFIG DATA - DO NOT CHANGE THIS!
, config: {
optionRootKeys: "effects,panes,north,south,west,east,center".split(",")
, allPanes: "north,south,west,east,center".split(",")
, borderPanes: "north,south,west,east".split(",")
, oppositeEdge: {
north: "south"
, south: "north"
, east: "west"
, west: "east"
}
// offscreen data
, offscreenCSS: { left: "-99999px", right: "auto" } // used by hide/close if useOffscreenClose=true
, offscreenReset: "offscreenReset" // key used for data
// CSS used in multiple places
, hidden: { visibility: "hidden" }
, visible: { visibility: "visible" }
// layout element settings
, resizers: {
cssReq: {
position: "absolute"
, padding: 0
, margin: 0
, fontSize: "1px"
, textAlign: "left" // to counter-act "center" alignment!
, overflow: "hidden" // prevent toggler-button from overflowing
// SEE $.layout.defaults.zIndexes.resizer_normal
}
, cssDemo: { // DEMO CSS - applied if: options.PANE.applyDemoStyles=true
background: "#DDD"
, border: "none"
}
}
, togglers: {
cssReq: {
position: "absolute"
, display: "block"
, padding: 0
, margin: 0
, overflow: "hidden"
, textAlign: "center"
, fontSize: "1px"
, cursor: "pointer"
, zIndex: 1
}
, cssDemo: { // DEMO CSS - applied if: options.PANE.applyDemoStyles=true
background: "#AAA"
}
}
, content: {
cssReq: {
position: "relative" /* contain floated or positioned elements */
}
, cssDemo: { // DEMO CSS - applied if: options.PANE.applyDemoStyles=true
overflow: "auto"
, padding: "10px"
}
, cssDemoPane: { // DEMO CSS - REMOVE scrolling from 'pane' when it has a content-div
overflow: "hidden"
, padding: 0
}
}
, panes: { // defaults for ALL panes - overridden by 'per-pane settings' below
cssReq: {
position: "absolute"
, margin: 0
// $.layout.defaults.zIndexes.pane_normal
}
, cssDemo: { // DEMO CSS - applied if: options.PANE.applyDemoStyles=true
padding: "10px"
, background: "#FFF"
, border: "1px solid #BBB"
, overflow: "auto"
}
}
, north: {
side: "top"
, sizeType: "Height"
, dir: "horz"
, cssReq: {
top: 0
, bottom: "auto"
, left: 0
, right: 0
, width: "auto"
// height: DYNAMIC
}
}
, south: {
side: "bottom"
, sizeType: "Height"
, dir: "horz"
, cssReq: {
top: "auto"
, bottom: 0
, left: 0
, right: 0
, width: "auto"
// height: DYNAMIC
}
}
, east: {
side: "right"
, sizeType: "Width"
, dir: "vert"
, cssReq: {
left: "auto"
, right: 0
, top: "auto" // DYNAMIC
, bottom: "auto" // DYNAMIC
, height: "auto"
// width: DYNAMIC
}
}
, west: {
side: "left"
, sizeType: "Width"
, dir: "vert"
, cssReq: {
left: 0
, right: "auto"
, top: "auto" // DYNAMIC
, bottom: "auto" // DYNAMIC
, height: "auto"
// width: DYNAMIC
}
}
, center: {
dir: "center"
, cssReq: {
left: "auto" // DYNAMIC
, right: "auto" // DYNAMIC
, top: "auto" // DYNAMIC
, bottom: "auto" // DYNAMIC
, height: "auto"
, width: "auto"
}
}
}
// CALLBACK FUNCTION NAMESPACE - used to store reusable callback functions
, callbacks: {}
, getParentPaneElem: function (el) {
// must pass either a container or pane element
var $el = $(el)
, layout = $el.data("layout") || $el.data("parentLayout");
if (layout) {
var $cont = layout.container;
// see if this container is directly-nested inside an outer-pane
if ($cont.data("layoutPane")) return $cont;
var $pane = $cont.closest("."+ $.layout.defaults.panes.paneClass);
// if a pane was found, return it
if ($pane.data("layoutPane")) return $pane;
}
return null;
}
, getParentPaneInstance: function (el) {
// must pass either a container or pane element
var $pane = $.layout.getParentPaneElem(el);
return $pane ? $pane.data("layoutPane") : null;
}
, getParentLayoutInstance: function (el) {
// must pass either a container or pane element
var $pane = $.layout.getParentPaneElem(el);
return $pane ? $pane.data("parentLayout") : null;
}
, getEventObject: function (evt) {
return typeof evt === "object" && evt.stopPropagation ? evt : null;
}
, parsePaneName: function (evt_or_pane) {
var evt = $.layout.getEventObject( evt_or_pane )
, pane = evt_or_pane;
if (evt) {
// ALWAYS stop propagation of events triggered in Layout!
evt.stopPropagation();
pane = $(this).data("layoutEdge");
}
if (pane && !/^(west|east|north|south|center)$/.test(pane)) {
$.layout.msg('LAYOUT ERROR - Invalid pane-name: "'+ pane +'"');
pane = "error";
}
return pane;
}
// LAYOUT-PLUGIN REGISTRATION
// more plugins can added beyond this default list
, plugins: {
draggable: !!$.fn.draggable // resizing
, effects: {
core: !!$.effects // animimations (specific effects tested by initOptions)
, slide: $.effects && ($.effects.slide || ($.effects.effect && $.effects.effect.slide)) // default effect
}
}
// arrays of plugin or other methods to be triggered for events in *each layout* - will be passed 'Instance'
, onCreate: [] // runs when layout is just starting to be created - right after options are set
, onLoad: [] // runs after layout container and global events init, but before initPanes is called
, onReady: [] // runs after initialization *completes* - ie, after initPanes completes successfully
, onDestroy: [] // runs after layout is destroyed
, onUnload: [] // runs after layout is destroyed OR when page unloads
, afterOpen: [] // runs after setAsOpen() completes
, afterClose: [] // runs after setAsClosed() completes
/*
* GENERIC UTILITY METHODS
*/
// calculate and return the scrollbar width, as an integer
, scrollbarWidth: function () { return window.scrollbarWidth || $.layout.getScrollbarSize('width'); }
, scrollbarHeight: function () { return window.scrollbarHeight || $.layout.getScrollbarSize('height'); }
, getScrollbarSize: function (dim) {
var $c = $('<div style="position: absolute; top: -10000px; left: -10000px; width: 100px; height: 100px; border: 0; overflow: scroll;"></div>').appendTo("body")
, d = { width: $c.outerWidth - $c[0].clientWidth, height: 100 - $c[0].clientHeight };
$c.remove();
window.scrollbarWidth = d.width;
window.scrollbarHeight = d.height;
return dim.match(/^(width|height)$/) ? d[dim] : d;
}
, disableTextSelection: function () {
var $d = $(document)
, s = 'textSelectionDisabled'
, x = 'textSelectionInitialized'
;
if ($.fn.disableSelection) {
if (!$d.data(x)) // document hasn't been initialized yet
$d.on('mouseup', $.layout.enableTextSelection ).data(x, true);
if (!$d.data(s))
$d.disableSelection().data(s, true);
}
}
, enableTextSelection: function () {
var $d = $(document)
, s = 'textSelectionDisabled';
if ($.fn.enableSelection && $d.data(s))
$d.enableSelection().data(s, false);
}
/**
* Returns hash container 'display' and 'visibility'
*
* @see $.swap() - swaps CSS, runs callback, resets CSS
* @param {!Object} $E jQuery element
* @param {boolean=} [force=false] Run even if display != none
* @return {!Object} Returns current style props, if applicable
*/
, showInvisibly: function ($E, force) {
if ($E && $E.length && (force || $E.css("display") === "none")) { // only if not *already hidden*
var s = $E[0].style
// save ONLY the 'style' props because that is what we must restore
, CSS = { display: s.display || '', visibility: s.visibility || '' };
// show element 'invisibly' so can be measured
$E.css({ display: "block", visibility: "hidden" });
return CSS;
}
return {};
}
/**
* Returns data for setting size of an element (container or a pane).
*
* @see _create(), onWindowResize() for container, plus others for pane
* @return JSON Returns a hash of all dimensions: top, bottom, left, right, outerWidth, innerHeight, etc
*/
, getElementDimensions: function ($E, inset) {
var
// dimensions hash - start with current data IF passed
d = { css: {}, inset: {} }
, x = d.css // CSS hash
, i = { bottom: 0 } // TEMP insets (bottom = complier hack)
, N = $.layout.cssNum
, R = Math.round
, off = $E.offset()
, b, p, ei // TEMP border, padding
;
d.offsetLeft = off.left;
d.offsetTop = off.top;
if (!inset) inset = {}; // simplify logic below
$.each("Left,Right,Top,Bottom".split(","), function (idx, e) { // e = edge
b = x["border" + e] = $.layout.borderWidth($E, e);
p = x["padding"+ e] = $.layout.cssNum($E, "padding"+e);
ei = e.toLowerCase();
d.inset[ei] = inset[ei] >= 0 ? inset[ei] : p; // any missing insetX value = paddingX
i[ei] = d.inset[ei] + b; // total offset of content from outer side
});
x.width = R($E.width());
x.height = R($E.height());
x.top = N($E,"top",true);
x.bottom = N($E,"bottom",true);
x.left = N($E,"left",true);
x.right = N($E,"right",true);
d.outerWidth = R($E.outerWidth());
d.outerHeight = R($E.outerHeight());
// calc the TRUE inner-dimensions, even in quirks-mode!
d.innerWidth = max(0, d.outerWidth - i.left - i.right);
d.innerHeight = max(0, d.outerHeight - i.top - i.bottom);
// layoutWidth/Height is used in calcs for manual resizing
// layoutW/H only differs from innerW/H when in quirks-mode - then is like outerW/H
d.layoutWidth = R($E.innerWidth());
d.layoutHeight = R($E.innerHeight());
//if ($E.prop('tagName') === 'BODY') { debugData( d, $E.prop('tagName') ); } // DEBUG
//d.visible = $E.is(":visible");// && x.width > 0 && x.height > 0;
return d;
}
, getElementStyles: function ($E, list) {
var
CSS = {}
, style = $E[0].style
, props = list.split(",")
, sides = "Top,Bottom,Left,Right".split(",")
, attrs = "Color,Style,Width".split(",")
, p, s, a, i, j, k
;
for (i=0; i < props.length; i++) {
p = props[i];
if (p.match(/(border|padding|margin)$/))
for (j=0; j < 4; j++) {
s = sides[j];
if (p === "border")
for (k=0; k < 3; k++) {
a = attrs[k];
CSS[p+s+a] = style[p+s+a];
}
else
CSS[p+s] = style[p+s];
}
else
CSS[p] = style[p];
}
return CSS
}
/**
* Return the innerWidth for the current browser/doctype
*
* @see initPanes(), sizeMidPanes(), initHandles(), sizeHandles()
* @param {Array.<Object>} $E Must pass a jQuery object - first element is processed
* @param {number=} outerWidth (optional) Can pass a width, allowing calculations BEFORE element is resized
* @return {number} Returns the innerWidth of the elem by subtracting padding and borders
*/
, cssWidth: function ($E, outerWidth) {
// a 'calculated' outerHeight can be passed so borders and/or padding are removed if needed
if (outerWidth <= 0) return 0;
var lb = $.layout.browser
, bs = !lb.boxModel ? "border-box" : lb.boxSizing ? $E.css("boxSizing") : "content-box"
, b = $.layout.borderWidth
, n = $.layout.cssNum
, W = outerWidth
;
// strip border and/or padding from outerWidth to get CSS Width
if (bs !== "border-box")
W -= (b($E, "Left") + b($E, "Right"));
if (bs === "content-box")
W -= (n($E, "paddingLeft") + n($E, "paddingRight"));
return max(0,W);
}
/**
* Return the innerHeight for the current browser/doctype
*
* @see initPanes(), sizeMidPanes(), initHandles(), sizeHandles()
* @param {Array.<Object>} $E Must pass a jQuery object - first element is processed
* @param {number=} outerHeight (optional) Can pass a width, allowing calculations BEFORE element is resized
* @return {number} Returns the innerHeight of the elem by subtracting padding and borders
*/
, cssHeight: function ($E, outerHeight) {
// a 'calculated' outerHeight can be passed so borders and/or padding are removed if needed
if (outerHeight <= 0) return 0;
var lb = $.layout.browser
, bs = !lb.boxModel ? "border-box" : lb.boxSizing ? $E.css("boxSizing") : "content-box"
, b = $.layout.borderWidth
, n = $.layout.cssNum
, H = outerHeight
;
// strip border and/or padding from outerHeight to get CSS Height
if (bs !== "border-box")
H -= (b($E, "Top") + b($E, "Bottom"));
if (bs === "content-box")
H -= (n($E, "paddingTop") + n($E, "paddingBottom"));
return max(0,H);
}
/**
* Returns the 'current CSS numeric value' for a CSS property - 0 if property does not exist
*
* @see Called by many methods
* @param {Array.<Object>} $E Must pass a jQuery object - first element is processed
* @param {string} prop The name of the CSS property, eg: top, width, etc.
* @param {boolean=} [allowAuto=false] true = return 'auto' if that is value; false = return 0
* @return {(string|number)} Usually used to get an integer value for position (top, left) or size (height, width)
*/
, cssNum: function ($E, prop, allowAuto) {
if (!$E.jquery) $E = $($E);
var CSS = $.layout.showInvisibly($E)
, p = $.css($E[0], prop, true)
, v = allowAuto && p=="auto" ? p : Math.round(parseFloat(p) || 0);
$E.css( CSS ); // RESET
return v;
}
, borderWidth: function (el, side) {
if (el.jquery) el = el[0];
var b = "border"+ side.substr(0,1).toUpperCase() + side.substr(1); // left => Left
return $.css(el, b+"Style", true) === "none" ? 0 : Math.round(parseFloat($.css(el, b+"Width", true)) || 0);
}
/**
* Mouse-tracking utility - FUTURE REFERENCE
*
* init: if (!window.mouse) {
* window.mouse = { x: 0, y: 0 };
* $(document).mousemove( $.layout.trackMouse );
* }
*
* @param {Object} evt
*
, trackMouse: function (evt) {
window.mouse = { x: evt.clientX, y: evt.clientY };
}
*/
/**
* SUBROUTINE for preventPrematureSlideClose option
*
* @param {Object} evt
* @param {Object=} el
*/
, isMouseOverElem: function (evt, el) {
var
$E = $(el || this)
, d = $E.offset()
, T = d.top
, L = d.left
, R = L + $E.outerWidth()
, B = T + $E.outerHeight()
, x = evt.pageX // evt.clientX ?
, y = evt.pageY // evt.clientY ?
;
// if X & Y are < 0, probably means is over an open SELECT
return ($.layout.browser.msie && x < 0 && y < 0) || ((x >= L && x <= R) && (y >= T && y <= B));
}
/**
* Message/Logging Utility
*
* @example $.layout.msg("My message"); // log text
* @example $.layout.msg("My message", true); // alert text
* @example $.layout.msg({ foo: "bar" }, "Title"); // log hash-data, with custom title
* @example $.layout.msg({ foo: "bar" }, true, "Title", { sort: false }); -OR-
* @example $.layout.msg({ foo: "bar" }, "Title", { sort: false, display: true }); // alert hash-data
*
* @param {(Object|string)} info String message OR Hash/Array
* @param {(Boolean|string|Object)=} [popup=false] True means alert-box - can be skipped
* @param {(Object|string)=} [debugTitle=""] Title for Hash data - can be skipped
* @param {Object=} [debugOpts] Extra options for debug output
*/
, msg: function (info, popup, debugTitle, debugOpts) {
if ($.isPlainObject(info) && window.debugData) {
if (typeof popup === "string") {
debugOpts = debugTitle;
debugTitle = popup;
}
else if (typeof debugTitle === "object") {
debugOpts = debugTitle;
debugTitle = null;
}
var t = debugTitle || "log( <object> )"
, o = $.extend({ sort: false, returnHTML: false, display: false }, debugOpts);
if (popup === true || o.display)
debugData( info, t, o );
else if (window.console)
console.log(debugData( info, t, o ));
}
else if (popup)
alert(info);
else if (window.console)
console.log(info);
else {
var id = "#layoutLogger"
, $l = $(id);
if (!$l.length)
$l = createLog();
$l.children("ul").append('<li style="padding: 4px 10px; margin: 0; border-top: 1px solid #CCC;">'+ info.replace(/\</g,"<").replace(/\>/g,">") +'</li>');
}
function createLog () {
var pos = $.support.fixedPosition ? 'fixed' : 'absolute'
, $e = $('<div id="layoutLogger" style="position: '+ pos +'; top: 5px; z-index: 999999; max-width: 25%; overflow: hidden; border: 1px solid #000; border-radius: 5px; background: #FBFBFB; box-shadow: 0 2px 10px rgba(0,0,0,0.3);">'
+ '<div style="font-size: 13px; font-weight: bold; padding: 5px 10px; background: #F6F6F6; border-radius: 5px 5px 0 0; cursor: move;">'
+ '<span style="float: right; padding-left: 7px; cursor: pointer;" title="Remove Console" onclick="$(this).closest(\'#layoutLogger\').remove()">X</span>Layout console.log</div>'
+ '<ul style="font-size: 13px; font-weight: none; list-style: none; margin: 0; padding: 0 0 2px;"></ul>'
+ '</div>'
).appendTo("body");
$e.css('left', $(window).width() - $e.outerWidth() - 5);
if ($.ui.draggable) $e.draggable({ handle: ':first-child' });
return $e;
}
}
};
/*
* $.layout.browser REPLACES removed $.browser, with extra data
* Parsing code here adapted from jQuery 1.8 $.browse
*/
(function(){
var u = navigator.userAgent.toLowerCase()
, m = /(chrome)[ \/]([\w.]+)/.exec( u )
|| /(webkit)[ \/]([\w.]+)/.exec( u )
|| /(opera)(?:.*version|)[ \/]([\w.]+)/.exec( u )
|| /(msie) ([\w.]+)/.exec( u )
|| u.indexOf("compatible") < 0 && /(mozilla)(?:.*? rv:([\w.]+)|)/.exec( u )
|| []
, b = m[1] || ""
, v = m[2] || 0
, ie = b === "msie"
, cm = document.compatMode
, $s = $.support
, bs = $s.boxSizing !== undefined ? $s.boxSizing : $s.boxSizingReliable
, bm = !ie || !cm || cm === "CSS1Compat" || $s.boxModel || false
, lb = $.layout.browser = {
version: v
, safari: b === "webkit" // webkit (NOT chrome) = safari
, webkit: b === "chrome" // chrome = webkit
, msie: ie
, isIE6: ie && v == 6
// ONLY IE reverts to old box-model - Note that compatMode was deprecated as of IE8
, boxModel: bm
, boxSizing: !!(typeof bs === "function" ? bs() : bs)
};
if (b) lb[b] = true; // set CURRENT browser
/* OLD versions of jQuery only set $.support.boxModel after page is loaded
* so if this is IE, use support.boxModel to test for quirks-mode (ONLY IE changes boxModel) */
if (!bm && !cm) $(function(){ lb.boxModel = $s.boxModel; });
})();
// DEFAULT OPTIONS
$.layout.defaults = {
/*
* LAYOUT & LAYOUT-CONTAINER OPTIONS
* - none of these options are applicable to individual panes
*/
name: "" // Not required, but useful for buttons and used for the state-cookie
, containerClass: "ui-layout-container" // layout-container element
, inset: null // custom container-inset values (override padding)
, scrollToBookmarkOnLoad: true // after creating a layout, scroll to bookmark in URL (.../page.htm#myBookmark)
, resizeWithWindow: true // bind thisLayout.resizeAll() to the window.resize event
, resizeWithWindowDelay: 50 // delay calling resizeAll because makes window resizing very jerky
, resizeWithWindowMaxDelay: 0 // 0 = none - force resize every XX ms while window is being resized
, maskPanesEarly: false // true = create pane-masks on resizer.mouseDown instead of waiting for resizer.dragstart
, onresizeall_start: null // CALLBACK when resizeAll() STARTS - NOT pane-specific
, onresizeall_end: null // CALLBACK when resizeAll() ENDS - NOT pane-specific
, onload_start: null // CALLBACK when Layout inits - after options initialized, but before elements
, onload_end: null // CALLBACK when Layout inits - after EVERYTHING has been initialized
, onunload_start: null // CALLBACK when Layout is destroyed OR onWindowUnload
, onunload_end: null // CALLBACK when Layout is destroyed OR onWindowUnload
, initPanes: true // false = DO NOT initialize the panes onLoad - will init later
, showErrorMessages: true // enables fatal error messages to warn developers of common errors
, showDebugMessages: false // display console-and-alert debug msgs - IF this Layout version _has_ debugging code!
// Changing this zIndex value will cause other zIndex values to automatically change
, zIndex: null // the PANE zIndex - resizers and masks will be +1
// DO NOT CHANGE the zIndex values below unless you clearly understand their relationships
, zIndexes: { // set _default_ z-index values here...
pane_normal: 0 // normal z-index for panes
, content_mask: 1 // applied to overlays used to mask content INSIDE panes during resizing
, resizer_normal: 2 // normal z-index for resizer-bars
, pane_sliding: 100 // applied to *BOTH* the pane and its resizer when a pane is 'slid open'
, pane_animate: 1000 // applied to the pane when being animated - not applied to the resizer
, resizer_drag: 10000 // applied to the CLONED resizer-bar when being 'dragged'
}
, errors: {
pane: "pane" // description of "layout pane element" - used only in error messages
, selector: "selector" // description of "jQuery-selector" - used only in error messages
, addButtonError: "Error Adding Button\nInvalid "
, containerMissing: "UI Layout Initialization Error\nThe specified layout-container does not exist."
, centerPaneMissing: "UI Layout Initialization Error\nThe center-pane element does not exist.\nThe center-pane is a required element."
, noContainerHeight: "UI Layout Initialization Warning\nThe layout-container \"CONTAINER\" has no height.\nTherefore the layout is 0-height and hence 'invisible'!"
, callbackError: "UI Layout Callback Error\nThe EVENT callback is not a valid function."
}
/*
* PANE DEFAULT SETTINGS
* - settings under the 'panes' key become the default settings for *all panes*
* - ALL pane-options can also be set specifically for each panes, which will override these 'default values'
*/
, panes: { // default options for 'all panes' - will be overridden by 'per-pane settings'
applyDemoStyles: false // NOTE: renamed from applyDefaultStyles for clarity
, closable: true // pane can open & close
, resizable: true // when open, pane can be resized
, slidable: true // when closed, pane can 'slide open' over other panes - closes on mouse-out
, initClosed: false // true = init pane as 'closed'
, initHidden: false // true = init pane as 'hidden' - no resizer-bar/spacing
// SELECTORS
//, paneSelector: "" // MUST be pane-specific - jQuery selector for pane
, contentSelector: ".ui-layout-content" // ThinkGem 自动高度的内容类。 // INNER div/element to auto-size so only it scrolls, not the entire pane!
, contentIgnoreSelector: ".ui-layout-ignore" // element(s) to 'ignore' when measuring 'content'
, findNestedContent: true // ThinkGem 设置 contentSelector 自动高度,默认false // true = $P.find(contentSelector), false = $P.children(contentSelector)
// GENERIC ROOT-CLASSES - for auto-generated classNames
, paneClass: "ui-layout-pane" // Layout Pane
, resizerClass: "ui-layout-resizer" // Resizer Bar
, togglerClass: "ui-layout-toggler" // Toggler Button
, buttonClass: "ui-layout-button" // CUSTOM Buttons - eg: '[ui-layout-button]-toggle/-open/-close/-pin'
// ELEMENT SIZE & SPACING
//, size: 100 // MUST be pane-specific -initial size of pane
, minSize: 0 // when manually resizing a pane
, maxSize: 0 // ditto, 0 = no limit
, spacing_open: 8 // ThinkGem 分隔符宽度,默认6 // space between pane and adjacent panes - when pane is 'open'
, spacing_closed: 8 // ThinkGem 分隔符宽度,默认6 // ditto - when pane is 'closed'
, togglerLength_open: 50 // Length = WIDTH of toggler button on north/south sides - HEIGHT on east/west sides
, togglerLength_closed: 50 // 100% OR -1 means 'full height/width of resizer bar' - 0 means 'hidden'
, togglerAlign_open: "center" // top/left, bottom/right, center, OR...
, togglerAlign_closed: "center" // 1 => nn = offset from top/left, -1 => -nn == offset from bottom/right
, togglerContent_open: "<i class=\"fa\"></i>" // ThinkGem 设置展开折叠图标,默认空"" // text or HTML to put INSIDE the toggler
, togglerContent_closed: "<i class=\"fa\"></i>" // ThinkGem 设置展开折叠图标,默认空"" // ditto
// RESIZING OPTIONS
, resizerDblClickToggle: true //
, autoResize: true // IF size is 'auto' or a percentage, then recalc 'pixel size' whenever the layout resizes
, autoReopen: true // IF a pane was auto-closed due to noRoom, reopen it when there is room? False = leave it closed
, resizerDragOpacity: 1 // option for ui.draggable
//, resizerCursor: "" // MUST be pane-specific - cursor when over resizer-bar
, maskContents: false // true = add DIV-mask over-or-inside this pane so can 'drag' over IFRAMES
, maskObjects: false // true = add IFRAME-mask over-or-inside this pane to cover objects/applets - content-mask will overlay this mask
, maskZindex: null // will override zIndexes.content_mask if specified - not applicable to iframe-panes
, resizingGrid: false // grid size that the resizers will snap-to during resizing, eg: [20,20]
, livePaneResizing: false // true = LIVE Resizing as resizer is dragged
, liveContentResizing: false // true = re-measure header/footer heights as resizer is dragged
, liveResizingTolerance: 1 // how many px change before pane resizes, to control performance
// SLIDING OPTIONS
, sliderCursor: "pointer" // cursor when resizer-bar will trigger 'sliding'
, slideTrigger_open: "mouseenter"// ThinkGem 设置侧边栏自动展开动作,默认click // click, dblclick, mouseenter
, slideTrigger_close: "mouseleave"// ThinkGem 设置侧边栏自动展开动作,默认mouseleave // click, mouseleave
, slideDelay_open: 100 // ThinkGem 设置鼠标放到侧边栏的时候自动展开的延迟时间,默认300 //applies only for mouseenter event - 0 = instant open
, slideDelay_close: 500 // ThinkGem 设置鼠标放到侧边栏的时候自动展开的延迟时间,默认300 //applies only for mouseleave event (300ms is the minimum!)
, hideTogglerOnSlide: false // when pane is slid-open, should the toggler show?
, preventQuickSlideClose: $.layout.browser.webkit // Chrome triggers slideClosed as it is opening
, preventPrematureSlideClose: false // handle incorrect mouseleave trigger, like when over a SELECT-list in IE
// PANE-SPECIFIC TIPS & MESSAGES
, tips: {
Open: "展开" // ThinkGem 汉化,默认Open // eg: "Open Pane"
, Close: "折叠" // ThinkGem 汉化,默认Close
, Resize: "调整大小/双击折叠" // ThinkGem 汉化,默认Resize
, Slide: "鼠标停留自动展开" // ThinkGem 汉化,默认Slide Open
, Pin: "Pin"
, Unpin: "Un-Pin"
, noRoomToOpen: "Not enough room to show this panel." // alert if user tries to open a pane that cannot
, minSizeWarning: "Panel has reached its minimum size" // displays in browser statusbar
, maxSizeWarning: "Panel has reached its maximum size" // ditto
}
// HOT-KEYS & MISC
, showOverflowOnHover: false // will bind allowOverflow() utility to pane.onMouseOver
, enableCursorHotkey: true // enabled 'cursor' hotkeys
//, customHotkey: "" // MUST be pane-specific - EITHER a charCode OR a character
, customHotkeyModifier: "SHIFT" // either 'SHIFT', 'CTRL' or 'CTRL+SHIFT' - NOT 'ALT'
// PANE ANIMATION
// NOTE: fxSss_open, fxSss_close & fxSss_size options (eg: fxName_open) are auto-generated if not passed
, fxName: "slide" // ('none' or blank), slide, drop, scale -- only relevant to 'open' & 'close', NOT 'size'
, fxSpeed: null // slow, normal, fast, 200, nnn - if passed, will OVERRIDE fxSettings.duration
, fxSettings: {} // can be passed, eg: { easing: "easeOutBounce", duration: 1500 }
, fxOpacityFix: true // tries to fix opacity in IE to restore anti-aliasing after animation
, animatePaneSizing: false // true = animate resizing after dragging resizer-bar OR sizePane() is called
/* NOTE: Action-specific FX options are auto-generated from the options above if not specifically set:
fxName_open: "slide" // 'Open' pane animation
fnName_close: "slide" // 'Close' pane animation
fxName_size: "slide" // 'Size' pane animation - when animatePaneSizing = true
fxSpeed_open: null
fxSpeed_close: null
fxSpeed_size: null
fxSettings_open: {}
fxSettings_close: {}
fxSettings_size: {}
*/
// CHILD/NESTED LAYOUTS
, children: null // Layout-options for nested/child layout - even {} is valid as options
, containerSelector: '' // if child is NOT 'directly nested', a selector to find it/them (can have more than one child layout!)
, initChildren: true // true = child layout will be created as soon as _this_ layout completes initialization
, destroyChildren: true // true = destroy child-layout if this pane is destroyed
, resizeChildren: true // true = trigger child-layout.resizeAll() when this pane is resized
// EVENT TRIGGERING
, triggerEventsOnLoad: false // true = trigger onopen OR onclose callbacks when layout initializes
, triggerEventsDuringLiveResize: true // true = trigger onresize callback REPEATEDLY if livePaneResizing==true
// PANE CALLBACKS
, onshow_start: null // CALLBACK when pane STARTS to Show - BEFORE onopen/onhide_start
, onshow_end: null // CALLBACK when pane ENDS being Shown - AFTER onopen/onhide_end
, onhide_start: null // CALLBACK when pane STARTS to Close - BEFORE onclose_start
, onhide_end: null // CALLBACK when pane ENDS being Closed - AFTER onclose_end
, onopen_start: null // CALLBACK when pane STARTS to Open
, onopen_end: null // CALLBACK when pane ENDS being Opened
, onclose_start: null // CALLBACK when pane STARTS to Close
, onclose_end: null // CALLBACK when pane ENDS being Closed
, onresize_start: null // CALLBACK when pane STARTS being Resized ***FOR ANY REASON***
, onresize_end: null // CALLBACK when pane ENDS being Resized ***FOR ANY REASON***
, onsizecontent_start: null // CALLBACK when sizing of content-element STARTS
, onsizecontent_end: null // CALLBACK when sizing of content-element ENDS
, onswap_start: null // CALLBACK when pane STARTS to Swap
, onswap_end: null // CALLBACK when pane ENDS being Swapped
, ondrag_start: null // CALLBACK when pane STARTS being ***MANUALLY*** Resized
, ondrag_end: null // CALLBACK when pane ENDS being ***MANUALLY*** Resized
}
/*
* PANE-SPECIFIC SETTINGS
* - options listed below MUST be specified per-pane - they CANNOT be set under 'panes'
* - all options under the 'panes' key can also be set specifically for any pane
* - most options under the 'panes' key apply only to 'border-panes' - NOT the the center-pane
*/
, north: {
paneSelector: ".ui-layout-north"
, size: "auto" // eg: "auto", "30%", .30, 200
, resizerCursor: "n-resize" // custom = url(myCursor.cur)
, customHotkey: "" // EITHER a charCode (43) OR a character ("o")
}
, south: {
paneSelector: ".ui-layout-south"
, size: "auto"
, resizerCursor: "s-resize"
, customHotkey: ""
}
, east: {
paneSelector: ".ui-layout-east"
, size: 200
, resizerCursor: "e-resize"
, customHotkey: ""
}
, west: {
paneSelector: ".ui-layout-west"
, size: 200
, resizerCursor: "w-resize"
, customHotkey: ""
}
, center: {
paneSelector: ".ui-layout-center"
, minWidth: 0
, minHeight: 0
}
};
$.layout.optionsMap = {
// layout/global options - NOT pane-options
layout: ("name,instanceKey,stateManagement,effects,inset,zIndexes,errors,"
+ "zIndex,scrollToBookmarkOnLoad,showErrorMessages,maskPanesEarly,"
+ "outset,resizeWithWindow,resizeWithWindowDelay,resizeWithWindowMaxDelay,"
+ "onresizeall,onresizeall_start,onresizeall_end,onload,onload_start,onload_end,onunload,onunload_start,onunload_end").split(",")
// borderPanes: [ ALL options that are NOT specified as 'layout' ]
// default.panes options that apply to the center-pane (most options apply _only_ to border-panes)
, center: ("paneClass,contentSelector,contentIgnoreSelector,findNestedContent,applyDemoStyles,triggerEventsOnLoad,"
+ "showOverflowOnHover,maskContents,maskObjects,liveContentResizing,"
+ "containerSelector,children,initChildren,resizeChildren,destroyChildren,"
+ "onresize,onresize_start,onresize_end,onsizecontent,onsizecontent_start,onsizecontent_end").split(",")
// options that MUST be specifically set 'per-pane' - CANNOT set in the panes (defaults) key
, noDefault: ("paneSelector,resizerCursor,customHotkey").split(",")
};
/**
* Processes options passed in converts flat-format data into subkey (JSON) format
* In flat-format, subkeys are _currently_ separated with 2 underscores, like north__optName
* Plugins may also call this method so they can transform their own data
*
* @param {!Object} hash Data/options passed by user - may be a single level or nested levels
* @param {boolean=} [addKeys=false] Should the primary layout.options keys be added if they do not exist?
* @return {Object} Returns hash of minWidth & minHeight
*/
$.layout.transformData = function (hash, addKeys) {
var json = addKeys ? { panes: {}, center: {} } : {} // init return object
, branch, optKey, keys, key, val, i, c;
if (typeof hash !== "object") return json; // no options passed
// convert all 'flat-keys' to 'sub-key' format
for (optKey in hash) {
branch = json;
val = hash[ optKey ];
keys = optKey.split("__"); // eg: west__size or north__fxSettings__duration
c = keys.length - 1;
// convert underscore-delimited to subkeys
for (i=0; i <= c; i++) {
key = keys[i];
if (i === c) { // last key = value
if ($.isPlainObject( val ))
branch[key] = $.layout.transformData( val ); // RECURSE
else
branch[key] = val;
}
else {
if (!branch[key])
branch[key] = {}; // create the subkey
// recurse to sub-key for next loop - if not done
branch = branch[key];
}
}
}
return json;
};
// INTERNAL CONFIG DATA - DO NOT CHANGE THIS!
$.layout.backwardCompatibility = {
// data used by renameOldOptions()
map: {
// OLD Option Name: NEW Option Name
applyDefaultStyles: "applyDemoStyles"
// CHILD/NESTED LAYOUTS
, childOptions: "children"
, initChildLayout: "initChildren"
, destroyChildLayout: "destroyChildren"
, resizeChildLayout: "resizeChildren"
, resizeNestedLayout: "resizeChildren"
// MISC Options
, resizeWhileDragging: "livePaneResizing"
, resizeContentWhileDragging: "liveContentResizing"
, triggerEventsWhileDragging: "triggerEventsDuringLiveResize"
, maskIframesOnResize: "maskContents"
// STATE MANAGEMENT
, useStateCookie: "stateManagement.enabled"
, "cookie.autoLoad": "stateManagement.autoLoad"
, "cookie.autoSave": "stateManagement.autoSave"
, "cookie.keys": "stateManagement.stateKeys"
, "cookie.name": "stateManagement.cookie.name"
, "cookie.domain": "stateManagement.cookie.domain"
, "cookie.path": "stateManagement.cookie.path"
, "cookie.expires": "stateManagement.cookie.expires"
, "cookie.secure": "stateManagement.cookie.secure"
// OLD Language options
, noRoomToOpenTip: "tips.noRoomToOpen"
, togglerTip_open: "tips.Close" // open = Close
, togglerTip_closed: "tips.Open" // closed = Open
, resizerTip: "tips.Resize"
, sliderTip: "tips.Slide"
}
/**
* @param {Object} opts
*/
, renameOptions: function (opts) {
var map = $.layout.backwardCompatibility.map
, oldData, newData, value
;
for (var itemPath in map) {
oldData = getBranch( itemPath );
value = oldData.branch[ oldData.key ];
if (value !== undefined) {
newData = getBranch( map[itemPath], true );
newData.branch[ newData.key ] = value;
delete oldData.branch[ oldData.key ];
}
}
/**
* @param {string} path
* @param {boolean=} [create=false] Create path if does not exist
*/
function getBranch (path, create) {
var a = path.split(".") // split keys into array
, c = a.length - 1
, D = { branch: opts, key: a[c] } // init branch at top & set key (last item)
, i = 0, k, undef;
for (; i<c; i++) { // skip the last key (data)
k = a[i];
if (D.branch[ k ] == undefined) { // child-key does not exist
if (create) {
D.branch = D.branch[ k ] = {}; // create child-branch
}
else // can't go any farther
D.branch = {}; // branch is undefined
}
else
D.branch = D.branch[ k ]; // get child-branch
}
return D;
}
}
/**
* @param {Object} opts
*/
, renameAllOptions: function (opts) {
var ren = $.layout.backwardCompatibility.renameOptions;
// rename root (layout) options
ren( opts );
// rename 'defaults' to 'panes'
if (opts.defaults) {
if (typeof opts.panes !== "object")
opts.panes = {};
$.extend(true, opts.panes, opts.defaults);
delete opts.defaults;
}
// rename options in the the options.panes key
if (opts.panes) ren( opts.panes );
// rename options inside *each pane key*, eg: options.west
$.each($.layout.config.allPanes, function (i, pane) {
if (opts[pane]) ren( opts[pane] );
});
return opts;
}
};
/* ============================================================
* BEGIN WIDGET: $( selector ).layout( {options} );
* ============================================================
*/
$.fn.layout = function (opts) {
var
// local aliases to global data
browser = $.layout.browser
, _c = $.layout.config
// local aliases to utlity methods
, cssW = $.layout.cssWidth
, cssH = $.layout.cssHeight
, elDims = $.layout.getElementDimensions
, styles = $.layout.getElementStyles
, evtObj = $.layout.getEventObject
, evtPane = $.layout.parsePaneName
/**
* options - populated by initOptions()
*/
, options = $.extend(true, {}, $.layout.defaults)
, effects = options.effects = $.extend(true, {}, $.layout.effects)
/**
* layout-state object
*/
, state = {
// generate unique ID to use for event.namespace so can unbind only events added by 'this layout'
id: "layout"+ $.now() // code uses alias: sID
, initialized: false
, paneResizing: false
, panesSliding: {}
, container: { // list all keys referenced in code to avoid compiler error msgs
innerWidth: 0
, innerHeight: 0
, outerWidth: 0
, outerHeight: 0
, layoutWidth: 0
, layoutHeight: 0
}
, north: { childIdx: 0 }
, south: { childIdx: 0 }
, east: { childIdx: 0 }
, west: { childIdx: 0 }
, center: { childIdx: 0 }
}
/**
* parent/child-layout pointers
*/
//, hasParentLayout = false - exists ONLY inside Instance so can be set externally
, children = {
north: null
, south: null
, east: null
, west: null
, center: null
}
/*
* ###########################
* INTERNAL HELPER FUNCTIONS
* ###########################
*/
/**
* Manages all internal timers
*/
, timer = {
data: {}
, set: function (s, fn, ms) { timer.clear(s); timer.data[s] = setTimeout(fn, ms); }
, clear: function (s) { var t=timer.data; if (t[s]) {clearTimeout(t[s]); delete t[s];} }
}
/**
* Alert or console.log a message - IF option is enabled.
*
* @param {(string|!Object)} msg Message (or debug-data) to display
* @param {boolean=} [popup=false] True by default, means 'alert', false means use console.log
* @param {boolean=} [debug=false] True means is a widget debugging message
*/
, _log = function (msg, popup, debug) {
var o = options;
if ((o.showErrorMessages && !debug) || (debug && o.showDebugMessages))
$.layout.msg( o.name +' / '+ msg, (popup !== false) );
return false;
}
/**
* Executes a Callback function after a trigger event, like resize, open or close
*
* @param {string} evtName Name of the layout callback, eg "onresize_start"
* @param {(string|boolean)=} [pane=""] This is passed only so we can pass the 'pane object' to the callback
* @param {(string|boolean)=} [skipBoundEvents=false] True = do not run events bound to the elements - only the callbacks set in options
*/
, _runCallbacks = function (evtName, pane, skipBoundEvents) {
var hasPane = pane && isStr(pane)
, s = hasPane ? state[pane] : state
, o = hasPane ? options[pane] : options
, lName = options.name
// names like onopen and onopen_end separate are interchangeable in options...
, lng = evtName + (evtName.match(/_/) ? "" : "_end")
, shrt = lng.match(/_end$/) ? lng.substr(0, lng.length - 4) : ""
, fn = o[lng] || o[shrt]
, retVal = "NC" // NC = No Callback
, args = []
, $P = hasPane ? $Ps[pane] : 0
;
if (hasPane && !$P) // a pane is specified, but does not exist!
return retVal;
if ( !hasPane && $.type(pane) === "boolean" ) {
skipBoundEvents = pane; // allow pane param to be skipped for Layout callback
pane = "";
}
// first trigger the callback set in the options
if (fn) {
try {
// convert function name (string) to function object
if (isStr( fn )) {
if (fn.match(/,/)) {
// function name cannot contain a comma,
// so must be a function name AND a parameter to pass
args = fn.split(",")
, fn = eval(args[0]);
}
else // just the name of an external function?
fn = eval(fn);
}
// execute the callback, if exists
if ($.isFunction( fn )) {
if (args.length)
retVal = g(fn)(args[1]); // pass the argument parsed from 'list'
else if ( hasPane )
// pass data: pane-name, pane-element, pane-state, pane-options, and layout-name
retVal = g(fn)( pane, $Ps[pane], s, o, lName );
else // must be a layout/container callback - pass suitable info
retVal = g(fn)( Instance, s, o, lName );
}
}
catch (ex) {
_log( options.errors.callbackError.replace(/EVENT/, $.trim((pane || "") +" "+ lng)), false );
if ($.type(ex) === "string" && string.length)
_log("Exception: "+ ex, false );
}
}
// trigger additional events bound directly to the pane
if (!skipBoundEvents && retVal !== false) {
if ( hasPane ) { // PANE events can be bound to each pane-elements
o = options[pane];
s = state[pane];
$P.triggerHandler("layoutpane"+ lng, [ pane, $P, s, o, lName ]);
if (shrt)
$P.triggerHandler("layoutpane"+ shrt, [ pane, $P, s, o, lName ]);
}
else { // LAYOUT events can be bound to the container-element
$N.triggerHandler("layout"+ lng, [ Instance, s, o, lName ]);
if (shrt)
$N.triggerHandler("layout"+ shrt, [ Instance, s, o, lName ]);
}
}
// ALWAYS resizeChildren after an onresize_end event - even during initialization
// IGNORE onsizecontent_end event because causes child-layouts to resize TWICE
if (hasPane && evtName === "onresize_end") // BAD: || evtName === "onsizecontent_end"
resizeChildren(pane+"", true); // compiler hack -force string
return retVal;
function g(f) {
return f;
} // compiler hack
}
/**
* cure iframe display issues in IE & other browsers
*/
, _fixIframe = function (pane) {
if (browser.mozilla) return; // skip FireFox - it auto-refreshes iframes onShow
var $P = $Ps[pane];
// if the 'pane' is an iframe, do it
if (state[pane].tagName === "IFRAME")
$P.css(_c.hidden).css(_c.visible);
else // ditto for any iframes INSIDE the pane
$P.find('IFRAME').css(_c.hidden).css(_c.visible);
}
/**
* @param {string} pane Can accept ONLY a 'pane' (east, west, etc)
* @param {number=} outerSize (optional) Can pass a width, allowing calculations BEFORE element is resized
* @return {number} Returns the innerHeight/Width of el by subtracting padding and borders
*/
, cssSize = function (pane, outerSize) {
var fn = _c[pane].dir=="horz" ? cssH : cssW;
return fn($Ps[pane], outerSize);
}
/**
* @param {string} pane Can accept ONLY a 'pane' (east, west, etc)
* @return {Object} Returns hash of minWidth & minHeight
*/
, cssMinDims = function (pane) {
// minWidth/Height means CSS width/height = 1px
var $P = $Ps[pane]
, dir = _c[pane].dir
, d = {
minWidth: 1001 - cssW($P, 1000)
, minHeight: 1001 - cssH($P, 1000)
}
;
if (dir === "horz") d.minSize = d.minHeight;
if (dir === "vert") d.minSize = d.minWidth;
return d;
}
// TODO: see if these methods can be made more useful...
// TODO: *maybe* return cssW/H from these so caller can use this info
/**
* @param {(string|!Object)} el
* @param {number=} outerWidth
* @param {boolean=} [autoHide=false]
*/
, setOuterWidth = function (el, outerWidth, autoHide) {
var $E = el, w;
if (isStr(el)) $E = $Ps[el]; // west
else if (!el.jquery) $E = $(el);
w = cssW($E, outerWidth);
$E.css({ width: w });
if (w > 0) {
if (autoHide && $E.data('autoHidden') && $E.innerHeight() > 0) {
$E.show().data('autoHidden', false);
if (!browser.mozilla) // FireFox refreshes iframes - IE does not
// make hidden, then visible to 'refresh' display after animation
$E.css(_c.hidden).css(_c.visible);
}
}
else if (autoHide && !$E.data('autoHidden'))
$E.hide().data('autoHidden', true);
}
/**
* @param {(string|!Object)} el
* @param {number=} outerHeight
* @param {boolean=} [autoHide=false]
*/
, setOuterHeight = function (el, outerHeight, autoHide) {
var $E = el, h;
if (isStr(el)) $E = $Ps[el]; // west
else if (!el.jquery) $E = $(el);
h = cssH($E, outerHeight);
$E.css({ height: h, visibility: "visible" }); // may have been 'hidden' by sizeContent
if (h > 0 && $E.innerWidth() > 0) {
if (autoHide && $E.data('autoHidden')) {
$E.show().data('autoHidden', false);
if (!browser.mozilla) // FireFox refreshes iframes - IE does not
$E.css(_c.hidden).css(_c.visible);
}
}
else if (autoHide && !$E.data('autoHidden'))
$E.hide().data('autoHidden', true);
}
/**
* Converts any 'size' params to a pixel/integer size, if not already
* If 'auto' or a decimal/percentage is passed as 'size', a pixel-size is calculated
*
/**
* @param {string} pane
* @param {(string|number)=} size
* @param {string=} [dir]
* @return {number}
*/
, _parseSize = function (pane, size, dir) {
if (!dir) dir = _c[pane].dir;
if (isStr(size) && size.match(/%/))
size = (size === '100%') ? -1 : parseInt(size, 10) / 100; // convert % to decimal
if (size === 0)
return 0;
else if (size >= 1)
return parseInt(size, 10);
var o = options, avail = 0;
if (dir=="horz") // north or south or center.minHeight
avail = sC.innerHeight - ($Ps.north ? o.north.spacing_open : 0) - ($Ps.south ? o.south.spacing_open : 0);
else if (dir=="vert") // east or west or center.minWidth
avail = sC.innerWidth - ($Ps.west ? o.west.spacing_open : 0) - ($Ps.east ? o.east.spacing_open : 0);
if (size === -1) // -1 == 100%
return avail;
else if (size > 0) // percentage, eg: .25
return round(avail * size);
else if (pane=="center")
return 0;
else { // size < 0 || size=='auto' || size==Missing || size==Invalid
// auto-size the pane
var dim = (dir === "horz" ? "height" : "width")
, $P = $Ps[pane]
, $C = dim === 'height' ? $Cs[pane] : false
, vis = $.layout.showInvisibly($P) // show pane invisibly if hidden
, szP = $P.css(dim) // SAVE current pane size
, szC = $C ? $C.css(dim) : 0 // SAVE current content size
;
$P.css(dim, "auto");
if ($C) $C.css(dim, "auto");
size = (dim === "height") ? $P.outerHeight() : $P.outerWidth(); // MEASURE
$P.css(dim, szP).css(vis); // RESET size & visibility
if ($C) $C.css(dim, szC);
return size;
}
}
/**
* Calculates current 'size' (outer-width or outer-height) of a border-pane - optionally with 'pane-spacing' added
*
* @param {(string|!Object)} pane
* @param {boolean=} [inclSpace=false]
* @return {number} Returns EITHER Width for east/west panes OR Height for north/south panes
*/
, getPaneSize = function (pane, inclSpace) {
var
$P = $Ps[pane]
, o = options[pane]
, s = state[pane]
, oSp = (inclSpace ? o.spacing_open : 0)
, cSp = (inclSpace ? o.spacing_closed : 0)
;
if (!$P || s.isHidden)
return 0;
else if (s.isClosed || (s.isSliding && inclSpace))
return cSp;
else if (_c[pane].dir === "horz")
return $P.outerHeight() + oSp;
else // dir === "vert"
return $P.outerWidth() + oSp;
}
/**
* Calculate min/max pane dimensions and limits for resizing
*
* @param {string} pane
* @param {boolean=} [slide=false]
*/
, setSizeLimits = function (pane, slide) {
if (!isInitialized()) return;
var
o = options[pane]
, s = state[pane]
, c = _c[pane]
, dir = c.dir
, type = c.sizeType.toLowerCase()
, isSliding = (slide != undefined ? slide : s.isSliding) // only open() passes 'slide' param
, $P = $Ps[pane]
, paneSpacing = o.spacing_open
// measure the pane on the *opposite side* from this pane
, altPane = _c.oppositeEdge[pane]
, altS = state[altPane]
, $altP = $Ps[altPane]
, altPaneSize = (!$altP || altS.isVisible===false || altS.isSliding ? 0 : (dir=="horz" ? $altP.outerHeight() : $altP.outerWidth()))
, altPaneSpacing = ((!$altP || altS.isHidden ? 0 : options[altPane][ altS.isClosed !== false ? "spacing_closed" : "spacing_open" ]) || 0)
// limitSize prevents this pane from 'overlapping' opposite pane
, containerSize = (dir=="horz" ? sC.innerHeight : sC.innerWidth)
, minCenterDims = cssMinDims("center")
, minCenterSize = dir=="horz" ? max(options.center.minHeight, minCenterDims.minHeight) : max(options.center.minWidth, minCenterDims.minWidth)
// if pane is 'sliding', then ignore center and alt-pane sizes - because 'overlays' them
, limitSize = (containerSize - paneSpacing - (isSliding ? 0 : (_parseSize("center", minCenterSize, dir) + altPaneSize + altPaneSpacing)))
, minSize = s.minSize = max( _parseSize(pane, o.minSize), cssMinDims(pane).minSize )
, maxSize = s.maxSize = min( (o.maxSize ? _parseSize(pane, o.maxSize) : 100000), limitSize )
, r = s.resizerPosition = {} // used to set resizing limits
, top = sC.inset.top
, left = sC.inset.left
, W = sC.innerWidth
, H = sC.innerHeight
, rW = o.spacing_open // subtract resizer-width to get top/left position for south/east
;
switch (pane) {
case "north": r.min = top + minSize;
r.max = top + maxSize;
break;
case "west": r.min = left + minSize;
r.max = left + maxSize;
break;
case "south": r.min = top + H - maxSize - rW;
r.max = top + H - minSize - rW;
break;
case "east": r.min = left + W - maxSize - rW;
r.max = left + W - minSize - rW;
break;
}
}
/**
* Returns data for setting the size/position of center pane. Also used to set Height for east/west panes
*
* @return JSON Returns a hash of all dimensions: top, bottom, left, right, (outer) width and (outer) height
*/
, calcNewCenterPaneDims = function () {
var d = {
top: getPaneSize("north", true) // true = include 'spacing' value for pane
, bottom: getPaneSize("south", true)
, left: getPaneSize("west", true)
, right: getPaneSize("east", true)
, width: 0
, height: 0
};
// NOTE: sC = state.container
// calc center-pane outer dimensions
d.width = sC.innerWidth - d.left - d.right; // outerWidth
d.height = sC.innerHeight - d.bottom - d.top; // outerHeight
// add the 'container border/padding' to get final positions relative to the container
d.top += sC.inset.top;
d.bottom += sC.inset.bottom;
d.left += sC.inset.left;
d.right += sC.inset.right;
return d;
}
/**
* @param {!Object} el
* @param {boolean=} [allStates=false]
*/
, getHoverClasses = function (el, allStates) {
var
$El = $(el)
, type = $El.data("layoutRole")
, pane = $El.data("layoutEdge")
, o = options[pane]
, root = o[type +"Class"]
, _pane = "-"+ pane // eg: "-west"
, _open = "-open"
, _closed = "-closed"
, _slide = "-sliding"
, _hover = "-hover " // NOTE the trailing space
, _state = $El.hasClass(root+_closed) ? _closed : _open
, _alt = _state === _closed ? _open : _closed
, classes = (root+_hover) + (root+_pane+_hover) + (root+_state+_hover) + (root+_pane+_state+_hover)
;
if (allStates) // when 'removing' classes, also remove alternate-state classes
classes += (root+_alt+_hover) + (root+_pane+_alt+_hover);
if (type=="resizer" && $El.hasClass(root+_slide))
classes += (root+_slide+_hover) + (root+_pane+_slide+_hover);
return $.trim(classes);
}
, addHover = function (evt, el) {
var $E = $(el || this);
if (evt && $E.data("layoutRole") === "toggler")
evt.stopPropagation(); // prevent triggering 'slide' on Resizer-bar
$E.addClass( getHoverClasses($E) );
}
, removeHover = function (evt, el) {
var $E = $(el || this);
$E.removeClass( getHoverClasses($E, true) );
}
, onResizerEnter = function (evt) { // ALSO called by toggler.mouseenter
var pane = $(this).data("layoutEdge")
, s = state[pane]
, $d = $(document)
;
// ignore closed-panes and mouse moving back & forth over resizer!
// also ignore if ANY pane is currently resizing
if ( s.isResizing || state.paneResizing ) return;
if (options.maskPanesEarly)
showMasks( pane, { resizing: true });
}
, onResizerLeave = function (evt, el) {
var e = el || this // el is only passed when called by the timer
, pane = $(e).data("layoutEdge")
, name = pane +"ResizerLeave"
, $d = $(document)
;
timer.clear(pane+"_openSlider"); // cancel slideOpen timer, if set
timer.clear(name); // cancel enableSelection timer - may re/set below
// this method calls itself on a timer because it needs to allow
// enough time for dragging to kick-in and set the isResizing flag
// dragging has a 100ms delay set, so this delay must be >100
if (!el) // 1st call - mouseleave event
timer.set(name, function(){ onResizerLeave(evt, e); }, 200);
// if user is resizing, dragStop will reset everything, so skip it here
else if (options.maskPanesEarly && !state.paneResizing) // 2nd call - by timer
hideMasks();
}
/*
* ###########################
* INITIALIZATION METHODS
* ###########################
*/
/**
* Initialize the layout - called automatically whenever an instance of layout is created
*
* @see none - triggered onInit
* @return mixed true = fully initialized | false = panes not initialized (yet) | 'cancel' = abort
*/
, _create = function () {
// initialize config/options
initOptions();
var o = options
, s = state;
// TEMP state so isInitialized returns true during init process
s.creatingLayout = true;
// init plugins for this layout, if there are any (eg: stateManagement)
runPluginCallbacks( Instance, $.layout.onCreate );
// options & state have been initialized, so now run beforeLoad callback
// onload will CANCEL layout creation if it returns false
if (false === _runCallbacks("onload_start"))
return 'cancel';
// initialize the container element
_initContainer();
// bind hotkey function - keyDown - if required
initHotkeys();
// bind window.onunload
$(window).bind("unload."+ sID, unload);
// init plugins for this layout, if there are any (eg: customButtons)
runPluginCallbacks( Instance, $.layout.onLoad );
// if layout elements are hidden, then layout WILL NOT complete initialization!
// initLayoutElements will set initialized=true and run the onload callback IF successful
if (o.initPanes) _initLayoutElements();
delete s.creatingLayout;
return state.initialized;
}
/**
* Initialize the layout IF not already
*
* @see All methods in Instance run this test
* @return boolean true = layoutElements have been initialized | false = panes are not initialized (yet)
*/
, isInitialized = function () {
if (state.initialized || state.creatingLayout) return true; // already initialized
else return _initLayoutElements(); // try to init panes NOW
}
/**
* Initialize the layout - called automatically whenever an instance of layout is created
*
* @see _create() & isInitialized
* @param {boolean=} [retry=false] // indicates this is a 2nd try
* @return An object pointer to the instance created
*/
, _initLayoutElements = function (retry) {
// initialize config/options
var o = options;
// CANNOT init panes inside a hidden container!
if (!$N.is(":visible")) {
// handle Chrome bug where popup window 'has no height'
// if layout is BODY element, try again in 50ms
// SEE: http://layout.jquery-dev.com/samples/test_popup_window.html
if ( !retry && browser.webkit && $N[0].tagName === "BODY" )
setTimeout(function(){ _initLayoutElements(true); }, 50);
return false;
}
// a center pane is required, so make sure it exists
if (!getPane("center").length) {
return _log( o.errors.centerPaneMissing );
}
// TEMP state so isInitialized returns true during init process
state.creatingLayout = true;
// update Container dims
$.extend(sC, elDims( $N, o.inset )); // passing inset means DO NOT include insetX values
// initialize all layout elements
initPanes(); // size & position panes - calls initHandles() - which calls initResizable()
if (o.scrollToBookmarkOnLoad) {
var l = self.location;
if (l.hash) l.replace( l.hash ); // scrollTo Bookmark
}
// check to see if this layout 'nested' inside a pane
if (Instance.hasParentLayout)
o.resizeWithWindow = false;
// bind resizeAll() for 'this layout instance' to window.resize event
else if (o.resizeWithWindow)
$(window).bind("resize."+ sID, windowResize);
delete state.creatingLayout;
state.initialized = true;
// init plugins for this layout, if there are any
runPluginCallbacks( Instance, $.layout.onReady );
// now run the onload callback, if exists
_runCallbacks("onload_end");
return true; // elements initialized successfully
}
/**
* Initialize nested layouts for a specific pane - can optionally pass layout-options
*
* @param {(string|Object)} evt_or_pane The pane being opened, ie: north, south, east, or west
* @param {Object=} [opts] Layout-options - if passed, will OVERRRIDE options[pane].children
* @return An object pointer to the layout instance created - or null
*/
, createChildren = function (evt_or_pane, opts) {
var pane = evtPane.call(this, evt_or_pane)
, $P = $Ps[pane]
;
if (!$P) return;
var $C = $Cs[pane]
, s = state[pane]
, o = options[pane]
, sm = options.stateManagement || {}
, cos = opts ? (o.children = opts) : o.children
;
if ( $.isPlainObject( cos ) )
cos = [ cos ]; // convert a hash to a 1-elem array
else if (!cos || !$.isArray( cos ))
return;
$.each( cos, function (idx, co) {
if ( !$.isPlainObject( co ) ) return;
// determine which element is supposed to be the 'child container'
// if pane has a 'containerSelector' OR a 'content-div', use those instead of the pane
var $containers = co.containerSelector ? $P.find( co.containerSelector ) : ($C || $P);
$containers.each(function(){
var $cont = $(this)
, child = $cont.data("layout") // see if a child-layout ALREADY exists on this element
;
// if no layout exists, but children are set, try to create the layout now
if (!child) {
// TODO: see about moving this to the stateManagement plugin, as a method
// set a unique child-instance key for this layout, if not already set
setInstanceKey({ container: $cont, options: co }, s );
// If THIS layout has a hash in stateManagement.autoLoad,
// then see if it also contains state-data for this child-layout
// If so, copy the stateData to child.options.stateManagement.autoLoad
if ( sm.includeChildren && state.stateData[pane] ) {
// THIS layout's state was cached when its state was loaded
var paneChildren = state.stateData[pane].children || {}
, childState = paneChildren[ co.instanceKey ]
, co_sm = co.stateManagement || (co.stateManagement = { autoLoad: true })
;
// COPY the stateData into the autoLoad key
if ( co_sm.autoLoad === true && childState ) {
co_sm.autoSave = false; // disable autoSave because saving handled by parent-layout
co_sm.includeChildren = true; // cascade option - FOR NOW
co_sm.autoLoad = $.extend(true, {}, childState); // COPY the state-hash
}
}
// create the layout
child = $cont.layout( co );
// if successful, update data
if (child) {
// add the child and update all layout-pointers
// MAY have already been done by child-layout calling parent.refreshChildren()
refreshChildren( pane, child );
}
}
});
});
}
, setInstanceKey = function (child, parentPaneState) {
// create a named key for use in state and instance branches
var $c = child.container
, o = child.options
, sm = o.stateManagement
, key = o.instanceKey || $c.data("layoutInstanceKey")
;
if (!key) key = (sm && sm.cookie ? sm.cookie.name : '') || o.name; // look for a name/key
if (!key) key = "layout"+ (++parentPaneState.childIdx); // if no name/key found, generate one
else key = key.replace(/[^\w-]/gi, '_').replace(/_{2,}/g, '_'); // ensure is valid as a hash key
o.instanceKey = key;
$c.data("layoutInstanceKey", key); // useful if layout is destroyed and then recreated
return key;
}
/**
* @param {string} pane The pane being opened, ie: north, south, east, or west
* @param {Object=} newChild New child-layout Instance to add to this pane
*/
, refreshChildren = function (pane, newChild) {
var $P = $Ps[pane]
, pC = children[pane]
, s = state[pane]
, o
;
// check for destroy()ed layouts and update the child pointers & arrays
if ($.isPlainObject( pC )) {
$.each( pC, function (key, child) {
if (child.destroyed) delete pC[key]
});
// if no more children, remove the children hash
if ($.isEmptyObject( pC ))
pC = children[pane] = null; // clear children hash
}
// see if there is a directly-nested layout inside this pane
// if there is, then there can be only ONE child-layout, so check that...
if (!newChild && !pC) {
newChild = $P.data("layout");
}
// if a newChild instance was passed, add it to children[pane]
if (newChild) {
// update child.state
newChild.hasParentLayout = true; // set parent-flag in child
// instanceKey is a key-name used in both state and children
o = newChild.options;
// set a unique child-instance key for this layout, if not already set
setInstanceKey( newChild, s );
// add pointer to pane.children hash
if (!pC) pC = children[pane] = {}; // create an empty children hash
pC[ o.instanceKey ] = newChild.container.data("layout"); // add childLayout instance
}
// ALWAYS refresh the pane.children alias, even if null
Instance[pane].children = children[pane];
// if newChild was NOT passed - see if there is a child layout NOW
if (!newChild) {
createChildren(pane); // MAY create a child and re-call this method
}
}
, windowResize = function () {
var o = options
, delay = Number(o.resizeWithWindowDelay);
if (delay < 10) delay = 100; // MUST have a delay!
// resizing uses a delay-loop because the resize event fires repeatly - except in FF, but delay anyway
timer.clear("winResize"); // if already running
timer.set("winResize", function(){
timer.clear("winResize");
timer.clear("winResizeRepeater");
var dims = elDims( $N, o.inset );
// only trigger resizeAll() if container has changed size
if (dims.innerWidth !== sC.innerWidth || dims.innerHeight !== sC.innerHeight)
resizeAll();
}, delay);
// ALSO set fixed-delay timer, if not already running
if (!timer.data["winResizeRepeater"]) setWindowResizeRepeater();
}
, setWindowResizeRepeater = function () {
var delay = Number(options.resizeWithWindowMaxDelay);
if (delay > 0)
timer.set("winResizeRepeater", function(){ setWindowResizeRepeater(); resizeAll(); }, delay);
}
, unload = function () {
var o = options;
_runCallbacks("onunload_start");
// trigger plugin callabacks for this layout (eg: stateManagement)
runPluginCallbacks( Instance, $.layout.onUnload );
_runCallbacks("onunload_end");
}
/**
* Validate and initialize container CSS and events
*
* @see _create()
*/
, _initContainer = function () {
var
N = $N[0]
, $H = $("html")
, tag = sC.tagName = N.tagName
, id = sC.id = N.id
, cls = sC.className = N.className
, o = options
, name = o.name
, props = "position,margin,padding,border"
, css = "layoutCSS"
, CSS = {}
, hid = "hidden" // used A LOT!
// see if this container is a 'pane' inside an outer-layout
, parent = $N.data("parentLayout") // parent-layout Instance
, pane = $N.data("layoutEdge") // pane-name in parent-layout
, isChild = parent && pane
, num = $.layout.cssNum
, $parent, n
;
// sC = state.container
sC.selector = $N.selector.split(".slice")[0];
sC.ref = (o.name ? o.name +' layout / ' : '') + tag + (id ? "#"+id : cls ? '.['+cls+']' : ''); // used in messages
sC.isBody = (tag === "BODY");
// try to find a parent-layout
if (!isChild && !sC.isBody) {
$parent = $N.closest("."+ $.layout.defaults.panes.paneClass);
parent = $parent.data("parentLayout");
pane = $parent.data("layoutEdge");
isChild = parent && pane;
}
$N .data({
layout: Instance
, layoutContainer: sID // FLAG to indicate this is a layout-container - contains unique internal ID
})
.addClass(o.containerClass)
;
var layoutMethods = {
destroy: ''
, initPanes: ''
, resizeAll: 'resizeAll'
, resize: 'resizeAll'
};
// loop hash and bind all methods - include layoutID namespacing
for (name in layoutMethods) {
$N.bind("layout"+ name.toLowerCase() +"."+ sID, Instance[ layoutMethods[name] || name ]);
}
// if this container is another layout's 'pane', then set child/parent pointers
if (isChild) {
// update parent flag
Instance.hasParentLayout = true;
// set pointers to THIS child-layout (Instance) in parent-layout
parent.refreshChildren( pane, Instance );
}
// SAVE original container CSS for use in destroy()
if (!$N.data(css)) {
// handle props like overflow different for BODY & HTML - has 'system default' values
if (sC.isBody) {
// SAVE <BODY> CSS
$N.data(css, $.extend( styles($N, props), {
height: $N.css("height")
, overflow: $N.css("overflow")
, overflowX: $N.css("overflowX")
, overflowY: $N.css("overflowY")
}));
// ALSO SAVE <HTML> CSS
$H.data(css, $.extend( styles($H, 'padding'), {
height: "auto" // FF would return a fixed px-size!
, overflow: $H.css("overflow")
, overflowX: $H.css("overflowX")
, overflowY: $H.css("overflowY")
}));
}
else // handle props normally for non-body elements
$N.data(css, styles($N, props+",top,bottom,left,right,width,height,overflow,overflowX,overflowY") );
}
try {
// common container CSS
CSS = {
overflow: hid
, overflowX: hid
, overflowY: hid
};
$N.css( CSS );
if (o.inset && !$.isPlainObject(o.inset)) {
// can specify a single number for equal outset all-around
n = parseInt(o.inset, 10) || 0;
o.inset = {
top: n
, bottom: n
, left: n
, right: n
};
}
// format html & body if this is a full page layout
if (sC.isBody) {
// if HTML has padding, use this as an outer-spacing around BODY
if (!o.outset) {
// use padding from parent-elem (HTML) as outset
o.outset = {
top: num($H, "paddingTop")
, bottom: num($H, "paddingBottom")
, left: num($H, "paddingLeft")
, right: num($H, "paddingRight")
};
}
else if (!$.isPlainObject(o.outset)) {
// can specify a single number for equal outset all-around
n = parseInt(o.outset, 10) || 0;
o.outset = {
top: n
, bottom: n
, left: n
, right: n
};
}
// HTML
$H.css( CSS ).css({
height: "100%"
, border: "none" // no border or padding allowed when using height = 100%
, padding: 0 // ditto
, margin: 0
});
// BODY
if (browser.isIE6) {
// IE6 CANNOT use the trick of setting absolute positioning on all 4 sides - must have 'height'
$N.css({
width: "100%"
, height: "100%"
, border: "none" // no border or padding allowed when using height = 100%
, padding: 0 // ditto
, margin: 0
, position: "relative"
});
// convert body padding to an inset option - the border cannot be measured in IE6!
if (!o.inset) o.inset = elDims( $N ).inset;
}
else { // use absolute positioning for BODY to allow borders & padding without overflow
$N.css({
width: "auto"
, height: "auto"
, margin: 0
, position: "absolute" // allows for border and padding on BODY
});
// apply edge-positioning created above
$N.css( o.outset );
}
// set current layout-container dimensions
$.extend(sC, elDims( $N, o.inset )); // passing inset means DO NOT include insetX values
}
else {
// container MUST have 'position'
var p = $N.css("position");
if (!p || !p.match(/(fixed|absolute|relative)/))
$N.css("position","relative");
// set current layout-container dimensions
if ( $N.is(":visible") ) {
$.extend(sC, elDims( $N, o.inset )); // passing inset means DO NOT change insetX (padding) values
if (sC.innerHeight < 1) // container has no 'height' - warn developer
_log( o.errors.noContainerHeight.replace(/CONTAINER/, sC.ref) );
}
}
// if container has min-width/height, then enable scrollbar(s)
if ( num($N, "minWidth") ) $N.parent().css("overflowX","auto");
if ( num($N, "minHeight") ) $N.parent().css("overflowY","auto");
} catch (ex) {}
}
/**
* Bind layout hotkeys - if options enabled
*
* @see _create() and addPane()
* @param {string=} [panes=""] The edge(s) to process
*/
, initHotkeys = function (panes) {
panes = panes ? panes.split(",") : _c.borderPanes;
// bind keyDown to capture hotkeys, if option enabled for ANY pane
$.each(panes, function (i, pane) {
var o = options[pane];
if (o.enableCursorHotkey || o.customHotkey) {
$(document).bind("keydown."+ sID, keyDown); // only need to bind this ONCE
return false; // BREAK - binding was done
}
});
}
/**
* Build final OPTIONS data
*
* @see _create()
*/
, initOptions = function () {
var data, d, pane, key, val, i, c, o;
// reprocess user's layout-options to have correct options sub-key structure
opts = $.layout.transformData( opts, true ); // panes = default subkey
// auto-rename old options for backward compatibility
opts = $.layout.backwardCompatibility.renameAllOptions( opts );
// if user-options has 'panes' key (pane-defaults), clean it...
if (!$.isEmptyObject(opts.panes)) {
// REMOVE any pane-defaults that MUST be set per-pane
data = $.layout.optionsMap.noDefault;
for (i=0, c=data.length; i<c; i++) {
key = data[i];
delete opts.panes[key]; // OK if does not exist
}
// REMOVE any layout-options specified under opts.panes
data = $.layout.optionsMap.layout;
for (i=0, c=data.length; i<c; i++) {
key = data[i];
delete opts.panes[key]; // OK if does not exist
}
}
// MOVE any NON-layout-options from opts-root to opts.panes
data = $.layout.optionsMap.layout;
var rootKeys = $.layout.config.optionRootKeys;
for (key in opts) {
val = opts[key];
if ($.inArray(key, rootKeys) < 0 && $.inArray(key, data) < 0) {
if (!opts.panes[key])
opts.panes[key] = $.isPlainObject(val) ? $.extend(true, {}, val) : val;
delete opts[key]
}
}
// START by updating ALL options from opts
$.extend(true, options, opts);
// CREATE final options (and config) for EACH pane
$.each(_c.allPanes, function (i, pane) {
// apply 'pane-defaults' to CONFIG.[PANE]
_c[pane] = $.extend(true, {}, _c.panes, _c[pane]);
d = options.panes;
o = options[pane];
// center-pane uses SOME keys in defaults.panes branch
if (pane === 'center') {
// ONLY copy keys from opts.panes listed in: $.layout.optionsMap.center
data = $.layout.optionsMap.center; // list of 'center-pane keys'
for (i=0, c=data.length; i<c; i++) { // loop the list...
key = data[i];
// only need to use pane-default if pane-specific value not set
if (!opts.center[key] && (opts.panes[key] || !o[key]))
o[key] = d[key]; // pane-default
}
}
else {
// border-panes use ALL keys in defaults.panes branch
o = options[pane] = $.extend(true, {}, d, o); // re-apply pane-specific opts AFTER pane-defaults
createFxOptions( pane );
// ensure all border-pane-specific base-classes exist
if (!o.resizerClass) o.resizerClass = "ui-layout-resizer";
if (!o.togglerClass) o.togglerClass = "ui-layout-toggler";
}
// ensure we have base pane-class (ALL panes)
if (!o.paneClass) o.paneClass = "ui-layout-pane";
});
// update options.zIndexes if a zIndex-option specified
var zo = opts.zIndex
, z = options.zIndexes;
if (zo > 0) {
z.pane_normal = zo;
z.content_mask = max(zo+1, z.content_mask); // MIN = +1
z.resizer_normal = max(zo+2, z.resizer_normal); // MIN = +2
}
// DELETE 'panes' key now that we are done - values were copied to EACH pane
delete options.panes;
function createFxOptions ( pane ) {
var o = options[pane]
, d = options.panes;
// ensure fxSettings key to avoid errors
if (!o.fxSettings) o.fxSettings = {};
if (!d.fxSettings) d.fxSettings = {};
$.each(["_open","_close","_size"], function (i,n) {
var
sName = "fxName"+ n
, sSpeed = "fxSpeed"+ n
, sSettings = "fxSettings"+ n
// recalculate fxName according to specificity rules
, fxName = o[sName] =
o[sName] // options.west.fxName_open
|| d[sName] // options.panes.fxName_open
|| o.fxName // options.west.fxName
|| d.fxName // options.panes.fxName
|| "none" // MEANS $.layout.defaults.panes.fxName == "" || false || null || 0
, fxExists = $.effects && ($.effects[fxName] || ($.effects.effect && $.effects.effect[fxName]))
;
// validate fxName to ensure is valid effect - MUST have effect-config data in options.effects
if (fxName === "none" || !options.effects[fxName] || !fxExists)
fxName = o[sName] = "none"; // effect not loaded OR unrecognized fxName
// set vars for effects subkeys to simplify logic
var fx = options.effects[fxName] || {} // effects.slide
, fx_all = fx.all || null // effects.slide.all
, fx_pane = fx[pane] || null // effects.slide.west
;
// create fxSpeed[_open|_close|_size]
o[sSpeed] =
o[sSpeed] // options.west.fxSpeed_open
|| d[sSpeed] // options.west.fxSpeed_open
|| o.fxSpeed // options.west.fxSpeed
|| d.fxSpeed // options.panes.fxSpeed
|| null // DEFAULT - let fxSetting.duration control speed
;
// create fxSettings[_open|_close|_size]
o[sSettings] = $.extend(
true
, {}
, fx_all // effects.slide.all
, fx_pane // effects.slide.west
, d.fxSettings // options.panes.fxSettings
, o.fxSettings // options.west.fxSettings
, d[sSettings] // options.panes.fxSettings_open
, o[sSettings] // options.west.fxSettings_open
);
});
// DONE creating action-specific-settings for this pane,
// so DELETE generic options - are no longer meaningful
delete o.fxName;
delete o.fxSpeed;
delete o.fxSettings;
}
}
/**
* Initialize module objects, styling, size and position for all panes
*
* @see _initElements()
* @param {string} pane The pane to process
*/
, getPane = function (pane) {
var sel = options[pane].paneSelector;
if (sel.substr(0,1)==="#") // ID selector
// NOTE: elements selected 'by ID' DO NOT have to be 'children'
return $N.find(sel).eq(0);
else { // class or other selector
var $P = $N.children(sel).eq(0);
// look for the pane nested inside a 'form' element
return $P.length ? $P : $N.children("form:first").children(sel).eq(0);
}
}
/**
* @param {Object=} evt
*/
, initPanes = function (evt) {
// stopPropagation if called by trigger("layoutinitpanes") - use evtPane utility
evtPane(evt);
// NOTE: do north & south FIRST so we can measure their height - do center LAST
$.each(_c.allPanes, function (idx, pane) {
addPane( pane, true );
});
// init the pane-handles NOW in case we have to hide or close the pane below
initHandles();
// now that all panes have been initialized and initially-sized,
// make sure there is really enough space available for each pane
$.each(_c.borderPanes, function (i, pane) {
if ($Ps[pane] && state[pane].isVisible) { // pane is OPEN
setSizeLimits(pane);
makePaneFit(pane); // pane may be Closed, Hidden or Resized by makePaneFit()
}
});
// size center-pane AGAIN in case we 'closed' a border-pane in loop above
sizeMidPanes("center");
// Chrome/Webkit sometimes fires callbacks BEFORE it completes resizing!
// Before RC30.3, there was a 10ms delay here, but that caused layout
// to load asynchrously, which is BAD, so try skipping delay for now
// process pane contents and callbacks, and init/resize child-layout if exists
$.each(_c.allPanes, function (idx, pane) {
afterInitPane(pane);
});
}
/**
* Add a pane to the layout - subroutine of initPanes()
*
* @see initPanes()
* @param {string} pane The pane to process
* @param {boolean=} [force=false] Size content after init
*/
, addPane = function (pane, force) {
if ( !force && !isInitialized() ) return;
var
o = options[pane]
, s = state[pane]
, c = _c[pane]
, dir = c.dir
, fx = s.fx
, spacing = o.spacing_open || 0
, isCenter = (pane === "center")
, CSS = {}
, $P = $Ps[pane]
, size, minSize, maxSize, child
;
// if pane-pointer already exists, remove the old one first
if ($P)
removePane( pane, false, true, false );
else
$Cs[pane] = false; // init
$P = $Ps[pane] = getPane(pane);
if (!$P.length) {
$Ps[pane] = false; // logic
return;
}
// SAVE original Pane CSS
if (!$P.data("layoutCSS")) {
var props = "position,top,left,bottom,right,width,height,overflow,zIndex,display,backgroundColor,padding,margin,border";
$P.data("layoutCSS", styles($P, props));
}
// create alias for pane data in Instance - initHandles will add more
Instance[pane] = {
name: pane
, pane: $Ps[pane]
, content: $Cs[pane]
, options: options[pane]
, state: state[pane]
, children: children[pane]
};
// add classes, attributes & events
$P .data({
parentLayout: Instance // pointer to Layout Instance
, layoutPane: Instance[pane] // NEW pointer to pane-alias-object
, layoutEdge: pane
, layoutRole: "pane"
})
.css(c.cssReq).css("zIndex", options.zIndexes.pane_normal)
.css(o.applyDemoStyles ? c.cssDemo : {}) // demo styles
.addClass( o.paneClass +" "+ o.paneClass+"-"+pane ) // default = "ui-layout-pane ui-layout-pane-west" - may be a dupe of 'paneSelector'
.bind("mouseenter."+ sID, addHover )
.bind("mouseleave."+ sID, removeHover )
;
var paneMethods = {
hide: ''
, show: ''
, toggle: ''
, close: ''
, open: ''
, slideOpen: ''
, slideClose: ''
, slideToggle: ''
, size: 'sizePane'
, sizePane: 'sizePane'
, sizeContent: ''
, sizeHandles: ''
, enableClosable: ''
, disableClosable: ''
, enableSlideable: ''
, disableSlideable: ''
, enableResizable: ''
, disableResizable: ''
, swapPanes: 'swapPanes'
, swap: 'swapPanes'
, move: 'swapPanes'
, removePane: 'removePane'
, remove: 'removePane'
, createChildren: ''
, resizeChildren: ''
, resizeAll: 'resizeAll'
, resizeLayout: 'resizeAll'
}
, name;
// loop hash and bind all methods - include layoutID namespacing
for (name in paneMethods) {
$P.bind("layoutpane"+ name.toLowerCase() +"."+ sID, Instance[ paneMethods[name] || name ]);
}
// see if this pane has a 'scrolling-content element'
initContent(pane, false); // false = do NOT sizeContent() - called later
if (!isCenter) {
// call _parseSize AFTER applying pane classes & styles - but before making visible (if hidden)
// if o.size is auto or not valid, then MEASURE the pane and use that as its 'size'
size = s.size = _parseSize(pane, o.size);
minSize = _parseSize(pane,o.minSize) || 1;
maxSize = _parseSize(pane,o.maxSize) || 100000;
if (size > 0) size = max(min(size, maxSize), minSize);
s.autoResize = o.autoResize; // used with percentage sizes
// state for border-panes
s.isClosed = false; // true = pane is closed
s.isSliding = false; // true = pane is currently open by 'sliding' over adjacent panes
s.isResizing= false; // true = pane is in process of being resized
s.isHidden = false; // true = pane is hidden - no spacing, resizer or toggler is visible!
// array for 'pin buttons' whose classNames are auto-updated on pane-open/-close
if (!s.pins) s.pins = [];
}
// states common to ALL panes
s.tagName = $P[0].tagName;
s.edge = pane; // useful if pane is (or about to be) 'swapped' - easy find out where it is (or is going)
s.noRoom = false; // true = pane 'automatically' hidden due to insufficient room - will unhide automatically
s.isVisible = true; // false = pane is invisible - closed OR hidden - simplify logic
// init pane positioning
setPanePosition( pane );
// if pane is not visible,
if (dir === "horz") // north or south pane
CSS.height = cssH($P, size);
else if (dir === "vert") // east or west pane
CSS.width = cssW($P, size);
//else if (isCenter) {}
$P.css(CSS); // apply size -- top, bottom & height will be set by sizeMidPanes
if (dir != "horz") sizeMidPanes(pane, true); // true = skipCallback
// if manually adding a pane AFTER layout initialization, then...
if (state.initialized) {
initHandles( pane );
initHotkeys( pane );
}
// close or hide the pane if specified in settings
if (o.initClosed && o.closable && !o.initHidden)
close(pane, true, true); // true, true = force, noAnimation
else if (o.initHidden || o.initClosed)
hide(pane); // will be completely invisible - no resizer or spacing
else if (!s.noRoom)
// make the pane visible - in case was initially hidden
$P.css("display","block");
// ELSE setAsOpen() - called later by initHandles()
// RESET visibility now - pane will appear IF display:block
$P.css("visibility","visible");
// check option for auto-handling of pop-ups & drop-downs
if (o.showOverflowOnHover)
$P.hover( allowOverflow, resetOverflow );
// if manually adding a pane AFTER layout initialization, then...
if (state.initialized) {
afterInitPane( pane );
}
}
, afterInitPane = function (pane) {
var $P = $Ps[pane]
, s = state[pane]
, o = options[pane]
;
if (!$P) return;
// see if there is a directly-nested layout inside this pane
if ($P.data("layout"))
refreshChildren( pane, $P.data("layout") );
// process pane contents and callbacks, and init/resize child-layout if exists
if (s.isVisible) { // pane is OPEN
if (state.initialized) // this pane was added AFTER layout was created
resizeAll(); // will also sizeContent
else
sizeContent(pane);
if (o.triggerEventsOnLoad)
_runCallbacks("onresize_end", pane);
else // automatic if onresize called, otherwise call it specifically
// resize child - IF inner-layout already exists (created before this layout)
resizeChildren(pane, true); // a previously existing childLayout
}
// init childLayouts - even if pane is not visible
if (o.initChildren && o.children)
createChildren(pane);
}
/**
* @param {string=} panes The pane(s) to process
*/
, setPanePosition = function (panes) {
panes = panes ? panes.split(",") : _c.borderPanes;
// create toggler DIVs for each pane, and set object pointers for them, eg: $R.north = north toggler DIV
$.each(panes, function (i, pane) {
var $P = $Ps[pane]
, $R = $Rs[pane]
, o = options[pane]
, s = state[pane]
, side = _c[pane].side
, CSS = {}
;
if (!$P) return; // pane does not exist - skip
// set css-position to account for container borders & padding
switch (pane) {
case "north": CSS.top = sC.inset.top;
CSS.left = sC.inset.left;
CSS.right = sC.inset.right;
break;
case "south": CSS.bottom = sC.inset.bottom;
CSS.left = sC.inset.left;
CSS.right = sC.inset.right;
break;
case "west": CSS.left = sC.inset.left; // top, bottom & height set by sizeMidPanes()
break;
case "east": CSS.right = sC.inset.right; // ditto
break;
case "center": // top, left, width & height set by sizeMidPanes()
}
// apply position
$P.css(CSS);
// update resizer position
if ($R && s.isClosed)
$R.css(side, sC.inset[side]);
else if ($R && !s.isHidden)
$R.css(side, sC.inset[side] + getPaneSize(pane));
});
}
/**
* Initialize module objects, styling, size and position for all resize bars and toggler buttons
*
* @see _create()
* @param {string=} [panes=""] The edge(s) to process
*/
, initHandles = function (panes) {
panes = panes ? panes.split(",") : _c.borderPanes;
// create toggler DIVs for each pane, and set object pointers for them, eg: $R.north = north toggler DIV
$.each(panes, function (i, pane) {
var $P = $Ps[pane];
$Rs[pane] = false; // INIT
$Ts[pane] = false;
if (!$P) return; // pane does not exist - skip
var o = options[pane]
, s = state[pane]
, c = _c[pane]
, paneId = o.paneSelector.substr(0,1) === "#" ? o.paneSelector.substr(1) : ""
, rClass = o.resizerClass
, tClass = o.togglerClass
, spacing = (s.isVisible ? o.spacing_open : o.spacing_closed)
, _pane = "-"+ pane // used for classNames
, _state = (s.isVisible ? "-open" : "-closed") // used for classNames
, I = Instance[pane]
// INIT RESIZER BAR
, $R = I.resizer = $Rs[pane] = $("<div></div>")
// INIT TOGGLER BUTTON
, $T = I.toggler = (o.closable ? $Ts[pane] = $("<div></div>") : false)
;
//if (s.isVisible && o.resizable) ... handled by initResizable
if (!s.isVisible && o.slidable)
$R.attr("title", o.tips.Slide).css("cursor", o.sliderCursor);
$R // if paneSelector is an ID, then create a matching ID for the resizer, eg: "#paneLeft" => "paneLeft-resizer"
.attr("id", paneId ? paneId +"-resizer" : "" )
.data({
parentLayout: Instance
, layoutPane: Instance[pane] // NEW pointer to pane-alias-object
, layoutEdge: pane
, layoutRole: "resizer"
})
.css(_c.resizers.cssReq).css("zIndex", options.zIndexes.resizer_normal)
.css(o.applyDemoStyles ? _c.resizers.cssDemo : {}) // add demo styles
.addClass(rClass +" "+ rClass+_pane)
.hover(addHover, removeHover) // ALWAYS add hover-classes, even if resizing is not enabled - handle with CSS instead
.hover(onResizerEnter, onResizerLeave) // ALWAYS NEED resizer.mouseleave to balance toggler.mouseenter
.mousedown($.layout.disableTextSelection) // prevent text-selection OUTSIDE resizer
.mouseup($.layout.enableTextSelection) // not really necessary, but just in case
.appendTo($N) // append DIV to container
;
if ($.fn.disableSelection)
$R.disableSelection(); // prevent text-selection INSIDE resizer
if (o.resizerDblClickToggle)
$R.bind("dblclick."+ sID, toggle );
if ($T) {
$T // if paneSelector is an ID, then create a matching ID for the resizer, eg: "#paneLeft" => "#paneLeft-toggler"
.attr("id", paneId ? paneId +"-toggler" : "" )
.data({
parentLayout: Instance
, layoutPane: Instance[pane] // NEW pointer to pane-alias-object
, layoutEdge: pane
, layoutRole: "toggler"
})
.css(_c.togglers.cssReq) // add base/required styles
.css(o.applyDemoStyles ? _c.togglers.cssDemo : {}) // add demo styles
.addClass(tClass +" "+ tClass+_pane)
.hover(addHover, removeHover) // ALWAYS add hover-classes, even if toggling is not enabled - handle with CSS instead
.bind("mouseenter", onResizerEnter) // NEED toggler.mouseenter because mouseenter MAY NOT fire on resizer
.appendTo($R) // append SPAN to resizer DIV
;
// ADD INNER-SPANS TO TOGGLER
if (o.togglerContent_open) // ui-layout-open
$("<span>"+ o.togglerContent_open +"</span>")
.data({
layoutEdge: pane
, layoutRole: "togglerContent"
})
.data("layoutRole", "togglerContent")
.data("layoutEdge", pane)
// .addClass("content content-open")
.addClass("ui-content content-open") // ThinkGem content 改为 ui-content 解决与AdminLTE类名冲突
.css("display","none")
.appendTo( $T )
//.hover( addHover, removeHover ) // use ui-layout-toggler-west-hover .content-open instead!
;
if (o.togglerContent_closed) // ui-layout-closed
$("<span>"+ o.togglerContent_closed +"</span>")
.data({
layoutEdge: pane
, layoutRole: "togglerContent"
})
// .addClass("content content-closed")
.addClass("ui-content content-closed") // ThinkGem content 改为 ui-content 解决与AdminLTE类名冲突
.css("display","none")
.appendTo( $T )
//.hover( addHover, removeHover ) // use ui-layout-toggler-west-hover .content-closed instead!
;
// ADD TOGGLER.click/.hover
enableClosable(pane);
}
// add Draggable events
initResizable(pane);
// ADD CLASSNAMES & SLIDE-BINDINGS - eg: class="resizer resizer-west resizer-open"
if (s.isVisible)
setAsOpen(pane); // onOpen will be called, but NOT onResize
else {
setAsClosed(pane); // onClose will be called
bindStartSlidingEvents(pane, true); // will enable events IF option is set
}
});
// SET ALL HANDLE DIMENSIONS
sizeHandles();
}
/**
* Initialize scrolling ui-layout-content div - if exists
*
* @see initPane() - or externally after an Ajax injection
* @param {string} pane The pane to process
* @param {boolean=} [resize=true] Size content after init
*/
, initContent = function (pane, resize) {
if (!isInitialized()) return;
var
o = options[pane]
, sel = o.contentSelector
, I = Instance[pane]
, $P = $Ps[pane]
, $C
;
if (sel) $C = I.content = $Cs[pane] = (o.findNestedContent)
? $P.find(sel).eq(0) // match 1-element only
: $P.children(sel).eq(0)
;
if ($C && $C.length) {
$C.data("layoutRole", "content");
// SAVE original Content CSS
if (!$C.data("layoutCSS"))
$C.data("layoutCSS", styles($C, "height"));
$C.css( _c.content.cssReq );
if (o.applyDemoStyles) {
$C.css( _c.content.cssDemo ); // add padding & overflow: auto to content-div
$P.css( _c.content.cssDemoPane ); // REMOVE padding/scrolling from pane
}
// ensure no vertical scrollbar on pane - will mess up measurements
if ($P.css("overflowX").match(/(scroll|auto)/)) {
$P.css("overflow", "hidden");
}
state[pane].content = {}; // init content state
if (resize !== false) sizeContent(pane);
// sizeContent() is called AFTER init of all elements
}
else
I.content = $Cs[pane] = false;
}
/**
* Add resize-bars to all panes that specify it in options
* -dependancy: $.fn.resizable - will skip if not found
*
* @see _create()
* @param {string=} [panes=""] The edge(s) to process
*/
, initResizable = function (panes) {
var draggingAvailable = $.layout.plugins.draggable
, side // set in start()
;
panes = panes ? panes.split(",") : _c.borderPanes;
$.each(panes, function (idx, pane) {
var o = options[pane];
if (!draggingAvailable || !$Ps[pane] || !o.resizable) {
o.resizable = false;
return true; // skip to next
}
var s = state[pane]
, z = options.zIndexes
, c = _c[pane]
, side = c.dir=="horz" ? "top" : "left"
, $P = $Ps[pane]
, $R = $Rs[pane]
, base = o.resizerClass
, lastPos = 0 // used when live-resizing
, r, live // set in start because may change
// 'drag' classes are applied to the ORIGINAL resizer-bar while dragging is in process
, resizerClass = base+"-drag" // resizer-drag
, resizerPaneClass = base+"-"+pane+"-drag" // resizer-north-drag
// 'helper' class is applied to the CLONED resizer-bar while it is being dragged
, helperClass = base+"-dragging" // resizer-dragging
, helperPaneClass = base+"-"+pane+"-dragging" // resizer-north-dragging
, helperLimitClass = base+"-dragging-limit" // resizer-drag
, helperPaneLimitClass = base+"-"+pane+"-dragging-limit" // resizer-north-drag
, helperClassesSet = false // logic var
;
if (!s.isClosed)
$R.attr("title", o.tips.Resize)
.css("cursor", o.resizerCursor); // n-resize, s-resize, etc
$R.draggable({
containment: $N[0] // limit resizing to layout container
, axis: (c.dir=="horz" ? "y" : "x") // limit resizing to horz or vert axis
, delay: 0
, distance: 1
, grid: o.resizingGrid
// basic format for helper - style it using class: .ui-draggable-dragging
, helper: "clone"
, opacity: o.resizerDragOpacity
, addClasses: false // avoid ui-state-disabled class when disabled
//, iframeFix: o.draggableIframeFix // TODO: consider using when bug is fixed
, zIndex: z.resizer_drag
, iframeFix: true // ThinkGem 修复有iframe时拖拽不平滑问题
, start: function (e, ui) {
// REFRESH options & state pointers in case we used swapPanes
o = options[pane];
s = state[pane];
// re-read options
live = o.livePaneResizing;
// ondrag_start callback - will CANCEL hide if returns false
// TODO: dragging CANNOT be cancelled like this, so see if there is a way?
if (false === _runCallbacks("ondrag_start", pane)) return false;
s.isResizing = true; // prevent pane from closing while resizing
state.paneResizing = pane; // easy to see if ANY pane is resizing
timer.clear(pane+"_closeSlider"); // just in case already triggered
// SET RESIZER LIMITS - used in drag()
setSizeLimits(pane); // update pane/resizer state
r = s.resizerPosition;
lastPos = ui.position[ side ];
$R.addClass( resizerClass +" "+ resizerPaneClass ); // add drag classes
helperClassesSet = false; // reset logic var - see drag()
// MASK PANES CONTAINING IFRAMES, APPLETS OR OTHER TROUBLESOME ELEMENTS
showMasks( pane, { resizing: true });
}
, drag: function (e, ui) {
if (!helperClassesSet) { // can only add classes after clone has been added to the DOM
//$(".ui-draggable-dragging")
ui.helper
.addClass( helperClass +" "+ helperPaneClass ) // add helper classes
.css({ right: "auto", bottom: "auto" }) // fix dir="rtl" issue
.children().css("visibility","hidden") // hide toggler inside dragged resizer-bar
;
helperClassesSet = true;
// draggable bug!? RE-SET zIndex to prevent E/W resize-bar showing through N/S pane!
if (s.isSliding) $Ps[pane].css("zIndex", z.pane_sliding);
}
// CONTAIN RESIZER-BAR TO RESIZING LIMITS
var limit = 0;
if (ui.position[side] < r.min) {
ui.position[side] = r.min;
limit = -1;
}
else if (ui.position[side] > r.max) {
ui.position[side] = r.max;
limit = 1;
}
// ADD/REMOVE dragging-limit CLASS
if (limit) {
ui.helper.addClass( helperLimitClass +" "+ helperPaneLimitClass ); // at dragging-limit
window.defaultStatus = (limit>0 && pane.match(/(north|west)/)) || (limit<0 && pane.match(/(south|east)/)) ? o.tips.maxSizeWarning : o.tips.minSizeWarning;
}
else {
ui.helper.removeClass( helperLimitClass +" "+ helperPaneLimitClass ); // not at dragging-limit
window.defaultStatus = "";
}
// DYNAMICALLY RESIZE PANES IF OPTION ENABLED
// won't trigger unless resizer has actually moved!
if (live && Math.abs(ui.position[side] - lastPos) >= o.liveResizingTolerance) {
lastPos = ui.position[side];
resizePanes(e, ui, pane)
}
}
, stop: function (e, ui) {
$('body').enableSelection(); // RE-ENABLE TEXT SELECTION
window.defaultStatus = ""; // clear 'resizing limit' message from statusbar
$R.removeClass( resizerClass +" "+ resizerPaneClass ); // remove drag classes from Resizer
s.isResizing = false;
state.paneResizing = false; // easy to see if ANY pane is resizing
resizePanes(e, ui, pane, true); // true = resizingDone
}
});
});
/**
* resizePanes
*
* Sub-routine called from stop() - and drag() if livePaneResizing
*
* @param {!Object} evt
* @param {!Object} ui
* @param {string} pane
* @param {boolean=} [resizingDone=false]
*/
var resizePanes = function (evt, ui, pane, resizingDone) {
var dragPos = ui.position
, c = _c[pane]
, o = options[pane]
, s = state[pane]
, resizerPos
;
switch (pane) {
case "north": resizerPos = dragPos.top; break;
case "west": resizerPos = dragPos.left; break;
case "south": resizerPos = sC.layoutHeight - dragPos.top - o.spacing_open; break;
case "east": resizerPos = sC.layoutWidth - dragPos.left - o.spacing_open; break;
}
// remove container margin from resizer position to get the pane size
var newSize = resizerPos - sC.inset[c.side];
// Disable OR Resize Mask(s) created in drag.start
if (!resizingDone) {
// ensure we meet liveResizingTolerance criteria
if (Math.abs(newSize - s.size) < o.liveResizingTolerance)
return; // SKIP resize this time
// resize the pane
manualSizePane(pane, newSize, false, true); // true = noAnimation
sizeMasks(); // resize all visible masks
}
else { // resizingDone
// ondrag_end callback
if (false !== _runCallbacks("ondrag_end", pane))
manualSizePane(pane, newSize, false, true); // true = noAnimation
hideMasks(true); // true = force hiding all masks even if one is 'sliding'
if (s.isSliding) // RE-SHOW 'object-masks' so objects won't show through sliding pane
showMasks( pane, { resizing: true });
}
};
}
/**
* sizeMask
*
* Needed to overlay a DIV over an IFRAME-pane because mask CANNOT be *inside* the pane
* Called when mask created, and during livePaneResizing
*/
, sizeMask = function () {
var $M = $(this)
, pane = $M.data("layoutMask") // eg: "west"
, s = state[pane]
;
// only masks over an IFRAME-pane need manual resizing
if (s.tagName == "IFRAME" && s.isVisible) // no need to mask closed/hidden panes
$M.css({
top: s.offsetTop
, left: s.offsetLeft
, width: s.outerWidth
, height: s.outerHeight
});
/* ALT Method...
var $P = $Ps[pane];
$M.css( $P.position() ).css({ width: $P[0].offsetWidth, height: $P[0].offsetHeight });
*/
}
, sizeMasks = function () {
$Ms.each( sizeMask ); // resize all 'visible' masks
}
/**
* @param {string} pane The pane being resized, animated or isSliding
* @param {Object=} [args] (optional) Options: which masks to apply, and to which panes
*/
, showMasks = function (pane, args) {
var c = _c[pane]
, panes = ["center"]
, z = options.zIndexes
, a = $.extend({
objectsOnly: false
, animation: false
, resizing: true
, sliding: state[pane].isSliding
}, args )
, o, s
;
if (a.resizing)
panes.push( pane );
if (a.sliding)
panes.push( _c.oppositeEdge[pane] ); // ADD the oppositeEdge-pane
if (c.dir === "horz") {
panes.push("west");
panes.push("east");
}
$.each(panes, function(i,p){
s = state[p];
o = options[p];
if (s.isVisible && ( o.maskObjects || (!a.objectsOnly && o.maskContents) )) {
getMasks(p).each(function(){
sizeMask.call(this);
this.style.zIndex = s.isSliding ? z.pane_sliding+1 : z.pane_normal+1;
this.style.display = "block";
});
}
});
}
/**
* @param {boolean=} force Hide masks even if a pane is sliding
*/
, hideMasks = function (force) {
// ensure no pane is resizing - could be a timing issue
if (force || !state.paneResizing) {
$Ms.hide(); // hide ALL masks
}
// if ANY pane is sliding, then DO NOT remove masks from panes with maskObjects enabled
else if (!force && !$.isEmptyObject( state.panesSliding )) {
var i = $Ms.length - 1
, p, $M;
for (; i >= 0; i--) {
$M = $Ms.eq(i);
p = $M.data("layoutMask");
if (!options[p].maskObjects) {
$M.hide();
}
}
}
}
/**
* @param {string} pane
*/
, getMasks = function (pane) {
var $Masks = $([])
, $M, i = 0, c = $Ms.length
;
for (; i<c; i++) {
$M = $Ms.eq(i);
if ($M.data("layoutMask") === pane)
$Masks = $Masks.add( $M );
}
if ($Masks.length)
return $Masks;
else
return createMasks(pane);
}
/**
* createMasks
*
* Generates both DIV (ALWAYS used) and IFRAME (optional) elements as masks
* An IFRAME mask is created *under* the DIV when maskObjects=true, because a DIV cannot mask an applet
*
* @param {string} pane
*/
, createMasks = function (pane) {
var
$P = $Ps[pane]
, s = state[pane]
, o = options[pane]
, z = options.zIndexes
, isIframe, el, $M, css, i
;
if (!o.maskContents && !o.maskObjects) return $([]);
// if o.maskObjects=true, then loop TWICE to create BOTH kinds of mask, else only create a DIV
for (i=0; i < (o.maskObjects ? 2 : 1); i++) {
isIframe = o.maskObjects && i==0;
el = document.createElement( isIframe ? "iframe" : "div" );
$M = $(el).data("layoutMask", pane); // add data to relate mask to pane
el.className = "ui-layout-mask ui-layout-mask-"+ pane; // for user styling
css = el.style;
// Both DIVs and IFRAMES
css.background = "#FFF";
css.position = "absolute";
css.display = "block";
if (isIframe) { // IFRAME-only props
el.src = "about:blank";
el.frameborder = 0;
css.border = 0;
css.opacity = 0;
css.filter = "Alpha(Opacity='0')";
//el.allowTransparency = true; - for IE, but breaks masking ability!
}
else { // DIV-only props
css.opacity = 0.001;
css.filter = "Alpha(Opacity='1')";
}
// if pane IS an IFRAME, then must mask the pane itself
if (s.tagName == "IFRAME") {
// NOTE sizing done by a subroutine so can be called during live-resizing
css.zIndex = z.pane_normal+1; // 1-higher than pane
$N.append( el ); // append to LAYOUT CONTAINER
}
// otherwise put masks *inside the pane* to mask its contents
else {
$M.addClass("ui-layout-mask-inside-pane");
css.zIndex = o.maskZindex || z.content_mask; // usually 1, but customizable
css.top = 0;
css.left = 0;
css.width = "100%";
css.height = "100%";
$P.append( el ); // append INSIDE pane element
}
// add Mask to cached array so can be resized & reused
$Ms = $Ms.add( el );
}
return $Ms;
}
/**
* Destroy this layout and reset all elements
*
* @param {boolean=} [destroyChildren=false] Destory Child-Layouts first?
*/
, destroy = function (evt_or_destroyChildren, destroyChildren) {
// UNBIND layout events and remove global object
$(window).unbind("."+ sID); // resize & unload
$(document).unbind("."+ sID); // keyDown (hotkeys)
if (typeof evt_or_destroyChildren === "object")
// stopPropagation if called by trigger("layoutdestroy") - use evtPane utility
evtPane(evt_or_destroyChildren);
else // no event, so transfer 1st param to destroyChildren param
destroyChildren = evt_or_destroyChildren;
// need to look for parent layout BEFORE we remove the container data, else skips a level
//var parentPane = Instance.hasParentLayout ? $.layout.getParentPaneInstance( $N ) : null;
// reset layout-container
$N .clearQueue()
.removeData("layout")
.removeData("layoutContainer")
.removeClass(options.containerClass)
.unbind("."+ sID) // remove ALL Layout events
;
// remove all mask elements that have been created
$Ms.remove();
// loop all panes to remove layout classes, attributes and bindings
$.each(_c.allPanes, function (i, pane) {
removePane( pane, false, true, destroyChildren ); // true = skipResize
});
// do NOT reset container CSS if is a 'pane' (or 'content') in an outer-layout - ie, THIS layout is 'nested'
var css = "layoutCSS";
if ($N.data(css) && !$N.data("layoutRole")) // RESET CSS
$N.css( $N.data(css) ).removeData(css);
// for full-page layouts, also reset the <HTML> CSS
if (sC.tagName === "BODY" && ($N = $("html")).data(css)) // RESET <HTML> CSS
$N.css( $N.data(css) ).removeData(css);
// trigger plugins for this layout, if there are any
runPluginCallbacks( Instance, $.layout.onDestroy );
// trigger state-management and onunload callback
unload();
// clear the Instance of everything except for container & options (so could recreate)
// RE-CREATE: myLayout = myLayout.container.layout( myLayout.options );
for (var n in Instance)
if (!n.match(/^(container|options)$/)) delete Instance[ n ];
// add a 'destroyed' flag to make it easy to check
Instance.destroyed = true;
// if this is a child layout, CLEAR the child-pointer in the parent
/* for now the pointer REMAINS, but with only container, options and destroyed keys
if (parentPane) {
var layout = parentPane.pane.data("parentLayout")
, key = layout.options.instanceKey || 'error';
// THIS SYNTAX MAY BE WRONG!
parentPane.children[key] = layout.children[ parentPane.name ].children[key] = null;
}
*/
return Instance; // for coding convenience
}
/**
* Remove a pane from the layout - subroutine of destroy()
*
* @see destroy()
* @param {(string|Object)} evt_or_pane The pane to process
* @param {boolean=} [remove=false] Remove the DOM element?
* @param {boolean=} [skipResize=false] Skip calling resizeAll()?
* @param {boolean=} [destroyChild=true] Destroy Child-layouts? If not passed, obeys options setting
*/
, removePane = function (evt_or_pane, remove, skipResize, destroyChild) {
if (!isInitialized()) return;
var pane = evtPane.call(this, evt_or_pane)
, $P = $Ps[pane]
, $C = $Cs[pane]
, $R = $Rs[pane]
, $T = $Ts[pane]
;
// NOTE: elements can still exist even after remove()
// so check for missing data(), which is cleared by removed()
if ($P && $.isEmptyObject( $P.data() )) $P = false;
if ($C && $.isEmptyObject( $C.data() )) $C = false;
if ($R && $.isEmptyObject( $R.data() )) $R = false;
if ($T && $.isEmptyObject( $T.data() )) $T = false;
if ($P) $P.stop(true, true);
var o = options[pane]
, s = state[pane]
, d = "layout"
, css = "layoutCSS"
, pC = children[pane]
, hasChildren = $.isPlainObject( pC ) && !$.isEmptyObject( pC )
, destroy = destroyChild !== undefined ? destroyChild : o.destroyChildren
;
// FIRST destroy the child-layout(s)
if (hasChildren && destroy) {
$.each( pC, function (key, child) {
if (!child.destroyed)
child.destroy(true);// tell child-layout to destroy ALL its child-layouts too
if (child.destroyed) // destroy was successful
delete pC[key];
});
// if no more children, remove the children hash
if ($.isEmptyObject( pC )) {
pC = children[pane] = null; // clear children hash
hasChildren = false;
}
}
// Note: can't 'remove' a pane element with non-destroyed children
if ($P && remove && !hasChildren)
$P.remove(); // remove the pane-element and everything inside it
else if ($P && $P[0]) {
// create list of ALL pane-classes that need to be removed
var root = o.paneClass // default="ui-layout-pane"
, pRoot = root +"-"+ pane // eg: "ui-layout-pane-west"
, _open = "-open"
, _sliding= "-sliding"
, _closed = "-closed"
, classes = [ root, root+_open, root+_closed, root+_sliding, // generic classes
pRoot, pRoot+_open, pRoot+_closed, pRoot+_sliding ] // pane-specific classes
;
$.merge(classes, getHoverClasses($P, true)); // ADD hover-classes
// remove all Layout classes from pane-element
$P .removeClass( classes.join(" ") ) // remove ALL pane-classes
.removeData("parentLayout")
.removeData("layoutPane")
.removeData("layoutRole")
.removeData("layoutEdge")
.removeData("autoHidden") // in case set
.unbind("."+ sID) // remove ALL Layout events
// TODO: remove these extra unbind commands when jQuery is fixed
//.unbind("mouseenter"+ sID)
//.unbind("mouseleave"+ sID)
;
// do NOT reset CSS if this pane/content is STILL the container of a nested layout!
// the nested layout will reset its 'container' CSS when/if it is destroyed
if (hasChildren && $C) {
// a content-div may not have a specific width, so give it one to contain the Layout
$C.width( $C.width() );
$.each( pC, function (key, child) {
child.resizeAll(); // resize the Layout
});
}
else if ($C)
$C.css( $C.data(css) ).removeData(css).removeData("layoutRole");
// remove pane AFTER content in case there was a nested layout
if (!$P.data(d))
$P.css( $P.data(css) ).removeData(css);
}
// REMOVE pane resizer and toggler elements
if ($T) $T.remove();
if ($R) $R.remove();
// CLEAR all pointers and state data
Instance[pane] = $Ps[pane] = $Cs[pane] = $Rs[pane] = $Ts[pane] = false;
s = { removed: true };
if (!skipResize)
resizeAll();
}
/*
* ###########################
* ACTION METHODS
* ###########################
*/
/**
* @param {string} pane
*/
, _hidePane = function (pane) {
var $P = $Ps[pane]
, o = options[pane]
, s = $P[0].style
;
if (o.useOffscreenClose) {
if (!$P.data(_c.offscreenReset))
$P.data(_c.offscreenReset, { left: s.left, right: s.right });
$P.css( _c.offscreenCSS );
}
else
$P.hide().removeData(_c.offscreenReset);
}
/**
* @param {string} pane
*/
, _showPane = function (pane) {
var $P = $Ps[pane]
, o = options[pane]
, off = _c.offscreenCSS
, old = $P.data(_c.offscreenReset)
, s = $P[0].style
;
$P .show() // ALWAYS show, just in case
.removeData(_c.offscreenReset);
if (o.useOffscreenClose && old) {
if (s.left == off.left)
s.left = old.left;
if (s.right == off.right)
s.right = old.right;
}
}
/**
* Completely 'hides' a pane, including its spacing - as if it does not exist
* The pane is not actually 'removed' from the source, so can use 'show' to un-hide it
*
* @param {(string|Object)} evt_or_pane The pane being hidden, ie: north, south, east, or west
* @param {boolean=} [noAnimation=false]
*/
, hide = function (evt_or_pane, noAnimation) {
if (!isInitialized()) return;
var pane = evtPane.call(this, evt_or_pane)
, o = options[pane]
, s = state[pane]
, $P = $Ps[pane]
, $R = $Rs[pane]
;
if (pane === "center" || !$P || s.isHidden) return; // pane does not exist OR is already hidden
// onhide_start callback - will CANCEL hide if returns false
if (state.initialized && false === _runCallbacks("onhide_start", pane)) return;
s.isSliding = false; // just in case
delete state.panesSliding[pane];
// now hide the elements
if ($R) $R.hide(); // hide resizer-bar
if (!state.initialized || s.isClosed) {
s.isClosed = true; // to trigger open-animation on show()
s.isHidden = true;
s.isVisible = false;
if (!state.initialized)
_hidePane(pane); // no animation when loading page
sizeMidPanes(_c[pane].dir === "horz" ? "" : "center");
if (state.initialized || o.triggerEventsOnLoad)
_runCallbacks("onhide_end", pane);
}
else {
s.isHiding = true; // used by onclose
close(pane, false, noAnimation); // adjust all panes to fit
}
}
/**
* Show a hidden pane - show as 'closed' by default unless openPane = true
*
* @param {(string|Object)} evt_or_pane The pane being opened, ie: north, south, east, or west
* @param {boolean=} [openPane=false]
* @param {boolean=} [noAnimation=false]
* @param {boolean=} [noAlert=false]
*/
, show = function (evt_or_pane, openPane, noAnimation, noAlert) {
if (!isInitialized()) return;
var pane = evtPane.call(this, evt_or_pane)
, o = options[pane]
, s = state[pane]
, $P = $Ps[pane]
, $R = $Rs[pane]
;
if (pane === "center" || !$P || !s.isHidden) return; // pane does not exist OR is not hidden
// onshow_start callback - will CANCEL show if returns false
if (false === _runCallbacks("onshow_start", pane)) return;
s.isShowing = true; // used by onopen/onclose
//s.isHidden = false; - will be set by open/close - if not cancelled
s.isSliding = false; // just in case
delete state.panesSliding[pane];
// now show the elements
//if ($R) $R.show(); - will be shown by open/close
if (openPane === false)
close(pane, true); // true = force
else
open(pane, false, noAnimation, noAlert); // adjust all panes to fit
}
/**
* Toggles a pane open/closed by calling either open or close
*
* @param {(string|Object)} evt_or_pane The pane being toggled, ie: north, south, east, or west
* @param {boolean=} [slide=false]
*/
, toggle = function (evt_or_pane, slide) {
if (!isInitialized()) return;
var evt = evtObj(evt_or_pane)
, pane = evtPane.call(this, evt_or_pane)
, s = state[pane]
;
if (evt) // called from to $R.dblclick OR triggerPaneEvent
evt.stopImmediatePropagation();
if (s.isHidden)
show(pane); // will call 'open' after unhiding it
else if (s.isClosed)
open(pane, !!slide);
else
close(pane);
}
/**
* Utility method used during init or other auto-processes
*
* @param {string} pane The pane being closed
* @param {boolean=} [setHandles=false]
*/
, _closePane = function (pane, setHandles) {
var
$P = $Ps[pane]
, s = state[pane]
;
_hidePane(pane);
s.isClosed = true;
s.isVisible = false;
if (setHandles) setAsClosed(pane);
}
/**
* Close the specified pane (animation optional), and resize all other panes as needed
*
* @param {(string|Object)} evt_or_pane The pane being closed, ie: north, south, east, or west
* @param {boolean=} [force=false]
* @param {boolean=} [noAnimation=false]
* @param {boolean=} [skipCallback=false]
*/
, close = function (evt_or_pane, force, noAnimation, skipCallback) {
var pane = evtPane.call(this, evt_or_pane);
if (pane === "center") return; // validate
// if pane has been initialized, but NOT the complete layout, close pane instantly
if (!state.initialized && $Ps[pane]) {
_closePane(pane, true); // INIT pane as closed
return;
}
if (!isInitialized()) return;
var
$P = $Ps[pane]
, $R = $Rs[pane]
, $T = $Ts[pane]
, o = options[pane]
, s = state[pane]
, c = _c[pane]
, doFX, isShowing, isHiding, wasSliding;
// QUEUE in case another action/animation is in progress
$N.queue(function( queueNext ){
if ( !$P
|| (!o.closable && !s.isShowing && !s.isHiding) // invalid request // (!o.resizable && !o.closable) ???
|| (!force && s.isClosed && !s.isShowing) // already closed
) return queueNext();
// onclose_start callback - will CANCEL hide if returns false
// SKIP if just 'showing' a hidden pane as 'closed'
var abort = !s.isShowing && false === _runCallbacks("onclose_start", pane);
// transfer logic vars to temp vars
isShowing = s.isShowing;
isHiding = s.isHiding;
wasSliding = s.isSliding;
// now clear the logic vars (REQUIRED before aborting)
delete s.isShowing;
delete s.isHiding;
if (abort) return queueNext();
doFX = !noAnimation && !s.isClosed && (o.fxName_close != "none");
s.isMoving = true;
s.isClosed = true;
s.isVisible = false;
// update isHidden BEFORE sizing panes
if (isHiding) s.isHidden = true;
else if (isShowing) s.isHidden = false;
if (s.isSliding) // pane is being closed, so UNBIND trigger events
bindStopSlidingEvents(pane, false); // will set isSliding=false
else // resize panes adjacent to this one
sizeMidPanes(_c[pane].dir === "horz" ? "" : "center", false); // false = NOT skipCallback
// if this pane has a resizer bar, move it NOW - before animation
setAsClosed(pane);
// CLOSE THE PANE
if (doFX) { // animate the close
lockPaneForFX(pane, true); // need to set left/top so animation will work
$P.hide( o.fxName_close, o.fxSettings_close, o.fxSpeed_close, function () {
lockPaneForFX(pane, false); // undo
if (s.isClosed) close_2();
queueNext();
});
}
else { // hide the pane without animation
_hidePane(pane);
close_2();
queueNext();
}
});
// SUBROUTINE
function close_2 () {
s.isMoving = false;
bindStartSlidingEvents(pane, true); // will enable if o.slidable = true
// if opposite-pane was autoClosed, see if it can be autoOpened now
var altPane = _c.oppositeEdge[pane];
if (state[ altPane ].noRoom) {
setSizeLimits( altPane );
makePaneFit( altPane );
}
if (!skipCallback && (state.initialized || o.triggerEventsOnLoad)) {
// onclose callback - UNLESS just 'showing' a hidden pane as 'closed'
if (!isShowing) _runCallbacks("onclose_end", pane);
// onhide OR onshow callback
if (isShowing) _runCallbacks("onshow_end", pane);
if (isHiding) _runCallbacks("onhide_end", pane);
}
}
}
/**
* @param {string} pane The pane just closed, ie: north, south, east, or west
*/
, setAsClosed = function (pane) {
if (!$Rs[pane]) return; // handles not initialized yet!
var
$P = $Ps[pane]
, $R = $Rs[pane]
, $T = $Ts[pane]
, o = options[pane]
, s = state[pane]
, side = _c[pane].side
, rClass = o.resizerClass
, tClass = o.togglerClass
, _pane = "-"+ pane // used for classNames
, _open = "-open"
, _sliding= "-sliding"
, _closed = "-closed"
;
$R
.css(side, sC.inset[side]) // move the resizer
.removeClass( rClass+_open +" "+ rClass+_pane+_open )
.removeClass( rClass+_sliding +" "+ rClass+_pane+_sliding )
.addClass( rClass+_closed +" "+ rClass+_pane+_closed )
;
// handle already-hidden panes in case called by swap() or a similar method
if (s.isHidden) $R.hide(); // hide resizer-bar
// DISABLE 'resizing' when closed - do this BEFORE bindStartSlidingEvents?
if (o.resizable && $.layout.plugins.draggable)
$R
.draggable("disable")
.removeClass("ui-state-disabled") // do NOT apply disabled styling - not suitable here
.css("cursor", "default")
.attr("title","")
;
// if pane has a toggler button, adjust that too
if ($T) {
$T
.removeClass( tClass+_open +" "+ tClass+_pane+_open )
.addClass( tClass+_closed +" "+ tClass+_pane+_closed )
.attr("title", o.tips.Open) // may be blank
;
// toggler-content - if exists
$T.children(".content-open").hide();
$T.children(".content-closed").css("display","block");
}
// sync any 'pin buttons'
syncPinBtns(pane, false);
if (state.initialized) {
// resize 'length' and position togglers for adjacent panes
sizeHandles();
}
}
/**
* Open the specified pane (animation optional), and resize all other panes as needed
*
* @param {(string|Object)} evt_or_pane The pane being opened, ie: north, south, east, or west
* @param {boolean=} [slide=false]
* @param {boolean=} [noAnimation=false]
* @param {boolean=} [noAlert=false]
*/
, open = function (evt_or_pane, slide, noAnimation, noAlert) {
if (!isInitialized()) return;
var pane = evtPane.call(this, evt_or_pane)
, $P = $Ps[pane]
, $R = $Rs[pane]
, $T = $Ts[pane]
, o = options[pane]
, s = state[pane]
, c = _c[pane]
, doFX, isShowing
;
if (pane === "center") return; // validate
// QUEUE in case another action/animation is in progress
$N.queue(function( queueNext ){
if ( !$P
|| (!o.resizable && !o.closable && !s.isShowing) // invalid request
|| (s.isVisible && !s.isSliding) // already open
) return queueNext();
// pane can ALSO be unhidden by just calling show(), so handle this scenario
if (s.isHidden && !s.isShowing) {
queueNext(); // call before show() because it needs the queue free
show(pane, true);
return;
}
if (s.autoResize && s.size != o.size) // resize pane to original size set in options
sizePane(pane, o.size, true, true, true); // true=skipCallback/noAnimation/forceResize
else
// make sure there is enough space available to open the pane
setSizeLimits(pane, slide);
// onopen_start callback - will CANCEL open if returns false
var cbReturn = _runCallbacks("onopen_start", pane);
if (cbReturn === "abort")
return queueNext();
// update pane-state again in case options were changed in onopen_start
if (cbReturn !== "NC") // NC = "No Callback"
setSizeLimits(pane, slide);
if (s.minSize > s.maxSize) { // INSUFFICIENT ROOM FOR PANE TO OPEN!
syncPinBtns(pane, false); // make sure pin-buttons are reset
if (!noAlert && o.tips.noRoomToOpen)
alert(o.tips.noRoomToOpen);
return queueNext(); // ABORT
}
if (slide) // START Sliding - will set isSliding=true
bindStopSlidingEvents(pane, true); // BIND trigger events to close sliding-pane
else if (s.isSliding) // PIN PANE (stop sliding) - open pane 'normally' instead
bindStopSlidingEvents(pane, false); // UNBIND trigger events - will set isSliding=false
else if (o.slidable)
bindStartSlidingEvents(pane, false); // UNBIND trigger events
s.noRoom = false; // will be reset by makePaneFit if 'noRoom'
makePaneFit(pane);
// transfer logic var to temp var
isShowing = s.isShowing;
// now clear the logic var
delete s.isShowing;
doFX = !noAnimation && s.isClosed && (o.fxName_open != "none");
s.isMoving = true;
s.isVisible = true;
s.isClosed = false;
// update isHidden BEFORE sizing panes - WHY??? Old?
if (isShowing) s.isHidden = false;
if (doFX) { // ANIMATE
// mask adjacent panes with objects
lockPaneForFX(pane, true); // need to set left/top so animation will work
$P.show( o.fxName_open, o.fxSettings_open, o.fxSpeed_open, function() {
lockPaneForFX(pane, false); // undo
if (s.isVisible) open_2(); // continue
queueNext();
});
}
else { // no animation
_showPane(pane);// just show pane and...
open_2(); // continue
queueNext();
}
});
// SUBROUTINE
function open_2 () {
s.isMoving = false;
// cure iframe display issues
_fixIframe(pane);
// NOTE: if isSliding, then other panes are NOT 'resized'
if (!s.isSliding) { // resize all panes adjacent to this one
sizeMidPanes(_c[pane].dir=="vert" ? "center" : "", false); // false = NOT skipCallback
}
// set classes, position handles and execute callbacks...
setAsOpen(pane);
}
}
/**
* @param {string} pane The pane just opened, ie: north, south, east, or west
* @param {boolean=} [skipCallback=false]
*/
, setAsOpen = function (pane, skipCallback) {
var
$P = $Ps[pane]
, $R = $Rs[pane]
, $T = $Ts[pane]
, o = options[pane]
, s = state[pane]
, side = _c[pane].side
, rClass = o.resizerClass
, tClass = o.togglerClass
, _pane = "-"+ pane // used for classNames
, _open = "-open"
, _closed = "-closed"
, _sliding= "-sliding"
;
$R
.css(side, sC.inset[side] + getPaneSize(pane)) // move the resizer
.removeClass( rClass+_closed +" "+ rClass+_pane+_closed )
.addClass( rClass+_open +" "+ rClass+_pane+_open )
;
if (s.isSliding)
$R.addClass( rClass+_sliding +" "+ rClass+_pane+_sliding );
else // in case 'was sliding'
$R.removeClass( rClass+_sliding +" "+ rClass+_pane+_sliding );
removeHover( 0, $R ); // remove hover classes
if (o.resizable && $.layout.plugins.draggable)
$R .draggable("enable")
.css("cursor", o.resizerCursor)
.attr("title", o.tips.Resize);
else if (!s.isSliding)
$R.css("cursor", "default"); // n-resize, s-resize, etc
// if pane also has a toggler button, adjust that too
if ($T) {
$T .removeClass( tClass+_closed +" "+ tClass+_pane+_closed )
.addClass( tClass+_open +" "+ tClass+_pane+_open )
.attr("title", o.tips.Close); // may be blank
removeHover( 0, $T ); // remove hover classes
// toggler-content - if exists
$T.children(".content-closed").hide();
$T.children(".content-open").css("display","block");
}
// sync any 'pin buttons'
syncPinBtns(pane, !s.isSliding);
// update pane-state dimensions - BEFORE resizing content
$.extend(s, elDims($P));
if (state.initialized) {
// resize resizer & toggler sizes for all panes
sizeHandles();
// resize content every time pane opens - to be sure
sizeContent(pane, true); // true = remeasure headers/footers, even if 'pane.isMoving'
}
if (!skipCallback && (state.initialized || o.triggerEventsOnLoad) && $P.is(":visible")) {
// onopen callback
_runCallbacks("onopen_end", pane);
// onshow callback - TODO: should this be here?
if (s.isShowing) _runCallbacks("onshow_end", pane);
// ALSO call onresize because layout-size *may* have changed while pane was closed
if (state.initialized)
_runCallbacks("onresize_end", pane);
}
// TODO: Somehow sizePane("north") is being called after this point???
}
/**
* slideOpen / slideClose / slideToggle
*
* Pass-though methods for sliding
*/
, slideOpen = function (evt_or_pane) {
if (!isInitialized()) return;
var evt = evtObj(evt_or_pane)
, pane = evtPane.call(this, evt_or_pane)
, s = state[pane]
, delay = options[pane].slideDelay_open
;
if (pane === "center") return; // validate
// prevent event from triggering on NEW resizer binding created below
if (evt) evt.stopImmediatePropagation();
if (s.isClosed && evt && evt.type === "mouseenter" && delay > 0)
// trigger = mouseenter - use a delay
timer.set(pane+"_openSlider", open_NOW, delay);
else
open_NOW(); // will unbind events if is already open
/**
* SUBROUTINE for timed open
*/
function open_NOW () {
if (!s.isClosed) // skip if no longer closed!
bindStopSlidingEvents(pane, true); // BIND trigger events to close sliding-pane
else if (!s.isMoving)
open(pane, true); // true = slide - open() will handle binding
}
}
, slideClose = function (evt_or_pane) {
if (!isInitialized()) return;
var evt = evtObj(evt_or_pane)
, pane = evtPane.call(this, evt_or_pane)
, o = options[pane]
, s = state[pane]
, delay = s.isMoving ? 1000 : 300 // MINIMUM delay - option may override
;
if (pane === "center") return; // validate
if (s.isClosed || s.isResizing){}
// skip if already closed OR in process of resizing
else if (o.slideTrigger_close === "click"){
close_NOW(); // close immediately onClick
}
else if (o.preventQuickSlideClose && s.isMoving){}
// handle Chrome quick-close on slide-open
else if (o.preventPrematureSlideClose && evt && $.layout.isMouseOverElem(evt, $Ps[pane])){}
// handle incorrect mouseleave trigger, like when over a SELECT-list in IE
else if (evt) {// trigger = mouseleave - use a delay
// 1 sec delay if 'opening', else .3 sec
timer.set(pane+"_closeSlider", close_NOW, max(o.slideDelay_close, delay));
}
else{close_NOW();} // called programically
/**
* SUBROUTINE for timed close
*/
function close_NOW () {
if (s.isClosed) // skip 'close' if already closed!
bindStopSlidingEvents(pane, false); // UNBIND trigger events - TODO: is this needed here?
else if (!s.isMoving)
close(pane); // close will handle unbinding
}
}
/**
* @param {(string|Object)} evt_or_pane The pane being opened, ie: north, south, east, or west
*/
, slideToggle = function (evt_or_pane) {
var pane = evtPane.call(this, evt_or_pane);
toggle(pane, true);
}
/**
* Must set left/top on East/South panes so animation will work properly
*
* @param {string} pane The pane to lock, 'east' or 'south' - any other is ignored!
* @param {boolean} doLock true = set left/top, false = remove
*/
, lockPaneForFX = function (pane, doLock) {
var $P = $Ps[pane]
, s = state[pane]
, o = options[pane]
, z = options.zIndexes
;
if (doLock) {
showMasks( pane, { animation: true, objectsOnly: true });
$P.css({ zIndex: z.pane_animate }); // overlay all elements during animation
if (pane=="south")
$P.css({ top: sC.inset.top + sC.innerHeight - $P.outerHeight() });
else if (pane=="east")
$P.css({ left: sC.inset.left + sC.innerWidth - $P.outerWidth() });
}
else { // animation DONE - RESET CSS
hideMasks();
$P.css({ zIndex: (s.isSliding ? z.pane_sliding : z.pane_normal) });
if (pane=="south")
$P.css({ top: "auto" });
// if pane is positioned 'off-screen', then DO NOT screw with it!
else if (pane=="east" && !$P.css("left").match(/\-99999/))
$P.css({ left: "auto" });
// fix anti-aliasing in IE - only needed for animations that change opacity
if (browser.msie && o.fxOpacityFix && o.fxName_open != "slide" && $P.css("filter") && $P.css("opacity") == 1)
$P[0].style.removeAttribute('filter');
}
}
/**
* Toggle sliding functionality of a specific pane on/off by adding removing 'slide open' trigger
*
* @see open(), close()
* @param {string} pane The pane to enable/disable, 'north', 'south', etc.
* @param {boolean} enable Enable or Disable sliding?
*/
, bindStartSlidingEvents = function (pane, enable) {
var o = options[pane]
, $P = $Ps[pane]
, $R = $Rs[pane]
, evtName = o.slideTrigger_open.toLowerCase()
;
if (!$R || (enable && !o.slidable)) return;
// make sure we have a valid event
if (evtName.match(/mouseover/))
evtName = o.slideTrigger_open = "mouseenter";
else if (!evtName.match(/(click|dblclick|mouseenter)/))
evtName = o.slideTrigger_open = "click";
// must remove double-click-toggle when using dblclick-slide
if (o.resizerDblClickToggle && evtName.match(/click/)) {
$R[enable ? "unbind" : "bind"]('dblclick.'+ sID, toggle)
}
$R
// add or remove event
[enable ? "bind" : "unbind"](evtName +'.'+ sID, slideOpen)
// set the appropriate cursor & title/tip
.css("cursor", enable ? o.sliderCursor : "default")
.attr("title", enable ? o.tips.Slide : "")
;
}
/**
* Add or remove 'mouseleave' events to 'slide close' when pane is 'sliding' open or closed
* Also increases zIndex when pane is sliding open
* See bindStartSlidingEvents for code to control 'slide open'
*
* @see slideOpen(), slideClose()
* @param {string} pane The pane to process, 'north', 'south', etc.
* @param {boolean} enable Enable or Disable events?
*/
, bindStopSlidingEvents = function (pane, enable) {
var o = options[pane]
, s = state[pane]
, c = _c[pane]
, z = options.zIndexes
, evtName = o.slideTrigger_close.toLowerCase()
, action = (enable ? "bind" : "unbind")
, $P = $Ps[pane]
, $R = $Rs[pane]
;
timer.clear(pane+"_closeSlider"); // just in case
if (enable) {
s.isSliding = true;
state.panesSliding[pane] = true;
// remove 'slideOpen' event from resizer
// ALSO will raise the zIndex of the pane & resizer
bindStartSlidingEvents(pane, false);
}
else {
s.isSliding = false;
delete state.panesSliding[pane];
}
// RE/SET zIndex - increases when pane is sliding-open, resets to normal when not
$P.css("zIndex", enable ? z.pane_sliding : z.pane_normal);
$R.css("zIndex", enable ? z.pane_sliding+2 : z.resizer_normal); // NOTE: mask = pane_sliding+1
// make sure we have a valid event
if (!evtName.match(/(click|mouseleave)/))
evtName = o.slideTrigger_close = "mouseleave"; // also catches 'mouseout'
// add/remove slide triggers
$R[action](evtName, slideClose); // base event on resize
// need extra events for mouseleave
if (evtName === "mouseleave") {
// also close on pane.mouseleave
$P[action]("mouseleave."+ sID, slideClose);
// cancel timer when mouse moves between 'pane' and 'resizer'
$R[action]("mouseenter."+ sID, cancelMouseOut);
$P[action]("mouseenter."+ sID, cancelMouseOut);
}
if (!enable)
timer.clear(pane+"_closeSlider");
else if (evtName === "click" && !o.resizable) {
// IF pane is not resizable (which already has a cursor and tip)
// then set the a cursor & title/tip on resizer when sliding
$R.css("cursor", enable ? o.sliderCursor : "default");
$R.attr("title", enable ? o.tips.Close : ""); // use Toggler-tip, eg: "Close Pane"
}
// SUBROUTINE for mouseleave timer clearing
function cancelMouseOut (evt) {
timer.clear(pane+"_closeSlider");
evt.stopPropagation();
}
}
/**
* Hides/closes a pane if there is insufficient room - reverses this when there is room again
* MUST have already called setSizeLimits() before calling this method
*
* @param {string} pane The pane being resized
* @param {boolean=} [isOpening=false] Called from onOpen?
* @param {boolean=} [skipCallback=false] Should the onresize callback be run?
* @param {boolean=} [force=false]
*/
, makePaneFit = function (pane, isOpening, skipCallback, force) {
var o = options[pane]
, s = state[pane]
, c = _c[pane]
, $P = $Ps[pane]
, $R = $Rs[pane]
, isSidePane = c.dir==="vert"
, hasRoom = false
;
// special handling for center & east/west panes
if (pane === "center" || (isSidePane && s.noVerticalRoom)) {
// see if there is enough room to display the pane
// ERROR: hasRoom = s.minHeight <= s.maxHeight && (isSidePane || s.minWidth <= s.maxWidth);
hasRoom = (s.maxHeight >= 0);
if (hasRoom && s.noRoom) { // previously hidden due to noRoom, so show now
_showPane(pane);
if ($R) $R.show();
s.isVisible = true;
s.noRoom = false;
if (isSidePane) s.noVerticalRoom = false;
_fixIframe(pane);
}
else if (!hasRoom && !s.noRoom) { // not currently hidden, so hide now
_hidePane(pane);
if ($R) $R.hide();
s.isVisible = false;
s.noRoom = true;
}
}
// see if there is enough room to fit the border-pane
if (pane === "center") {
// ignore center in this block
}
else if (s.minSize <= s.maxSize) { // pane CAN fit
hasRoom = true;
if (s.size > s.maxSize) // pane is too big - shrink it
sizePane(pane, s.maxSize, skipCallback, true, force); // true = noAnimation
else if (s.size < s.minSize) // pane is too small - enlarge it
sizePane(pane, s.minSize, skipCallback, true, force); // true = noAnimation
// need s.isVisible because new pseudoClose method keeps pane visible, but off-screen
else if ($R && s.isVisible && $P.is(":visible")) {
// make sure resizer-bar is positioned correctly
// handles situation where nested layout was 'hidden' when initialized
var pos = s.size + sC.inset[c.side];
if ($.layout.cssNum( $R, c.side ) != pos) $R.css( c.side, pos );
}
// if was previously hidden due to noRoom, then RESET because NOW there is room
if (s.noRoom) {
// s.noRoom state will be set by open or show
if (s.wasOpen && o.closable) {
if (o.autoReopen)
open(pane, false, true, true); // true = noAnimation, true = noAlert
else // leave the pane closed, so just update state
s.noRoom = false;
}
else
show(pane, s.wasOpen, true, true); // true = noAnimation, true = noAlert
}
}
else { // !hasRoom - pane CANNOT fit
if (!s.noRoom) { // pane not set as noRoom yet, so hide or close it now...
s.noRoom = true; // update state
s.wasOpen = !s.isClosed && !s.isSliding;
if (s.isClosed){} // SKIP
else if (o.closable) // 'close' if possible
close(pane, true, true); // true = force, true = noAnimation
else // 'hide' pane if cannot just be closed
hide(pane, true); // true = noAnimation
}
}
}
/**
* manualSizePane is an exposed flow-through method allowing extra code when pane is 'manually resized'
*
* @param {(string|Object)} evt_or_pane The pane being resized
* @param {number} size The *desired* new size for this pane - will be validated
* @param {boolean=} [skipCallback=false] Should the onresize callback be run?
* @param {boolean=} [noAnimation=false]
* @param {boolean=} [force=false] Force resizing even if does not seem necessary
*/
, manualSizePane = function (evt_or_pane, size, skipCallback, noAnimation, force) {
if (!isInitialized()) return;
var pane = evtPane.call(this, evt_or_pane)
, o = options[pane]
, s = state[pane]
// if resizing callbacks have been delayed and resizing is now DONE, force resizing to complete...
, forceResize = force || (o.livePaneResizing && !s.isResizing)
;
if (pane === "center") return; // validate
// ANY call to manualSizePane disables autoResize - ie, percentage sizing
s.autoResize = false;
// flow-through...
sizePane(pane, size, skipCallback, noAnimation, forceResize); // will animate resize if option enabled
}
/**
* sizePane is called only by internal methods whenever a pane needs to be resized
*
* @param {(string|Object)} evt_or_pane The pane being resized
* @param {number} size The *desired* new size for this pane - will be validated
* @param {boolean=} [skipCallback=false] Should the onresize callback be run?
* @param {boolean=} [noAnimation=false]
* @param {boolean=} [force=false] Force resizing even if does not seem necessary
*/
, sizePane = function (evt_or_pane, size, skipCallback, noAnimation, force) {
if (!isInitialized()) return;
var pane = evtPane.call(this, evt_or_pane) // probably NEVER called from event?
, o = options[pane]
, s = state[pane]
, $P = $Ps[pane]
, $R = $Rs[pane]
, side = _c[pane].side
, dimName = _c[pane].sizeType.toLowerCase()
, skipResizeWhileDragging = s.isResizing && !o.triggerEventsDuringLiveResize
, doFX = noAnimation !== true && o.animatePaneSizing
, oldSize, newSize
;
if (pane === "center") return; // validate
// QUEUE in case another action/animation is in progress
$N.queue(function( queueNext ){
// calculate 'current' min/max sizes
setSizeLimits(pane); // update pane-state
oldSize = s.size;
size = _parseSize(pane, size); // handle percentages & auto
size = max(size, _parseSize(pane, o.minSize));
size = min(size, s.maxSize);
if (size < s.minSize) { // not enough room for pane!
queueNext(); // call before makePaneFit() because it needs the queue free
makePaneFit(pane, false, skipCallback); // will hide or close pane
return;
}
// IF newSize is same as oldSize, then nothing to do - abort
if (!force && size === oldSize)
return queueNext();
s.newSize = size;
// onresize_start callback CANNOT cancel resizing because this would break the layout!
if (!skipCallback && state.initialized && s.isVisible)
_runCallbacks("onresize_start", pane);
// resize the pane, and make sure its visible
newSize = cssSize(pane, size);
if (doFX && $P.is(":visible")) { // ANIMATE
var fx = $.layout.effects.size[pane] || $.layout.effects.size.all
, easing = o.fxSettings_size.easing || fx.easing
, z = options.zIndexes
, props = {};
props[ dimName ] = newSize +'px';
s.isMoving = true;
// overlay all elements during animation
$P.css({ zIndex: z.pane_animate })
.show().animate( props, o.fxSpeed_size, easing, function(){
// reset zIndex after animation
$P.css({ zIndex: (s.isSliding ? z.pane_sliding : z.pane_normal) });
s.isMoving = false;
delete s.newSize;
sizePane_2(); // continue
queueNext();
});
}
else { // no animation
$P.css( dimName, newSize ); // resize pane
delete s.newSize;
// if pane is visible, then
if ($P.is(":visible"))
sizePane_2(); // continue
else {
// pane is NOT VISIBLE, so just update state data...
// when pane is *next opened*, it will have the new size
s.size = size; // update state.size
//$.extend(s, elDims($P)); // update state dimensions - CANNOT do this when not visible! }
}
queueNext();
}
});
// SUBROUTINE
function sizePane_2 () {
/* Panes are sometimes not sized precisely in some browsers!?
* This code will resize the pane up to 3 times to nudge the pane to the correct size
*/
var actual = dimName==='width' ? $P.outerWidth() : $P.outerHeight()
, tries = [{
pane: pane
, count: 1
, target: size
, actual: actual
, correct: (size === actual)
, attempt: size
, cssSize: newSize
}]
, lastTry = tries[0]
, thisTry = {}
, msg = 'Inaccurate size after resizing the '+ pane +'-pane.'
;
while ( !lastTry.correct ) {
thisTry = { pane: pane, count: lastTry.count+1, target: size };
if (lastTry.actual > size)
thisTry.attempt = max(0, lastTry.attempt - (lastTry.actual - size));
else // lastTry.actual < size
thisTry.attempt = max(0, lastTry.attempt + (size - lastTry.actual));
thisTry.cssSize = cssSize(pane, thisTry.attempt);
$P.css( dimName, thisTry.cssSize );
thisTry.actual = dimName=='width' ? $P.outerWidth() : $P.outerHeight();
thisTry.correct = (size === thisTry.actual);
// log attempts and alert the user of this *non-fatal error* (if showDebugMessages)
if ( tries.length === 1) {
_log(msg, false, true);
_log(lastTry, false, true);
}
_log(thisTry, false, true);
// after 4 tries, is as close as its gonna get!
if (tries.length > 3) break;
tries.push( thisTry );
lastTry = tries[ tries.length - 1 ];
}
// END TESTING CODE
// update pane-state dimensions
s.size = size;
$.extend(s, elDims($P));
if (s.isVisible && $P.is(":visible")) {
// reposition the resizer-bar
if ($R) $R.css( side, size + sC.inset[side] );
// resize the content-div
sizeContent(pane);
}
if (!skipCallback && !skipResizeWhileDragging && state.initialized && s.isVisible)
_runCallbacks("onresize_end", pane);
// resize all the adjacent panes, and adjust their toggler buttons
// when skipCallback passed, it means the controlling method will handle 'other panes'
if (!skipCallback) {
// also no callback if live-resize is in progress and NOT triggerEventsDuringLiveResize
if (!s.isSliding) sizeMidPanes(_c[pane].dir=="horz" ? "" : "center", skipResizeWhileDragging, force);
sizeHandles();
}
// if opposite-pane was autoClosed, see if it can be autoOpened now
var altPane = _c.oppositeEdge[pane];
if (size < oldSize && state[ altPane ].noRoom) {
setSizeLimits( altPane );
makePaneFit( altPane, false, skipCallback );
}
// DEBUG - ALERT user/developer so they know there was a sizing problem
if (tries.length > 1)
_log(msg +'\nSee the Error Console for details.', true, true);
}
}
/**
* @see initPanes(), sizePane(), resizeAll(), open(), close(), hide()
* @param {(Array.<string>|string)} panes The pane(s) being resized, comma-delmited string
* @param {boolean=} [skipCallback=false] Should the onresize callback be run?
* @param {boolean=} [force=false]
*/
, sizeMidPanes = function (panes, skipCallback, force) {
panes = (panes ? panes : "east,west,center").split(",");
$.each(panes, function (i, pane) {
if (!$Ps[pane]) return; // NO PANE - skip
var
o = options[pane]
, s = state[pane]
, $P = $Ps[pane]
, $R = $Rs[pane]
, isCenter= (pane=="center")
, hasRoom = true
, CSS = {}
// if pane is not visible, show it invisibly NOW rather than for *each call* in this script
, visCSS = $.layout.showInvisibly($P)
, newCenter = calcNewCenterPaneDims()
;
// update pane-state dimensions
$.extend(s, elDims($P));
if (pane === "center") {
if (!force && s.isVisible && newCenter.width === s.outerWidth && newCenter.height === s.outerHeight) {
$P.css(visCSS);
return true; // SKIP - pane already the correct size
}
// set state for makePaneFit() logic
$.extend(s, cssMinDims(pane), {
maxWidth: newCenter.width
, maxHeight: newCenter.height
});
CSS = newCenter;
s.newWidth = CSS.width;
s.newHeight = CSS.height;
// convert OUTER width/height to CSS width/height
CSS.width = cssW($P, CSS.width);
// NEW - allow pane to extend 'below' visible area rather than hide it
CSS.height = cssH($P, CSS.height);
hasRoom = CSS.width >= 0 && CSS.height >= 0; // height >= 0 = ALWAYS TRUE NOW
// during layout init, try to shrink east/west panes to make room for center
if (!state.initialized && o.minWidth > newCenter.width) {
var
reqPx = o.minWidth - s.outerWidth
, minE = options.east.minSize || 0
, minW = options.west.minSize || 0
, sizeE = state.east.size
, sizeW = state.west.size
, newE = sizeE
, newW = sizeW
;
if (reqPx > 0 && state.east.isVisible && sizeE > minE) {
newE = max( sizeE-minE, sizeE-reqPx );
reqPx -= sizeE-newE;
}
if (reqPx > 0 && state.west.isVisible && sizeW > minW) {
newW = max( sizeW-minW, sizeW-reqPx );
reqPx -= sizeW-newW;
}
// IF we found enough extra space, then resize the border panes as calculated
if (reqPx === 0) {
if (sizeE && sizeE != minE)
sizePane('east', newE, true, true, force); // true = skipCallback/noAnimation - initPanes will handle when done
if (sizeW && sizeW != minW)
sizePane('west', newW, true, true, force); // true = skipCallback/noAnimation
// now start over!
sizeMidPanes('center', skipCallback, force);
$P.css(visCSS);
return; // abort this loop
}
}
}
else { // for east and west, set only the height, which is same as center height
// set state.min/maxWidth/Height for makePaneFit() logic
if (s.isVisible && !s.noVerticalRoom)
$.extend(s, elDims($P), cssMinDims(pane));
if (!force && !s.noVerticalRoom && newCenter.height === s.outerHeight) {
$P.css(visCSS);
return true; // SKIP - pane already the correct size
}
// east/west have same top, bottom & height as center
CSS.top = newCenter.top;
CSS.bottom = newCenter.bottom;
s.newSize = newCenter.height;
// NEW - allow pane to extend 'below' visible area rather than hide it
CSS.height = cssH($P, newCenter.height);
s.maxHeight = CSS.height;
hasRoom = (s.maxHeight >= 0); // ALWAYS TRUE NOW
if (!hasRoom) s.noVerticalRoom = true; // makePaneFit() logic
}
if (hasRoom) {
// resizeAll passes skipCallback because it triggers callbacks after ALL panes are resized
if (!skipCallback && state.initialized)
_runCallbacks("onresize_start", pane);
$P.css(CSS); // apply the CSS to pane
if (pane !== "center")
sizeHandles(pane); // also update resizer length
if (s.noRoom && !s.isClosed && !s.isHidden)
makePaneFit(pane); // will re-open/show auto-closed/hidden pane
if (s.isVisible) {
$.extend(s, elDims($P)); // update pane dimensions
if (state.initialized) sizeContent(pane); // also resize the contents, if exists
}
}
else if (!s.noRoom && s.isVisible) // no room for pane
makePaneFit(pane); // will hide or close pane
// reset visibility, if necessary
$P.css(visCSS);
delete s.newSize;
delete s.newWidth;
delete s.newHeight;
if (!s.isVisible)
return true; // DONE - next pane
/*
* Extra CSS for IE6 or IE7 in Quirks-mode - add 'width' to NORTH/SOUTH panes
* Normally these panes have only 'left' & 'right' positions so pane auto-sizes
* ALSO required when pane is an IFRAME because will NOT default to 'full width'
* TODO: Can I use width:100% for a north/south iframe?
* TODO: Sounds like a job for $P.outerWidth( sC.innerWidth ) SETTER METHOD
*/
if (pane === "center") { // finished processing midPanes
var fix = browser.isIE6 || !browser.boxModel;
if ($Ps.north && (fix || state.north.tagName=="IFRAME"))
$Ps.north.css("width", cssW($Ps.north, sC.innerWidth));
if ($Ps.south && (fix || state.south.tagName=="IFRAME"))
$Ps.south.css("width", cssW($Ps.south, sC.innerWidth));
}
// resizeAll passes skipCallback because it triggers callbacks after ALL panes are resized
if (!skipCallback && state.initialized)
_runCallbacks("onresize_end", pane);
});
}
/**
* @see window.onresize(), callbacks or custom code
* @param {(Object|boolean)=} evt_or_refresh If 'true', then also reset pane-positioning
*/
, resizeAll = function (evt_or_refresh) {
var oldW = sC.innerWidth
, oldH = sC.innerHeight
;
// stopPropagation if called by trigger("layoutdestroy") - use evtPane utility
evtPane(evt_or_refresh);
// cannot size layout when 'container' is hidden or collapsed
if (!$N.is(":visible")) return;
if (!state.initialized) {
_initLayoutElements();
return; // no need to resize since we just initialized!
}
if (evt_or_refresh === true && $.isPlainObject(options.outset)) {
// update container CSS in case outset option has changed
$N.css( options.outset );
}
// UPDATE container dimensions
$.extend(sC, elDims( $N, options.inset ));
if (!sC.outerHeight) return;
// if 'true' passed, refresh pane & handle positioning too
if (evt_or_refresh === true) {
setPanePosition();
}
// onresizeall_start will CANCEL resizing if returns false
// state.container has already been set, so user can access this info for calcuations
if (false === _runCallbacks("onresizeall_start")) return false;
var // see if container is now 'smaller' than before
shrunkH = (sC.innerHeight < oldH)
, shrunkW = (sC.innerWidth < oldW)
, $P, o, s
;
// NOTE special order for sizing: S-N-E-W
$.each(["south","north","east","west"], function (i, pane) {
if (!$Ps[pane]) return; // no pane - SKIP
o = options[pane];
s = state[pane];
if (s.autoResize && s.size != o.size) // resize pane to original size set in options
sizePane(pane, o.size, true, true, true); // true=skipCallback/noAnimation/forceResize
else {
setSizeLimits(pane);
makePaneFit(pane, false, true, true); // true=skipCallback/forceResize
}
});
sizeMidPanes("", true, true); // true=skipCallback/forceResize
sizeHandles(); // reposition the toggler elements
// trigger all individual pane callbacks AFTER layout has finished resizing
$.each(_c.allPanes, function (i, pane) {
$P = $Ps[pane];
if (!$P) return; // SKIP
if (state[pane].isVisible) // undefined for non-existent panes
_runCallbacks("onresize_end", pane); // callback - if exists
});
_runCallbacks("onresizeall_end");
//_triggerLayoutEvent(pane, 'resizeall');
}
/**
* Whenever a pane resizes or opens that has a nested layout, trigger resizeAll
*
* @param {(string|Object)} evt_or_pane The pane just resized or opened
*/
, resizeChildren = function (evt_or_pane, skipRefresh) {
var pane = evtPane.call(this, evt_or_pane);
if (!options[pane].resizeChildren) return;
// ensure the pane-children are up-to-date
if (!skipRefresh) refreshChildren( pane );
var pC = children[pane];
if ($.isPlainObject( pC )) {
// resize one or more children
$.each( pC, function (key, child) {
if (!child.destroyed) child.resizeAll();
});
}
}
/**
* IF pane has a content-div, then resize all elements inside pane to fit pane-height
*
* @param {(string|Object)} evt_or_panes The pane(s) being resized
* @param {boolean=} [remeasure=false] Should the content (header/footer) be remeasured?
*/
, sizeContent = function (evt_or_panes, remeasure) {
if (!isInitialized()) return;
var panes = evtPane.call(this, evt_or_panes);
panes = panes ? panes.split(",") : _c.allPanes;
$.each(panes, function (idx, pane) {
var
$P = $Ps[pane]
, $C = $Cs[pane]
, o = options[pane]
, s = state[pane]
, m = s.content // m = measurements
;
if (!$P || !$C || !$P.is(":visible")) return true; // NOT VISIBLE - skip
// if content-element was REMOVED, update OR remove the pointer
if (!$C.length) {
initContent(pane, false); // false = do NOT sizeContent() - already there!
if (!$C) return; // no replacement element found - pointer have been removed
}
// onsizecontent_start will CANCEL resizing if returns false
if (false === _runCallbacks("onsizecontent_start", pane)) return;
// skip re-measuring offsets if live-resizing
if ((!s.isMoving && !s.isResizing) || o.liveContentResizing || remeasure || m.top == undefined) {
_measure();
// if any footers are below pane-bottom, they may not measure correctly,
// so allow pane overflow and re-measure
if (m.hiddenFooters > 0 && $P.css("overflow") === "hidden") {
$P.css("overflow", "visible");
_measure(); // remeasure while overflowing
$P.css("overflow", "hidden");
}
}
// NOTE: spaceAbove/Below *includes* the pane paddingTop/Bottom, but not pane.borders
var newH = s.innerHeight - (m.spaceAbove - s.css.paddingTop) - (m.spaceBelow - s.css.paddingBottom);
if (!$C.is(":visible") || m.height != newH) {
// size the Content element to fit new pane-size - will autoHide if not enough room
setOuterHeight($C, newH, true); // true=autoHide
m.height = newH; // save new height
}
if (state.initialized)
_runCallbacks("onsizecontent_end", pane);
function _below ($E) {
return max(s.css.paddingBottom, (parseInt($E.css("marginBottom"), 10) || 0));
}
function _measure () {
var
ignore = options[pane].contentIgnoreSelector
, $Fs = $C.nextAll().not(".ui-layout-mask").not(ignore || ":lt(0)") // not :lt(0) = ALL
, $Fs_vis = $Fs.filter(':visible')
, $F = $Fs_vis.filter(':last')
;
m = {
top: $C[0].offsetTop
, height: $C.outerHeight()
, numFooters: $Fs.length
, hiddenFooters: $Fs.length - $Fs_vis.length
, spaceBelow: 0 // correct if no content footer ($E)
};
m.spaceAbove = m.top; // just for state - not used in calc
m.bottom = m.top + m.height;
if ($F.length)
//spaceBelow = (LastFooter.top + LastFooter.height) [footerBottom] - Content.bottom + max(LastFooter.marginBottom, pane.paddingBotom)
m.spaceBelow = ($F[0].offsetTop + $F.outerHeight()) - m.bottom + _below($F);
else // no footer - check marginBottom on Content element itself
m.spaceBelow = _below($C);
}
});
}
/**
* Called every time a pane is opened, closed, or resized to slide the togglers to 'center' and adjust their length if necessary
*
* @see initHandles(), open(), close(), resizeAll()
* @param {(string|Object)=} evt_or_panes The pane(s) being resized
*/
, sizeHandles = function (evt_or_panes) {
var panes = evtPane.call(this, evt_or_panes);
panes = panes ? panes.split(",") : _c.borderPanes;
$.each(panes, function (i, pane) {
var
o = options[pane]
, s = state[pane]
, $P = $Ps[pane]
, $R = $Rs[pane]
, $T = $Ts[pane]
, $TC
;
if (!$P || !$R) return;
var
dir = _c[pane].dir
, _state = (s.isClosed ? "_closed" : "_open")
, spacing = o["spacing"+ _state]
, togAlign = o["togglerAlign"+ _state]
, togLen = o["togglerLength"+ _state]
, paneLen
, left
, offset
, CSS = {}
;
if (spacing === 0) {
$R.hide();
return;
}
else if (!s.noRoom && !s.isHidden) // skip if resizer was hidden for any reason
$R.show(); // in case was previously hidden
// Resizer Bar is ALWAYS same width/height of pane it is attached to
if (dir === "horz") { // north/south
//paneLen = $P.outerWidth(); // s.outerWidth ||
paneLen = sC.innerWidth; // handle offscreen-panes
s.resizerLength = paneLen;
left = $.layout.cssNum($P, "left");
$R.css({
width: cssW($R, paneLen) // account for borders & padding
, height: cssH($R, spacing) // ditto
, left: left > -9999 ? left : sC.inset.left // handle offscreen-panes
});
}
else { // east/west
paneLen = $P.outerHeight(); // s.outerHeight ||
s.resizerLength = paneLen;
$R.css({
height: cssH($R, paneLen) // account for borders & padding
, width: cssW($R, spacing) // ditto
, top: sC.inset.top + getPaneSize("north", true) // TODO: what if no North pane?
//, top: $.layout.cssNum($Ps["center"], "top")
});
}
// remove hover classes
removeHover( o, $R );
if ($T) {
if (togLen === 0 || (s.isSliding && o.hideTogglerOnSlide)) {
$T.hide(); // always HIDE the toggler when 'sliding'
return;
}
else
$T.show(); // in case was previously hidden
if (!(togLen > 0) || togLen === "100%" || togLen > paneLen) {
togLen = paneLen;
offset = 0;
}
else { // calculate 'offset' based on options.PANE.togglerAlign_open/closed
if (isStr(togAlign)) {
switch (togAlign) {
case "top":
case "left": offset = 0;
break;
case "bottom":
case "right": offset = paneLen - togLen;
break;
case "middle":
case "center":
default: offset = round((paneLen - togLen) / 2); // 'default' catches typos
}
}
else { // togAlign = number
var x = parseInt(togAlign, 10); //
if (togAlign >= 0) offset = x;
else offset = paneLen - togLen + x; // NOTE: x is negative!
}
}
if (dir === "horz") { // north/south
var width = cssW($T, togLen);
$T.css({
width: width // account for borders & padding
, height: cssH($T, spacing) // ditto
, left: offset // TODO: VERIFY that toggler positions correctly for ALL values
, top: 0
});
// CENTER the toggler content SPAN
// $T.children(".content").each(function(){
// $T.children(".ui-content").each(function(){ // ThinkGem content 改为 ui-content 解决与AdminLTE类名冲突
// $TC = $(this);
// $TC.css("marginLeft", round((width-$TC.outerWidth())/2)); // could be negative
// });
// ThinkGem 以上4行代码不需要,因为在css里会自动居中
}
else { // east/west
var height = cssH($T, togLen);
$T.css({
height: height // account for borders & padding
, width: cssW($T, spacing) // ditto
, top: offset // POSITION the toggler
, left: 0
});
// CENTER the toggler content SPAN
// $T.children(".content").each(function(){
$T.children(".ui-content").each(function(){ // ThinkGem content 改为 ui-content 解决与AdminLTE类名冲突
$TC = $(this);
$TC.css("marginTop", round((height-$TC.outerHeight())/2)); // could be negative
});
}
// remove ALL hover classes
removeHover( 0, $T );
}
// DONE measuring and sizing this resizer/toggler, so can be 'hidden' now
if (!state.initialized && (o.initHidden || s.isHidden)) {
$R.hide();
if ($T) $T.hide();
}
});
}
/**
* @param {(string|Object)} evt_or_pane
*/
, enableClosable = function (evt_or_pane) {
if (!isInitialized()) return;
var pane = evtPane.call(this, evt_or_pane)
, $T = $Ts[pane]
, o = options[pane]
;
if (!$T) return;
o.closable = true;
$T .bind("click."+ sID, function(evt){ evt.stopPropagation(); toggle(pane); })
.css("visibility", "visible")
.css("cursor", "pointer")
.attr("title", state[pane].isClosed ? o.tips.Open : o.tips.Close) // may be blank
.show();
}
/**
* @param {(string|Object)} evt_or_pane
* @param {boolean=} [hide=false]
*/
, disableClosable = function (evt_or_pane, hide) {
if (!isInitialized()) return;
var pane = evtPane.call(this, evt_or_pane)
, $T = $Ts[pane]
;
if (!$T) return;
options[pane].closable = false;
// is closable is disable, then pane MUST be open!
if (state[pane].isClosed) open(pane, false, true);
$T .unbind("."+ sID)
.css("visibility", hide ? "hidden" : "visible") // instead of hide(), which creates logic issues
.css("cursor", "default")
.attr("title", "");
}
/**
* @param {(string|Object)} evt_or_pane
*/
, enableSlidable = function (evt_or_pane) {
if (!isInitialized()) return;
var pane = evtPane.call(this, evt_or_pane)
, $R = $Rs[pane]
;
if (!$R || !$R.data('draggable')) return;
options[pane].slidable = true;
if (state[pane].isClosed)
bindStartSlidingEvents(pane, true);
}
/**
* @param {(string|Object)} evt_or_pane
*/
, disableSlidable = function (evt_or_pane) {
if (!isInitialized()) return;
var pane = evtPane.call(this, evt_or_pane)
, $R = $Rs[pane]
;
if (!$R) return;
options[pane].slidable = false;
if (state[pane].isSliding)
close(pane, false, true);
else {
bindStartSlidingEvents(pane, false);
$R .css("cursor", "default")
.attr("title", "");
removeHover(null, $R[0]); // in case currently hovered
}
}
/**
* @param {(string|Object)} evt_or_pane
*/
, enableResizable = function (evt_or_pane) {
if (!isInitialized()) return;
var pane = evtPane.call(this, evt_or_pane)
, $R = $Rs[pane]
, o = options[pane]
;
if (!$R || !$R.data('draggable')) return;
o.resizable = true;
$R.draggable("enable");
if (!state[pane].isClosed)
$R .css("cursor", o.resizerCursor)
.attr("title", o.tips.Resize);
}
/**
* @param {(string|Object)} evt_or_pane
*/
, disableResizable = function (evt_or_pane) {
if (!isInitialized()) return;
var pane = evtPane.call(this, evt_or_pane)
, $R = $Rs[pane]
;
if (!$R || !$R.data('draggable')) return;
options[pane].resizable = false;
$R .draggable("disable")
.css("cursor", "default")
.attr("title", "");
removeHover(null, $R[0]); // in case currently hovered
}
/**
* Move a pane from source-side (eg, west) to target-side (eg, east)
* If pane exists on target-side, move that to source-side, ie, 'swap' the panes
*
* @param {(string|Object)} evt_or_pane1 The pane/edge being swapped
* @param {string} pane2 ditto
*/
, swapPanes = function (evt_or_pane1, pane2) {
if (!isInitialized()) return;
var pane1 = evtPane.call(this, evt_or_pane1);
// change state.edge NOW so callbacks can know where pane is headed...
state[pane1].edge = pane2;
state[pane2].edge = pane1;
// run these even if NOT state.initialized
if (false === _runCallbacks("onswap_start", pane1)
|| false === _runCallbacks("onswap_start", pane2)
) {
state[pane1].edge = pane1; // reset
state[pane2].edge = pane2;
return;
}
var
oPane1 = copy( pane1 )
, oPane2 = copy( pane2 )
, sizes = {}
;
sizes[pane1] = oPane1 ? oPane1.state.size : 0;
sizes[pane2] = oPane2 ? oPane2.state.size : 0;
// clear pointers & state
$Ps[pane1] = false;
$Ps[pane2] = false;
state[pane1] = {};
state[pane2] = {};
// ALWAYS remove the resizer & toggler elements
if ($Ts[pane1]) $Ts[pane1].remove();
if ($Ts[pane2]) $Ts[pane2].remove();
if ($Rs[pane1]) $Rs[pane1].remove();
if ($Rs[pane2]) $Rs[pane2].remove();
$Rs[pane1] = $Rs[pane2] = $Ts[pane1] = $Ts[pane2] = false;
// transfer element pointers and data to NEW Layout keys
move( oPane1, pane2 );
move( oPane2, pane1 );
// cleanup objects
oPane1 = oPane2 = sizes = null;
// make panes 'visible' again
if ($Ps[pane1]) $Ps[pane1].css(_c.visible);
if ($Ps[pane2]) $Ps[pane2].css(_c.visible);
// fix any size discrepancies caused by swap
resizeAll();
// run these even if NOT state.initialized
_runCallbacks("onswap_end", pane1);
_runCallbacks("onswap_end", pane2);
function copy (n) { // n = pane
var
$P = $Ps[n]
, $C = $Cs[n]
;
return !$P ? false : {
pane: n
, P: $P ? $P[0] : false
, C: $C ? $C[0] : false
, state: $.extend(true, {}, state[n])
, options: $.extend(true, {}, options[n])
}
}
function move (oPane, pane) {
if (!oPane) return;
var
P = oPane.P
, C = oPane.C
, oldPane = oPane.pane
, c = _c[pane]
// save pane-options that should be retained
, s = $.extend(true, {}, state[pane])
, o = options[pane]
// RETAIN side-specific FX Settings - more below
, fx = { resizerCursor: o.resizerCursor }
, re, size, pos
;
$.each("fxName,fxSpeed,fxSettings".split(","), function (i, k) {
fx[k +"_open"] = o[k +"_open"];
fx[k +"_close"] = o[k +"_close"];
fx[k +"_size"] = o[k +"_size"];
});
// update object pointers and attributes
$Ps[pane] = $(P)
.data({
layoutPane: Instance[pane] // NEW pointer to pane-alias-object
, layoutEdge: pane
})
.css(_c.hidden)
.css(c.cssReq)
;
$Cs[pane] = C ? $(C) : false;
// set options and state
options[pane] = $.extend(true, {}, oPane.options, fx);
state[pane] = $.extend(true, {}, oPane.state);
// change classNames on the pane, eg: ui-layout-pane-east ==> ui-layout-pane-west
re = new RegExp(o.paneClass +"-"+ oldPane, "g");
P.className = P.className.replace(re, o.paneClass +"-"+ pane);
// ALWAYS regenerate the resizer & toggler elements
initHandles(pane); // create the required resizer & toggler
// if moving to different orientation, then keep 'target' pane size
if (c.dir != _c[oldPane].dir) {
size = sizes[pane] || 0;
setSizeLimits(pane); // update pane-state
size = max(size, state[pane].minSize);
// use manualSizePane to disable autoResize - not useful after panes are swapped
manualSizePane(pane, size, true, true); // true/true = skipCallback/noAnimation
}
else // move the resizer here
$Rs[pane].css(c.side, sC.inset[c.side] + (state[pane].isVisible ? getPaneSize(pane) : 0));
// ADD CLASSNAMES & SLIDE-BINDINGS
if (oPane.state.isVisible && !s.isVisible)
setAsOpen(pane, true); // true = skipCallback
else {
setAsClosed(pane);
bindStartSlidingEvents(pane, true); // will enable events IF option is set
}
// DESTROY the object
oPane = null;
}
}
/**
* INTERNAL method to sync pin-buttons when pane is opened or closed
* Unpinned means the pane is 'sliding' - ie, over-top of the adjacent panes
*
* @see open(), setAsOpen(), setAsClosed()
* @param {string} pane These are the params returned to callbacks by layout()
* @param {boolean} doPin True means set the pin 'down', False means 'up'
*/
, syncPinBtns = function (pane, doPin) {
if ($.layout.plugins.buttons)
$.each(state[pane].pins, function (i, selector) {
$.layout.buttons.setPinState(Instance, $(selector), pane, doPin);
});
}
; // END var DECLARATIONS
/**
* Capture keys when enableCursorHotkey - toggle pane if hotkey pressed
*
* @see document.keydown()
*/
function keyDown (evt) {
if (!evt) return true;
var code = evt.keyCode;
if (code < 33) return true; // ignore special keys: ENTER, TAB, etc
var
PANE = {
38: "north" // Up Cursor - $.ui.keyCode.UP
, 40: "south" // Down Cursor - $.ui.keyCode.DOWN
, 37: "west" // Left Cursor - $.ui.keyCode.LEFT
, 39: "east" // Right Cursor - $.ui.keyCode.RIGHT
}
, ALT = evt.altKey // no worky!
, SHIFT = evt.shiftKey
, CTRL = evt.ctrlKey
, CURSOR = (CTRL && code >= 37 && code <= 40)
, o, k, m, pane
;
if (CURSOR && options[PANE[code]].enableCursorHotkey) // valid cursor-hotkey
pane = PANE[code];
else if (CTRL || SHIFT) // check to see if this matches a custom-hotkey
$.each(_c.borderPanes, function (i, p) { // loop each pane to check its hotkey
o = options[p];
k = o.customHotkey;
m = o.customHotkeyModifier; // if missing or invalid, treated as "CTRL+SHIFT"
if ((SHIFT && m=="SHIFT") || (CTRL && m=="CTRL") || (CTRL && SHIFT)) { // Modifier matches
if (k && code === (isNaN(k) || k <= 9 ? k.toUpperCase().charCodeAt(0) : k)) { // Key matches
pane = p;
return false; // BREAK
}
}
});
// validate pane
if (!pane || !$Ps[pane] || !options[pane].closable || state[pane].isHidden)
return true;
toggle(pane);
evt.stopPropagation();
evt.returnValue = false; // CANCEL key
return false;
}
/*
* ######################################
* UTILITY METHODS
* called externally or by initButtons
* ######################################
*/
/**
* Change/reset a pane overflow setting & zIndex to allow popups/drop-downs to work
*
* @param {Object=} [el] (optional) Can also be 'bound' to a click, mouseOver, or other event
*/
function allowOverflow (el) {
if (!isInitialized()) return;
if (this && this.tagName) el = this; // BOUND to element
var $P;
if (isStr(el))
$P = $Ps[el];
else if ($(el).data("layoutRole"))
$P = $(el);
else
$(el).parents().each(function(){
if ($(this).data("layoutRole")) {
$P = $(this);
return false; // BREAK
}
});
if (!$P || !$P.length) return; // INVALID
var
pane = $P.data("layoutEdge")
, s = state[pane]
;
// if pane is already raised, then reset it before doing it again!
// this would happen if allowOverflow is attached to BOTH the pane and an element
if (s.cssSaved)
resetOverflow(pane); // reset previous CSS before continuing
// if pane is raised by sliding or resizing, or its closed, then abort
if (s.isSliding || s.isResizing || s.isClosed) {
s.cssSaved = false;
return;
}
var
newCSS = { zIndex: (options.zIndexes.resizer_normal + 1) }
, curCSS = {}
, of = $P.css("overflow")
, ofX = $P.css("overflowX")
, ofY = $P.css("overflowY")
;
// determine which, if any, overflow settings need to be changed
if (of != "visible") {
curCSS.overflow = of;
newCSS.overflow = "visible";
}
if (ofX && !ofX.match(/(visible|auto)/)) {
curCSS.overflowX = ofX;
newCSS.overflowX = "visible";
}
if (ofY && !ofY.match(/(visible|auto)/)) {
curCSS.overflowY = ofX;
newCSS.overflowY = "visible";
}
// save the current overflow settings - even if blank!
s.cssSaved = curCSS;
// apply new CSS to raise zIndex and, if necessary, make overflow 'visible'
$P.css( newCSS );
// make sure the zIndex of all other panes is normal
$.each(_c.allPanes, function(i, p) {
if (p != pane) resetOverflow(p);
});
}
/**
* @param {Object=} [el] (optional) Can also be 'bound' to a click, mouseOver, or other event
*/
function resetOverflow (el) {
if (!isInitialized()) return;
if (this && this.tagName) el = this; // BOUND to element
var $P;
if (isStr(el))
$P = $Ps[el];
else if ($(el).data("layoutRole"))
$P = $(el);
else
$(el).parents().each(function(){
if ($(this).data("layoutRole")) {
$P = $(this);
return false; // BREAK
}
});
if (!$P || !$P.length) return; // INVALID
var
pane = $P.data("layoutEdge")
, s = state[pane]
, CSS = s.cssSaved || {}
;
// reset the zIndex
if (!s.isSliding && !s.isResizing)
$P.css("zIndex", options.zIndexes.pane_normal);
// reset Overflow - if necessary
$P.css( CSS );
// clear var
s.cssSaved = false;
}
/*
* #####################
* CREATE/RETURN LAYOUT
* #####################
*/
// validate that container exists
var $N = $(this).eq(0); // FIRST matching Container element
if (!$N.length) {
return _log( options.errors.containerMissing );
}
// Users retrieve Instance of a layout with: $N.layout() OR $N.data("layout")
// return the Instance-pointer if layout has already been initialized
if ($N.data("layoutContainer") && $N.data("layout"))
return $N.data("layout"); // cached pointer
// init global vars
var
$Ps = {} // Panes x5 - set in initPanes()
, $Cs = {} // Content x5 - set in initPanes()
, $Rs = {} // Resizers x4 - set in initHandles()
, $Ts = {} // Togglers x4 - set in initHandles()
, $Ms = $([]) // Masks - up to 2 masks per pane (IFRAME + DIV)
// aliases for code brevity
, sC = state.container // alias for easy access to 'container dimensions'
, sID = state.id // alias for unique layout ID/namespace - eg: "layout435"
;
// create Instance object to expose data & option Properties, and primary action Methods
var Instance = {
// layout data
options: options // property - options hash
, state: state // property - dimensions hash
// object pointers
, container: $N // property - object pointers for layout container
, panes: $Ps // property - object pointers for ALL Panes: panes.north, panes.center
, contents: $Cs // property - object pointers for ALL Content: contents.north, contents.center
, resizers: $Rs // property - object pointers for ALL Resizers, eg: resizers.north
, togglers: $Ts // property - object pointers for ALL Togglers, eg: togglers.north
// border-pane open/close
, hide: hide // method - ditto
, show: show // method - ditto
, toggle: toggle // method - pass a 'pane' ("north", "west", etc)
, open: open // method - ditto
, close: close // method - ditto
, slideOpen: slideOpen // method - ditto
, slideClose: slideClose // method - ditto
, slideToggle: slideToggle // method - ditto
// pane actions
, setSizeLimits: setSizeLimits // method - pass a 'pane' - update state min/max data
, _sizePane: sizePane // method -intended for user by plugins only!
, sizePane: manualSizePane // method - pass a 'pane' AND an 'outer-size' in pixels or percent, or 'auto'
, sizeContent: sizeContent // method - pass a 'pane'
, swapPanes: swapPanes // method - pass TWO 'panes' - will swap them
, showMasks: showMasks // method - pass a 'pane' OR list of panes - default = all panes with mask option set
, hideMasks: hideMasks // method - ditto'
// pane element methods
, initContent: initContent // method - ditto
, addPane: addPane // method - pass a 'pane'
, removePane: removePane // method - pass a 'pane' to remove from layout, add 'true' to delete the pane-elem
, createChildren: createChildren // method - pass a 'pane' and (optional) layout-options (OVERRIDES options[pane].children
, refreshChildren: refreshChildren // method - pass a 'pane' and a layout-instance
// special pane option setting
, enableClosable: enableClosable // method - pass a 'pane'
, disableClosable: disableClosable // method - ditto
, enableSlidable: enableSlidable // method - ditto
, disableSlidable: disableSlidable // method - ditto
, enableResizable: enableResizable // method - ditto
, disableResizable: disableResizable// method - ditto
// utility methods for panes
, allowOverflow: allowOverflow // utility - pass calling element (this)
, resetOverflow: resetOverflow // utility - ditto
// layout control
, destroy: destroy // method - no parameters
, initPanes: isInitialized // method - no parameters
, resizeAll: resizeAll // method - no parameters
// callback triggering
, runCallbacks: _runCallbacks // method - pass evtName & pane (if a pane-event), eg: trigger("onopen", "west")
// alias collections of options, state and children - created in addPane and extended elsewhere
, hasParentLayout: false // set by initContainer()
, children: children // pointers to child-layouts, eg: Instance.children.west.layoutName
, north: false // alias group: { name: pane, pane: $Ps[pane], options: options[pane], state: state[pane], children: children[pane] }
, south: false // ditto
, west: false // ditto
, east: false // ditto
, center: false // ditto
};
// create the border layout NOW
if (_create() === 'cancel') // onload_start callback returned false to CANCEL layout creation
return null;
else // true OR false -- if layout-elements did NOT init (hidden or do not exist), can auto-init later
return Instance; // return the Instance object
}
})( jQuery );
(function ($) {
if (!$.layout) return;
/**
* UI COOKIE UTILITY
*
* A $.cookie OR $.ui.cookie namespace *should be standard*, but until then...
* This creates $.ui.cookie so Layout does not need the cookie.jquery.js plugin
* NOTE: This utility is REQUIRED by the layout.state plugin
*
* Cookie methods in Layout are created as part of State Management
*/
if (!$.ui) $.ui = {};
$.ui.cookie = {
// cookieEnabled is not in DOM specs, but DOES works in all browsers,including IE6
acceptsCookies: !!navigator.cookieEnabled
, read: function (name) {
var
c = document.cookie
, cs = c ? c.split(';') : []
, pair, data, i
;
for (i=0; pair=cs[i]; i++) {
data = $.trim(pair).split('='); // name=value => [ name, value ]
if (data[0] == name) // found the layout cookie
return decodeURIComponent(data[1]);
}
return null;
}
, write: function (name, val, cookieOpts) {
var params = ""
, date = ""
, clear = false
, o = cookieOpts || {}
, x = o.expires || null
, t = $.type(x)
;
if (t === "date")
date = x;
else if (t === "string" && x > 0) {
x = parseInt(x,10);
t = "number";
}
if (t === "number") {
date = new Date();
if (x > 0)
date.setDate(date.getDate() + x);
else {
date.setFullYear(1970);
clear = true;
}
}
if (date) params += ";expires="+ date.toUTCString();
if (o.path) params += ";path="+ o.path;
if (o.domain) params += ";domain="+ o.domain;
if (o.secure) params += ";secure";
document.cookie = name +"="+ (clear ? "" : encodeURIComponent( val )) + params; // write or clear cookie
}
, clear: function (name) {
$.ui.cookie.write(name, "", {expires: -1});
}
};
// if cookie.jquery.js is not loaded, create an alias to replicate it
// this may be useful to other plugins or code dependent on that plugin
if (!$.cookie) $.cookie = function (k, v, o) {
var C = $.ui.cookie;
if (v === null)
C.clear(k);
else if (v === undefined)
return C.read(k);
else
C.write(k, v, o);
};
/**
* State-management options stored in options.stateManagement, which includes a .cookie hash
* Default options saves ALL KEYS for ALL PANES, ie: pane.size, pane.isClosed, pane.isHidden
*
* // STATE/COOKIE OPTIONS
* @example $(el).layout({
stateManagement: {
enabled: true
, stateKeys: "east.size,west.size,east.isClosed,west.isClosed"
, cookie: { name: "appLayout", path: "/" }
}
})
* @example $(el).layout({ stateManagement__enabled: true }) // enable auto-state-management using cookies
* @example $(el).layout({ stateManagement__cookie: { name: "appLayout", path: "/" } })
* @example $(el).layout({ stateManagement__cookie__name: "appLayout", stateManagement__cookie__path: "/" })
*
* // STATE/COOKIE METHODS
* @example myLayout.saveCookie( "west.isClosed,north.size,south.isHidden", {expires: 7} );
* @example myLayout.loadCookie();
* @example myLayout.deleteCookie();
* @example var JSON = myLayout.readState(); // CURRENT Layout State
* @example var JSON = myLayout.readCookie(); // SAVED Layout State (from cookie)
* @example var JSON = myLayout.state.stateData; // LAST LOADED Layout State (cookie saved in layout.state hash)
*
* CUSTOM STATE-MANAGEMENT (eg, saved in a database)
* @example var JSON = myLayout.readState( "west.isClosed,north.size,south.isHidden" );
* @example myLayout.loadState( JSON );
*/
// tell Layout that the state plugin is available
$.layout.plugins.stateManagement = true;
// Add State-Management options to layout.defaults
$.layout.defaults.stateManagement = {
enabled: false // true = enable state-management, even if not using cookies
, autoSave: true // Save a state-cookie when page exits?
, autoLoad: true // Load the state-cookie when Layout inits?
, animateLoad: true // animate panes when loading state into an active layout
, includeChildren: true // recurse into child layouts to include their state as well
// List state-data to save - must be pane-specific
, stateKeys: "north.size,south.size,east.size,west.size,"+
"north.isClosed,south.isClosed,east.isClosed,west.isClosed,"+
"north.isHidden,south.isHidden,east.isHidden,west.isHidden"
, cookie: {
name: "" // If not specified, will use Layout.name, else just "Layout"
, domain: "" // blank = current domain
, path: "" // blank = current page, "/" = entire website
, expires: "" // 'days' to keep cookie - leave blank for 'session cookie'
, secure: false
}
};
// Set stateManagement as a 'layout-option', NOT a 'pane-option'
$.layout.optionsMap.layout.push("stateManagement");
// Update config so layout does not move options into the pane-default branch (panes)
$.layout.config.optionRootKeys.push("stateManagement");
/*
* State Management methods
*/
$.layout.state = {
/**
* Get the current layout state and save it to a cookie
*
* myLayout.saveCookie( keys, cookieOpts )
*
* @param {Object} inst
* @param {(string|Array)=} keys
* @param {Object=} cookieOpts
*/
saveCookie: function (inst, keys, cookieOpts) {
var o = inst.options
, sm = o.stateManagement
, oC = $.extend(true, {}, sm.cookie, cookieOpts || null)
, data = inst.state.stateData = inst.readState( keys || sm.stateKeys ) // read current panes-state
;
$.ui.cookie.write( oC.name || o.name || "Layout", $.layout.state.encodeJSON(data), oC );
return $.extend(true, {}, data); // return COPY of state.stateData data
}
/**
* Remove the state cookie
*
* @param {Object} inst
*/
, deleteCookie: function (inst) {
var o = inst.options;
$.ui.cookie.clear( o.stateManagement.cookie.name || o.name || "Layout" );
}
/**
* Read & return data from the cookie - as JSON
*
* @param {Object} inst
*/
, readCookie: function (inst) {
var o = inst.options;
var c = $.ui.cookie.read( o.stateManagement.cookie.name || o.name || "Layout" );
// convert cookie string back to a hash and return it
return c ? $.layout.state.decodeJSON(c) : {};
}
/**
* Get data from the cookie and USE IT to loadState
*
* @param {Object} inst
*/
, loadCookie: function (inst) {
var c = $.layout.state.readCookie(inst); // READ the cookie
if (c && !$.isEmptyObject( c )) {
inst.state.stateData = $.extend(true, {}, c); // SET state.stateData
inst.loadState(c); // LOAD the retrieved state
}
return c;
}
/**
* Update layout options from the cookie, if one exists
*
* @param {Object} inst
* @param {Object=} stateData
* @param {boolean=} animate
*/
, loadState: function (inst, data, opts) {
if (!$.isPlainObject( data ) || $.isEmptyObject( data )) return;
// normalize data & cache in the state object
data = inst.state.stateData = $.layout.transformData( data ); // panes = default subkey
// add missing/default state-restore options
var smo = inst.options.stateManagement;
opts = $.extend({
animateLoad: false //smo.animateLoad
, includeChildren: smo.includeChildren
}, opts );
if (!inst.state.initialized) {
/*
* layout NOT initialized, so just update its options
*/
// MUST remove pane.children keys before applying to options
// use a copy so we don't remove keys from original data
var o = $.extend(true, {}, data);
//delete o.center; // center has no state-data - only children
$.each($.layout.config.allPanes, function (idx, pane) {
if (o[pane]) delete o[pane].children;
});
// update CURRENT layout-options with saved state data
$.extend(true, inst.options, o);
}
else {
/*
* layout already initialized, so modify layout's configuration
*/
var noAnimate = !opts.animateLoad
, o, c, h, state, open
;
$.each($.layout.config.borderPanes, function (idx, pane) {
o = data[ pane ];
if (!$.isPlainObject( o )) return; // no key, skip pane
s = o.size;
c = o.initClosed;
h = o.initHidden;
ar = o.autoResize;
state = inst.state[pane];
open = state.isVisible;
// reset autoResize
if (ar)
state.autoResize = ar;
// resize BEFORE opening
if (!open)
inst._sizePane(pane, s, false, false, false); // false=skipCallback/noAnimation/forceResize
// open/close as necessary - DO NOT CHANGE THIS ORDER!
if (h === true) inst.hide(pane, noAnimate);
else if (c === true) inst.close(pane, false, noAnimate);
else if (c === false) inst.open (pane, false, noAnimate);
else if (h === false) inst.show (pane, false, noAnimate);
// resize AFTER any other actions
if (open)
inst._sizePane(pane, s, false, false, noAnimate); // animate resize if option passed
});
/*
* RECURSE INTO CHILD-LAYOUTS
*/
if (opts.includeChildren) {
var paneStateChildren, childState;
$.each(inst.children, function (pane, paneChildren) {
paneStateChildren = data[pane] ? data[pane].children : 0;
if (paneStateChildren && paneChildren) {
$.each(paneChildren, function (stateKey, child) {
childState = paneStateChildren[stateKey];
if (child && childState)
child.loadState( childState );
});
}
});
}
}
}
/**
* Get the *current layout state* and return it as a hash
*
* @param {Object=} inst // Layout instance to get state for
* @param {object=} [opts] // State-Managements override options
*/
, readState: function (inst, opts) {
// backward compatility
if ($.type(opts) === 'string') opts = { keys: opts };
if (!opts) opts = {};
var sm = inst.options.stateManagement
, ic = opts.includeChildren
, recurse = ic !== undefined ? ic : sm.includeChildren
, keys = opts.stateKeys || sm.stateKeys
, alt = { isClosed: 'initClosed', isHidden: 'initHidden' }
, state = inst.state
, panes = $.layout.config.allPanes
, data = {}
, pair, pane, key, val
, ps, pC, child, array, count, branch
;
if ($.isArray(keys)) keys = keys.join(",");
// convert keys to an array and change delimiters from '__' to '.'
keys = keys.replace(/__/g, ".").split(',');
// loop keys and create a data hash
for (var i=0, n=keys.length; i < n; i++) {
pair = keys[i].split(".");
pane = pair[0];
key = pair[1];
if ($.inArray(pane, panes) < 0) continue; // bad pane!
val = state[ pane ][ key ];
if (val == undefined) continue;
if (key=="isClosed" && state[pane]["isSliding"])
val = true; // if sliding, then *really* isClosed
( data[pane] || (data[pane]={}) )[ alt[key] ? alt[key] : key ] = val;
}
// recurse into the child-layouts for each pane
if (recurse) {
$.each(panes, function (idx, pane) {
pC = inst.children[pane];
ps = state.stateData[pane];
if ($.isPlainObject( pC ) && !$.isEmptyObject( pC )) {
// ensure a key exists for this 'pane', eg: branch = data.center
branch = data[pane] || (data[pane] = {});
if (!branch.children) branch.children = {};
$.each( pC, function (key, child) {
// ONLY read state from an initialize layout
if ( child.state.initialized )
branch.children[ key ] = $.layout.state.readState( child );
// if we have PREVIOUS (onLoad) state for this child-layout, KEEP IT!
else if ( ps && ps.children && ps.children[ key ] ) {
branch.children[ key ] = $.extend(true, {}, ps.children[ key ] );
}
});
}
});
}
return data;
}
/**
* Stringify a JSON hash so can save in a cookie or db-field
*/
, encodeJSON: function (json) {
var local = window.JSON || {};
return (local.stringify || stringify)(json);
function stringify (h) {
var D=[], i=0, k, v, t // k = key, v = value
, a = $.isArray(h)
;
for (k in h) {
v = h[k];
t = typeof v;
if (t == 'string') // STRING - add quotes
v = '"'+ v +'"';
else if (t == 'object') // SUB-KEY - recurse into it
v = parse(v);
D[i++] = (!a ? '"'+ k +'":' : '') + v;
}
return (a ? '[' : '{') + D.join(',') + (a ? ']' : '}');
}
}
/**
* Convert stringified JSON back to a hash object
* @see $.parseJSON(), adding in jQuery 1.4.1
*/
, decodeJSON: function (str) {
try { return $.parseJSON ? $.parseJSON(str) : window["eval"]("("+ str +")") || {}; }
catch (e) { return {}; }
}
, _create: function (inst) {
var s = $.layout.state
, o = inst.options
, sm = o.stateManagement
;
// ADD State-Management plugin methods to inst
$.extend( inst, {
// readCookie - update options from cookie - returns hash of cookie data
readCookie: function () { return s.readCookie(inst); }
// deleteCookie
, deleteCookie: function () { s.deleteCookie(inst); }
// saveCookie - optionally pass keys-list and cookie-options (hash)
, saveCookie: function (keys, cookieOpts) { return s.saveCookie(inst, keys, cookieOpts); }
// loadCookie - readCookie and use to loadState() - returns hash of cookie data
, loadCookie: function () { return s.loadCookie(inst); }
// loadState - pass a hash of state to use to update options
, loadState: function (stateData, opts) { s.loadState(inst, stateData, opts); }
// readState - returns hash of current layout-state
, readState: function (keys) { return s.readState(inst, keys); }
// add JSON utility methods too...
, encodeJSON: s.encodeJSON
, decodeJSON: s.decodeJSON
});
// init state.stateData key, even if plugin is initially disabled
inst.state.stateData = {};
// autoLoad MUST BE one of: data-array, data-hash, callback-function, or TRUE
if ( !sm.autoLoad ) return;
// When state-data exists in the autoLoad key USE IT,
// even if stateManagement.enabled == false
if ($.isPlainObject( sm.autoLoad )) {
if (!$.isEmptyObject( sm.autoLoad )) {
inst.loadState( sm.autoLoad );
}
}
else if ( sm.enabled ) {
// update the options from cookie or callback
// if options is a function, call it to get stateData
if ($.isFunction( sm.autoLoad )) {
var d = {};
try {
d = sm.autoLoad( inst, inst.state, inst.options, inst.options.name || '' ); // try to get data from fn
} catch (e) {}
if (d && $.isPlainObject( d ) && !$.isEmptyObject( d ))
inst.loadState(d);
}
else // any other truthy value will trigger loadCookie
inst.loadCookie();
}
}
, _unload: function (inst) {
var sm = inst.options.stateManagement;
if (sm.enabled && sm.autoSave) {
// if options is a function, call it to save the stateData
if ($.isFunction( sm.autoSave )) {
try {
sm.autoSave( inst, inst.state, inst.options, inst.options.name || '' ); // try to get data from fn
} catch (e) {}
}
else // any truthy value will trigger saveCookie
inst.saveCookie();
}
}
};
// add state initialization method to Layout's onCreate array of functions
$.layout.onCreate.push( $.layout.state._create );
$.layout.onUnload.push( $.layout.state._unload );
})( jQuery );
(function ($) {
if (!$.layout) return;
// tell Layout that the state plugin is available
$.layout.plugins.buttons = true;
// Add State-Management options to layout.defaults
$.layout.defaults.autoBindCustomButtons = false;
// Set stateManagement as a layout-option, NOT a pane-option
$.layout.optionsMap.layout.push("autoBindCustomButtons");
/*
* Button methods
*/
$.layout.buttons = {
// set data used by multiple methods below
config: {
borderPanes: "north,south,west,east"
}
/**
* Searches for .ui-layout-button-xxx elements and auto-binds them as layout-buttons
*
* @see _create()
*/
, init: function (inst) {
var pre = "ui-layout-button-"
, layout = inst.options.name || ""
, name;
$.each("toggle,open,close,pin,toggle-slide,open-slide".split(","), function (i, action) {
$.each($.layout.buttons.config.borderPanes.split(","), function (ii, pane) {
$("."+pre+action+"-"+pane).each(function(){
// if button was previously 'bound', data.layoutName was set, but is blank if layout has no 'name'
name = $(this).data("layoutName") || $(this).attr("layoutName");
if (name == undefined || name === layout)
inst.bindButton(this, action, pane);
});
});
});
}
/**
* Helper function to validate params received by addButton utilities
*
* Two classes are added to the element, based on the buttonClass...
* The type of button is appended to create the 2nd className:
* - ui-layout-button-pin
* - ui-layout-pane-button-toggle
* - ui-layout-pane-button-open
* - ui-layout-pane-button-close
*
* @param {(string|!Object)} selector jQuery selector (or element) for button, eg: ".ui-layout-north .toggle-button"
* @param {string} pane Name of the pane the button is for: 'north', 'south', etc.
* @return {Array.<Object>} If both params valid, the element matching 'selector' in a jQuery wrapper - otherwise returns null
*/
, get: function (inst, selector, pane, action) {
var $E = $(selector)
, o = inst.options
//, err = o.showErrorMessages
;
if ($E.length && $.layout.buttons.config.borderPanes.indexOf(pane) >= 0) {
var btn = o[pane].buttonClass +"-"+ action;
$E .addClass( btn +" "+ btn +"-"+ pane )
.data("layoutName", o.name); // add layout identifier - even if blank!
}
return $E;
}
/**
* NEW syntax for binding layout-buttons - will eventually replace addToggle, addOpen, etc.
*
* @param {(string|!Object)} sel jQuery selector (or element) for button, eg: ".ui-layout-north .toggle-button"
* @param {string} action
* @param {string} pane
*/
, bind: function (inst, sel, action, pane) {
var _ = $.layout.buttons;
switch (action.toLowerCase()) {
case "toggle": _.addToggle (inst, sel, pane); break;
case "open": _.addOpen (inst, sel, pane); break;
case "close": _.addClose (inst, sel, pane); break;
case "pin": _.addPin (inst, sel, pane); break;
case "toggle-slide": _.addToggle (inst, sel, pane, true); break;
case "open-slide": _.addOpen (inst, sel, pane, true); break;
}
return inst;
}
/**
* Add a custom Toggler button for a pane
*
* @param {(string|!Object)} selector jQuery selector (or element) for button, eg: ".ui-layout-north .toggle-button"
* @param {string} pane Name of the pane the button is for: 'north', 'south', etc.
* @param {boolean=} slide true = slide-open, false = pin-open
*/
, addToggle: function (inst, selector, pane, slide) {
$.layout.buttons.get(inst, selector, pane, "toggle")
.click(function(evt){
inst.toggle(pane, !!slide);
evt.stopPropagation();
});
return inst;
}
/**
* Add a custom Open button for a pane
*
* @param {(string|!Object)} selector jQuery selector (or element) for button, eg: ".ui-layout-north .toggle-button"
* @param {string} pane Name of the pane the button is for: 'north', 'south', etc.
* @param {boolean=} slide true = slide-open, false = pin-open
*/
, addOpen: function (inst, selector, pane, slide) {
$.layout.buttons.get(inst, selector, pane, "open")
.attr("title", inst.options[pane].tips.Open)
.click(function (evt) {
inst.open(pane, !!slide);
evt.stopPropagation();
});
return inst;
}
/**
* Add a custom Close button for a pane
*
* @param {(string|!Object)} selector jQuery selector (or element) for button, eg: ".ui-layout-north .toggle-button"
* @param {string} pane Name of the pane the button is for: 'north', 'south', etc.
*/
, addClose: function (inst, selector, pane) {
$.layout.buttons.get(inst, selector, pane, "close")
.attr("title", inst.options[pane].tips.Close)
.click(function (evt) {
inst.close(pane);
evt.stopPropagation();
});
return inst;
}
/**
* Add a custom Pin button for a pane
*
* Four classes are added to the element, based on the paneClass for the associated pane...
* Assuming the default paneClass and the pin is 'up', these classes are added for a west-pane pin:
* - ui-layout-pane-pin
* - ui-layout-pane-west-pin
* - ui-layout-pane-pin-up
* - ui-layout-pane-west-pin-up
*
* @param {(string|!Object)} selector jQuery selector (or element) for button, eg: ".ui-layout-north .toggle-button"
* @param {string} pane Name of the pane the pin is for: 'north', 'south', etc.
*/
, addPin: function (inst, selector, pane) {
var $E = $.layout.buttons.get(inst, selector, pane, "pin");
if ($E.length) {
var s = inst.state[pane];
$E.click(function (evt) {
$.layout.buttons.setPinState(inst, $(this), pane, (s.isSliding || s.isClosed));
if (s.isSliding || s.isClosed) inst.open( pane ); // change from sliding to open
else inst.close( pane ); // slide-closed
evt.stopPropagation();
});
// add up/down pin attributes and classes
$.layout.buttons.setPinState(inst, $E, pane, (!s.isClosed && !s.isSliding));
// add this pin to the pane data so we can 'sync it' automatically
// PANE.pins key is an array so we can store multiple pins for each pane
s.pins.push( selector ); // just save the selector string
}
return inst;
}
/**
* Change the class of the pin button to make it look 'up' or 'down'
*
* @see addPin(), syncPins()
* @param {Array.<Object>} $Pin The pin-span element in a jQuery wrapper
* @param {string} pane These are the params returned to callbacks by layout()
* @param {boolean} doPin true = set the pin 'down', false = set it 'up'
*/
, setPinState: function (inst, $Pin, pane, doPin) {
var updown = $Pin.attr("pin");
if (updown && doPin === (updown=="down")) return; // already in correct state
var
po = inst.options[pane]
, lang = po.tips
, pin = po.buttonClass +"-pin"
, side = pin +"-"+ pane
, UP = pin +"-up "+ side +"-up"
, DN = pin +"-down "+side +"-down"
;
$Pin
.attr("pin", doPin ? "down" : "up") // logic
.attr("title", doPin ? lang.Unpin : lang.Pin)
.removeClass( doPin ? UP : DN )
.addClass( doPin ? DN : UP )
;
}
/**
* INTERNAL function to sync 'pin buttons' when pane is opened or closed
* Unpinned means the pane is 'sliding' - ie, over-top of the adjacent panes
*
* @see open(), close()
* @param {string} pane These are the params returned to callbacks by layout()
* @param {boolean} doPin True means set the pin 'down', False means 'up'
*/
, syncPinBtns: function (inst, pane, doPin) {
// REAL METHOD IS _INSIDE_ LAYOUT - THIS IS HERE JUST FOR REFERENCE
$.each(state[pane].pins, function (i, selector) {
$.layout.buttons.setPinState(inst, $(selector), pane, doPin);
});
}
, _load: function (inst) {
// ADD Button methods to Layout Instance
$.extend( inst, {
bindButton: function (selector, action, pane) { return $.layout.buttons.bind(inst, selector, action, pane); }
// DEPRECATED METHODS...
, addToggleBtn: function (selector, pane, slide) { return $.layout.buttons.addToggle(inst, selector, pane, slide); }
, addOpenBtn: function (selector, pane, slide) { return $.layout.buttons.addOpen(inst, selector, pane, slide); }
, addCloseBtn: function (selector, pane) { return $.layout.buttons.addClose(inst, selector, pane); }
, addPinBtn: function (selector, pane) { return $.layout.buttons.addPin(inst, selector, pane); }
});
// init state array to hold pin-buttons
for (var i=0; i<4; i++) {
var pane = $.layout.buttons.config.borderPanes[i];
inst.state[pane].pins = [];
}
// auto-init buttons onLoad if option is enabled
if ( inst.options.autoBindCustomButtons )
$.layout.buttons.init(inst);
}
, _unload: function (inst) {
// TODO: unbind all buttons???
}
};
// add initialization method to Layout's onLoad array of functions
$.layout.onLoad.push( $.layout.buttons._load );
//$.layout.onUnload.push( $.layout.buttons._unload );
})( jQuery );
/**
* jquery.layout.browserZoom 1.0
* $Date: 2011-12-29 08:00:00 (Thu, 29 Dec 2011) $
*
* Copyright (c) 2012
* Kevin Dalman (http://allpro.net)
*
* Dual licensed under the GPL (http://www.gnu.org/licenses/gpl.html)
* and MIT (http://www.opensource.org/licenses/mit-license.php) licenses.
*
* @requires: UI Layout 1.3.0.rc30.1 or higher
*
* @see: http://groups.google.com/group/jquery-ui-layout
*
* TODO: Extend logic to handle other problematic zooming in browsers
* TODO: Add hotkey/mousewheel bindings to _instantly_ respond to these zoom event
*/
(function ($) {
// tell Layout that the plugin is available
$.layout.plugins.browserZoom = true;
$.layout.defaults.browserZoomCheckInterval = 1000;
$.layout.optionsMap.layout.push("browserZoomCheckInterval");
/*
* browserZoom methods
*/
$.layout.browserZoom = {
_init: function (inst) {
// abort if browser does not need this check
if ($.layout.browserZoom.ratio() !== false)
$.layout.browserZoom._setTimer(inst);
}
, _setTimer: function (inst) {
// abort if layout destroyed or browser does not need this check
if (inst.destroyed) return;
var o = inst.options
, s = inst.state
// don't need check if inst has parentLayout, but check occassionally in case parent destroyed!
// MINIMUM 100ms interval, for performance
, ms = inst.hasParentLayout ? 5000 : Math.max( o.browserZoomCheckInterval, 100 )
;
// set the timer
setTimeout(function(){
if (inst.destroyed || !o.resizeWithWindow) return;
var d = $.layout.browserZoom.ratio();
if (d !== s.browserZoom) {
s.browserZoom = d;
inst.resizeAll();
}
// set a NEW timeout
$.layout.browserZoom._setTimer(inst);
}
, ms );
}
, ratio: function () {
var w = window
, s = screen
, d = document
, dE = d.documentElement || d.body
, b = $.layout.browser
, v = b.version
, r, sW, cW
;
// we can ignore all browsers that fire window.resize event onZoom
if (!b.msie || v > 8)
return false; // don't need to track zoom
if (s.deviceXDPI && s.systemXDPI) // syntax compiler hack
return calc(s.deviceXDPI, s.systemXDPI);
// everything below is just for future reference!
if (b.webkit && (r = d.body.getBoundingClientRect))
return calc((r.left - r.right), d.body.offsetWidth);
if (b.webkit && (sW = w.outerWidth))
return calc(sW, w.innerWidth);
if ((sW = s.width) && (cW = dE.clientWidth))
return calc(sW, cW);
return false; // no match, so cannot - or don't need to - track zoom
function calc (x,y) { return (parseInt(x,10) / parseInt(y,10) * 100).toFixed(); }
}
};
// add initialization method to Layout's onLoad array of functions
$.layout.onReady.push( $.layout.browserZoom._init );
})( jQuery );
(function ($) {
// Add a new "slideOffscreen" effect
if ($.effects) {
// add an option so initClosed and initHidden will work
$.layout.defaults.panes.useOffscreenClose = false; // user must enable when needed
/* set the new animation as the default for all panes
$.layout.defaults.panes.fxName = "slideOffscreen";
*/
if ($.layout.plugins)
$.layout.plugins.effects.slideOffscreen = true;
// dupe 'slide' effect defaults as new effect defaults
$.layout.effects.slideOffscreen = $.extend(true, {}, $.layout.effects.slide);
// add new effect to jQuery UI
$.effects.slideOffscreen = function(o) {
return this.queue(function(){
var fx = $.effects
, opt = o.options
, $el = $(this)
, pane = $el.data('layoutEdge')
, state = $el.data('parentLayout').state
, dist = state[pane].size
, s = this.style
, props = ['top','bottom','left','right']
// Set options
, mode = fx.setMode($el, opt.mode || 'show') // Set Mode
, show = (mode == 'show')
, dir = opt.direction || 'left' // Default Direction
, ref = (dir == 'up' || dir == 'down') ? 'top' : 'left'
, pos = (dir == 'up' || dir == 'left')
, offscrn = $.layout.config.offscreenCSS || {}
, keyLR = $.layout.config.offscreenReset
, keyTB = 'offscreenResetTop' // only used internally
, animation = {}
;
// Animation settings
animation[ref] = (show ? (pos ? '+=' : '-=') : (pos ? '-=' : '+=')) + dist;
if (show) { // show() animation, so save top/bottom but retain left/right set when 'hidden'
$el.data(keyTB, { top: s.top, bottom: s.bottom });
// set the top or left offset in preparation for animation
// Note: ALL animations work by shifting the top or left edges
if (pos) { // top (north) or left (west)
$el.css(ref, isNaN(dist) ? "-" + dist : -dist); // Shift outside the left/top edge
}
else { // bottom (south) or right (east) - shift all the way across container
if (dir === 'right')
$el.css({ left: state.container.layoutWidth, right: 'auto' });
else // dir === bottom
$el.css({ top: state.container.layoutHeight, bottom: 'auto' });
}
// restore the left/right setting if is a top/bottom animation
if (ref === 'top')
$el.css( $el.data( keyLR ) || {} );
}
else { // hide() animation, so save ALL CSS
$el.data(keyTB, { top: s.top, bottom: s.bottom });
$el.data(keyLR, { left: s.left, right: s.right });
}
// Animate
$el.show().animate(animation, { queue: false, duration: o.duration, easing: opt.easing, complete: function(){
// Restore top/bottom
if ($el.data( keyTB ))
$el.css($el.data( keyTB )).removeData( keyTB );
if (show) // Restore left/right too
$el.css($el.data( keyLR ) || {}).removeData( keyLR );
else // Move the pane off-screen (left: -99999, right: 'auto')
$el.css( offscrn );
if (o.callback) o.callback.apply(this, arguments); // Callback
$el.dequeue();
}});
});
};
}
})( jQuery );
|
jQuery(function($) {
// var initMap;
// var starkMap = {
// zoom: 11,
// center: new google.maps.LatLng(40.706446,-73.953616),
// mapTypeId: 'terrain'
// };
// initMap = new google.maps.Map($('.map')[0], starkMap)
});
|
var searchData=
[
['sentinel_5fdisconnect_5fhandler_5ft',['sentinel_disconnect_handler_t',['../classcpp__redis_1_1sentinel.html#a923e06b5b700c16dffec8a01d2fa9aa4',1,'cpp_redis::sentinel']]],
['subscribe_5fcallback_5ft',['read_callback_t',['../classcpp__redis_1_1subscriber.html#a2ac29261280f488dab483866ae875656',1,'cpp_redis::subscriber']]]
];
|
import React from 'react'
export default function Dados(props){//coloca-se props para poder passar seus atributos para outro componente
let n1 = 15 //váriaveis que irão ser carregadas da função
let n2 = 20
return(
<section>
<p>Frase1 : {props.frase1}</p>
<p>Frase 2 : {props.frase2}</p>
<p>Frase 3 : {props.frase3}</p>
<p>Frase 4 : {props.arrowfunction() }</p>
<p>{`A soma de ${n1} com ${n2} é igual ` +props.somar(n1,n2)}</p>
</section>
)
}
|
'use strict'
const path = require('path')
const utils = require('./utils')
const webpack = require('webpack')
const config = require('../config')
const merge = require('webpack-merge')
const baseWebpackConfig = require('./webpack.base.conf')
const CopyWebpackPlugin = require('copy-webpack-plugin')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const ExtractTextPlugin = require('extract-text-webpack-plugin')
const OptimizeCSSPlugin = require('optimize-css-assets-webpack-plugin')
// const UglifyJsPlugin = require('uglifyjs-webpack-plugin')
const env = require('../config/prod.env')
const webpackConfig = merge(baseWebpackConfig, {
// 添加webapck4默认的生产模式
mode: 'production',
module: {
rules: utils.styleLoaders({
sourceMap: config.build.productionSourceMap,
extract: true,
usePostCSS: true
})
},
devtool: config.build.productionSourceMap ? config.build.devtool : false,
output: {
path: config.build.assetsRoot,
filename: utils.assetsPath('js/[name].[chunkhash].js'),
chunkFilename: utils.assetsPath('js/[id].[chunkhash].js')
},
plugins: [
// http://vuejs.github.io/vue-loader/en/workflow/production.html
new webpack.DefinePlugin({
'process.env': env
}),
// webpack4中内置了optimization.minimize
// new UglifyJsPlugin({
/*uglifyOptions: {
compress: {
warnings: false
}
},
sourceMap: config.build.productionSourceMap,
parallel: true
}), */
// extract css into its own file
new ExtractTextPlugin({
filename: 'css/[name].[hash].css'
// filename: utils.assetsPath('css/[name].[contenthash].css'),
// Setting the following option to `false` will not extract CSS from codesplit chunks.
// Their CSS will instead be inserted dynamically with style-loader when the codesplit chunk has been loaded by webpack.
// It's currently set to `true` because we are seeing that sourcemaps are included in the codesplit bundle as well when it's `false`,
// increasing file size: https://github.com/vuejs-templates/webpack/issues/1110
// allChunks: true,
}),
// Compress extracted CSS. We are using this plugin so that possible
// duplicated CSS from different components can be deduped.
new OptimizeCSSPlugin({
cssProcessorOptions: config.build.productionSourceMap
? { safe: true, map: { inline: false } }
: { safe: true }
}),
// generate dist index.html with correct asset hash for caching.
// you can customize output by editing /index.html
// see https://github.com/ampedandwired/html-webpack-plugin
new HtmlWebpackPlugin({
filename: config.build.index,
template: 'index.html',
inject: true,
minify: {
removeComments: true,
collapseWhitespace: true,
removeAttributeQuotes: true
// more options:
// https://github.com/kangax/html-minifier#options-quick-reference
},
// necessary to consistently work with multiple chunks via CommonsChunkPlugin
chunksSortMode: 'none'
}),
// keep module.id stable when vendor modules does not change
new webpack.HashedModuleIdsPlugin(),
// enable scope hoisting
new webpack.optimize.ModuleConcatenationPlugin(),
// webpack4中废弃了CommonsChunkPlugin,采用optimization.splitChunks、optimization.runtimeChunk来代替
// split vendor js into its own file
/*new webpack.optimize.CommonsChunkPlugin({
name: 'vendor',
minChunks (module) {
// any required modules inside node_modules are extracted to vendor
return (
module.resource &&
/\.js$/.test(module.resource) &&
module.resource.indexOf(
path.join(__dirname, '../node_modules')
) === 0
)
}}),
// extract webpack runtime and module manifest to its own file in order to
// prevent vendor hash from being updated whenever app bundle is updated
new webpack.optimize.CommonsChunkPlugin({
name: 'manifest',
minChunks: Infinity
}),
// This instance extracts shared chunks from code splitted chunks and bundles them
// in a separate chunk, similar to the vendor chunk
// see: https://webpack.js.org/plugins/commons-chunk-plugin/#extra-async-commons-chunk
new webpack.optimize.CommonsChunkPlugin({
name: 'app',
async: 'vendor-async',
children: true,
minChunks: 3
}), */
// copy custom static assets
new CopyWebpackPlugin([
{
from: path.resolve(__dirname, '../static'),
to: config.build.assetsSubDirectory,
ignore: ['.*']
}
])
],
// optimization: {
// // 采用splitChunks提取出entry chunk的chunk Group
// splitChunks: {
// cacheGroups: {
// // 处理入口chunk
// vendors: {
// test: /[\\/]node_modules[\\/]/,
// chunks: 'initial',
// name: 'vendors',
// },
// // 处理异步chunk
// 'async-vendors': {
// test: /[\\/]node_modules[\\/]/,
// minChunks: 2,
// chunks: 'async',
// name: 'async-vendors',
// maxSize: 200000,
// }
// }
// },
// // 为每个入口提取出webpack runtime模块
// runtimeChunk: { name: 'manifest' }
// }
optimization: {
splitChunks: {
chunks: 'async',
// 大于30KB才单独分离成chunk
minSize: 30000,
// 最大800KB
maxSize: 800000,
maxAsyncRequests: 5,
maxInitialRequests: 3,
name: true,
cacheGroups: {
default: {
priority: -20,
reuseExistingChunk: true
},
vendors: {
name: 'vendors',
test: /[\\/]node_modules[\\/]/,
priority: -10,
chunks: 'all'
}
// 'element-ui': {
// name: 'element-ui',
// chunks: 'all',
// // 对echarts进行单独优化,优先级较高
// priority: 20,
// test: function(module){
// var context = module.context;
// return context && (context.indexOf('element-ui') >= 0)
// }
// }
// echarts: {
// name: 'echarts',
// chunks: 'all',
// // 对echarts进行单独优化,优先级较高
// priority: 20,
// test: function(module){
// var context = module.context;
// return context && (context.indexOf('echarts') >= 0 || context.indexOf('zrender') >= 0)
// }
// }
}
}
}
})
if (config.build.productionGzip) {
const CompressionWebpackPlugin = require('compression-webpack-plugin')
webpackConfig.plugins.push(
new CompressionWebpackPlugin({
asset: '[path].gz[query]',
algorithm: 'gzip',
test: new RegExp(
'\\.(' +
config.build.productionGzipExtensions.join('|') +
')$'
),
threshold: 10240,
minRatio: 0.8
})
)
}
if (config.build.bundleAnalyzerReport) {
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin
webpackConfig.plugins.push(new BundleAnalyzerPlugin())
}
module.exports = webpackConfig
|
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
// THIS CODE IS GENERATED - DO NOT MODIFY
// See angular/tools/gulp-tasks/cldr/extract.js
export default [
[
['полн.', 'полд.', 'утра', 'дня', 'вечера', 'ночи'], ,
['полночь', 'полдень', 'утра', 'дня', 'вечера', 'ночи']
],
[
['полн.', 'полд.', 'утро', 'день', 'веч.', 'ночь'], ,
['полночь', 'полдень', 'утро', 'день', 'вечер', 'ночь']
],
[
'00:00', '12:00', ['04:00', '12:00'], ['12:00', '18:00'], ['18:00', '24:00'],
['00:00', '04:00']
]
];
//# sourceMappingURL=ru-KG.js.map
|
(self["webpackChunk"] = self["webpackChunk"] || []).push([["resources_js_components_backend_error_404Components_vue"],{
/***/ "./resources/js/components/backend/error/404Components.vue":
/*!*****************************************************************!*\
!*** ./resources/js/components/backend/error/404Components.vue ***!
\*****************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_vue_loader_lib_runtime_componentNormalizer_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! !../../../../../node_modules/vue-loader/lib/runtime/componentNormalizer.js */ "./node_modules/vue-loader/lib/runtime/componentNormalizer.js");
var render, staticRenderFns
var script = {}
/* normalize component */
;
var component = (0,_node_modules_vue_loader_lib_runtime_componentNormalizer_js__WEBPACK_IMPORTED_MODULE_0__.default)(
script,
render,
staticRenderFns,
false,
null,
null,
null
)
component.options.__file = "resources/js/components/backend/error/404Components.vue"
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (component.exports);
/***/ }),
/***/ "./node_modules/vue-loader/lib/runtime/componentNormalizer.js":
/*!********************************************************************!*\
!*** ./node_modules/vue-loader/lib/runtime/componentNormalizer.js ***!
\********************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ "default": () => (/* binding */ normalizeComponent)
/* harmony export */ });
/* globals __VUE_SSR_CONTEXT__ */
// IMPORTANT: Do NOT use ES2015 features in this file (except for modules).
// This module is a runtime utility for cleaner component module output and will
// be included in the final webpack user bundle.
function normalizeComponent (
scriptExports,
render,
staticRenderFns,
functionalTemplate,
injectStyles,
scopeId,
moduleIdentifier, /* server only */
shadowMode /* vue-cli only */
) {
// Vue.extend constructor export interop
var options = typeof scriptExports === 'function'
? scriptExports.options
: scriptExports
// render functions
if (render) {
options.render = render
options.staticRenderFns = staticRenderFns
options._compiled = true
}
// functional template
if (functionalTemplate) {
options.functional = true
}
// scopedId
if (scopeId) {
options._scopeId = 'data-v-' + scopeId
}
var hook
if (moduleIdentifier) { // server build
hook = function (context) {
// 2.3 injection
context =
context || // cached call
(this.$vnode && this.$vnode.ssrContext) || // stateful
(this.parent && this.parent.$vnode && this.parent.$vnode.ssrContext) // functional
// 2.2 with runInNewContext: true
if (!context && typeof __VUE_SSR_CONTEXT__ !== 'undefined') {
context = __VUE_SSR_CONTEXT__
}
// inject component styles
if (injectStyles) {
injectStyles.call(this, context)
}
// register component module identifier for async chunk inferrence
if (context && context._registeredComponents) {
context._registeredComponents.add(moduleIdentifier)
}
}
// used by ssr in case component is cached and beforeCreate
// never gets called
options._ssrRegister = hook
} else if (injectStyles) {
hook = shadowMode
? function () {
injectStyles.call(
this,
(options.functional ? this.parent : this).$root.$options.shadowRoot
)
}
: injectStyles
}
if (hook) {
if (options.functional) {
// for template-only hot-reload because in that case the render fn doesn't
// go through the normalizer
options._injectStyles = hook
// register for functional component in vue file
var originalRender = options.render
options.render = function renderWithStyleInjection (h, context) {
hook.call(context)
return originalRender(h, context)
}
} else {
// inject component registration as beforeCreate hook
var existing = options.beforeCreate
options.beforeCreate = existing
? [].concat(existing, hook)
: [hook]
}
}
return {
exports: scriptExports,
options: options
}
}
/***/ })
}]);
|
QUnit.module('lodash.reject');
(function () {
var array = [
__num_top__,
2,
3
];
QUnit.test('should return elements the `predicate` returns falsey for', function (assert) {
assert.expect(1);
assert.deepEqual(_.reject(array, isEven), [
1,
3
]);
});
}());
|
// @flow
import prep from './internal/unmutable';
export const objectHas = (key: string) => (value: *): boolean => key in value;
export const arrayHas = (key: number) => (value: Array<*>): boolean => key < value.length && key >= -value.length;
export default prep({
name: 'has',
immutable: 'has',
record: 'has',
object: objectHas,
array: arrayHas
});
|
const alunos = [{nome: 'joão', nota: 7.3, bolsista: false},
{nome: 'maria', nota: 9.2, bolsista: true},
{nome: 'pedro', nota: 9.8, bolsista: false},
{nome: 'ana', nota: 8.7, bolsista: true}]
//Desafio: todos os alunos são bolsistas?
const todosbolsistas = (resultado, bolsista) => resultado && bolsista
console.log (alunos.map(a => a.bolsista).reduce(todosbolsistas))
//Desafio: algum aluno é bolsista?
const algumbolsista = (resultado,bolsista) => resultado || bolsista
console.log(alunos.map (a=> a.bolsista).reduce(algumbolsista))
|
console.log('as-it');
console.log(typeof window.document); // eslint-disable-line
|
/*
* Jssor 18.0
* http://www.jssor.com/
*
* TERMS OF USE - Jssor
*
* Copyright 2014 Jssor
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
/*! Jssor */
//$JssorDebug$
var $JssorDebug$ = new function () {
this.$DebugMode = true;
// Methods
this.$Log = function (msg, important) {
var console = window.console || {};
var debug = this.$DebugMode;
if (debug && console.log) {
console.log(msg);
} else if (debug && important) {
alert(msg);
}
};
this.$Error = function (msg, e) {
var console = window.console || {};
var debug = this.$DebugMode;
if (debug && console.error) {
console.error(msg);
} else if (debug) {
alert(msg);
}
if (debug) {
// since we're debugging, fail fast by crashing
throw e || new Error(msg);
}
};
this.$Fail = function (msg) {
throw new Error(msg);
};
this.$Assert = function (value, msg) {
var debug = this.$DebugMode;
if (debug) {
if (!value)
throw new Error("Assert failed " + msg || "");
}
};
this.$Trace = function (msg) {
var console = window.console || {};
var debug = this.$DebugMode;
if (debug && console.log) {
console.log(msg);
}
};
this.$Execute = function (func) {
var debug = this.$DebugMode;
if (debug)
func();
};
this.$LiveStamp = function (obj, id) {
var debug = this.$DebugMode;
if (debug) {
var stamp = document.createElement("DIV");
stamp.setAttribute("id", id);
obj.$Live = stamp;
}
};
this.$C_AbstractMethod = function () {
/// <summary>
/// Tells compiler the method is abstract, it should be implemented by subclass.
/// </summary>
throw new Error("The method is abstract, it should be implemented by subclass.");
};
function C_AbstractClass(instance) {
/// <summary>
/// Tells compiler the class is abstract, it should be implemented by subclass.
/// </summary>
if (instance.constructor === C_AbstractClass.caller)
throw new Error("Cannot create instance of an abstract class.");
}
this.$C_AbstractClass = C_AbstractClass;
};
//$JssorPoint$
var $JssorPoint$ = function (x, y) {
var _ThisPoint = this;
// Properties
_ThisPoint.x = x;
_ThisPoint.y = y;
_ThisPoint.$Plus = function (point) {
return new $JssorPoint$(x + point.x, y + point.y);
};
_ThisPoint.$Minus = function (point) {
return new $JssorPoint$(x - point.x, y - point.y);
};
_ThisPoint.$Times = function (factor) {
return new $JssorPoint$(x * factor, y * factor);
};
_ThisPoint.$Divide = function (factor) {
return new $JssorPoint$(x / factor, y / factor);
};
_ThisPoint.$Negate = function () {
return new $JssorPoint$(-x, -y);
};
_ThisPoint.$DistanceTo = function (point) {
return Math.sqrt(Math.pow(x - point.x, 2) + Math.pow(y - point.y, 2));
};
_ThisPoint.$Apply = function (func) {
return new $JssorPoint$(func(x), func(y));
};
_ThisPoint.$Equals = function (point) {
return (point instanceof $JssorPoint$) && (x === point.x) && (y === point.y);
};
_ThisPoint.$ToString = function () {
return "(" + x + "," + y + ")";
};
};
//$JssorEasing$
var $JssorEasing$ = window.$JssorEasing$ = {
$EaseLinear: function (t) {
return t;
},
$EaseGoBack: function (t) {
return 1 - Math.abs((t *= 2) - 1);
},
$EaseSwing: function (t) {
return -Math.cos(t * Math.PI) / 2 + .5;
},
$EaseInQuad: function (t) {
return t * t;
},
$EaseOutQuad: function (t) {
return -t * (t - 2);
},
$EaseInOutQuad: function (t) {
return (t *= 2) < 1 ? 1 / 2 * t * t : -1 / 2 * (--t * (t - 2) - 1);
},
$EaseInCubic: function (t) {
return t * t * t;
},
$EaseOutCubic: function (t) {
return (t -= 1) * t * t + 1;
},
$EaseInOutCubic: function (t) {
return (t *= 2) < 1 ? 1 / 2 * t * t * t : 1 / 2 * ((t -= 2) * t * t + 2);
},
$EaseInQuart: function (t) {
return t * t * t * t;
},
$EaseOutQuart: function (t) {
return -((t -= 1) * t * t * t - 1);
},
$EaseInOutQuart: function (t) {
return (t *= 2) < 1 ? 1 / 2 * t * t * t * t : -1 / 2 * ((t -= 2) * t * t * t - 2);
},
$EaseInQuint: function (t) {
return t * t * t * t * t;
},
$EaseOutQuint: function (t) {
return (t -= 1) * t * t * t * t + 1;
},
$EaseInOutQuint: function (t) {
return (t *= 2) < 1 ? 1 / 2 * t * t * t * t * t : 1 / 2 * ((t -= 2) * t * t * t * t + 2);
},
$EaseInSine: function (t) {
return 1 - Math.cos(t * Math.PI / 2);
},
$EaseOutSine: function (t) {
return Math.sin(t * Math.PI / 2);
},
$EaseInOutSine: function (t) {
return -1 / 2 * (Math.cos(Math.PI * t) - 1);
},
$EaseInExpo: function (t) {
return t == 0 ? 0 : Math.pow(2, 10 * (t - 1));
},
$EaseOutExpo: function (t) {
return t == 1 ? 1 : -Math.pow(2, -10 * t) + 1;
},
$EaseInOutExpo: function (t) {
return t == 0 || t == 1 ? t : (t *= 2) < 1 ? 1 / 2 * Math.pow(2, 10 * (t - 1)) : 1 / 2 * (-Math.pow(2, -10 * --t) + 2);
},
$EaseInCirc: function (t) {
return -(Math.sqrt(1 - t * t) - 1);
},
$EaseOutCirc: function (t) {
return Math.sqrt(1 - (t -= 1) * t);
},
$EaseInOutCirc: function (t) {
return (t *= 2) < 1 ? -1 / 2 * (Math.sqrt(1 - t * t) - 1) : 1 / 2 * (Math.sqrt(1 - (t -= 2) * t) + 1);
},
$EaseInElastic: function (t) {
if (!t || t == 1)
return t;
var p = .3, s = .075;
return -(Math.pow(2, 10 * (t -= 1)) * Math.sin((t - s) * 2 * Math.PI / p));
},
$EaseOutElastic: function (t) {
if (!t || t == 1)
return t;
var p = .3, s = .075;
return Math.pow(2, -10 * t) * Math.sin((t - s) * 2 * Math.PI / p) + 1;
},
$EaseInOutElastic: function (t) {
if (!t || t == 1)
return t;
var p = .45, s = .1125;
return (t *= 2) < 1 ? -.5 * Math.pow(2, 10 * (t -= 1)) * Math.sin((t - s) * 2 * Math.PI / p) : Math.pow(2, -10 * (t -= 1)) * Math.sin((t - s) * 2 * Math.PI / p) * .5 + 1;
},
$EaseInBack: function (t) {
var s = 1.70158;
return t * t * ((s + 1) * t - s);
},
$EaseOutBack: function (t) {
var s = 1.70158;
return (t -= 1) * t * ((s + 1) * t + s) + 1;
},
$EaseInOutBack: function (t) {
var s = 1.70158;
return (t *= 2) < 1 ? 1 / 2 * t * t * (((s *= 1.525) + 1) * t - s) : 1 / 2 * ((t -= 2) * t * (((s *= 1.525) + 1) * t + s) + 2);
},
$EaseInBounce: function (t) {
return 1 - $JssorEasing$.$EaseOutBounce(1 - t)
},
$EaseOutBounce: function (t) {
return t < 1 / 2.75 ? 7.5625 * t * t : t < 2 / 2.75 ? 7.5625 * (t -= 1.5 / 2.75) * t + .75 : t < 2.5 / 2.75 ? 7.5625 * (t -= 2.25 / 2.75) * t + .9375 : 7.5625 * (t -= 2.625 / 2.75) * t + .984375;
},
$EaseInOutBounce: function (t) {
return t < 1 / 2 ? $JssorEasing$.$EaseInBounce(t * 2) * .5 : $JssorEasing$.$EaseOutBounce(t * 2 - 1) * .5 + .5;
},
$EaseInWave: function (t) {
return 1 - Math.cos(t * Math.PI * 2)
},
$EaseOutWave: function (t) {
return Math.sin(t * Math.PI * 2);
},
$EaseOutJump: function (t) {
return 1 - (((t *= 2) < 1) ? (t = 1 - t) * t * t : (t -= 1) * t * t);
},
$EaseInJump: function (t) {
return ((t *= 2) < 1) ? t * t * t : (t = 2 - t) * t * t;
}
};
var $JssorDirection$ = window.$JssorDirection$ = {
$TO_LEFT: 0x0001,
$TO_RIGHT: 0x0002,
$TO_TOP: 0x0004,
$TO_BOTTOM: 0x0008,
$HORIZONTAL: 0x0003,
$VERTICAL: 0x000C,
$LEFTRIGHT: 0x0003,
$TOPBOTOM: 0x000C,
$TOPLEFT: 0x0005,
$TOPRIGHT: 0x0006,
$BOTTOMLEFT: 0x0009,
$BOTTOMRIGHT: 0x000A,
$AROUND: 0x000F,
$GetDirectionHorizontal: function (direction) {
return direction & 0x0003;
},
$GetDirectionVertical: function (direction) {
return direction & 0x000C;
},
$ChessHorizontal: function (direction) {
return (~direction & 0x0003) + (direction & 0x000C);
},
$ChessVertical: function (direction) {
return (~direction & 0x000C) + (direction & 0x0003);
},
$IsToLeft: function (direction) {
return (direction & 0x0003) == 0x0001;
},
$IsToRight: function (direction) {
return (direction & 0x0003) == 0x0002;
},
$IsToTop: function (direction) {
return (direction & 0x000C) == 0x0004;
},
$IsToBottom: function (direction) {
return (direction & 0x000C) == 0x0008;
},
$IsHorizontal: function (direction) {
return (direction & 0x0003) > 0;
},
$IsVertical: function (direction) {
return (direction & 0x000C) > 0;
}
};
var $JssorKeyCode$ = {
$BACKSPACE: 8,
$COMMA: 188,
$DELETE: 46,
$DOWN: 40,
$END: 35,
$ENTER: 13,
$ESCAPE: 27,
$HOME: 36,
$LEFT: 37,
$NUMPAD_ADD: 107,
$NUMPAD_DECIMAL: 110,
$NUMPAD_DIVIDE: 111,
$NUMPAD_ENTER: 108,
$NUMPAD_MULTIPLY: 106,
$NUMPAD_SUBTRACT: 109,
$PAGE_DOWN: 34,
$PAGE_UP: 33,
$PERIOD: 190,
$RIGHT: 39,
$SPACE: 32,
$TAB: 9,
$UP: 38
};
var $JssorAlignment$ = {
$TopLeft: 0x11,
$TopCenter: 0x12,
$TopRight: 0x14,
$MiddleLeft: 0x21,
$MiddleCenter: 0x22,
$MiddleRight: 0x24,
$BottomLeft: 0x41,
$BottomCenter: 0x42,
$BottomRight: 0x44,
$IsTop: function (aligment) {
return aligment & 0x10 > 0;
},
$IsMiddle: function (alignment) {
return alignment & 0x20 > 0;
},
$IsBottom: function (alignment) {
return alignment & 0x40 > 0;
},
$IsLeft: function (alignment) {
return alignment & 0x01 > 0;
},
$IsCenter: function (alignment) {
return alignment & 0x02 > 0;
},
$IsRight: function (alignment) {
return alignment & 0x04 > 0;
}
};
var $JssorMatrix$;
var $JssorAnimator$;
// $Jssor$ is a static class, so make it singleton instance
var $Jssor$ = window.$Jssor$ = new function () {
// Fields
var _This = this;
var REGEX_WHITESPACE_GLOBAL = /\S+/g;
var ROWSER_UNKNOWN = 0;
var BROWSER_IE = 1;
var BROWSER_FIREFOX = 2;
var BROWSER_FIREFOX = 3;
var BROWSER_CHROME = 4;
var BROWSER_OPERA = 5;
//var arrActiveX = ["Msxml2.XMLHTTP", "Msxml3.XMLHTTP", "Microsoft.XMLHTTP"];
var browser = 0;
var browserRuntimeVersion = 0;
var browserEngineVersion = 0;
var browserJavascriptVersion = 0;
var webkitVersion = 0;
var app = navigator.appName;
var ver = navigator.appVersion;
var ua = navigator.userAgent;
var _DocElmt = document.documentElement;
var _TransformProperty;
function DetectBrowser() {
if (!browser) {
if (app == "Microsoft Internet Explorer" &&
!!window.attachEvent && !!window.ActiveXObject) {
var ieOffset = ua.indexOf("MSIE");
browser = BROWSER_IE;
browserEngineVersion = ParseFloat(ua.substring(ieOffset + 5, ua.indexOf(";", ieOffset)));
//check IE javascript version
/*@cc_on
browserJavascriptVersion = @_jscript_version;
@*/
// update: for intranet sites and compat view list sites, IE sends
// an IE7 User-Agent to the server to be interoperable, and even if
// the page requests a later IE version, IE will still report the
// IE7 UA to JS. we should be robust to self
//var docMode = document.documentMode;
//if (typeof docMode !== "undefined") {
// browserRuntimeVersion = docMode;
//}
browserRuntimeVersion = document.documentMode || browserEngineVersion;
}
else if (app == "Netscape" && !!window.addEventListener) {
var ffOffset = ua.indexOf("Firefox");
var saOffset = ua.indexOf("Safari");
var chOffset = ua.indexOf("Chrome");
var webkitOffset = ua.indexOf("AppleWebKit");
if (ffOffset >= 0) {
browser = BROWSER_FIREFOX;
browserRuntimeVersion = ParseFloat(ua.substring(ffOffset + 8));
}
else if (saOffset >= 0) {
var slash = ua.substring(0, saOffset).lastIndexOf("/");
browser = (chOffset >= 0) ? BROWSER_CHROME : BROWSER_FIREFOX;
browserRuntimeVersion = ParseFloat(ua.substring(slash + 1, saOffset));
}
if (webkitOffset >= 0)
webkitVersion = ParseFloat(ua.substring(webkitOffset + 12));
}
else {
var match = /(opera)(?:.*version|)[ \/]([\w.]+)/i.exec(ua);
if (match) {
browser = BROWSER_OPERA;
browserRuntimeVersion = ParseFloat(match[2]);
}
}
}
}
function IsBrowserIE() {
DetectBrowser();
return browser == BROWSER_IE;
}
function IsBrowserIeQuirks() {
return IsBrowserIE() && (browserRuntimeVersion < 6 || document.compatMode == "BackCompat"); //Composite to "CSS1Compat"
}
function IsBrowserFireFox() {
DetectBrowser();
return browser == BROWSER_FIREFOX;
}
function IsBrowserSafari() {
DetectBrowser();
return browser == BROWSER_FIREFOX;
}
function IsBrowserChrome() {
DetectBrowser();
return browser == BROWSER_CHROME;
}
function IsBrowserOpera() {
DetectBrowser();
return browser == BROWSER_OPERA;
}
function IsBrowserBadTransform() {
return IsBrowserSafari() && (webkitVersion > 534) && (webkitVersion < 535);
}
function IsBrowserSafeHWA() {
return IsBrowserSafari() && (webkitVersion < 535);
}
function IsBrowserIe9Earlier() {
return IsBrowserIE() && browserRuntimeVersion < 9;
}
function GetTransformProperty(elmt) {
if (!_TransformProperty) {
// Note that in some versions of IE9 it is critical that
// msTransform appear in this list before MozTransform
each(['transform', 'WebkitTransform', 'msTransform', 'MozTransform', 'OTransform'], function (property) {
if (elmt.style[property] != undefined) {
_TransformProperty = property;
return true;
}
});
_TransformProperty = _TransformProperty || "transform";
}
return _TransformProperty;
}
// Helpers
function getOffsetParent(elmt, isFixed) {
// IE and Opera "fixed" position elements don't have offset parents.
// regardless, if it's fixed, its offset parent is the body.
if (isFixed && elmt != document.body) {
return document.body;
} else {
return elmt.offsetParent;
}
}
function toString(obj) {
return Object.prototype.toString.call(obj);
}
// [[Class]] -> type pairs
var class2type;
function each(object, callback) {
if (toString(object) == "[object Array]") {
for (var i = 0; i < object.length; i++) {
if (callback(object[i], i, object)) {
return true;
}
}
}
else {
for (var name in object) {
if (callback(object[name], name, object)) {
return true;
}
}
}
}
function GetClass2Type() {
if (!class2type) {
class2type = {};
each(["Boolean", "Number", "String", "Function", "Array", "Date", "RegExp", "Object"], function (name) {
class2type["[object " + name + "]"] = name.toLowerCase();
});
}
return class2type;
}
function type(obj) {
return obj == null ? String(obj) : GetClass2Type()[toString(obj)] || "object";
}
function isPlainObject(obj) {
// Must be an Object.
// Because of IE, we also have to check the presence of the constructor property.
// Make sure that DOM nodes and window objects don't pass through, as well
if (!obj || type(obj) !== "object" || obj.nodeType || _This.$IsWindow(obj)) {
return false;
}
var hasOwn = Object.prototype.hasOwnProperty;
try {
// Not own constructor property must be Object
if (obj.constructor &&
!hasOwn.call(obj, "constructor") &&
!hasOwn.call(obj.constructor.prototype, "isPrototypeOf")) {
return false;
}
} catch (e) {
// IE8,9 Will throw exceptions on certain host objects #9897
return false;
}
// Own properties are enumerated firstly, so to speed up,
// if last one is own, then all properties are own.
var key;
for (key in obj) {
}
return key === undefined || hasOwn.call(obj, key);
}
function Delay(code, delay) {
setTimeout(code, delay || 0);
}
function RemoveByReg(str, reg) {
var m = reg.exec(str);
if (m) {
var header = str.substr(0, m.index);
var tailer = str.substr(m.lastIndex + 1, str.length - (m.lastIndex + 1));
str = header + tailer;
}
return str;
}
function BuildNewCss(oldCss, removeRegs, replaceValue) {
var css = (!oldCss || oldCss == "inherit") ? "" : oldCss;
each(removeRegs, function (removeReg) {
var m = removeReg.exec(css);
if (m) {
var header = css.substr(0, m.index);
var tailer = css.substr(m.lastIndex + 1, css.length - (m.lastIndex + 1));
css = header + tailer;
}
});
css = replaceValue + (css.indexOf(" ") != 0 ? " " : "") + css;
return css;
}
function SetStyleFilterIE(elmt, value) {
if (browserRuntimeVersion < 9) {
elmt.style.filter = value;
}
}
function SetStyleMatrixIE(elmt, matrix, offset) {
//matrix is not for ie9+ running in ie8- mode
if (browserJavascriptVersion < 9) {
var oldFilterValue = elmt.style.filter;
var matrixReg = new RegExp(/[\s]*progid:DXImageTransform\.Microsoft\.Matrix\([^\)]*\)/g);
var matrixValue = matrix ? "progid:DXImageTransform.Microsoft.Matrix(" + "M11=" + matrix[0][0] + ", M12=" + matrix[0][1] + ", M21=" + matrix[1][0] + ", M22=" + matrix[1][1] + ", SizingMethod='auto expand')" : "";
var newFilterValue = BuildNewCss(oldFilterValue, [matrixReg], matrixValue);
SetStyleFilterIE(elmt, newFilterValue);
_This.$CssMarginTop(elmt, offset.y);
_This.$CssMarginLeft(elmt, offset.x);
}
}
// Methods
_This.$IsBrowserIE = IsBrowserIE;
_This.$IsBrowserIeQuirks = IsBrowserIeQuirks;
_This.$IsBrowserFireFox = IsBrowserFireFox;
_This.$IsBrowserSafari = IsBrowserSafari;
_This.$IsBrowserChrome = IsBrowserChrome;
_This.$IsBrowserOpera = IsBrowserOpera;
_This.$IsBrowserBadTransform = IsBrowserBadTransform;
_This.$IsBrowserSafeHWA = IsBrowserSafeHWA;
_This.$IsBrowserIe9Earlier = IsBrowserIe9Earlier;
_This.$BrowserVersion = function () {
return browserRuntimeVersion;
};
_This.$BrowserEngineVersion = function () {
return browserEngineVersion || browserRuntimeVersion;
};
_This.$WebKitVersion = function () {
return webkitVersion;
};
_This.$Delay = Delay;
_This.$Inherit = function (instance, baseClass) {
baseClass.apply(instance, [].slice.call(arguments, 2));
return Extend({}, instance);
};
function Construct(instance, constructor) {
instance.constructor === Construct.caller && instance.$Construct && instance.$Construct();
}
_This.$Construct = Construct;
_This.$GetElement = function (elmt) {
if (_This.$IsString(elmt)) {
elmt = document.getElementById(elmt);
}
return elmt;
};
function GetEvent(event) {
return event || window.event;
}
GetEvent = GetEvent;
_This.$EventSrc = function (event) {
event = GetEvent(event);
return event.target || event.srcElement || document;
};
_This.$EventDst = function (event) {
event = GetEvent(event);
return event.relatedTarget || event.toElement;
};
_This.$MousePosition = function (event) {
event = GetEvent(event);
var body = document.body;
return {
x: event.pageX || event.clientX + (_DocElmt.scrollLeft || body.scrollLeft || 0) - (_DocElmt.clientLeft || body.clientLeft || 0) || 0,
y: event.pageY || event.clientY + (_DocElmt.scrollTop || body.scrollTop || 0) - (_DocElmt.clientTop || body.clientTop || 0) || 0
};
};
_This.$PageScroll = function () {
var body = document.body;
return {
x: (window.pageXOffset || _DocElmt.scrollLeft || body.scrollLeft || 0) - (_DocElmt.clientLeft || body.clientLeft || 0),
y: (window.pageYOffset || _DocElmt.scrollTop || body.scrollTop || 0) - (_DocElmt.clientTop || body.clientTop || 0)
};
};
_This.$WindowSize = function () {
var body = document.body;
return {
x: body.clientWidth || _DocElmt.clientWidth,
y: body.clientHeight || _DocElmt.clientHeight
};
};
//_This.$GetElementPosition = function (elmt) {
// elmt = _This.$GetElement(elmt);
// var result = new $JssorPoint$();
// // technique from:
// // http://www.quirksmode.org/js/findpos.html
// // with special check for "fixed" elements.
// while (elmt) {
// result.x += elmt.offsetLeft;
// result.y += elmt.offsetTop;
// var isFixed = _This.$GetElementStyle(elmt).position == "fixed";
// if (isFixed) {
// result = result.$Plus(_This.$PageScroll(window));
// }
// elmt = getOffsetParent(elmt, isFixed);
// }
// return result;
//};
//_This.$GetMouseScroll = function (event) {
// event = GetEvent(event);
// var delta = 0; // default value
// // technique from:
// // http://blog.paranoidferret.com/index.php/2007/10/31/javascript-tutorial-the-scroll-wheel/
// if (typeof (event.wheelDelta) == "number") {
// delta = event.wheelDelta;
// } else if (typeof (event.detail) == "number") {
// delta = event.detail * -1;
// } else {
// $JssorDebug$.$Fail("Unknown event mouse scroll, no known technique.");
// }
// // normalize value to [-1, 1]
// return delta ? delta / Math.abs(delta) : 0;
//};
//_This.$MakeAjaxRequest = function (url, callback) {
// var async = typeof (callback) == "function";
// var req = null;
// if (async) {
// var actual = callback;
// var callback = function () {
// Delay($Jssor$.$CreateCallback(null, actual, req), 1);
// };
// }
// if (window.ActiveXObject) {
// for (var i = 0; i < arrActiveX.length; i++) {
// try {
// req = new ActiveXObject(arrActiveX[i]);
// break;
// } catch (e) {
// continue;
// }
// }
// } else if (window.XMLHttpRequest) {
// req = new XMLHttpRequest();
// }
// if (!req) {
// $JssorDebug$.$Fail("Browser doesn't support XMLHttpRequest.");
// }
// if (async) {
// req.onreadystatechange = function () {
// if (req.readyState == 4) {
// // prevent memory leaks by breaking circular reference now
// req.onreadystatechange = new Function();
// callback();
// }
// };
// }
// try {
// req.open("GET", url, async);
// req.send(null);
// } catch (e) {
// $JssorDebug$.$Log(e.name + " while making AJAX request: " + e.message);
// req.onreadystatechange = null;
// req = null;
// if (async) {
// callback();
// }
// }
// return async ? null : req;
//};
//_This.$ParseXml = function (string) {
// var xmlDoc = null;
// if (window.ActiveXObject) {
// try {
// xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
// xmlDoc.async = false;
// xmlDoc.loadXML(string);
// } catch (e) {
// $JssorDebug$.$Log(e.name + " while parsing XML (ActiveX): " + e.message);
// }
// } else if (window.DOMParser) {
// try {
// var parser = new DOMParser();
// xmlDoc = parser.parseFromString(string, "text/xml");
// } catch (e) {
// $JssorDebug$.$Log(e.name + " while parsing XML (DOMParser): " + e.message);
// }
// } else {
// $JssorDebug$.$Fail("Browser doesn't support XML DOM.");
// }
// return xmlDoc;
//};
function Css(elmt, name, value) {
/// <summary>
/// access css
/// $Jssor$.$Css(elmt, name); //get css value
/// $Jssor$.$Css(elmt, name, value); //set css value
/// </summary>
/// <param name="elmt" type="HTMLElement">
/// the element to access css
/// </param>
/// <param name="name" type="String">
/// the name of css property
/// </param>
/// <param name="value" optional="true">
/// the value to set
/// </param>
if (value != undefined) {
elmt.style[name] = value;
}
else {
var style = elmt.currentStyle || elmt.style;
value = style[name];
if (value == "" && window.getComputedStyle) {
style = elmt.ownerDocument.defaultView.getComputedStyle(elmt, null);
style && (value = style.getPropertyValue(name) || style[name]);
}
return value;
}
}
function CssN(elmt, name, value, isDimensional) {
/// <summary>
/// access css as numeric
/// $Jssor$.$CssN(elmt, name); //get css value
/// $Jssor$.$CssN(elmt, name, value); //set css value
/// </summary>
/// <param name="elmt" type="HTMLElement">
/// the element to access css
/// </param>
/// <param name="name" type="String">
/// the name of css property
/// </param>
/// <param name="value" type="Number" optional="true">
/// the value to set
/// </param>
if (value != undefined) {
isDimensional && (value += "px");
Css(elmt, name, value);
}
else {
return ParseFloat(Css(elmt, name));
}
}
function CssP(elmt, name, value) {
/// <summary>
/// access css in pixel as numeric, like 'top', 'left', 'width', 'height'
/// $Jssor$.$CssP(elmt, name); //get css value
/// $Jssor$.$CssP(elmt, name, value); //set css value
/// </summary>
/// <param name="elmt" type="HTMLElement">
/// the element to access css
/// </param>
/// <param name="name" type="String">
/// the name of css property
/// </param>
/// <param name="value" type="Number" optional="true">
/// the value to set
/// </param>
return CssN(elmt, name, value, true);
}
function CssProxy(name, numericOrDimension) {
/// <summary>
/// create proxy to access css, CssProxy(name[, numericOrDimension]);
/// </summary>
/// <param name="elmt" type="HTMLElement">
/// the element to access css
/// </param>
/// <param name="numericOrDimension" type="Number" optional="true">
/// not set: access original css, 1: access css as numeric, 2: access css in pixel as numeric
/// </param>
var isDimensional = numericOrDimension & 2;
var cssAccessor = numericOrDimension ? CssN : Css;
return function (elmt, value) {
return cssAccessor(elmt, name, value, isDimensional);
};
}
function GetStyleOpacity(elmt) {
if (IsBrowserIE() && browserEngineVersion < 9) {
var match = /opacity=([^)]*)/.exec(elmt.style.filter || "");
return match ? (ParseFloat(match[1]) / 100) : 1;
}
else
return ParseFloat(elmt.style.opacity || "1");
}
function SetStyleOpacity(elmt, opacity, ie9EarlierForce) {
if (IsBrowserIE() && browserEngineVersion < 9) {
//var filterName = "filter"; // browserEngineVersion < 8 ? "filter" : "-ms-filter";
var finalFilter = elmt.style.filter || "";
// for CSS filter browsers (IE), remove alpha filter if it's unnecessary.
// update: doing _This always since IE9 beta seems to have broken the
// behavior if we rely on the programmatic filters collection.
var alphaReg = new RegExp(/[\s]*alpha\([^\)]*\)/g);
// important: note the lazy star! _This protects against
// multiple filters; we don't want to delete the other ones.
// update: also trimming extra whitespace around filter.
var ieOpacity = Math.round(100 * opacity);
var alphaFilter = "";
if (ieOpacity < 100 || ie9EarlierForce) {
alphaFilter = "alpha(opacity=" + ieOpacity + ") ";
//elmt.style["-ms-filter"] = "progid:DXImageTransform.Microsoft.Alpha(opacity=" + ieOpacity + ") ";
}
var newFilterValue = BuildNewCss(finalFilter, [alphaReg], alphaFilter);
SetStyleFilterIE(elmt, newFilterValue);
}
//if (!IsBrowserIE() || browserEngineVersion >= 9)
else {
elmt.style.opacity = opacity == 1 ? "" : Math.round(opacity * 100) / 100;
}
}
function SetStyleTransformInternal(elmt, transform) {
var rotate = transform.$Rotate || 0;
var scale = transform.$Scale == undefined ? 1 : transform.$Scale;
if (IsBrowserIe9Earlier()) {
var matrix = _This.$CreateMatrix(rotate / 180 * Math.PI, scale, scale);
SetStyleMatrixIE(elmt, (!rotate && scale == 1) ? null : matrix, _This.$GetMatrixOffset(matrix, transform.$OriginalWidth, transform.$OriginalHeight));
}
else {
//rotate(15deg) scale(.5) translateZ(0)
var transformProperty = GetTransformProperty(elmt);
if (transformProperty) {
var transformValue = "rotate(" + rotate % 360 + "deg) scale(" + scale + ")";
if (IsBrowserChrome() && webkitVersion > 535)
transformValue += " perspective(2000px)";
elmt.style[transformProperty] = transformValue;
}
}
}
_This.$SetStyleTransform = function (elmt, transform) {
if (IsBrowserBadTransform()) {
Delay(_This.$CreateCallback(null, SetStyleTransformInternal, elmt, transform));
}
else {
SetStyleTransformInternal(elmt, transform);
}
};
_This.$SetStyleTransformOrigin = function (elmt, transformOrigin) {
var transformProperty = GetTransformProperty(elmt);
if (transformProperty)
elmt.style[transformProperty + "Origin"] = transformOrigin;
};
_This.$CssScale = function (elmt, scale) {
if (IsBrowserIE() && browserEngineVersion < 9 || (browserEngineVersion < 10 && IsBrowserIeQuirks())) {
elmt.style.zoom = (scale == 1) ? "" : scale;
}
else {
var transformProperty = GetTransformProperty(elmt);
if (transformProperty) {
//rotate(15deg) scale(.5)
var transformValue = "scale(" + scale + ")";
var oldTransformValue = elmt.style[transformProperty];
var scaleReg = new RegExp(/[\s]*scale\(.*?\)/g);
var newTransformValue = BuildNewCss(oldTransformValue, [scaleReg], transformValue);
elmt.style[transformProperty] = newTransformValue;
}
}
};
_This.$EnableHWA = function (elmt) {
if (!elmt.style[GetTransformProperty(elmt)] || elmt.style[GetTransformProperty(elmt)] == "none")
elmt.style[GetTransformProperty(elmt)] = "perspective(2000px)";
};
_This.$DisableHWA = function (elmt) {
//if (force || elmt.style[GetTransformProperty(elmt)] == "perspective(2000px)")
elmt.style[GetTransformProperty(elmt)] = "none";
};
var ie8OffsetWidth = 0;
var ie8OffsetHeight = 0;
//var ie8WindowResizeCallbackHandlers;
//var ie8LastVerticalScrollbar;
//var toggleInfo = "";
//function Ie8WindowResizeFilter(window, handler) {
// var trigger = true;
// var checkElement = (IsBrowserIeQuirks() ? window.document.body : window.document.documentElement);
// if (checkElement) {
// //check vertical bar
// //var hasVerticalBar = checkElement.scrollHeight > checkElement.clientHeight;
// //var verticalBarToggle = hasVerticalBar != ie8LastVerticalScrollbar;
// //ie8LastVerticalScrollbar = hasVerticalBar;
// var widthChange = checkElement.offsetWidth - ie8OffsetWidth;
// var heightChange = checkElement.offsetHeight - ie8OffsetHeight;
// if (widthChange || heightChange) {
// ie8OffsetWidth += widthChange;
// ie8OffsetHeight += heightChange;
// }
// else
// trigger = false;
// }
// trigger && handler();
//}
//_This.$OnWindowResize = function (window, handler) {
// if (IsBrowserIE() && browserEngineVersion < 9) {
// if (!ie8WindowResizeCallbackHandlers) {
// ie8WindowResizeCallbackHandlers = [handler];
// handler = _This.$CreateCallback(null, Ie8WindowResizeFilter, window);
// }
// else {
// ie8WindowResizeCallbackHandlers.push(handler);
// return;
// }
// }
// _This.$AddEvent(window, "resize", handler);
//};
_This.$WindowResizeFilter = function (window, handler) {
return IsBrowserIe9Earlier() ? function () {
var trigger = true;
var checkElement = (IsBrowserIeQuirks() ? window.document.body : window.document.documentElement);
if (checkElement) {
//check vertical bar
//var hasVerticalBar = checkElement.scrollHeight > checkElement.clientHeight;
//var verticalBarToggle = hasVerticalBar != ie8LastVerticalScrollbar;
//ie8LastVerticalScrollbar = hasVerticalBar;
var widthChange = checkElement.offsetWidth - ie8OffsetWidth;
var heightChange = checkElement.offsetHeight - ie8OffsetHeight;
if (widthChange || heightChange) {
ie8OffsetWidth += widthChange;
ie8OffsetHeight += heightChange;
}
else
trigger = false;
}
trigger && handler();
} : handler;
};
_This.$MouseOverOutFilter = function (handler, target) {
/// <param name="target" type="HTMLDomElement">
/// The target element to detect mouse over/out events. (for ie < 9 compatibility)
/// </param>
$JssorDebug$.$Execute(function () {
if (!target) {
throw new Error("Null reference, parameter \"target\".");
}
});
return function (event) {
event = GetEvent(event);
var eventName = event.type;
var related = event.relatedTarget || (eventName == "mouseout" ? event.toElement : event.fromElement);
if (!related || (related !== target && !_This.$IsChild(target, related))) {
handler(event);
}
};
};
_This.$AddEvent = function (elmt, eventName, handler, useCapture) {
elmt = _This.$GetElement(elmt);
// technique from:
// http://blog.paranoidferret.com/index.php/2007/08/10/javascript-working-with-events/
if (elmt.addEventListener) {
if (eventName == "mousewheel") {
elmt.addEventListener("DOMMouseScroll", handler, useCapture);
}
// we are still going to add the mousewheel -- not a mistake!
// _This is for opera, since it uses onmousewheel but needs addEventListener.
elmt.addEventListener(eventName, handler, useCapture);
}
else if (elmt.attachEvent) {
elmt.attachEvent("on" + eventName, handler);
if (useCapture && elmt.setCapture) {
elmt.setCapture();
}
}
$JssorDebug$.$Execute(function () {
if (!elmt.addEventListener && !elmt.attachEvent) {
$JssorDebug$.$Fail("Unable to attach event handler, no known technique.");
}
});
};
_This.$RemoveEvent = function (elmt, eventName, handler, useCapture) {
elmt = _This.$GetElement(elmt);
// technique from:
// http://blog.paranoidferret.com/index.php/2007/08/10/javascript-working-with-events/
if (elmt.removeEventListener) {
if (eventName == "mousewheel") {
elmt.removeEventListener("DOMMouseScroll", handler, useCapture);
}
// we are still going to remove the mousewheel -- not a mistake!
// _This is for opera, since it uses onmousewheel but needs removeEventListener.
elmt.removeEventListener(eventName, handler, useCapture);
}
else if (elmt.detachEvent) {
elmt.detachEvent("on" + eventName, handler);
if (useCapture && elmt.releaseCapture) {
elmt.releaseCapture();
}
}
};
_This.$FireEvent = function (elmt, eventName) {
//var document = elmt.document;
$JssorDebug$.$Execute(function () {
if (!document.createEvent && !document.createEventObject) {
$JssorDebug$.$Fail("Unable to fire event, no known technique.");
}
if (!elmt.dispatchEvent && !elmt.fireEvent) {
$JssorDebug$.$Fail("Unable to fire event, no known technique.");
}
});
var evento;
if (document.createEvent) {
evento = document.createEvent("HTMLEvents");
evento.initEvent(eventName, false, false);
elmt.dispatchEvent(evento);
}
else {
var ieEventName = "on" + eventName;
evento = document.createEventObject();
//event.eventType = ieEventName;
//event.eventName = ieEventName;
elmt.fireEvent(ieEventName, evento);
}
};
_This.$AddEventBrowserMouseUp = function (handler, userCapture) {
_This.$AddEvent((IsBrowserIe9Earlier()) ? document : window, "mouseup", handler, userCapture);
};
_This.$RemoveEventBrowserMouseUp = function (handler, userCapture) {
_This.$RemoveEvent((IsBrowserIe9Earlier()) ? document : window, "mouseup", handler, userCapture);
};
//_This.$AddEventBrowserMouseDown = function (handler, userCapture) {
// _This.$AddEvent((IsBrowserIe9Earlier()) ? document : window, "mousedown", handler, userCapture);
//};
//_This.$RemoveEventBrowserMouseDown = function (handler, userCapture) {
// _This.$RemoveEvent((IsBrowserIe9Earlier()) ? document : window, "mousedown", handler, userCapture);
//};
_This.$CancelEvent = function (event) {
event = GetEvent(event);
// technique from:
// http://blog.paranoidferret.com/index.php/2007/08/10/javascript-working-with-events/
if (event.preventDefault) {
event.preventDefault(); // W3C for preventing default
}
event.cancel = true; // legacy for preventing default
event.returnValue = false; // IE for preventing default
};
_This.$StopEvent = function (event) {
event = GetEvent(event);
// technique from:
// http://blog.paranoidferret.com/index.php/2007/08/10/javascript-working-with-events/
if (event.stopPropagation) {
event.stopPropagation(); // W3C for stopping propagation
}
event.cancelBubble = true; // IE for stopping propagation
};
_This.$CreateCallback = function (object, method) {
// create callback args
var initialArgs = [].slice.call(arguments, 2);
// create closure to apply method
var callback = function () {
// concatenate new args, but make a copy of initialArgs first
var args = initialArgs.concat([].slice.call(arguments, 0));
return method.apply(object, args);
};
//$JssorDebug$.$LiveStamp(callback, "callback_" + ($Jssor$.$GetNow() & 0xFFFFFF));
return callback;
};
var _Freeer;
_This.$FreeElement = function (elmt) {
if (!_Freeer)
_Freeer = _This.$CreateDiv();
if (elmt) {
$Jssor$.$AppendChild(_Freeer, elmt);
$Jssor$.$ClearInnerHtml(_Freeer);
}
};
_This.$InnerText = function (elmt, text) {
if (text == undefined)
return elmt.textContent || elmt.innerText;
var textNode = document.createTextNode(text);
_This.$ClearInnerHtml(elmt);
elmt.appendChild(textNode);
};
_This.$InnerHtml = function (elmt, html) {
if (html == undefined)
return elmt.innerHTML;
elmt.innerHTML = html;
};
_This.$GetClientRect = function (elmt) {
var rect = elmt.getBoundingClientRect();
return {x: rect.left, y: rect.top, w: rect.right - rect.left, h: rect.bottom - rect.top};
};
_This.$ClearInnerHtml = function (elmt) {
elmt.innerHTML = "";
};
_This.$EncodeHtml = function (text) {
var div = _This.$CreateDiv();
_This.$InnerText(div, text);
return _This.$InnerHtml(div);
};
_This.$DecodeHtml = function (html) {
var div = _This.$CreateDiv();
_This.$InnerHtml(div, html);
return _This.$InnerText(div);
};
_This.$SelectElement = function (elmt) {
var userSelection;
if (window.getSelection) {
//W3C default
userSelection = window.getSelection();
}
var theRange = null;
if (document.createRange) {
theRange = document.createRange();
theRange.selectNode(elmt);
}
else {
theRange = document.body.createTextRange();
theRange.moveToElementText(elmt);
theRange.select();
}
//set user selection
if (userSelection)
userSelection.addRange(theRange);
};
_This.$DeselectElements = function () {
if (document.selection) {
document.selection.empty();
} else if (window.getSelection) {
window.getSelection().removeAllRanges();
}
};
_This.$Children = function (elmt) {
var children = [];
for (var tmpEl = elmt.firstChild; tmpEl; tmpEl = tmpEl.nextSibling) {
if (tmpEl.nodeType == 1) {
children.push(tmpEl);
}
}
return children;
};
function FindFirstChild(elmt, attrValue, attrName, deep) {
if (!attrName)
attrName = "u";
for (elmt = elmt ? elmt.firstChild : null; elmt; elmt = elmt.nextSibling) {
if (elmt.nodeType == 1) {
if (AttributeEx(elmt, attrName) == attrValue)
return elmt;
if (deep) {
var childRet = FindFirstChild(elmt, attrValue, attrName, deep);
if (childRet)
return childRet;
}
}
}
}
_This.$FindFirstChild = FindFirstChild;
function FindChildren(elmt, attrValue, attrName, deep) {
if (!attrName)
attrName = "u";
var ret = [];
for (elmt = elmt ? elmt.firstChild : null; elmt; elmt = elmt.nextSibling) {
if (elmt.nodeType == 1) {
if (AttributeEx(elmt, attrName) == attrValue)
ret.push(elmt);
if (deep) {
var childRet = FindChildren(elmt, attrValue, attrName, deep);
if (childRet.length)
ret = ret.concat(childRet);
}
}
}
return ret;
}
_This.$FindChildren = FindChildren;
function FindFirstChildByTag(elmt, tagName, deep) {
for (elmt = elmt ? elmt.firstChild : null; elmt; elmt = elmt.nextSibling) {
if (elmt.nodeType == 1) {
if (elmt.tagName == tagName)
return elmt;
if (deep) {
var childRet = FindFirstChildByTag(elmt, tagName, deep);
if (childRet)
return childRet;
}
}
}
}
_This.$FindFirstChildByTag = FindFirstChildByTag;
function FindChildrenByTag(elmt, tagName, deep) {
var ret = [];
for (elmt = elmt ? elmt.firstChild : null; elmt; elmt = elmt.nextSibling) {
if (elmt.nodeType == 1) {
if (!tagName || elmt.tagName == tagName)
ret.push(elmt);
if (deep) {
var childRet = FindChildrenByTag(elmt, tagName, true);
if (childRet.length)
ret = ret.concat(childRet);
}
}
}
return ret;
}
_This.$FindChildrenByTag = FindChildrenByTag;
_This.$GetElementsByTag = function (elmt, tagName) {
return elmt.getElementsByTagName(tagName);
};
function Extend(target) {
for (var i = 1; i < arguments.length; i++) {
var options = arguments[i];
// Only deal with non-null/undefined values
if (options) {
// Extend the base object
for (var name in options) {
target[name] = options[name];
}
}
}
// Return the modified object
return target;
}
_This.$Extend = Extend;
function Unextend(target, options) {
$JssorDebug$.$Assert(options);
var unextended = {};
// Extend the base object
for (var name in target) {
if (target[name] != options[name]) {
unextended[name] = target[name];
}
}
// Return the modified object
return unextended;
}
_This.$Unextend = Unextend;
_This.$IsUndefined = function (obj) {
return type(obj) == "undefined";
};
_This.$IsFunction = function (obj) {
return type(obj) == "function";
};
_This.$IsArray = function (obj) {
return type(obj) == "array";
};
_This.$IsString = function (obj) {
return type(obj) == "string";
};
_This.$IsNumeric = function (obj) {
return !isNaN(ParseFloat(obj)) && isFinite(obj);
};
_This.$IsWindow = function (obj) {
return obj && obj == obj.window;
};
_This.$Type = type;
// args is for internal usage only
_This.$Each = each;
_This.$IsPlainObject = isPlainObject;
function CreateElement(tagName) {
return document.createElement(tagName);
}
_This.$CreateElement = CreateElement;
_This.$CreateDiv = function () {
return CreateElement("DIV", document);
};
_This.$CreateSpan = function () {
return CreateElement("SPAN", document);
};
_This.$EmptyFunction = function () {
};
function Attribute(elmt, name, value) {
if (value == undefined)
return elmt.getAttribute(name);
elmt.setAttribute(name, value);
}
function AttributeEx(elmt, name) {
return Attribute(elmt, name) || Attribute(elmt, "data-" + name);
}
_This.$Attribute = Attribute;
_This.$AttributeEx = AttributeEx;
function ClassName(elmt, className) {
if (className == undefined)
return elmt.className;
elmt.className = className;
}
_This.$ClassName = ClassName;
function ToHash(array) {
var hash = {};
each(array, function (item) {
hash[item] = item;
});
return hash;
}
_This.$ToHash = ToHash;
function Join(separator, strings) {
/// <param name="separator" type="String">
/// The element to show the dialog around
/// </param>
/// <param name="strings" type="Array" value="['1']">
/// The element to show the dialog around
/// </param>
var joined = "";
each(strings, function (str) {
joined && (joined += separator);
joined += str;
});
return joined;
}
_This.$Join = Join;
_This.$AddClass = function (elmt, className) {
var newClassName = ClassName(elmt) + " " + className;
ClassName(elmt, Join(" ", ToHash(newClassName.match(REGEX_WHITESPACE_GLOBAL))));
};
_This.$RemoveClass = function (elmt, className) {
ClassName(elmt, Join(" ", _This.$Unextend(ToHash(ClassName(elmt).match(REGEX_WHITESPACE_GLOBAL)), ToHash(className.match(REGEX_WHITESPACE_GLOBAL)))));
};
_This.$ParentNode = function (elmt) {
return elmt.parentNode;
};
_This.$HideElement = function (elmt) {
_This.$CssDisplay(elmt, "none");
};
_This.$HideElements = function (elmts) {
for (var i = 0; i < elmts.length; i++) {
_This.$HideElement(elmts[i]);
}
};
_This.$ShowElement = function (elmt, show) {
_This.$CssDisplay(elmt, show == false ? "none" : "");
};
_This.$ShowElements = function (elmts) {
for (var i = 0; i < elmts.length; i++) {
_This.$ShowElement(elmts[i]);
}
};
_This.$RemoveAttribute = function (elmt, attrbuteName) {
elmt.removeAttribute(attrbuteName);
};
_This.$CanClearClip = function () {
return IsBrowserIE() && browserRuntimeVersion < 10;
};
_This.$SetStyleClip = function (elmt, clip) {
if (clip) {
elmt.style.clip = "rect(" + Math.round(clip.$Top) + "px " + Math.round(clip.$Right) + "px " + Math.round(clip.$Bottom) + "px " + Math.round(clip.$Left) + "px)";
}
else {
var cssText = elmt.style.cssText;
var clipRegs = [
new RegExp(/[\s]*clip: rect\(.*?\)[;]?/i),
new RegExp(/[\s]*cliptop: .*?[;]?/i),
new RegExp(/[\s]*clipright: .*?[;]?/i),
new RegExp(/[\s]*clipbottom: .*?[;]?/i),
new RegExp(/[\s]*clipleft: .*?[;]?/i)
];
var newCssText = BuildNewCss(cssText, clipRegs, "");
$Jssor$.$CssCssText(elmt, newCssText);
}
};
_This.$GetNow = function () {
return new Date().getTime();
};
_This.$AppendChild = function (elmt, child) {
elmt.appendChild(child);
};
_This.$AppendChildren = function (elmt, children) {
each(children, function (child) {
_This.$AppendChild(elmt, child);
});
};
_This.$InsertBefore = function (elmt, child, refObject) {
elmt.insertBefore(child, refObject);
};
_This.$InsertAdjacentHtml = function (elmt, where, text) {
elmt.insertAdjacentHTML(where, text);
};
_This.$RemoveChild = function (elmt, child) {
elmt.removeChild(child);
};
_This.$RemoveChildren = function (elmt, children) {
each(children, function (child) {
_This.$RemoveChild(elmt, child);
});
};
_This.$ClearChildren = function (elmt) {
_This.$RemoveChildren(elmt, _This.$Children(elmt));
};
_This.$ParseInt = function (str, radix) {
return parseInt(str, radix || 10);
};
function ParseFloat(str) {
return parseFloat(str);
}
_This.$ParseFloat = ParseFloat;
_This.$IsChild = function (elmtA, elmtB) {
var body = document.body;
while (elmtB && elmtA != elmtB && body != elmtB) {
try {
elmtB = elmtB.parentNode;
} catch (e) {
// Firefox sometimes fires events for XUL elements, which throws
// a "permission denied" error. so this is not a child.
return false;
}
}
return elmtA == elmtB;
};
function CloneNode(elmt, deep) {
return elmt.cloneNode(deep);
}
_This.$CloneNode = CloneNode;
function TranslateTransition(transition) {
if (transition) {
var flyDirection = transition.$FlyDirection;
if (flyDirection & 1) {
transition.x = transition.$ScaleHorizontal || 1;
}
if (flyDirection & 2) {
transition.x = -transition.$ScaleHorizontal || -1;
}
if (flyDirection & 4) {
transition.y = transition.$ScaleVertical || 1;
}
if (flyDirection & 8) {
transition.y = -transition.$ScaleVertical || -1;
}
TranslateTransition(transition.$Brother);
}
}
_This.$TranslateTransitions = function (transitions) {
/// <summary>
/// For backward compatibility only.
/// </summary>
if (transitions) {
for (var i = 0; i < transitions.length; i++) {
TranslateTransition(transitions[i]);
}
for (var name in transitions) {
TranslateTransition(transitions[name]);
}
}
};
function LoadImageCallback(callback, image, abort) {
image.onload = null;
image.abort = null;
if (callback)
callback(image, abort);
}
_This.$LoadImage = function (src, callback) {
if (IsBrowserOpera() && browserRuntimeVersion < 11.6 || !src) {
LoadImageCallback(callback, null);
}
else {
var image = new Image();
image.onload = _This.$CreateCallback(null, LoadImageCallback, callback, image);
image.onabort = _This.$CreateCallback(null, LoadImageCallback, callback, image, true);
image.src = src;
}
};
_This.$LoadImages = function (imageElmts, mainImageElmt, callback) {
var _ImageLoading = imageElmts.length + 1;
function LoadImageCompleteEventHandler(image, abort) {
_ImageLoading--;
if (mainImageElmt && image && image.src == mainImageElmt.src)
mainImageElmt = image;
!_ImageLoading && callback && callback(mainImageElmt);
}
each(imageElmts, function (imageElmt) {
$Jssor$.$LoadImage(imageElmt.src, LoadImageCompleteEventHandler);
});
LoadImageCompleteEventHandler();
};
_This.$BuildElement = function (template, tagName, replacer, createCopy) {
if (createCopy)
template = CloneNode(template, true);
var templateHolders = $Jssor$.$GetElementsByTag(template, tagName);
for (var j = templateHolders.length - 1; j > -1; j--) {
var templateHolder = templateHolders[j];
var replaceItem = CloneNode(replacer, true);
ClassName(replaceItem, ClassName(templateHolder));
$Jssor$.$CssCssText(replaceItem, templateHolder.style.cssText);
var thumbnailPlaceHolderParent = $Jssor$.$ParentNode(templateHolder);
$Jssor$.$InsertBefore(thumbnailPlaceHolderParent, replaceItem, templateHolder);
$Jssor$.$RemoveChild(thumbnailPlaceHolderParent, templateHolder);
}
return template;
};
var _MouseDownButtons;
function JssorButtonEx(elmt) {
var _Self = this;
var _OriginClassName;
var _IsMouseDown; //class name 'dn'
var _IsActive; //class name 'av'
var _IsDisabled; //class name 'ds'
function Highlight() {
var className = _OriginClassName;
if (_IsDisabled) {
className += 'ds';
}
else if (_IsMouseDown) {
className += 'dn';
}
else if (_IsActive) {
className += "av";
}
ClassName(elmt, className);
}
function OnMouseDown(event) {
if (_IsDisabled) {
_This.$CancelEvent(event);
}
else {
_MouseDownButtons.push(_Self);
_IsMouseDown = true;
Highlight();
}
}
_Self.$MouseUp = function () {
/// <summary>
/// Internal member function, do not use it.
/// </summary>
/// <private />
_IsMouseDown = false;
Highlight();
};
_Self.$Activate = function (activate) {
if (activate != undefined) {
_IsActive = activate;
Highlight();
}
else {
return _IsActive;
}
};
_Self.$Enable = function (enable) {
if (enable != undefined) {
_IsDisabled = !enable;
Highlight();
}
else {
return !_IsDisabled;
}
};
//JssorButtonEx Constructor
{
elmt = _This.$GetElement(elmt);
if (!_MouseDownButtons) {
_This.$AddEventBrowserMouseUp(function () {
var oldMouseDownButtons = _MouseDownButtons;
_MouseDownButtons = [];
each(oldMouseDownButtons, function (button) {
button.$MouseUp();
});
});
_MouseDownButtons = [];
}
_OriginClassName = ClassName(elmt);
$Jssor$.$AddEvent(elmt, "mousedown", OnMouseDown);
}
}
_This.$Buttonize = function (elmt) {
return new JssorButtonEx(elmt);
};
_This.$Css = Css;
_This.$CssN = CssN;
_This.$CssP = CssP;
_This.$CssOverflow = CssProxy("overflow");
_This.$CssTop = CssProxy("top", 2);
_This.$CssLeft = CssProxy("left", 2);
_This.$CssWidth = CssProxy("width", 2);
_This.$CssHeight = CssProxy("height", 2);
_This.$CssMarginLeft = CssProxy("marginLeft", 2);
_This.$CssMarginTop = CssProxy("marginTop", 2);
_This.$CssPosition = CssProxy("position");
_This.$CssDisplay = CssProxy("display");
_This.$CssZIndex = CssProxy("zIndex", 1);
_This.$CssFloat = function (elmt, float) {
return Css(elmt, IsBrowserIE() ? "styleFloat" : "cssFloat", float);
};
_This.$CssOpacity = function (elmt, opacity, ie9EarlierForce) {
if (opacity != undefined) {
SetStyleOpacity(elmt, opacity, ie9EarlierForce);
}
else {
return GetStyleOpacity(elmt);
}
};
_This.$CssCssText = function (elmt, text) {
if (text != undefined) {
elmt.style.cssText = text;
}
else {
return elmt.style.cssText;
}
};
var _StyleGetter = {
$Opacity: _This.$CssOpacity,
$Top: _This.$CssTop,
$Left: _This.$CssLeft,
$Width: _This.$CssWidth,
$Height: _This.$CssHeight,
$Position: _This.$CssPosition,
$Display: _This.$CssDisplay,
$ZIndex: _This.$CssZIndex
};
//var _StyleGetter = {
// $Opacity: _This.$GetStyleOpacity,
// $Top: _This.$GetStyleTop,
// $Left: _This.$GetStyleLeft,
// $Width: _This.$GetStyleWidth,
// $Height: _This.$GetStyleHeight,
// $Position: _This.$GetStylePosition,
// $Display: _This.$GetStyleDisplay,
// $ZIndex: _This.$GetStyleZIndex
//};
var _StyleSetterReserved;
//var _StyleSetterReserved = {
// $Opacity: _This.$SetStyleOpacity,
// $Top: _This.$SetStyleTop,
// $Left: _This.$SetStyleLeft,
// $Width: _This.$SetStyleWidth,
// $Height: _This.$SetStyleHeight,
// $Display: _This.$SetStyleDisplay,
// $Clip: _This.$SetStyleClip,
// $MarginLeft: _This.$SetStyleMarginLeft,
// $MarginTop: _This.$SetStyleMarginTop,
// $Transform: _This.$SetStyleTransform,
// $Position: _This.$SetStylePosition,
// $ZIndex: _This.$SetStyleZIndex
//};
function StyleSetter() {
if (!_StyleSetterReserved) {
_StyleSetterReserved = Extend({
$MarginTop: _This.$CssMarginTop,
$MarginLeft: _This.$CssMarginLeft,
$Clip: _This.$SetStyleClip,
$Transform: _This.$SetStyleTransform
}, _StyleGetter);
}
return _StyleSetterReserved;
}
function StyleSetterEx() {
StyleSetter();
//For Compression Only
_StyleSetterReserved.$Transform = _StyleSetterReserved.$Transform;
return _StyleSetterReserved;
}
_This.$StyleSetter = StyleSetter;
_This.$StyleSetterEx = StyleSetterEx;
_This.$GetStyles = function (elmt, originStyles) {
StyleSetter();
var styles = {};
each(originStyles, function (value, key) {
if (_StyleGetter[key]) {
styles[key] = _StyleGetter[key](elmt);
}
});
return styles;
};
_This.$SetStyles = function (elmt, styles) {
var styleSetter = StyleSetter();
each(styles, function (value, key) {
styleSetter[key] && styleSetter[key](elmt, value);
});
};
_This.$SetStylesEx = function (elmt, styles) {
StyleSetterEx();
_This.$SetStyles(elmt, styles);
};
$JssorMatrix$ = new function () {
var _ThisMatrix = this;
function Multiply(ma, mb) {
var acs = ma[0].length;
var rows = ma.length;
var cols = mb[0].length;
var matrix = [];
for (var r = 0; r < rows; r++) {
var row = matrix[r] = [];
for (var c = 0; c < cols; c++) {
var unitValue = 0;
for (var ac = 0; ac < acs; ac++) {
unitValue += ma[r][ac] * mb[ac][c];
}
row[c] = unitValue;
}
}
return matrix;
}
_ThisMatrix.$ScaleX = function (matrix, sx) {
return _ThisMatrix.$ScaleXY(matrix, sx, 0);
};
_ThisMatrix.$ScaleY = function (matrix, sy) {
return _ThisMatrix.$ScaleXY(matrix, 0, sy);
};
_ThisMatrix.$ScaleXY = function (matrix, sx, sy) {
return Multiply(matrix, [[sx, 0], [0, sy]]);
};
_ThisMatrix.$TransformPoint = function (matrix, p) {
var pMatrix = Multiply(matrix, [[p.x], [p.y]]);
return new $JssorPoint$(pMatrix[0][0], pMatrix[1][0]);
};
};
_This.$CreateMatrix = function (alpha, scaleX, scaleY) {
var cos = Math.cos(alpha);
var sin = Math.sin(alpha);
//var r11 = cos;
//var r21 = sin;
//var r12 = -sin;
//var r22 = cos;
//var m11 = cos * scaleX;
//var m12 = -sin * scaleY;
//var m21 = sin * scaleX;
//var m22 = cos * scaleY;
return [[cos * scaleX, -sin * scaleY], [sin * scaleX, cos * scaleY]];
};
_This.$GetMatrixOffset = function (matrix, width, height) {
var p1 = $JssorMatrix$.$TransformPoint(matrix, new $JssorPoint$(-width / 2, -height / 2));
var p2 = $JssorMatrix$.$TransformPoint(matrix, new $JssorPoint$(width / 2, -height / 2));
var p3 = $JssorMatrix$.$TransformPoint(matrix, new $JssorPoint$(width / 2, height / 2));
var p4 = $JssorMatrix$.$TransformPoint(matrix, new $JssorPoint$(-width / 2, height / 2));
return new $JssorPoint$(Math.min(p1.x, p2.x, p3.x, p4.x) + width / 2, Math.min(p1.y, p2.y, p3.y, p4.y) + height / 2);
};
};
//for backward compatibility
//var $JssorUtils$ = window.$JssorUtils$ = $Jssor$;
//$JssorObject$
var $JssorObject$ = window.$JssorObject$ = function () {
var _ThisObject = this;
// Fields
var _Listeners = []; // dictionary of eventName --> array of handlers
var _Listenees = [];
// Private Methods
function AddListener(eventName, handler) {
$JssorDebug$.$Execute(function () {
if (eventName == undefined || eventName == null)
throw new Error("param 'eventName' is null or empty.");
if (typeof (handler) != "function") {
throw "param 'handler' must be a function.";
}
$Jssor$.$Each(_Listeners, function (listener) {
if (listener.$EventName == eventName && listener.$Handler === handler) {
throw new Error("The handler listened to the event already, cannot listen to the same event of the same object with the same handler twice.");
}
});
});
_Listeners.push({$EventName: eventName, $Handler: handler});
}
function RemoveListener(eventName, handler) {
$JssorDebug$.$Execute(function () {
if (eventName == undefined || eventName == null)
throw new Error("param 'eventName' is null or empty.");
if (typeof (handler) != "function") {
throw "param 'handler' must be a function.";
}
});
$Jssor$.$Each(_Listeners, function (listener, index) {
if (listener.$EventName == eventName && listener.$Handler === handler) {
_Listeners.splice(index, 1);
}
});
}
function ClearListeners() {
_Listeners = [];
}
function ClearListenees() {
$Jssor$.$Each(_Listenees, function (listenee) {
$Jssor$.$RemoveEvent(listenee.$Obj, listenee.$EventName, listenee.$Handler);
});
_Listenees = [];
}
//Protected Methods
_ThisObject.$Listen = function (obj, eventName, handler, useCapture) {
$JssorDebug$.$Execute(function () {
if (!obj)
throw new Error("param 'obj' is null or empty.");
if (eventName == undefined || eventName == null)
throw new Error("param 'eventName' is null or empty.");
if (typeof (handler) != "function") {
throw "param 'handler' must be a function.";
}
$Jssor$.$Each(_Listenees, function (listenee) {
if (listenee.$Obj === obj && listenee.$EventName == eventName && listenee.$Handler === handler) {
throw new Error("The handler listened to the event already, cannot listen to the same event of the same object with the same handler twice.");
}
});
});
$Jssor$.$AddEvent(obj, eventName, handler, useCapture);
_Listenees.push({$Obj: obj, $EventName: eventName, $Handler: handler});
};
_ThisObject.$Unlisten = function (obj, eventName, handler) {
$JssorDebug$.$Execute(function () {
if (!obj)
throw new Error("param 'obj' is null or empty.");
if (eventName == undefined || eventName == null)
throw new Error("param 'eventName' is null or empty.");
if (typeof (handler) != "function") {
throw "param 'handler' must be a function.";
}
});
$Jssor$.$Each(_Listenees, function (listenee, index) {
if (listenee.$Obj === obj && listenee.$EventName == eventName && listenee.$Handler === handler) {
$Jssor$.$RemoveEvent(obj, eventName, handler);
_Listenees.splice(index, 1);
}
});
};
_ThisObject.$UnlistenAll = ClearListenees;
// Public Methods
_ThisObject.$On = _ThisObject.addEventListener = AddListener;
_ThisObject.$Off = _ThisObject.removeEventListener = RemoveListener;
_ThisObject.$TriggerEvent = function (eventName) {
var args = [].slice.call(arguments, 1);
$Jssor$.$Each(_Listeners, function (listener) {
try {
listener.$EventName == eventName && listener.$Handler.apply(window, args);
} catch (e) {
// handler threw an error, ignore, go on to next one
$JssorDebug$.$Error(e.name + " while executing " + eventName +
" handler: " + e.message, e);
}
});
};
_ThisObject.$Destroy = function () {
ClearListenees();
ClearListeners();
for (var name in _ThisObject)
delete _ThisObject[name];
};
$JssorDebug$.$C_AbstractClass(_ThisObject);
};
$JssorAnimator$ = function (delay, duration, options, elmt, fromStyles, toStyles) {
delay = delay || 0;
var _ThisAnimator = this;
var _AutoPlay;
var _Hiden;
var _CombineMode;
var _PlayToPosition;
var _PlayDirection;
var _NoStop;
var _TimeStampLastFrame = 0;
var _SubEasings;
var _SubRounds;
var _SubDurings;
var _Callback;
var _Position_Current = 0;
var _Position_Display = 0;
var _Hooked;
var _Position_InnerBegin = delay;
var _Position_InnerEnd = delay + duration;
var _Position_OuterBegin;
var _Position_OuterEnd;
var _LoopLength;
var _NestedAnimators = [];
var _StyleSetter;
function GetPositionRange(position, begin, end) {
var range = 0;
if (position < begin)
range = -1;
else if (position > end)
range = 1;
return range;
}
function GetInnerPositionRange(position) {
return GetPositionRange(position, _Position_InnerBegin, _Position_InnerEnd);
}
function GetOuterPositionRange(position) {
return GetPositionRange(position, _Position_OuterBegin, _Position_OuterEnd);
}
function Shift(offset) {
_Position_OuterBegin += offset;
_Position_OuterEnd += offset;
_Position_InnerBegin += offset;
_Position_InnerEnd += offset;
_Position_Current += offset;
_Position_Display += offset;
$Jssor$.$Each(_NestedAnimators, function (animator) {
animator, animator.$Shift(offset);
});
}
function Locate(position, relative) {
var offset = position - _Position_OuterBegin + delay * relative;
Shift(offset);
//$JssorDebug$.$Execute(function () {
// _ThisAnimator.$Position_InnerBegin = _Position_InnerBegin;
// _ThisAnimator.$Position_InnerEnd = _Position_InnerEnd;
// _ThisAnimator.$Position_OuterBegin = _Position_OuterBegin;
// _ThisAnimator.$Position_OuterEnd = _Position_OuterEnd;
//});
return _Position_OuterEnd;
}
function GoToPosition(positionOuter, force) {
var trimedPositionOuter = positionOuter;
if (_LoopLength && (trimedPositionOuter >= _Position_OuterEnd || trimedPositionOuter <= _Position_OuterBegin)) {
trimedPositionOuter = ((trimedPositionOuter - _Position_OuterBegin) % _LoopLength + _LoopLength) % _LoopLength + _Position_OuterBegin;
}
if (!_Hooked || _NoStop || force || _Position_Current != trimedPositionOuter) {
var positionToDisplay = Math.min(trimedPositionOuter, _Position_OuterEnd);
positionToDisplay = Math.max(positionToDisplay, _Position_OuterBegin);
if (!_Hooked || _NoStop || force || positionToDisplay != _Position_Display) {
if (toStyles) {
var currentStyles = toStyles;
if (fromStyles) {
var interPosition = (positionToDisplay - _Position_InnerBegin) / (duration || 1);
if (options.$Optimize && $Jssor$.$IsBrowserChrome() && duration) {
interPosition = Math.round(interPosition / 16 * duration) * 16 / duration;
}
if (options.$Reverse)
interPosition = 1 - interPosition;
currentStyles = {};
for (var key in toStyles) {
var round = _SubRounds[key] || 1;
var during = _SubDurings[key] || [0, 1];
var propertyInterPosition = (interPosition - during[0]) / during[1];
propertyInterPosition = Math.min(Math.max(propertyInterPosition, 0), 1);
propertyInterPosition = propertyInterPosition * round;
var floorPosition = Math.floor(propertyInterPosition);
if (propertyInterPosition != floorPosition)
propertyInterPosition -= floorPosition;
var easing = _SubEasings[key] || _SubEasings.$Default;
var easingValue = easing(propertyInterPosition);
var currentPropertyValue;
var value = fromStyles[key];
var toValue = toStyles[key];
if ($Jssor$.$IsNumeric(toValue)) {
currentPropertyValue = value + (toValue - value) * easingValue;
}
else {
currentPropertyValue = $Jssor$.$Extend({$Offset: {}}, fromStyles[key]);
$Jssor$.$Each(toValue.$Offset, function (rectX, n) {
var offsetValue = rectX * easingValue;
currentPropertyValue.$Offset[n] = offsetValue;
currentPropertyValue[n] += offsetValue;
});
}
currentStyles[key] = currentPropertyValue;
}
}
if (fromStyles.$Zoom) {
currentStyles.$Transform = {
$Rotate: currentStyles.$Rotate || 0,
$Scale: currentStyles.$Zoom,
$OriginalWidth: options.$OriginalWidth,
$OriginalHeight: options.$OriginalHeight
};
}
if (toStyles.$Clip && options.$Move) {
var styleFrameNClipOffset = currentStyles.$Clip.$Offset;
var offsetY = (styleFrameNClipOffset.$Top || 0) + (styleFrameNClipOffset.$Bottom || 0);
var offsetX = (styleFrameNClipOffset.$Left || 0) + (styleFrameNClipOffset.$Right || 0);
currentStyles.$Left = (currentStyles.$Left || 0) + offsetX;
currentStyles.$Top = (currentStyles.$Top || 0) + offsetY;
currentStyles.$Clip.$Left -= offsetX;
currentStyles.$Clip.$Right -= offsetX;
currentStyles.$Clip.$Top -= offsetY;
currentStyles.$Clip.$Bottom -= offsetY;
}
if (currentStyles.$Clip && $Jssor$.$CanClearClip() && !currentStyles.$Clip.$Top && !currentStyles.$Clip.$Left && (currentStyles.$Clip.$Right == options.$OriginalWidth) && (currentStyles.$Clip.$Bottom == options.$OriginalHeight))
currentStyles.$Clip = null;
$Jssor$.$Each(currentStyles, function (value, key) {
_StyleSetter[key] && _StyleSetter[key](elmt, value);
});
}
_ThisAnimator.$OnInnerOffsetChange(_Position_Display - _Position_InnerBegin, positionToDisplay - _Position_InnerBegin);
}
_Position_Display = positionToDisplay;
$Jssor$.$Each(_NestedAnimators, function (animator, i) {
var nestedAnimator = positionOuter < _Position_Current ? _NestedAnimators[_NestedAnimators.length - i - 1] : animator;
nestedAnimator.$GoToPosition(positionOuter, force);
});
var positionOld = _Position_Current;
var positionNew = positionOuter;
_Position_Current = trimedPositionOuter;
_Hooked = true;
_ThisAnimator.$OnPositionChange(positionOld, positionNew);
}
}
function Join(animator, combineMode) {
/// <summary>
/// Combine another animator as nested animator
/// </summary>
/// <param name="animator" type="$JssorAnimator$">
/// An instance of $JssorAnimator$
/// </param>
/// <param name="combineMode" type="int">
/// 0: parallel - place the animator parallel to this animator.
/// 1: chain - chain the animator at the _Position_InnerEnd of this animator.
/// </param>
$JssorDebug$.$Execute(function () {
if (combineMode !== 0 && combineMode !== 1)
$JssorDebug$.$Fail("Argument out of range, the value of 'combineMode' should be either 0 or 1.");
});
if (combineMode)
animator.$Locate(_Position_OuterEnd, 1);
_Position_OuterEnd = Math.max(_Position_OuterEnd, animator.$GetPosition_OuterEnd());
_NestedAnimators.push(animator);
}
function PlayFrame() {
if (_AutoPlay) {
var now = $Jssor$.$GetNow();
//var timeOffset = Math.min(now - _TimeStampLastFrame, $Jssor$.$IsBrowserOpera() ? 80 : 20);
var timeOffset = Math.min(now - _TimeStampLastFrame, 80);
var timePosition = _Position_Current + timeOffset * _PlayDirection;
_TimeStampLastFrame = now;
if (timePosition * _PlayDirection >= _PlayToPosition * _PlayDirection)
timePosition = _PlayToPosition;
GoToPosition(timePosition);
if (!_NoStop && timePosition * _PlayDirection >= _PlayToPosition * _PlayDirection) {
Stop(_Callback);
}
else {
$Jssor$.$Delay(PlayFrame, options.$Interval);
}
}
}
function PlayToPosition(toPosition, callback, noStop) {
if (!_AutoPlay) {
_AutoPlay = true;
_NoStop = noStop;
_Callback = callback;
toPosition = Math.max(toPosition, _Position_OuterBegin);
toPosition = Math.min(toPosition, _Position_OuterEnd);
_PlayToPosition = toPosition;
_PlayDirection = _PlayToPosition < _Position_Current ? -1 : 1;
_ThisAnimator.$OnStart();
_TimeStampLastFrame = $Jssor$.$GetNow();
PlayFrame();
}
}
function Stop(callback) {
if (_AutoPlay) {
_NoStop = _AutoPlay = _Callback = false;
_ThisAnimator.$OnStop();
if (callback)
callback();
}
}
_ThisAnimator.$Play = function (positionLength, callback, noStop) {
PlayToPosition(positionLength ? _Position_Current + positionLength : _Position_OuterEnd, callback, noStop);
};
_ThisAnimator.$PlayToPosition = PlayToPosition;
_ThisAnimator.$PlayToBegin = function (callback, noStop) {
PlayToPosition(_Position_OuterBegin, callback, noStop);
};
_ThisAnimator.$PlayToEnd = function (callback, noStop) {
PlayToPosition(_Position_OuterEnd, callback, noStop);
};
_ThisAnimator.$Stop = Stop;
_ThisAnimator.$Continue = function (toPosition) {
PlayToPosition(toPosition);
};
_ThisAnimator.$GetPosition = function () {
return _Position_Current;
};
_ThisAnimator.$GetPlayToPosition = function () {
return _PlayToPosition;
};
_ThisAnimator.$GetPosition_Display = function () {
return _Position_Display;
};
_ThisAnimator.$GoToPosition = GoToPosition;
_ThisAnimator.$GoToBegin = function () {
GoToPosition(_Position_OuterBegin, true);
};
_ThisAnimator.$GoToEnd = function () {
GoToPosition(_Position_OuterEnd, true);
};
_ThisAnimator.$Move = function (offset) {
GoToPosition(_Position_Current + offset);
};
_ThisAnimator.$CombineMode = function () {
return _CombineMode;
};
_ThisAnimator.$GetDuration = function () {
return duration;
};
_ThisAnimator.$IsPlaying = function () {
return _AutoPlay;
};
_ThisAnimator.$IsOnTheWay = function () {
return _Position_Current > _Position_InnerBegin && _Position_Current <= _Position_InnerEnd;
};
_ThisAnimator.$SetLoopLength = function (length) {
_LoopLength = length;
};
_ThisAnimator.$Locate = Locate;
_ThisAnimator.$Shift = Shift;
_ThisAnimator.$Join = Join;
_ThisAnimator.$Combine = function (animator) {
/// <summary>
/// Combine another animator parallel to this animator
/// </summary>
/// <param name="animator" type="$JssorAnimator$">
/// An instance of $JssorAnimator$
/// </param>
Join(animator, 0);
};
_ThisAnimator.$Chain = function (animator) {
/// <summary>
/// Chain another animator at the _Position_InnerEnd of this animator
/// </summary>
/// <param name="animator" type="$JssorAnimator$">
/// An instance of $JssorAnimator$
/// </param>
Join(animator, 1);
};
_ThisAnimator.$GetPosition_InnerBegin = function () {
/// <summary>
/// Internal member function, do not use it.
/// </summary>
/// <private />
/// <returns type="int" />
return _Position_InnerBegin;
};
_ThisAnimator.$GetPosition_InnerEnd = function () {
/// <summary>
/// Internal member function, do not use it.
/// </summary>
/// <private />
/// <returns type="int" />
return _Position_InnerEnd;
};
_ThisAnimator.$GetPosition_OuterBegin = function () {
/// <summary>
/// Internal member function, do not use it.
/// </summary>
/// <private />
/// <returns type="int" />
return _Position_OuterBegin;
};
_ThisAnimator.$GetPosition_OuterEnd = function () {
/// <summary>
/// Internal member function, do not use it.
/// </summary>
/// <private />
/// <returns type="int" />
return _Position_OuterEnd;
};
_ThisAnimator.$OnPositionChange = _ThisAnimator.$OnStart = _ThisAnimator.$OnStop = _ThisAnimator.$OnInnerOffsetChange = $Jssor$.$EmptyFunction;
_ThisAnimator.$Version = $Jssor$.$GetNow();
//Constructor 1
{
options = $Jssor$.$Extend({
$Interval: 16
}, options);
//Sodo statement, for development time intellisence only
$JssorDebug$.$Execute(function () {
options = $Jssor$.$Extend({
$LoopLength: undefined,
$Setter: undefined,
$Easing: undefined
}, options);
});
_LoopLength = options.$LoopLength;
_StyleSetter = $Jssor$.$Extend({}, $Jssor$.$StyleSetter(), options.$Setter);
_Position_OuterBegin = _Position_InnerBegin = delay;
_Position_OuterEnd = _Position_InnerEnd = delay + duration;
var _SubRounds = options.$Round || {};
var _SubDurings = options.$During || {};
_SubEasings = $Jssor$.$Extend({$Default: $Jssor$.$IsFunction(options.$Easing) && options.$Easing || $JssorEasing$.$EaseSwing}, options.$Easing);
}
};
function $JssorPlayerClass$() {
var _ThisPlayer = this;
var _PlayerControllers = [];
function PlayerController(playerElement) {
var _SelfPlayerController = this;
var _PlayerInstance;
var _PlayerInstantces = [];
function OnPlayerInstanceDataAvailable(event) {
var srcElement = $Jssor$.$EventSrc(event);
_PlayerInstance = srcElement.pInstance;
$Jssor$.$RemoveEvent(srcElement, "dataavailable", OnPlayerInstanceDataAvailable);
$Jssor$.$Each(_PlayerInstantces, function (playerInstance) {
if (playerInstance != _PlayerInstance) {
playerInstance.$Remove();
}
});
playerElement.pTagName = _PlayerInstance.tagName;
_PlayerInstantces = null;
}
function HandlePlayerInstance(playerInstanceElement) {
var playerHandler;
if (!playerInstanceElement.pInstance) {
var playerHandlerAttribute = $Jssor$.$AttributeEx(playerInstanceElement, "pHandler");
if ($JssorPlayer$[playerHandlerAttribute]) {
$Jssor$.$AddEvent(playerInstanceElement, "dataavailable", OnPlayerInstanceDataAvailable);
playerHandler = new $JssorPlayer$[playerHandlerAttribute](playerElement, playerInstanceElement);
_PlayerInstantces.push(playerHandler);
$JssorDebug$.$Execute(function () {
if ($Jssor$.$Type(playerHandler.$Remove) != "function") {
$JssorDebug$.$Fail("'pRemove' interface not implemented for player handler '" + playerHandlerAttribute + "'.");
}
});
}
}
return playerHandler;
}
_SelfPlayerController.$InitPlayerController = function () {
if (!playerElement.pInstance && !HandlePlayerInstance(playerElement)) {
var playerInstanceElements = $Jssor$.$Children(playerElement);
$Jssor$.$Each(playerInstanceElements, function (playerInstanceElement) {
HandlePlayerInstance(playerInstanceElement);
});
}
};
}
_ThisPlayer.$EVT_SWITCH = 21;
_ThisPlayer.$FetchPlayers = function (elmt) {
elmt = elmt || document.body;
var playerElements = $Jssor$.$FindChildren(elmt, "player", null, true);
$Jssor$.$Each(playerElements, function (playerElement) {
if (!_PlayerControllers[playerElement.pId]) {
playerElement.pId = _PlayerControllers.length;
_PlayerControllers.push(new PlayerController(playerElement));
}
var playerController = _PlayerControllers[playerElement.pId];
playerController.$InitPlayerController();
});
};
}
|
// Grab reference to dropdown select element
var selector = d3.select("#selDataset");
// Use list of sample names to populate select options
d3.json("samples.json").then((data) => {
console.log(data);
var names = data.names;
names.forEach((sample) => {
selector
.append("option")
.text(sample)
.attr("value", sample);
});
// Use first sample from list to build initial plots
var firstSample = names[0];
buildCharts(firstSample);
metadata(firstSample);
});
function metadata(sample) {
d3.json("samples.json").then((data) => {
var metadata = data.metadata;
// Loop through array of objects then each object
var filtered = metadata.filter((item) => item.id == sample);
console.log(filtered[0]);
// Then, select unordered list element by class name
var list = d3.select("#sample-metadata");
// Clear any existing data
list.html("");
// Display sample metadata
// Append id data to dropdown menu
list.append("li").text(filtered[0].id);
list.append("li").text(filtered[0].ethnicity);
list.append("li").text(filtered[0].gender);
list.append("li").text(filtered[0].age);
list.append("li").text(filtered[0].location);
});
}
function buildCharts(sample) {
d3.json("samples.json").then((data) => {
var samples = data.samples;
var sample_id = samples.filter(item => item.id == sample);
var result = sample_id[0];
var otu_ids = result.otu_ids;
var otu_labels = result.otu_labels;
var sample_values = result.sample_values;
var yticks = otu_ids.slice(0, 10).map(otuID => `OTU ${otuID}`).reverse();
// Build BarChart
var trace1 = [
{
y: yticks,
x: sample_values.slice(0, 10).reverse(),
text: otu_labels.slice(0, 10).reverse(),
type: "bar",
orientation: "h",
marker: {
color: 'lightblue',
}
}
];
var barLayout = {
title: "Top 10 Bacteria Cultures Found",
font:{
family: 'Arial'
},
margin: { t: 30, l: 150 },
xaxis: {
title: "Sample Value",
},
yaxis: {
title: "OTU ID",
}
};
// Render plot to div tag with id "bar"
Plotly.newPlot("bar", trace1, barLayout);
// Build Bubble Chart
var trace2 = [
{
x: otu_ids,
y: sample_values,
text: otu_labels,
mode: "markers",
marker: {
size: sample_values,
color: otu_ids,
colorscale: "YlGnBu"
}
}
];
var bubbleChartLayout = {
title: "Bacteria Cultures Per Sample",
margin: { t: 0 },
hovermode: "closest",
xaxis: { title: "OTU ID" },
margin: { t: 40 }
};
Plotly.newPlot("bubble", trace2, bubbleChartLayout);
});
}
function optionChanged(newSample) {
// Fetch new data each time a new sample is selected
buildCharts(newSample);
metadata(newSample);
}
|
var searchData=
[
['message_0',['message',['../classbadgerdb_1_1_badger_db_exception.html#af2e9da03ce798e35150adf74730068d5',1,'badgerdb::BadgerDbException']]],
['message_5f_1',['message_',['../classbadgerdb_1_1_badger_db_exception.html#a4510b66828c819004489218abeb1cf32',1,'badgerdb::BadgerDbException']]]
];
|
import { ADVANCE, LOAD_HISTORY_COMPLETE } from '../constants/actionTypes/booth';
const initialState = [];
const normalize = entry => ({
_id: entry._id || entry.historyID,
user: entry.user,
media: {
...entry.media.media,
...entry.media
},
timestamp: new Date(entry.timestamp || entry.playedAt).getTime(),
stats: entry.stats || {
upvotes: entry.upvotes || [],
downvotes: entry.downvotes || [],
favorites: entry.favorites || []
}
});
export default function reduce(state = initialState, action = {}) {
const { type, payload, meta } = action;
switch (type) {
case LOAD_HISTORY_COMPLETE:
return payload.map(normalize);
case ADVANCE: {
const mostRecent = state[0];
// If the currently playing track is already in the history, remove it--
// it'll be added back on the next advance, and will be handled by the
// roomHistorySelector in the mean time.
if (mostRecent && payload && mostRecent._id === payload.historyID) {
return state.slice(1);
}
if (!meta || !meta.previous) {
return state;
}
return [ normalize(meta.previous), ...state ];
}
default:
return state;
}
}
|
export default class Comparator {
static defaultCompareFunction (a, b) {
if(a === b){
return 0;
}
return a < b ? -1 : 1;
}
constructor(compareFunction) {
this.compare= compareFunction || Comparator.defaultCompareFunction;
}
equal(a, b){
return this.compare(a, b) === 0;
}
lessThan(a, b){
return this.compare(a, b) < 0;
}
greaterThan(a, b){
return this.compare(a, b) > 0;
}
lessThanOrEqual(a, b) {
return this.lessThan(a, b) || this.equal(a, b);
}
greaterThanOrEqual(a, b) {
return this.greaterThan(a, b) || this.equal(a, b);
}
};
|
import * as tslib_1 from "tslib";
import { r as registerInstance, d as createEvent, c as getIonMode, h, H as Host, e as getElement } from './chunk-09ec7fc0.js';
import './chunk-1074393c.js';
import { c as popoverController, b as actionSheetController, a as alertController, s as safeCall } from './chunk-d83bfeae.js';
import { h as hostContext } from './chunk-ba834eff.js';
import { f as findItemLabel, r as renderHiddenInput } from './chunk-c90aaa66.js';
/**
* @virtualProp {"ios" | "md"} mode - The mode determines which platform styles to use.
*/
var Select = /** @class */ (function () {
function Select(hostRef) {
var _this = this;
registerInstance(this, hostRef);
this.childOpts = [];
this.inputId = "ion-sel-" + selectIds++;
this.didInit = false;
this.isExpanded = false;
/**
* If `true`, the user cannot interact with the select.
*/
this.disabled = false;
/**
* The text to display on the cancel button.
*/
this.cancelText = 'Cancel';
/**
* The text to display on the ok button.
*/
this.okText = 'OK';
/**
* The name of the control, which is submitted with the form data.
*/
this.name = this.inputId;
/**
* If `true`, the select can accept multiple values.
*/
this.multiple = false;
/**
* The interface the select should use: `action-sheet`, `popover` or `alert`.
*/
this.interface = 'alert';
/**
* Any additional options that the `alert`, `action-sheet` or `popover` interface
* can take. See the [AlertController API docs](../../alert/AlertController/#create), the
* [ActionSheetController API docs](../../action-sheet/ActionSheetController/#create) and the
* [PopoverController API docs](../../popover/PopoverController/#create) for the
* create options for each interface.
*/
this.interfaceOptions = {};
this.onClick = function (ev) {
_this.setFocus();
_this.open(ev);
};
this.onFocus = function () {
_this.ionFocus.emit();
};
this.onBlur = function () {
_this.ionBlur.emit();
};
this.ionChange = createEvent(this, "ionChange", 7);
this.ionCancel = createEvent(this, "ionCancel", 7);
this.ionFocus = createEvent(this, "ionFocus", 7);
this.ionBlur = createEvent(this, "ionBlur", 7);
this.ionStyle = createEvent(this, "ionStyle", 7);
}
Select.prototype.disabledChanged = function () {
this.emitStyle();
};
Select.prototype.valueChanged = function () {
if (this.didInit) {
this.updateOptions();
this.ionChange.emit({
value: this.value,
});
this.emitStyle();
}
};
Select.prototype.selectOptionChanged = function () {
return tslib_1.__awaiter(this, void 0, void 0, function () {
return tslib_1.__generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.loadOptions()];
case 1:
_a.sent();
if (this.didInit) {
this.updateOptions();
this.updateOverlayOptions();
this.emitStyle();
/**
* In the event that options
* are not loaded at component load
* this ensures that any value that is
* set is properly rendered once
* options have been loaded
*/
if (this.value !== undefined) {
this.el.forceUpdate();
}
}
return [2 /*return*/];
}
});
});
};
Select.prototype.componentDidLoad = function () {
return tslib_1.__awaiter(this, void 0, void 0, function () {
var checked, checked;
return tslib_1.__generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.loadOptions()];
case 1:
_a.sent();
if (this.value === undefined) {
if (this.multiple) {
checked = this.childOpts.filter(function (o) { return o.selected; });
this.value = checked.map(function (o) { return o.value; });
}
else {
checked = this.childOpts.find(function (o) { return o.selected; });
if (checked) {
this.value = checked.value;
}
}
}
this.updateOptions();
this.emitStyle();
this.el.forceUpdate();
this.didInit = true;
return [2 /*return*/];
}
});
});
};
/**
* Open the select overlay. The overlay is either an alert, action sheet, or popover,
* depending on the `interface` property on the `ion-select`.
*
* @param event The user interface event that called the open.
*/
Select.prototype.open = function (event) {
return tslib_1.__awaiter(this, void 0, void 0, function () {
var overlay, _a;
var _this = this;
return tslib_1.__generator(this, function (_b) {
switch (_b.label) {
case 0:
if (this.disabled || this.isExpanded) {
return [2 /*return*/, undefined];
}
_a = this;
return [4 /*yield*/, this.createOverlay(event)];
case 1:
overlay = _a.overlay = _b.sent();
this.isExpanded = true;
overlay.onDidDismiss().then(function () {
_this.overlay = undefined;
_this.isExpanded = false;
_this.setFocus();
});
return [4 /*yield*/, overlay.present()];
case 2:
_b.sent();
return [2 /*return*/, overlay];
}
});
});
};
Select.prototype.createOverlay = function (ev) {
var selectInterface = this.interface;
if ((selectInterface === 'action-sheet' || selectInterface === 'popover') && this.multiple) {
console.warn("Select interface cannot be \"" + selectInterface + "\" with a multi-value select. Using the \"alert\" interface instead.");
selectInterface = 'alert';
}
if (selectInterface === 'popover' && !ev) {
console.warn('Select interface cannot be a "popover" without passing an event. Using the "alert" interface instead.');
selectInterface = 'alert';
}
if (selectInterface === 'popover') {
return this.openPopover(ev);
}
if (selectInterface === 'action-sheet') {
return this.openActionSheet();
}
return this.openAlert();
};
Select.prototype.updateOverlayOptions = function () {
if (!this.overlay) {
return;
}
var overlay = this.overlay;
switch (this.interface) {
case 'action-sheet':
overlay.buttons = this.createActionSheetButtons(this.childOpts);
break;
case 'popover':
var popover = overlay.querySelector('ion-select-popover');
if (popover) {
popover.options = this.createPopoverOptions(this.childOpts);
}
break;
default:
var inputType = (this.multiple ? 'checkbox' : 'radio');
overlay.inputs = this.createAlertInputs(this.childOpts, inputType);
break;
}
};
Select.prototype.createActionSheetButtons = function (data) {
var _this = this;
var actionSheetButtons = data.map(function (option) {
return {
role: (option.selected ? 'selected' : ''),
text: option.textContent,
handler: function () {
_this.value = option.value;
}
};
});
// Add "cancel" button
actionSheetButtons.push({
text: this.cancelText,
role: 'cancel',
handler: function () {
_this.ionCancel.emit();
}
});
return actionSheetButtons;
};
Select.prototype.createAlertInputs = function (data, inputType) {
return data.map(function (o) {
return {
type: inputType,
label: o.textContent,
value: o.value,
checked: o.selected,
disabled: o.disabled
};
});
};
Select.prototype.createPopoverOptions = function (data) {
var _this = this;
return data.map(function (o) {
return {
text: o.textContent,
value: o.value,
checked: o.selected,
disabled: o.disabled,
handler: function () {
_this.value = o.value;
_this.close();
}
};
});
};
Select.prototype.openPopover = function (ev) {
return tslib_1.__awaiter(this, void 0, void 0, function () {
var interfaceOptions, mode, popoverOpts;
return tslib_1.__generator(this, function (_a) {
interfaceOptions = this.interfaceOptions;
mode = getIonMode(this);
popoverOpts = Object.assign({ mode: mode }, interfaceOptions, { component: 'ion-select-popover', cssClass: ['select-popover', interfaceOptions.cssClass], event: ev, componentProps: {
header: interfaceOptions.header,
subHeader: interfaceOptions.subHeader,
message: interfaceOptions.message,
value: this.value,
options: this.createPopoverOptions(this.childOpts)
} });
return [2 /*return*/, popoverController.create(popoverOpts)];
});
});
};
Select.prototype.openActionSheet = function () {
return tslib_1.__awaiter(this, void 0, void 0, function () {
var mode, interfaceOptions, actionSheetOpts;
return tslib_1.__generator(this, function (_a) {
mode = getIonMode(this);
interfaceOptions = this.interfaceOptions;
actionSheetOpts = Object.assign({ mode: mode }, interfaceOptions, { buttons: this.createActionSheetButtons(this.childOpts), cssClass: ['select-action-sheet', interfaceOptions.cssClass] });
return [2 /*return*/, actionSheetController.create(actionSheetOpts)];
});
});
};
Select.prototype.openAlert = function () {
return tslib_1.__awaiter(this, void 0, void 0, function () {
var label, labelText, interfaceOptions, inputType, mode, alertOpts;
var _this = this;
return tslib_1.__generator(this, function (_a) {
label = this.getLabel();
labelText = (label) ? label.textContent : null;
interfaceOptions = this.interfaceOptions;
inputType = (this.multiple ? 'checkbox' : 'radio');
mode = getIonMode(this);
alertOpts = Object.assign({ mode: mode }, interfaceOptions, { header: interfaceOptions.header ? interfaceOptions.header : labelText, inputs: this.createAlertInputs(this.childOpts, inputType), buttons: [
{
text: this.cancelText,
role: 'cancel',
handler: function () {
_this.ionCancel.emit();
}
},
{
text: this.okText,
handler: function (selectedValues) {
_this.value = selectedValues;
}
}
], cssClass: ['select-alert', interfaceOptions.cssClass,
(this.multiple ? 'multiple-select-alert' : 'single-select-alert')] });
return [2 /*return*/, alertController.create(alertOpts)];
});
});
};
/**
* Close the select interface.
*/
Select.prototype.close = function () {
// TODO check !this.overlay || !this.isFocus()
if (!this.overlay) {
return Promise.resolve(false);
}
return this.overlay.dismiss();
};
Select.prototype.loadOptions = function () {
return tslib_1.__awaiter(this, void 0, void 0, function () {
var _a;
return tslib_1.__generator(this, function (_b) {
switch (_b.label) {
case 0:
_a = this;
return [4 /*yield*/, Promise.all(Array.from(this.el.querySelectorAll('ion-select-option')).map(function (o) { return o.componentOnReady(); }))];
case 1:
_a.childOpts = _b.sent();
return [2 /*return*/];
}
});
});
};
Select.prototype.updateOptions = function () {
// iterate all options, updating the selected prop
var canSelect = true;
for (var _i = 0, _a = this.childOpts; _i < _a.length; _i++) {
var selectOption = _a[_i];
var selected = canSelect && isOptionSelected(this.value, selectOption.value, this.compareWith);
selectOption.selected = selected;
// if current option is selected and select is single-option, we can't select
// any option more
if (selected && !this.multiple) {
canSelect = false;
}
}
};
Select.prototype.getLabel = function () {
return findItemLabel(this.el);
};
Select.prototype.hasValue = function () {
return this.getText() !== '';
};
Select.prototype.getText = function () {
var selectedText = this.selectedText;
if (selectedText != null && selectedText !== '') {
return selectedText;
}
return generateText(this.childOpts, this.value, this.compareWith);
};
Select.prototype.setFocus = function () {
if (this.buttonEl) {
this.buttonEl.focus();
}
};
Select.prototype.emitStyle = function () {
this.ionStyle.emit({
'interactive': true,
'select': true,
'has-placeholder': this.placeholder != null,
'has-value': this.hasValue(),
'interactive-disabled': this.disabled,
'select-disabled': this.disabled
});
};
Select.prototype.render = function () {
var _a;
var _this = this;
var _b = this, placeholder = _b.placeholder, name = _b.name, disabled = _b.disabled, isExpanded = _b.isExpanded, value = _b.value, el = _b.el;
var mode = getIonMode(this);
var labelId = this.inputId + '-lbl';
var label = findItemLabel(el);
if (label) {
label.id = labelId;
}
var addPlaceholderClass = false;
var selectText = this.getText();
if (selectText === '' && placeholder != null) {
selectText = placeholder;
addPlaceholderClass = true;
}
renderHiddenInput(true, el, name, parseValue(value), disabled);
var selectTextClasses = {
'select-text': true,
'select-placeholder': addPlaceholderClass
};
return (h(Host, { onClick: this.onClick, role: "combobox", "aria-haspopup": "dialog", "aria-disabled": disabled ? 'true' : null, "aria-expanded": "" + isExpanded, "aria-labelledby": labelId, class: (_a = {},
_a[mode] = true,
_a['in-item'] = hostContext('ion-item', el),
_a['select-disabled'] = disabled,
_a) }, h("div", { class: selectTextClasses }, selectText), h("div", { class: "select-icon", role: "presentation" }, h("div", { class: "select-icon-inner" })), h("button", { type: "button", onFocus: this.onFocus, onBlur: this.onBlur, disabled: disabled, ref: (function (btnEl) { return _this.buttonEl = btnEl; }) })));
};
Object.defineProperty(Select.prototype, "el", {
get: function () { return getElement(this); },
enumerable: true,
configurable: true
});
Object.defineProperty(Select, "watchers", {
get: function () {
return {
"disabled": ["disabledChanged"],
"value": ["valueChanged"]
};
},
enumerable: true,
configurable: true
});
Object.defineProperty(Select, "style", {
get: function () { return ":host{padding-left:var(--padding-start);padding-right:var(--padding-end);padding-top:var(--padding-top);padding-bottom:var(--padding-bottom);display:-ms-flexbox;display:flex;position:relative;font-family:var(--ion-font-family,inherit);overflow:hidden;z-index:2}\@supports ((-webkit-margin-start:0) or (margin-inline-start:0)) or (-webkit-margin-start:0){:host{padding-left:unset;padding-right:unset;-webkit-padding-start:var(--padding-start);padding-inline-start:var(--padding-start);-webkit-padding-end:var(--padding-end);padding-inline-end:var(--padding-end)}}:host(.in-item){position:static;max-width:45%}:host(.select-disabled){opacity:.4;pointer-events:none}:host(.ion-focused) button{border:2px solid #5e9ed6}.select-placeholder{color:currentColor;opacity:.33}button{left:0;top:0;margin-left:0;margin-right:0;margin-top:0;margin-bottom:0;position:absolute;width:100%;height:100%;border:0;background:transparent;cursor:pointer;-webkit-appearance:none;-moz-appearance:none;appearance:none;outline:none}:host-context([dir=rtl]) button,[dir=rtl] button{left:unset;right:unset;right:0}button::-moz-focus-inner{border:0}.select-icon{position:relative}.select-text{-ms-flex:1;flex:1;min-width:16px;font-size:inherit;text-overflow:ellipsis;white-space:nowrap;overflow:hidden}.select-icon-inner{left:5px;top:50%;margin-top:-3px;position:absolute;width:0;height:0;border-top:5px solid;border-right:5px solid transparent;border-left:5px solid transparent;color:currentColor;opacity:.33;pointer-events:none}:host-context([dir=rtl]) .select-icon-inner,[dir=rtl] .select-icon-inner{left:unset;right:unset;right:5px}:host{--padding-top:10px;--padding-end:8px;--padding-bottom:10px;--padding-start:16px}.select-icon{width:12px;height:18px}"; },
enumerable: true,
configurable: true
});
return Select;
}());
var parseValue = function (value) {
if (value == null) {
return undefined;
}
if (Array.isArray(value)) {
return value.join(',');
}
return value.toString();
};
var isOptionSelected = function (currentValue, compareValue, compareWith) {
if (currentValue === undefined) {
return false;
}
if (Array.isArray(currentValue)) {
return currentValue.some(function (val) { return compareOptions(val, compareValue, compareWith); });
}
else {
return compareOptions(currentValue, compareValue, compareWith);
}
};
var compareOptions = function (currentValue, compareValue, compareWith) {
if (typeof compareWith === 'function') {
return compareWith(currentValue, compareValue);
}
else if (typeof compareWith === 'string') {
return currentValue[compareWith] === compareValue[compareWith];
}
else {
return currentValue === compareValue;
}
};
var generateText = function (opts, value, compareWith) {
if (value === undefined) {
return '';
}
if (Array.isArray(value)) {
return value
.map(function (v) { return textForValue(opts, v, compareWith); })
.filter(function (opt) { return opt !== null; })
.join(', ');
}
else {
return textForValue(opts, value, compareWith) || '';
}
};
var textForValue = function (opts, value, compareWith) {
var selectOpt = opts.find(function (opt) {
return compareOptions(opt.value, value, compareWith);
});
return selectOpt
? selectOpt.textContent
: null;
};
var selectIds = 0;
var SelectOption = /** @class */ (function () {
function SelectOption(hostRef) {
registerInstance(this, hostRef);
this.inputId = "ion-selopt-" + selectOptionIds++;
/**
* If `true`, the user cannot interact with the select option.
*/
this.disabled = false;
/**
* If `true`, the element is selected.
*/
this.selected = false;
this.ionSelectOptionDidLoad = createEvent(this, "ionSelectOptionDidLoad", 7);
this.ionSelectOptionDidUnload = createEvent(this, "ionSelectOptionDidUnload", 7);
}
SelectOption.prototype.componentWillLoad = function () {
if (this.value === undefined) {
this.value = this.el.textContent || '';
}
};
SelectOption.prototype.componentDidLoad = function () {
this.ionSelectOptionDidLoad.emit();
};
SelectOption.prototype.componentDidUnload = function () {
this.ionSelectOptionDidUnload.emit();
};
SelectOption.prototype.hostData = function () {
var _a;
var mode = getIonMode(this);
return {
'role': 'option',
'id': this.inputId,
class: (_a = {},
_a[mode] = true,
_a)
};
};
Object.defineProperty(SelectOption.prototype, "el", {
get: function () { return getElement(this); },
enumerable: true,
configurable: true
});
SelectOption.prototype.render = function () { return h(Host, this.hostData()); };
Object.defineProperty(SelectOption, "style", {
get: function () { return ":host{display:none}"; },
enumerable: true,
configurable: true
});
return SelectOption;
}());
var selectOptionIds = 0;
/**
* @internal
*/
var SelectPopover = /** @class */ (function () {
function SelectPopover(hostRef) {
registerInstance(this, hostRef);
/** Array of options for the popover */
this.options = [];
}
SelectPopover.prototype.onSelect = function (ev) {
var option = this.options.find(function (o) { return o.value === ev.target.value; });
if (option) {
safeCall(option.handler);
}
};
SelectPopover.prototype.hostData = function () {
var _a;
var mode = getIonMode(this);
return {
class: (_a = {},
_a[mode] = true,
_a)
};
};
SelectPopover.prototype.__stencil_render = function () {
return (h("ion-list", null, this.header !== undefined && h("ion-list-header", null, this.header), (this.subHeader !== undefined || this.message !== undefined) &&
h("ion-item", null, h("ion-label", { "text-wrap": true }, this.subHeader !== undefined && h("h3", null, this.subHeader), this.message !== undefined && h("p", null, this.message))), h("ion-radio-group", null, this.options.map(function (option) { return h("ion-item", null, h("ion-label", null, option.text), h("ion-radio", { checked: option.checked, value: option.value, disabled: option.disabled })); }))));
};
SelectPopover.prototype.render = function () { return h(Host, this.hostData(), this.__stencil_render()); };
Object.defineProperty(SelectPopover, "style", {
get: function () { return ".sc-ion-select-popover-h ion-list.sc-ion-select-popover{margin-left:0;margin-right:0;margin-top:-1px;margin-bottom:-1px}.sc-ion-select-popover-h ion-label.sc-ion-select-popover, .sc-ion-select-popover-h ion-list-header.sc-ion-select-popover{margin-left:0;margin-right:0;margin-top:0;margin-bottom:0}"; },
enumerable: true,
configurable: true
});
return SelectPopover;
}());
export { Select as ion_select, SelectOption as ion_select_option, SelectPopover as ion_select_popover };
|
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import {
View,
StyleSheet,
Text,
TouchableOpacity,
} from 'react-native';
export default class NavBarButton extends Component {
render() {
const { location, text, color, icon, handleButtonPress } = this.props;
const marginPosition = location === 'right' ? { marginRight: 20 } : { marginLeft: 20 };
let content;
if (text) {
content = <Text style={[{ color }, marginPosition, styles.buttonText]}> {text}</Text>;
} else if (icon) {
content = <View style={marginPosition}>{icon}</View>;
}
return (
<TouchableOpacity onPress={handleButtonPress}>
{content}
</TouchableOpacity>
);
}
}
NavBarButton.propTypes = {
text: PropTypes.string,
icon: PropTypes.object,
handleButtonPress: PropTypes.func.isRequired,
location: PropTypes.string,
color: PropTypes.string,
};
const styles = StyleSheet.create({
buttonText: {
fontSize: 16,
},
});
|
import Compiler from './compiler';
export default function compile(ql, procs) {
return new Compiler(procs).compile(ql);
}
|
const {compareNumbers, compareText, chooseSortsCompareFn, defineCustomElement, TableComponent} = require('../src/wc-grid-table.js');
const {regexFilter, textFilter, compareFilter} = require('../src/filter-utils.js');
jest.mock('../src/wc-grid-table.css')
describe('compareNumbers', () => {
test('when first arg bigger then second return should be positive', () => {
expect(compareNumbers(23, 22)).toBeGreaterThan(0);
expect(compareNumbers(1.8, 0.9)).toBeGreaterThan(0);
expect(compareNumbers(100, -12)).toBeGreaterThan(0);
expect(compareNumbers(-32.9, -78)).toBeGreaterThan(0);
});
test('when first arg smaller then second should be negative', () => {
expect(compareNumbers(22, 23)).toBeLessThan(0);
expect(compareNumbers(0.2, 1)).toBeLessThan(0);
expect(compareNumbers(-12.65, 100.12)).toBeLessThan(0);
expect(compareNumbers(-198, -123)).toBeLessThan(0);
});
test('when equal, should return 0', () => {
expect(compareNumbers(22, 22)).toEqual(0);
expect(compareNumbers(0, 0)).toEqual(0);
expect(compareNumbers(-0.3, -0.3)).toEqual(0);
});
test('undefined values are supposed to always be "biggest"', () => {
expect(compareNumbers(undefined, 10.5)).toBeGreaterThan(0);
expect(compareNumbers(0, undefined)).toBeLessThan(0);
});
test('type mismatches should compare as usual, numerical', () => {
expect(compareNumbers(1, '02')).toBeLessThan(0);
expect(compareNumbers('0100', 100)).toEqual(0);
});
});
describe('compareText', () => {
test('when first arg "earlier" then second return should be positive', () => {
expect(compareText('001', '234')).toBeGreaterThan(0);
expect(compareText('test', 'zest')).toBeGreaterThan(0);
expect(compareText('', ' sa')).toBeGreaterThan(0);
expect(compareText('0', '78')).toBeGreaterThan(0);
});
test('when first arg "later" then second should be negative', () => {
expect(compareText('234', '001')).toBeLessThan(0);
expect(compareText('zest', 'test')).toBeLessThan(0);
expect(compareText('a', 'A')).toBeLessThan(0);
expect(compareText('198', '0')).toBeLessThan(0);
});
test('when equal, should return 0', () => {
expect(compareText('22', '22')).toEqual(0);
expect(compareText('test', 'test')).toEqual(0);
expect(compareText('', '')).toEqual(1);
});
test('undefined values are supposed to always be "biggest"', () => {
expect(compareText(undefined, 'test')).toBeGreaterThan(0);
expect(compareText(' ', undefined)).toBeLessThan(0);
});
test('type mismatches should compare as usual, alphabetic', () => {
expect(compareText(12, '012')).toBeLessThan(0);
expect(compareText([1, 2, 3], '1,2,3')).toEqual(0);
});
});
describe('regexFilter', () => {
test('basic examples', () => {
expect(regexFilter(false, '105', '00AA105GH00')).toBe(true);
expect(regexFilter(false, 'AA0', '00AA105GH00')).toBe(false);
expect(regexFilter(true, '105', '00AA105GH00')).toBe(false);
expect(regexFilter(true, 'AA0', '00AA105GH00')).toBe(true);
expect(regexFilter(false, 'GH00$', '00AA105GH00')).toBe(true);
expect(regexFilter(true, 'GH00$', '00AA105GH00')).toBe(false);
expect(regexFilter(false, '^00A', '00AA105GH00')).toBe(true);
expect(regexFilter(true, '^00A', '00AA105GH00')).toBe(false);
expect(regexFilter(false, '^0A', '00AA105GH00')).toBe(false);
expect(regexFilter(true, '^0A', '00AA105GH00')).toBe(true);
expect(regexFilter(true, '^00AA105GH00$', '00AA105GH00')).toBe(false);
expect(regexFilter(false, '^00AA105GH00$', '00AA105GH00')).toBe(true);
expect(regexFilter(true, '^00.*00$', '00AA105GH00')).toBe(false);
expect(regexFilter(false, '^00.*00$', '00AA105GH00')).toBe(true);
});
test('special cases', () => {
expect(regexFilter(false, '', '')).toBe(true);
expect(regexFilter(false, ' ', '')).toBe(false);
expect(regexFilter(false, '12', 12.66)).toBe(true);
// regex not escaped square bracket -> character class
expect(regexFilter(false, '[1,2,3,4]', [1, 2, 3, 4])).toBe(true);
// regex litteral square brackets; dont get rendered on Array.toString(); so it's removed in both args.
expect(regexFilter(false, '\[1,2,3,4\]', [1, 2, 3, 4])).toBe(true);
// regex escaped square brackets; dont get rendered on Array.toString()
expect(regexFilter(false, '\\[1,2,3,4\\]', [1, 2, 3, 4])).toBe(false);
expect(regexFilter(false, '1,2,3,4', [1, 2, 3, 4])).toBe(true);
})
test('RegExp special characters', () => {
expect(regexFilter(false, '00$', '00$')).toBe(false);
expect(regexFilter(false, '00\\$', '00$')).toBe(true);
});
});
describe('textFilter', () => {});
describe('compareFilter', () => {});
|
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { NavLink } from 'react-router-dom';
import {
Collapse,
Nav,
Navbar,
NavbarBrand,
NavbarToggler,
NavItem,
} from 'reactstrap';
class Navigation extends Component {
constructor(props) {
super(props);
this.toggle = this.toggle.bind(this);
this.state = {
isOpen: false,
};
}
toggle() {
this.setState({
isOpen: !this.state.isOpen,
});
}
render() {
return (
<Navbar color="light" light expand="md" className="sticky-top">
<NavbarToggler onClick={this.toggle} />
<NavbarBrand href="/">Home</NavbarBrand>
<Collapse isOpen={this.state.isOpen} navbar>
<Nav className="ml-auto" navbar>
<br></br>
<NavItem>
<NavLink
to="/news"
style={{ textDecoration: 'none' }}
onClick={this.toggle}
>
News Feed
</NavLink>
</NavItem>
<br></br>
{!this.props.isLoggedIn ? (
<Nav navbar>
<NavItem>
<NavLink
to="/signin"
style={{ textDecoration: 'none' }}
onClick={this.toggle}
>
Login
</NavLink>
</NavItem>
<br></br>
<NavItem>
<NavLink
to="/signup"
style={{ textDecoration: 'none' }}
onClick={this.toggle}
>
Sign Up
</NavLink>
</NavItem>
<br></br>
</Nav>
) : (
<Nav navbar>
<NavItem>
<NavLink
to="/notes"
style={{ textDecoration: 'none' }}
onClick={this.toggle}
>
Saved Stories
</NavLink>
</NavItem>
<br></br>
<NavItem>
<NavLink
to="/signout"
style={{ textDecoration: 'none' }}
onClick={this.toggle}
>
Sign Out
</NavLink>
</NavItem>
<br></br>
</Nav>
)}
</Nav>
</Collapse>
</Navbar>
);
}
}
const mapStateToProps = (state) => {
return { isLoggedIn: state.userReducer.isLoggedIn };
};
export default connect(mapStateToProps)(Navigation);
|
// scroll to top of the page
window.onbeforeunload = () => {
window.scrollTo(0, 0);
}
// fill/keep values in input fields (if they are in localStorage)
// listen for button clicks
window.onload = () => {
// show localStorage in input fields
populateValues();
// select all 'buttons'
const buttons = document.querySelectorAll('a');
// for each button, listen to on click event
// and execute function
buttons.forEach(button => {
button.onclick = onButtonClick;
})
};
// function to set items in to localStorage (with button click above)
const onButtonClick = (event) => {
// select the clicked button
const button = event.currentTarget;
// select the section in which that button is located
const section = button.parentElement;
// select all input fields inside that section
const inputs = section.querySelectorAll('input');
inputs.forEach(input => {
// if there's a value, then put it in localStorage
if (input.name)
localStorage.setItem(input.name, input.value);
})
};
// fill input fiels with values (if they are in localStorage)
const populateValues = () => {
// select all input fields on the page
const inputs = document.querySelectorAll('input');
inputs.forEach(input => {
// get the localStorage values
const item = localStorage.getItem(input.name)
// if there's an item, put it in the input field
if (item) input.value = item;
})
};
// form validation
// one for text, one for number
// because i don't want to select my buttons with input type=button
// form validation text
const inputText = document.querySelectorAll('input[type="text"]')
inputText.forEach(input => {
// listen for blur event (leave input field)
input.addEventListener('blur', (event) => {
// if empty, add error class
if (input.value === '' || input.value == null) {
input.classList.add('error')
// if not empty, remove error class & add valid class
} else {
input.classList.remove('error')
input.classList.add('valid')
}
})
})
// for validation number
const inputNumber = document.querySelectorAll('input[type="number"]')
inputNumber.forEach(input => {
// listen for blur event (leave input field)
input.addEventListener('blur', (event) => {
// if empty, add error class
if (input.value === '' || input.value == null) {
input.classList.add('error')
// if not empty, remove error class & add valid class
} else {
input.classList.remove('error')
input.classList.add('valid')
}
})
})
|
import React from 'react';
import PropTypes from 'prop-types';
import { isEqual } from 'lodash';
import { FormattedMessage } from 'react-intl';
import setFieldData from 'final-form-set-field-data';
import { composeValidators, handleSaveKeyCommand, requiredValidator } from '@folio/stripes-erm-components';
import { TitleManager } from '@folio/stripes/core';
import { Field } from 'react-final-form';
import {
Button,
HasCommand,
IconButton,
InfoPopover,
Layout,
Pane,
PaneFooter,
PaneMenu,
Paneset,
Row,
TextArea,
TextField,
checkScope,
collapseAllSections,
expandAllSections
} from '@folio/stripes/components';
import stripesFinalForm from '@folio/stripes/final-form';
import css from './UrlCustomizerForm.css';
class UrlCustomizerForm extends React.Component {
static propTypes = {
form: PropTypes.shape({
getRegisteredFields: PropTypes.func.isRequired,
}).isRequired,
handlers: PropTypes.PropTypes.shape({
onClose: PropTypes.func.isRequired,
}),
handleSubmit: PropTypes.func.isRequired,
pristine: PropTypes.bool,
submitting: PropTypes.bool,
values: PropTypes.object,
}
renderPaneFooter() {
const {
handlers,
handleSubmit,
pristine,
submitting,
values,
} = this.props;
return (
<PaneFooter
renderEnd={(
<Button
buttonStyle="primary mega"
disabled={pristine || submitting}
id={values.id ? 'clickable-update-url-customiser' : 'clickable-create-url-customiser'}
marginBottom0
onClick={handleSubmit}
type="submit"
>
<FormattedMessage id="stripes-components.saveAndClose" />
</Button>
)}
renderStart={(
<Button
buttonStyle="default mega"
id="clickable-cancel"
marginBottom0
onClick={handlers.onClose}
>
<FormattedMessage id="stripes-components.cancel" />
</Button>
)}
/>
);
}
renderFirstMenu() {
return (
<PaneMenu>
<FormattedMessage id="ui-agreements.platform.urlCustomizer.closeEdit">
{([ariaLabel]) => (
<IconButton
aria-label={ariaLabel}
icon="times"
id="close-url-customiser-form-button"
onClick={this.props.handlers.onClose}
/>
)}
</FormattedMessage>
</PaneMenu>
);
}
shortcuts = [
{
name: 'save',
handler: (e) => handleSaveKeyCommand(e, this.props),
},
{
name: 'expandAllSections',
handler: (e) => expandAllSections(e, this.accordionStatusRef),
},
{
name: 'collapseAllSections',
handler: (e) => collapseAllSections(e, this.accordionStatusRef),
}
];
render() {
const { form, values: { id, name } } = this.props;
const hasLoaded = form.getRegisteredFields().length > 0;
return (
<HasCommand
commands={this.shortcuts}
isWithinScope={checkScope}
scope={document.body}
>
<Paneset>
<FormattedMessage id="ui-agreements.create">
{create => (
<Pane
centerContent
defaultWidth="100%"
firstMenu={this.renderFirstMenu()}
footer={this.renderPaneFooter()}
id="pane-url-customizer-form"
paneTitle={id ? name : <FormattedMessage id="ui-agreements.platform.newUrlCustomization" />}
>
<TitleManager record={id ? name : create}>
<form id="form-url-customization">
{hasLoaded ? <div id="form-loaded" /> : null}
<Row>
<Field
component={TextField}
data-test-proxy-server-setting-name-edit
id="proxy-server-setting-name-edit"
label={<FormattedMessage id="ui-agreements.platform.urlCustomization.name" />}
name="name"
required
validate={composeValidators(
requiredValidator,
)}
/>
</Row>
<Row>
<Field
component={TextArea}
data-test-proxy-server-setting-url-customization-code
fullWidth
id="proxy-server-setting-url-customization-code"
label={
<>
<FormattedMessage id="ui-agreements.platform.urlCustomization.customizationCode" />
<InfoPopover
allowAnchorClick
buttonHref="https://wiki.folio.org/display/FOLIOtips/Proxy+server+configuration+and+URL+customizations"
buttonLabel={<FormattedMessage id="ui-agreements.platform.urlCustomizationCode.learnMore" />}
content={<FormattedMessage id="ui-agreements.platform.urlCustomizationCode.info" />}
contentClass={css.infoPopoverContent}
hideOnButtonClick
/>
</>
}
name="rule"
required
validate={requiredValidator}
/>
</Row>
<Row>
<Layout className="display-flex flex-direction-column padding-bottom-gutter">
<FormattedMessage id="ui-agreements.platform.urlCustomizationCode.variables" tagName="div" />
<FormattedMessage id="ui-agreements.platform.urlCustomizationCode.helpers" tagName="div" />
</Layout>
</Row>
</form>
</TitleManager>
</Pane>
)}
</FormattedMessage>
</Paneset>
</HasCommand>
);
}
}
export default stripesFinalForm({
initialValuesEqual: (a, b) => isEqual(a, b),
keepDirtyOnReinitialize: true,
subscription: {
values: true,
},
mutators: { setFieldData },
navigationCheck: true,
})(UrlCustomizerForm);
|
/* allow folding of complete cell, if IPython magic symbol "%" is in first line */
CodeMirror.registerHelper("fold", "magic", function(cm, start) {
var mode = cm.getMode(), Token = "%%";
if (start.line == 0) {
var lineText = cm.getLine(start.line);
var found = lineText.lastIndexOf(Token,0);
if (found == 0) {
end = cm.lastLine();
return {from: CodeMirror.Pos(start.line, null),
to: CodeMirror.Pos(end, null)};
}
}
return ;
});
|
const { VerificationToken, User } = require('../models');
module.exports = {
init(app) {
app.get('/api/users', async (req, res) => {
if (!req.user || req.user.role === 'none') {
return res.jsonp([]);
}
const conditions = {};
if (global.isProduction) {
conditions.verified = true;
}
const users = await User.find(conditions);
return res.jsonp(users.map(x => x.toJSON()));
});
app.get('/api/users/verify/:token', async (req, res) => {
try {
const result = await VerificationToken.verify(req.params.token);
const user = await User.findOne({ did: result.userDid });
if (!user) {
throw new Error('User not found');
}
user.emailVerified = true;
user.updatedAt = new Date();
await user.save();
logger.info('user.verify.success', req.params, result);
return res.json('verification success')
} catch (err) {
logger.error('user.verify.error', req.params);
res.status(400).send(err.message);
}
});
},
};
|
function Highlighter(paperEl, highlightClass="is-highlighted") {
function generateTree(node, idx=0) {
let state = {
el: node,
index: idx,
text: false,
size: 0,
children: []
};
const kids = Array.from(node.childNodes);
if (kids.length > 0) {
let idxRoll = idx;
let sizeRoll = 0;
for (let k = 0; k < kids.length; k++) {
let data = generateTree(kids[k], idxRoll);
state.children.push(data);
sizeRoll += data.size;
idxRoll += data.size;
}
state.size = sizeRoll;
} else {
state.index = idx;
state.text = node.textContent;
state.size = node.textContent.length;
// console.log(state.text, state.size)
}
return state;
}
function getNodesFromTree(node) {
// Only leaf nodes hold text
if (node.text) {
return [node];
} else {
const kids = node.children || [];
return kids.reduce((res, kid) => {
getNodesFromTree(kid).forEach((kn) => {
res.push(kn);
});
return res;
}, []);
}
}
function getTextFromTree(node) {
// Only leaf nodes hold text
if (node.text) {
return node.text;
} else {
const kids = node.children || [];
return kids.reduce((text, kid) => {
return text + getTextFromTree(kid);
}, "");
}
}
function sortHighlights(highlights) {
return highlights.sort((a, b) => {
if (a.start === b.start) {
const sizeA = a.end - a.start;
const sizeB = b.end - b.start;
return sizeA - sizeB;
} else {
return a.start - b.start;
}
});
}
function renderHighlights(hl, node, highlights) {
if (!Array.isArray(highlights)) {
highlights = [highlights]
}
highlights.forEach((h) => {hl.allHighlights.push(h)});
const tree = generateTree(node);
const sortedHighlights = sortHighlights(highlights);
recursiveRender(tree, sortedHighlights);
}
function recursiveRender(node, highlights) {
if (node.text) {
const trimmed = node.text.trim();
if (trimmed.length === 0) {
return;
}
// I might want to draw a span here
const startIdx = node.index;
const endIdx = startIdx + node.size;
const relevant = highlights.filter((h) => {
// Possible off-by-one errors
const startsIn = h.start >= startIdx && h.start <= endIdx;
const endsIn = h.end >= startIdx && h.end <= endIdx;
const containsIt = h.start < startIdx && h.end > endIdx;
return startsIn || endsIn || containsIt;
}).map((h) => {
// Possible off-by-one errors
const startNew = Math.max(startIdx, h.start);
const endNew = Math.min(endIdx, h.end);
return {
start: startNew,
end: endNew
};
}).sort((a, b) => {
const sizeA = a.end - a.start;
const sizeB = b.end - b.start;
return sizeB - sizeA;
});
if (relevant.length === 0) {
return;
}
const highMap = relevant.reduce((map, h) => {
if (!(h.start in map)) {
map[h.start] = {starts: 0, ends: 0};
}
if (!(h.end in map)) {
map[h.end] = {starts: 0, ends: 0};
}
map[h.start].starts++;
map[h.end].ends++;
return map;
}, {});
let html = ``;
let i;
for (i = 0; i <= node.text.length; i++) {
const site = highMap[startIdx + i] || {starts: 0, ends: 0};
if (site.starts > 0 || site.ends > 0) {
// console.log(startIdx + i, site);
}
for (let ki = 0; ki < site.starts; ki++) {
html += `<span class="${highlightClass}">`;
// html += `<span class="is-marker">|</span>`;
}
for (let ji = 0; ji < site.ends; ji++) {
html += `</span>`;
// html += `<span class="is-marker">|</span>`;
}
if (i < node.text.length) {
html += node.text[i];
}
}
// console.log("Finished on index:", startIdx + i)
const span = document.createElement("span");
span.innerHTML = html;
node.el.parentNode.insertBefore(span, node.el);
node.el.parentNode.removeChild(node.el);
} else {
const kids = node.children;
for (let k = 0; k < kids.length; k++) {
recursiveRender(kids[k], highlights);
}
}
}
function getTreeNodeByEl(node, el) {
if (node.el === el) {
return node;
} else {
if (node.children.length > 0) {
for (let i = 0; i < node.children.length; i++) {
const res = getTreeNodeByEl(node.children[i], el);
if (res) {
return res;
}
}
}
}
return false;
}
function getTreeNodeRangeByEl(node, startEl, endEl) {
const nodes = getNodesFromTree(node);
const res = [];
let searching = false;
for (let i = 0; i < nodes.length; i++) {
if (nodes[i].el === startEl) {
searching = true;
}
if (searching) {
res.push(nodes[i]);
}
if (nodes[i].el === endEl) {
searching = false;
}
}
return res;
}
function captureHighlight(tree) {
const sel = window.getSelection();
if (sel.type === "Range") {
const el = sel.anchorNode;
const node = getTreeNodeByEl(tree, el);
if (!node) {
console.error(node)
}
const range = sel.getRangeAt(0);
if (sel.rangeCount > 1) {
console.warn(`Range count = ${sel.rangeCount}.`);
}
const nodeRange = getTreeNodeRangeByEl(tree, range.startContainer, range.endContainer);
const text = nodeRange.map((pn, i) => {
let submsg = pn.text;
if (i === 0 && i === (nodeRange.length - 1)) {
submsg = pn.text.substring(range.startOffset, range.endOffset);
} else if (i === 0) {
submsg = pn.text.substring(range.startOffset);
} else if (i === (nodeRange.length - 1)) {
submsg = pn.text.substring(0, range.endOffset);
}
return submsg;
}).reduce((msg, pn, i) => {
return msg + pn;
}, "");
const start = node.index + sel.anchorOffset;
const end = start + text.length;
return {
el: el,
start: start,
end: end,
text: text,
timestamp: Date.now()
};
}
return false;
}
function shiftHighlights(origText, newText, highlights) {
const sortedHighlights = sortHighlights(highlights);
const total = Math.max(origText.length, newText.length);
let origChar;
let newChar;
let origIndex = 0;
let newIndex = 0;
for (let i = 0; i < total; i++) {
if (origIndex >= origText.length || newIndex >= newText.length) {
break;
}
origChar = origText[origIndex];
newChar = newText[newIndex];
if (origChar === newChar) {
origIndex++;
newIndex++;
} else {
origIndex++;
newIndex++;
sortedHighlights.forEach((h) => {
if (i >= h.start) {
h.start--;
}
if (i <= h.end) {
h.end--;
}
});
}
}
return sortedHighlights;
}
function removeHighlights(hl, targetEl) {
hl.allHighlights = [];
// Array.from(targetEl.querySelectorAll(".is-marker")).forEach((el) => {
// el.parentNode.removeChild(el);
// });
Array.from(targetEl.querySelectorAll(`.${highlightClass}`)).forEach((el) => {
const span = document.createElement("span");
span.textContent = el.textContent;
el.parentNode.insertBefore(span, el);
el.parentNode.removeChild(el);
});
}
function removeTooltips() {
Array.from(document.querySelectorAll(".is-tooltip") || []).forEach((el) => {
el.parentNode.removeChild(el);
});
}
function onHighlight(targetEl, callback) {
targetEl.onmouseup = targetEl.onkeyup = (e) => {
const newTree = generateTree(targetEl);
const high = captureHighlight(newTree);
if (high) {
removeTooltips();
const tooltip = document.createElement("div");
tooltip.classList.add("is-tooltip");
tooltip.textContent = "Highlight";
tooltip.style.top = `${e.layerY + 20}px`;
tooltip.style.left = `${e.layerX - 20}px`;
tooltip.addEventListener("click", (e) => {
// removeHighlights(paperEl);
// renderHighlights(targetEl, [high]);
removeTooltips();
callback(high);
});
document.body.appendChild(tooltip);
}
}
}
let hlState = {allHighlights: []};
let hl = {
renderHighlights: (highlights) => renderHighlights(hlState, paperEl, highlights),
removeHighlights: () => removeHighlights(hlState, paperEl),
onHighlight: (callback) => onHighlight(paperEl, callback),
getHighlights: () => hlState.allHighlights
};
return hl;
}
|
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _flatten2 = _interopRequireDefault(require("lodash/flatten"));
var _Entry = require("../../../valueObjects/Entry");
var _collections = require("../../../reducers/collections");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; var ownKeys = Object.keys(source); if (typeof Object.getOwnPropertySymbols === 'function') { ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) { return Object.getOwnPropertyDescriptor(source, sym).enumerable; })); } ownKeys.forEach(function (key) { _defineProperty(target, key, source[key]); }); } return target; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function getSlug(path) {
return path.split('/').pop().replace(/\.[^.]+$/, '');
}
class Algolia {
constructor(config) {
this.config = config;
if (config.get('applicationID') == null || config.get('apiKey') == null) {
throw 'The Algolia search integration needs the credentials (applicationID and apiKey) in the integration configuration.';
}
this.applicationID = config.get('applicationID');
this.apiKey = config.get('apiKey');
const prefix = config.get('indexPrefix');
this.indexPrefix = prefix ? "".concat(prefix, "-") : '';
this.searchURL = "https://".concat(this.applicationID, "-dsn.algolia.net/1");
this.entriesCache = {
collection: null,
page: null,
entries: []
};
}
requestHeaders() {
let headers = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
return _objectSpread({
'X-Algolia-API-Key': this.apiKey,
'X-Algolia-Application-Id': this.applicationID,
'Content-Type': 'application/json'
}, headers);
}
parseJsonResponse(response) {
return response.json().then(json => {
if (!response.ok) {
return Promise.reject(json);
}
return json;
});
}
urlFor(path, options) {
const params = [];
if (options.params) {
for (const key in options.params) {
params.push("".concat(key, "=").concat(encodeURIComponent(options.params[key])));
}
}
if (params.length) {
path += "?".concat(params.join('&'));
}
return path;
}
request(path) {
let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
const headers = this.requestHeaders(options.headers || {});
const url = this.urlFor(path, options);
return fetch(url, _objectSpread({}, options, {
headers
})).then(response => {
const contentType = response.headers.get('Content-Type');
if (contentType && contentType.match(/json/)) {
return this.parseJsonResponse(response);
}
return response.text();
});
}
search(collections, searchTerm, page) {
const searchCollections = collections.map(collection => ({
indexName: "".concat(this.indexPrefix).concat(collection),
params: "query=".concat(searchTerm, "&page=").concat(page)
}));
return this.request("".concat(this.searchURL, "/indexes/*/queries"), {
method: 'POST',
body: JSON.stringify({
requests: searchCollections
})
}).then(response => {
const entries = response.results.map((result, index) => result.hits.map(hit => {
const slug = getSlug(hit.path);
return (0, _Entry.createEntry)(collections[index], slug, hit.path, {
data: hit.data,
partial: true
});
}));
return {
entries: (0, _flatten2.default)(entries),
pagination: page
};
});
}
searchBy(field, collection, query) {
return this.request("".concat(this.searchURL, "/indexes/").concat(this.indexPrefix).concat(collection), {
params: {
restrictSearchableAttributes: field,
query
}
});
}
listEntries(collection, page) {
if (this.entriesCache.collection === collection && this.entriesCache.page === page) {
return Promise.resolve({
page: this.entriesCache.page,
entries: this.entriesCache.entries
});
} else {
return this.request("".concat(this.searchURL, "/indexes/").concat(this.indexPrefix).concat(collection.get('name')), {
params: {
page
}
}).then(response => {
const entries = response.hits.map(hit => {
const slug = (0, _collections.selectEntrySlug)(collection, hit.path);
return (0, _Entry.createEntry)(collection.get('name'), slug, hit.path, {
data: hit.data,
partial: true
});
});
this.entriesCache = {
collection,
pagination: response.page,
entries
};
return {
entries,
pagination: response.page
};
});
}
}
getEntry(collection, slug) {
return this.searchBy('slug', collection.get('name'), slug).then(response => {
const entry = response.hits.filter(hit => hit.slug === slug)[0];
return (0, _Entry.createEntry)(collection.get('name'), slug, entry.path, {
data: entry.data,
partial: true
});
});
}
}
exports.default = Algolia;
|
import React, { Component } from 'react'
import PropTypes from "prop-types"
import Img from "gatsby-image"
import EmblaCarouselReact from 'embla-carousel-react'
import { motion } from 'framer-motion'
import { IoIosArrowBack, IoIosArrowForward } from 'react-icons/io'
const duration = 0.75
const container = {
visible: {
transition: {
when: 'beforeChildren',
staggerChildren: 0.25,
delayChildren: duration,
},
},
}
const item = {
hidden: { y: 10, opacity: 0 },
visible: {
y: 0,
opacity: 1
},
}
class GalleryCarousel extends Component {
constructor(props) {
super(props);
this.state = {
images: props.images,
isLoading: true,
};
}
componentDidMount() {
this.setState({
isLoading: false
})
}
render() {
if (this.state.images.length > 1) {
return (
<>
{!this.state.isLoading ? (
<motion.section
variants={container}
initial="hidden"
animate="visible"
>
<div className="relative">
<EmblaCarouselReact
emblaRef={c => (this.embla = c)}
htmlTagName={`div`}
options={{
align: 'start',
slidesToScroll: 1,
draggable: true,
loop: true,
speed: 8
}}
className="embla-viewport"
>
<div className="max-w-full embla__container">
{this.state.images.map((image, index) =>
<motion.div
key={index}
variants={item}
transition="easeInOut"
className="block embla__slide embla__slide--gallery"
>
<Img
backgroundColor="#26486E"
fluid={image.fluid}
key={image.title}
alt={image.alt}
className="block w-full mb-px"
/>
<span className="absolute bottom-0 right-0 z-20 p-1 text-sm text-black bg-white">{('0' + (index + 1)).slice(-2)}</span>
</motion.div>
)}
</div>
</EmblaCarouselReact>
<motion.button
variants={item}
transition="easeInOut"
className="absolute top-0 left-0 z-10 p-1 font-serif text-4xl font-bold text-white appearance-none cursor-pointer bg-green focus:outline-none"
onClick={() => this.embla.scrollPrev()}
aria-label="Previous image"
>
<IoIosArrowBack />
</motion.button>
<motion.button
variants={item}
transition="easeInOut"
className="absolute top-0 right-0 z-10 p-1 font-serif text-4xl font-bold text-white appearance-none cursor-pointer bg-green focus:outline-none"
onClick={() => this.embla.scrollNext()}
aria-label="Next image"
>
<IoIosArrowForward />
</motion.button>
</div>
</motion.section>
) : (
<p>Loading images…</p>
)}
</>
)
}
else
return (
<>
{!this.state.isLoading ? (
<motion.section
variants={container}
initial="hidden"
animate="visible"
>
<div className="relative">
<EmblaCarouselReact
emblaRef={c => (this.embla = c)}
htmlTagName={`div`}
options={{
align: 'start',
slidesToScroll: 1,
draggable: false,
loop: true,
speed: 8
}}
className="embla-viewport"
>
<div className="max-w-full embla__container">
{this.state.images.map((image, index) =>
<motion.div
key={index}
variants={item}
transition="easeInOut"
className="block embla__slide embla__slide--gallery"
>
<Img
backgroundColor="#26486E"
fluid={image.fluid}
key={image.title}
alt={image.alt}
className="block w-full mb-px"
/>
</motion.div>
)}
</div>
</EmblaCarouselReact>
</div>
</motion.section>
) : (
<p>Loading images…</p>
)}
</>
)
}
}
GalleryCarousel.propTypes = {
images: PropTypes.array,
}
GalleryCarousel.defaultProps = {
images: [],
}
export default GalleryCarousel
|
// prefer default export if available
const preferDefault = m => m && m.default || m
exports.components = {
"component---src-pages-404-js": () => import("/Users/mrakharawit/Documents/Tests/cal_area/src/pages/404.js" /* webpackChunkName: "component---src-pages-404-js" */),
"component---src-pages-index-js": () => import("/Users/mrakharawit/Documents/Tests/cal_area/src/pages/index.js" /* webpackChunkName: "component---src-pages-index-js" */),
"component---src-pages-page-2-js": () => import("/Users/mrakharawit/Documents/Tests/cal_area/src/pages/page-2.js" /* webpackChunkName: "component---src-pages-page-2-js" */)
}
exports.data = () => import(/* webpackChunkName: "pages-manifest" */ "/Users/mrakharawit/Documents/Tests/cal_area/.cache/data.json")
|
var assert = require('assert');
var EmailObfuscator = require('../index.js');
var obfuse = new EmailObfuscator;
describe('obfuscate', function() {
describe('simple mail', function() {
it('should be obfuscated', function() {
email.random = function() { return 1 };
assert.equal(
email.obfuscate('example@example.com'),
'example<!-- @ -->@example<B>.</b>com'
);
});
it('should be obfuscated more', function() {
email.random = function() { return 0.1 };
assert.equal(
email.obfuscate('example@example.com'),
'example<!-- @ -->@example<B>.</b>com'
);
});
it('should be obfuscated with all rules', function() {
email.random = function() { return 0 };
assert.equal(
email.obfuscate('example@example.com'),
'<!-- @ -->e<!-- @ -->x<!-- @ -->a<!-- @ -->m<!-- @ -->p<!-- @ -->l<!-- @ -->e<!-- @ --><!-- @ -->@<!-- @ -->e<!-- @ -->x<!-- @ -->a<!-- @ -->m<!-- @ -->p<!-- @ -->l<!-- @ -->e<!-- @ --><B>.</b><!-- @ -->c<!-- @ -->o<!-- @ -->m'
);
});
});
});
|
export default {RadioBase: `import React from 'react';
import { Radio, withStyles } from '@evg-b/evg-ui';
const styles = {
base: {
display: 'flex',
flexWrap: 'wrap',
'&>*': {
margin: '5px'
}
}
}
const RadioBase = (props) => {
const { classes } = props
return (
<div className={classes.base}>
<Radio />
<Radio defaultChecked />
<Radio disabled />
</div>
)
}
export default withStyles(styles)(RadioBase)`,
RadioColor: `import React, { useState } from 'react';
import { Radio, withStyles } from '@evg-b/evg-ui';
const styles = {
base: {
display: 'flex',
flexWrap: 'wrap',
'&>*': {
margin: '5px'
}
}
}
const RadioColor = (props) => {
const { classes } = props
const [checkName, setCheckName] = useState('radio1')
const handleChange = (e) => {
setCheckName(e.target.name)
}
return (
<div className={classes.base}>
<Radio onChange={handleChange} checked={checkName === 'radio1'} name="radio1" color="default" />
<Radio onChange={handleChange} checked={checkName === 'radio2'} name="radio2" color="primary" />
<Radio onChange={handleChange} checked={checkName === 'radio3'} name="radio3" color="warn" />
<Radio onChange={handleChange} checked={checkName === 'radio4'} name="radio4" color="success" />
<Radio onChange={handleChange} checked={checkName === 'radio5'} name="radio5" color="fail" />
</div>
)
}
export default withStyles(styles)(RadioColor)`,
RadioSize: `import React from 'react';
import { Radio, withStyles } from '@evg-b/evg-ui';
const styles = {
base: {
'&>*': {
margin: '5px'
}
}
}
const RadioSize = (props) => {
const { classes } = props
return (
<div className={classes.base}>
<Radio size='small' color="primary" />
<Radio size='medium' color="primary" />
<Radio size='large' color="primary" />
<Radio size='extra' color="primary" />
</div>
)
}
export default withStyles(styles)(RadioSize)`,
}
|
(window.webpackJsonp=window.webpackJsonp||[]).push([[237],{3871:function(t,e,r){"use strict";r.r(e),r.d(e,"icon",(function(){return o}));r(6),r(7);var n=r(0);function l(){return(l=Object.assign||function(t){for(var e=1;e<arguments.length;e++){var r=arguments[e];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(t[n]=r[n])}return t}).apply(this,arguments)}function i(t,e){if(null==t)return{};var r,n,l=function(t,e){if(null==t)return{};var r,n,l={},i=Object.keys(t);for(n=0;n<i.length;n++)r=i[n],e.indexOf(r)>=0||(l[r]=t[r]);return l}(t,e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(t);for(n=0;n<i.length;n++)r=i[n],e.indexOf(r)>=0||Object.prototype.propertyIsEnumerable.call(t,r)&&(l[r]=t[r])}return l}var o=function(t){var e=t.title,r=t.titleId,o=i(t,["title","titleId"]);return n.createElement("svg",l({width:16,height:16,viewBox:"0 0 16 16",xmlns:"http://www.w3.org/2000/svg","aria-labelledby":r},o),e?n.createElement("title",{id:r},e):null,n.createElement("path",{d:"M2.21 4.008H13.76V0h1v4.008h.088c.619 0 1.122.504 1.122 1.123V7.49c0 .62-.503 1.122-1.122 1.122H1.122A1.122 1.122 0 010 7.49V5.13c0-.618.503-1.122 1.122-1.122h.089V0h1v4.008zm11.549 1H1.12A.123.123 0 001 5.13V7.49c0 .068.055.122.122.122h13.725a.122.122 0 00.122-.122V5.13a.123.123 0 00-.122-.122h-1.088zm-5.301 9.097l2.405-2.26.686.728-3.58 3.363-3.58-3.363.686-.728 2.383 2.24V9.577h1v4.528z"}))}}}]);
//# sourceMappingURL=icon.logstash_output-js.min.js.map
|
/**
* @license Copyright (c) 2003-2022, CKSource - Holding sp. z o.o. All rights reserved.
* For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
*/
import CharacterGridView from '../../src/ui/charactergridview';
import ViewCollection from '@ckeditor/ckeditor5-ui/src/viewcollection';
import ButtonView from '@ckeditor/ckeditor5-ui/src/button/buttonview';
import testUtils from '@ckeditor/ckeditor5-core/tests/_utils/utils';
describe( 'CharacterGridView', () => {
let view;
testUtils.createSinonSandbox();
beforeEach( () => {
view = new CharacterGridView();
view.render();
} );
afterEach( () => {
view.destroy();
} );
describe( 'constructor()', () => {
it( 'creates view#tiles collection', () => {
expect( view.tiles ).to.be.instanceOf( ViewCollection );
} );
it( 'creates #element from template', () => {
const tile = view.createTile( 'ε', 'foo bar baz' );
const tilesElement = view.element.firstChild;
view.tiles.add( tile );
expect( view.element.classList.contains( 'ck' ) ).to.be.true;
expect( view.element.classList.contains( 'ck-character-grid' ) ).to.be.true;
expect( tilesElement.classList.contains( 'ck' ) ).to.be.true;
expect( tilesElement.classList.contains( 'ck-character-grid__tiles' ) ).to.be.true;
expect( tile.element.parentNode ).to.equal( tilesElement );
} );
} );
describe( 'createTile()', () => {
it( 'creates a new tile button', () => {
const tile = view.createTile( 'ε', 'foo bar baz' );
expect( tile ).to.be.instanceOf( ButtonView );
expect( tile.label ).to.equal( 'ε' );
expect( tile.withText ).to.be.true;
expect( tile.class ).to.equal( 'ck-character-grid__tile' );
} );
it( 'delegates #execute from the tile to the grid', () => {
const tile = view.createTile( 'ε', 'foo bar baz' );
const spy = sinon.spy();
view.on( 'execute', spy );
tile.fire( 'execute' );
sinon.assert.calledOnce( spy );
sinon.assert.calledWithExactly( spy, sinon.match.any, { name: 'foo bar baz', character: 'ε' } );
} );
it( 'delegates #tileHover from the tile to the grid on hover the tile', () => {
const tile = view.createTile( 'ε', 'foo bar baz' );
const spy = sinon.spy();
view.on( 'tileHover', spy );
tile.fire( 'mouseover' );
sinon.assert.calledOnce( spy );
sinon.assert.calledWithExactly( spy, sinon.match.any, { name: 'foo bar baz', character: 'ε' } );
} );
} );
} );
|
UI.listbox = function(x,y,w,h){
var me = UI.element(x,y,w,h,true);
me.selectedIndex = 0;
var previousSelectedIndex = 0;
var font = window.fontMed;
var items = [];
var visibleIndex = 0;
var visibleIitems = 0;
var lineHeight = 18;
var startY = 10;
var scrollBarItemOffset = 0;
var properties = ["left","top","width","height","name","type","onChange","selectedIndex","centerSelection"];
me.setProperties = function(p){
properties.forEach(function(key){
if (typeof p[key] != "undefined") me[key] = p[key];
});
me.setSize(me.width,me.height);
me.setPosition(me.left,me.top);
background.setSize(me.width,me.height);
setScrollBarPosition();
buttonUp.setProperties({
left: me.width - 18,
top: 2,
width: 16,
height: 16,
label:"↑"
});
buttonDown.setProperties({
left: me.width - 18,
top: me.height - 19,
width: 16,
height: 16,
label:"↓"
});
if (me.centerSelection){
startY = Math.ceil((me.height - lineHeight)/2);
}
};
me.setSelectedIndex = function(index,internal){
me.selectedIndex = index;
if (me.centerSelection) visibleIndex = me.selectedIndex;
me.refresh();
if (!internal && me.onChange && previousSelectedIndex!=me.selectedIndex) me.onChange();
previousSelectedIndex = me.selectedIndex;
};
me.getSelectedIndex = function(){
return me.selectedIndex;
};
var background = UI.scale9Panel(0,0,me.width,me.height,{
img: Y.getImage("panel_dark"),
left:3,
top:3,
right:2,
bottom: 2
});
background.ignoreEvents = true;
me.addChild(background);
var buttonUp = UI.Assets.generate("button20_20");
me.addChild(buttonUp);
buttonUp.onClick = function(){
me.navigateUp();
};
var buttonDown = UI.Assets.generate("button20_20");
me.addChild(buttonDown);
buttonDown.onClick = function(){
me.navigateDown();
};
var scrollBar = UI.scale9Panel(w-28,18,16,h-3,{
img: Y.getImage("bar"),
left:2,
top:2,
right:3,
bottom: 3
});
scrollBar.onDragStart=function(){
scrollBar.startDragIndex = visibleIndex;
};
scrollBar.onDrag=function(touchData){
if (items.length>visibleIitems && scrollBarItemOffset){
var delta = touchData.dragY - touchData.startY;
visibleIndex = Math.floor(scrollBar.startDragIndex + delta/scrollBarItemOffset);
visibleIndex = Math.min(visibleIndex,getMaxIndex());
visibleIndex = Math.max(visibleIndex,0);
setScrollBarPosition();
if (me.centerSelection) {
me.setSelectedIndex(visibleIndex);
}
}
};
me.addChild(scrollBar);
me.navigateUp = function(){
if (visibleIndex>0){
visibleIndex--;
setScrollBarPosition();
}
if (me.centerSelection) {
me.setSelectedIndex(visibleIndex);
}else{
me.refresh();
}
};
me.navigateDown = function(){
if (visibleIndex<getMaxIndex()){
visibleIndex++;
setScrollBarPosition();
}
if (me.centerSelection) {
me.setSelectedIndex(visibleIndex);
}else{
me.refresh();
}
};
me.render = function(internal){
internal = !!internal;
if (!me.isVisible()) return;
if (this.needsRendering){
background.render();
var line = Y.getImage("line_hor");
for (var i = 0, len = items.length;i<len;i++){
var item = items[i];
var textX = 10;
var indent = 10;
var textY = startY + ((i-visibleIndex)*lineHeight);
if ((textY>0) && (textY<me.height)){
var targetCtx = me.ctx;
var _y = textY;
var clip = textY>=me.height-lineHeight;
var itemCanvas;
if(clip){
var lastItemHeight = me.height-textY-2;
if (lastItemHeight>1){
itemCanvas = document.createElement("canvas");
itemCanvas.width = me.width-2;
itemCanvas.height = lastItemHeight;
targetCtx = itemCanvas.getContext("2d");
_y = 0;
}else {
targetCtx = undefined;
}
}
if (targetCtx){
if (me.selectedIndex === i){
targetCtx.fillStyle = 'rgba(100,100,255,0.1';
targetCtx.fillRect(0,_y-4,me.width-2,lineHeight);
}
if (item.level) textX += item.level*indent;
if (item.icon){
targetCtx.drawImage(item.icon,textX,_y-2);
textX += item.icon.width + 4;
}
if (font) font.write(targetCtx,item.label,textX,_y,0);
textY += 11;
_y += 11;
if (line) targetCtx.drawImage(line,0,_y,me.width-2,2);
if(clip){
me.ctx.drawImage(itemCanvas,0,textY-11);
}
}
}
}
scrollBar.render();
buttonUp.render();
buttonDown.render();
}
this.needsRendering = false;
if (internal){
return me.canvas;
}else{
me.parentCtx.drawImage(me.canvas,me.left,me.top,me.width,me.height);
}
};
me.setItems = function(newItems){
items = newItems;
visibleIndex = Math.min(visibleIndex,getMaxIndex()+1);
setScrollBarPosition();
me.refresh();
};
me.getItems = function(){
return items;
};
me.getItemAtPosition = function(x,y){
y = y-startY;
var index = Math.floor(y/lineHeight) + visibleIndex;
if (index>=0 && index<items.length){
return(items[index]);
}else{
return undefined;
}
};
me.insertItemAfterIndex = function(newItem,index,indent){
};
function setScrollBarPosition(){
var max = items.length;
visibleIitems = Math.floor(me.height/lineHeight);
if (me.centerSelection){visibleIitems = 1;}
var startTop = 18;
var top = startTop;
var startHeight = me.height - 4 - 32;
var height = startHeight;
scrollBarItemOffset = 0;
if (max>visibleIitems){
height = Math.floor((visibleIitems / max) * startHeight);
if (height<12) height = 12;
scrollBarItemOffset = (startHeight - height) / (max-visibleIitems);
}
if (visibleIndex && scrollBarItemOffset){
top = Math.floor(startTop + scrollBarItemOffset*visibleIndex);
}
scrollBar.setProperties({
left: me.width - 18,
top: top,
width: 16,
height: height
});
}
me.onMouseWheel = function(touchData){
if (touchData.mouseWheels[0] > 0){
me.navigateUp();
}else{
me.navigateDown();
}
};
me.onDragStart = function(touchData){
me.startDragIndex = visibleIndex;
};
me.onDrag = function(touchData){
if (items.length>visibleIitems){
var delta = Math.round((touchData.dragY - touchData.startY)/lineHeight);
visibleIndex = me.startDragIndex - delta;
visibleIndex = Math.max(visibleIndex,0);
visibleIndex = Math.min(visibleIndex,getMaxIndex());
if (me.centerSelection) {
me.setSelectedIndex(visibleIndex);
}
setScrollBarPosition();
}
};
function getMaxIndex(){
var max = items.length-1;
if (!me.centerSelection) {
max = items.length-visibleIitems;
}
if (max<0) max=0;
return max;
}
return me;
};
|
import * as _util from './util';
// chapters 05 and 07
export const util = _util;
// chapter 03
export { default as StackArray } from './data-structures/stack-array';
export { default as Stack } from './data-structures/stack';
export { hanoi } from './others/hanoi';
export { hanoiStack } from './others/hanoi';
export { baseConverter } from './others/base-converter';
export { decimalToBinary } from './others/base-converter';
export { parenthesesChecker } from './others/balanced-symbols';
// chapter 04
export { default as Queue } from './data-structures/queue';
export { default as Deque } from './data-structures/deque';
export { hotPotato } from './others/hot-potato';
export { palindromeChecker } from './others/palindrome-checker';
// chapter 05
export { default as LinkedList } from './data-structures/linked-list';
export { default as DoublyLinkedList } from './data-structures/doubly-linked-list';
export { default as CircularLinkedList } from './data-structures/circular-linked-list';
export { default as SortedLinkedList } from './data-structures/sorted-linked-list';
export { default as StackLinkedList } from './data-structures/stack-linked-list';
// chapter 06
export { default as Set } from './data-structures/set';
// chapter 07
export { default as Dictionary } from './data-structures/dictionary';
export { default as HashTable } from './data-structures/hash-table';
export { default as HashTableSeparateChaining } from './data-structures/hash-table-separate-chaining';
export { default as HashTableLinearProbing } from './data-structures/hash-table-linear-probing';
export { default as HashTableLinearProbingLazy } from './data-structures/hash-table-linear-probing-lazy';
// chapter 08
export { factorialIterative } from './others/factorial';
export { factorial } from './others/factorial';
export { fibonacci } from './others/fibonacci';
export { fibonacciIterative } from './others/fibonacci';
export { fibonacciMemoization } from './others/fibonacci';
// chapter 09
export { default as BinarySearchTree } from './data-structures/binary-search-tree';
export { default as AVLTree } from './data-structures/avl-tree';
// chapter 10
export { MinHeap } from './data-structures/heap';
export { MaxHeap } from './data-structures/heap';
export { default as heapSort } from './algorithms/sorting/heap-sort';
// chapter 11
export { default as Graph } from './data-structures/graph';
export { breadthFirstSearch } from './algorithms/graph/breadth-first-search';
export { BFS } from './algorithms/graph/breadth-first-search';
export { depthFirstSearch } from './algorithms/graph/depth-first-search';
export { DFS } from './algorithms/graph/depth-first-search';
export { dijkstra } from './algorithms/graph/dijkstra';
export { floydWarshall } from './algorithms/graph/floyd-warshall';
export { prim } from './algorithms/graph/prim';
export { kruskal } from './algorithms/graph/kruskal';
// chapter 12
export { shuffle } from './algorithms/shuffle/fisher -yates';
export { bubbleSort } from './algorithms/sorting/bubble-sort';
export { modifiedBubbleSort } from './algorithms/sorting/bubble-sort-improved';
export { bucketSort } from './algorithms/sorting/bucket-sort';
export { countingSort } from './algorithms/sorting/counting-sort';
export { insertionSort } from './algorithms/sorting/insertion-sort';
export { mergeSort } from './algorithms/sorting/merge-sort';
export { quickSort } from './algorithms/sorting/quicksort';
export { radixSort } from './algorithms/sorting/radix-sort';
export { selectionSort } from './algorithms/sorting/selection-sort';
export { shellSort } from './algorithms/sorting/shell-sort';
export { binarySearch } from './algorithms/search/binary-search';
export { interpolationSearch } from './algorithms/search/interpolation-search';
export { sequentialSearch } from './algorithms/search/sequential-search';
export { findMaxValue } from './algorithms/search/min-max-search';
export { findMinValue } from './algorithms/search/min-max-search';
// chapter 14
export { binarySearch as binarySearchRecursive } from './algorithms/search/binary-search-recursive';
export { minCoinChange } from './algorithms/dynamic-programing/min-coin-change';
export { minCoinChange as minCoinChangeGreedy } from './algorithms/greedy/min-coin-change';
export { knapSack } from './algorithms/dynamic-programing/knapsack';
export { knapSack as knapSackRecursive } from './algorithms/dynamic-programing/knapsack-recursive';
export { knapSack as knapSackGreedy } from './algorithms/greedy/knapsack';
export { lcs } from './algorithms/dynamic-programing/longest-common-subsequence';
export { lcs as lcsPrint } from './algorithms/dynamic-programing/longest-common-subsequence-print';
export { lcs as lcsRecursive } from './algorithms/greedy/longest-common-subsequence';
export { matrixChainOrder } from './algorithms/dynamic-programing/matrix-chain-multiplication';
export { matrixChainOrder as matrixChainOrderGreedy } from './algorithms/greedy/matrix-chain-multiplication';
export { ratInAMaze } from './algorithms/backtracking/rat-in-maze';
export { sudokuSolver } from './algorithms/backtracking/sudoku-solver';
|
/**
* First we will load all of this project's JavaScript dependencies which
* includes Vue and other libraries. It is a great starting point when
* building robust, powerful web applications using Vue and Laravel.
*/
require('./bootstrap');
//window.Vue = require('vue');
import Vue from 'vue'
/**
* The following block of code may be used to automatically register your
* Vue components. It will recursively scan this directory for the Vue
* components and automatically register them with their "basename".
*
* Eg. ./components/ExampleComponent.vue -> <example-component></example-component>
*/
// const files = require.context('./', true, /\.vue$/i)
// files.keys().map(key => Vue.component(key.split('/').pop().split('.')[0], files(key).default))
Vue.component('example-component', require('./components/ExampleComponent.vue').default);
Vue.component('instant-search', require('./components/InstantSearch.vue').default);
/**
* Next, we will create a fresh Vue application instance and attach it to
* the page. Then, you may begin adding components to this application
* or customize the JavaScript scaffolding to fit your unique needs.
*/
const app = new Vue({
el: '#app',
created() {
//
},
mounted() {
//
},
});
|
import React, {PureComponent} from 'react';
import {connect} from 'react-redux';
import moment from 'moment';
import {createEvent, createEventFail} from '../../action';
import Card, {CardContent, CardActions} from 'material-ui/Card';
import IconButton from 'material-ui/IconButton';
import AddIcon from 'material-ui-icons/Add';
import Typography from 'material-ui/Typography';
import TextField from 'material-ui/TextField';
class EventCreate extends PureComponent {
resetInput () {
this.nameInput.value = '';
this.codeInput.value = '';
this.fromInput.value = '';
this.toInput.value = '';
}
handleCreateEvent() {
const name = this.nameInput.value;
const code = this.codeInput.value;
const from = this.fromInput.value;
const to = this.toInput.value;
if (name && code && from && to) {
this.props.createEvent({name, code, from, to});
this.resetInput();
} else {
this.props.createEventFail({
message: 'Event must has Name, Code, Start/End Date'
});
}
}
render() {
return (
<div className="event-create">
<Card>
<CardContent className="column-layout">
<Typography gutterBottom variant="subheading">
Create Event
</Typography>
<TextField
id="name"
label="Name"
autoFocus
required
inputRef={field => {this.nameInput = field}}
/>
<TextField
id="code"
label="Code"
required
inputRef={field => {this.codeInput = field}}
/>
<br/>
<TextField
id="from"
label="Start Event"
type="datetime-local"
required
InputLabelProps={{
shrink: true,
}}
defaultValue={`${moment().format('YYYY-MM-DDTHH:mm')}`}
inputRef={field => {this.fromInput = field}}
/>
<TextField
id="to"
label="End Event"
type="datetime-local"
required
InputLabelProps={{
shrink: true,
}}
defaultValue={`${moment().add(1, 'days').format('YYYY-MM-DDTHH:mm')}`}
inputRef={field => {this.toInput = field}}
/>
</CardContent>
<CardActions>
<IconButton className="add-button" variant="fab" aria-label="add" color="primary" onClick={this.handleCreateEvent.bind(this)}>
<AddIcon />
</IconButton>
</CardActions>
</Card>
</div>
);
}
}
export default connect(
({isLoading}) => ({isLoading}),
{createEvent, createEventFail}
)(EventCreate);
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.