code
stringlengths
2
1.05M
$(function() { $(window).on('scroll', function() { if ($(this).scrollTop() > 460) { $('#scroll-social-btn').addClass('d-fixed'); } else { $('#scroll-social-btn').removeClass('d-fixed'); } }); });
var responses = [ 'As I see it, yes.', 'It is certain.', 'It is decidedly so.', 'Most likely.', 'Outlook good.', 'Signs point to yes.', 'Without a doubt.', 'Yes.', 'Yes — definitely.', 'You may rely on it.', 'Reply hazy. Try again.', 'Ask again later.', 'Better not tell you now.', 'Cannot predict now.', 'Concentrate and ask again.', 'Don\'t count on it.', 'My reply is no.', 'My sources say no.', 'Outlook not so good.', 'Very doubtful.' ]; module.exports = function(bot){ var l = responses.length; bot.addCommand('8ball', 'Answers your question', '[<question>]', USER_LEVEL_NORMAL, false, function(event){ var response = responses[Math.floor(Math.random()*(l-1))]; bot.message(event.target, event.source.nick + ': ' + response); }); }
//支持md5或扩展名称 var through = require("through2"); var path = require("path"); var gutil = require("gulp-util"); var PluginError = gutil.PluginError; var crypto = require('crypto'); var fs = require("fs"); var pluginName = 'gulp-jmbuild-rename'; var cache = require('./cache'); //给文件生成md5路径后缀 exports.md5 = function(opt) { opt = opt || {}; var stream = through.obj(function (file, enc, cb) { if (!file) { this.emit("error", new PluginError(pluginName, "files can not be empty")); return cb(); } else if (file.isNull()) { return cb(); } else { calcMd5(file, opt, function(md5Hash) { if(md5Hash) { var size = opt.size || 8; //截取指定长度的md5码 if(size > 0 && size < md5Hash.length) md5Hash = md5Hash.slice(0, size); var key = file.path; if (file.path[0] == '.') { key = path.join(file.base, file.path); } //在文件名后缀前加上md5 file.path = createMd5Path(key, md5Hash, (opt.separator || '.'), opt);//path.join(dir, basename + (opt.separator || '.') + md5Hash + ext); //缓存当前md5信息 var info = { "path": file.path, "md5": md5Hash }; cache.setCache(key, info); } stream.push(file); cb(); }); } }); return stream; } //生成文件md5码 function calcMd5(file, opt, callback) { if(typeof opt == 'function') { callback = opt; opt = {}; } var md5 = crypto.createHash('md5'); //如果是流,则以流的方式处理 if(file.isStream && file.isStream()) { var s = fs.createReadStream(file.path, {flags:'r'}); s.on('error', function(){ callback && callback(); }); //s.on('data', md5.update.bind(md5)); s.on('data', function(d){ md5.update(d); }); s.on('end', function () { var hex = md5.digest('hex'); callback && callback(hex); }); } else { md5.update(file.contents || file, 'utf8'); var hex = md5.digest('hex'); callback && callback(hex); return hex; } } exports.calcMd5 = calcMd5; //初始化更名,收集当前文件集的路径集合,以备多文件合并后的映射 exports.initSource = function() { var stream = through.obj(function (file, enc, cb) { if (!file) { this.emit("error", new PluginError(pluginName, "files can not be empty")); return cb(); } var sources = cache.getInfo('source_list') || []; var p = file.path; if (p[0] == '.') { p = path.join(file.base, file.path); } sources.push(p); //console.log('initSource'); //console.log(p); cache.setCache('source_list', sources); this.push(file); cb(); }); return stream; } //结束收集文件名集合,写入缓存 exports.endSource = function() { var stream = through.obj(function (file, enc, cb) { if (!file) { this.emit("error", new PluginError(pluginName, "files can not be empty")); return cb(); } var sources = cache.getInfo('source_list') if(sources) { var info = cache.getInfo(file.path)||{}; for(var i=0;i<sources.length;i++) { var key = sources[i]; var tmpinfo = {"path": key, "md5": info.md5, "id": info.id} //缓存当前md5信息 tmpinfo.dest = file.path; cache.setCache(key, tmpinfo); } //console.log('endSource'); //console.log(file.path); //重置 cache.setCache('source_list', []); } this.push(file); cb(); }); return stream; } //给文件名加扩展 exports.expandName = function(opt) { opt = opt || {}; var stream = through.obj(function (file, enc, cb) { if (!file) { this.emit("error", new PluginError(pluginName, "files can not be empty")); return cb(); } else if (file.isNull()) { return cb(); } else { if(opt.expand) { //在文件名加上扩展 var ext = path.extname(file.path); var basename = path.basename(file.path, ext); file.path = path.join(path.dirname(file.path), basename+opt.separator+opt.expand+ext).replace(/\\/g,'/'); } this.push(file); cb(); } }); return stream; } //给文件更名,如果有md5则加上,或有扩展名,也加上 exports.changeFileName = function(opt) { opt = opt || {}; var stream = through.obj(function (file, enc, cb) { if (!file) { this.emit("error", new PluginError(pluginName, "files can not be empty")); return cb(); } else if (file.isNull()) { return cb(); } else { if(opt.md5) { calcMd5(file, opt, function(md5Hash) { if(md5Hash) { var size = opt.size || 8; //截取指定长度的md5码 if(size > 0 && size < md5Hash.length) md5Hash = md5Hash.slice(0, size); } var key = file.path; if (file.path[0] == '.') { key = path.join(file.base, file.path); } //在文件名后缀前加上md5 file.path = createMd5Path(key, md5Hash, (opt.separator || '.'), opt.expand, opt); //缓存当前md5信息 var info = { "path": file.path, "md5": md5Hash }; cache.setCache(key, info); stream.push(file); cb(); }); } else { if(opt.expand) { file.path = createMd5Path(file.path, '', (opt.separator || '.'), opt.expand, opt); } stream.push(file); cb(); } } }); return stream; } //据md5生成路径 function createMd5Path(oldpath, md5, separator, expand, opt) { var ext = path.extname(oldpath); var basename = path.basename(oldpath, ext); if(expand) ext = separator + expand + ext; if(md5) { //如果指定了md5合的的方式,则使用配置的函数来处理 if(opt && typeof opt.md5 == 'function') { ext = opt.md5(ext, md5); } else { ext = separator + md5 + ext; } } return path.join(path.dirname(oldpath), basename + ext).replace(/\\/g,'/'); }
(function () { "use strict"; var mediaPlayer = null; var midrollAd = new PlayerFramework.Advertising.MidrollAdvertisement(); midrollAd.source = new Microsoft.PlayerFramework.Js.Advertising.RemoteAdSource(); midrollAd.source.type = Microsoft.Media.Advertising.VastAdPayloadHandler.adType; midrollAd.source.uri = new Windows.Foundation.Uri("http://smf.blob.core.windows.net/samples/win8/ads/vast_linear_nonlinear.xml"); midrollAd.time = 5; WinJS.UI.Pages.define("/pages/advertising/linearnonlinear/linearnonlinear.html", { // This function is called whenever a user navigates to this page. // It populates the page with data and initializes the media player control. ready: function (element, options) { var item = options && options.item ? Data.resolveItemReference(options.item) : Data.items.getAt(0); element.querySelector(".titlearea .pagetitle").textContent = item.title; if (WinJS.Utilities.isPhone) { document.getElementById("header").style.display = "none"; } var mediaPlayerElement = element.querySelector("[data-win-control='PlayerFramework.MediaPlayer']"); mediaPlayer = mediaPlayerElement.winControl; mediaPlayer.adSchedulerPlugin.advertisements.push(midrollAd); mediaPlayer.focus(); }, // This function is called whenever a user navigates away from this page. // It resets the page and disposes of the media player control. unload: function () { if (mediaPlayer) { mediaPlayer.dispose(); mediaPlayer = null; } } }); })();
var faye = require('faye') , http = require('http') , util = require('../../../lib/pubsub/util') ; exports.World = function World(callback) { this.app = require('../../../app'); this.app.storage.clear(); this.fayeClient = new faye.Client('http://localhost:3000/faye'); this.messages = []; this.request = function(method, url, body, done) { var world = this, headers, request; if (body) { headers = { 'Content-Type': 'application/json' } } request = http.request({ host: 'localhost', port: 3000, method: method, path: url, headers: headers }); request.on('response', function (response) { world.httpResponse = response; world.responseData = ''; response.on('data', function(chunk) { world.responseData += chunk; }); response.on('end', function () { done(); }); }); if (body !== undefined) { request.write(body); } request.end(); }; this.get = function(url, done) { this.request('GET', url, undefined, done); }; this.post = function(url, body, done) { this.request('POST', url, body, done); }; this.put = function(url, body, done) { this.request('PUT', url, body, done); }; this.responseContainsObject = function (expectedObject) { return _.any(JSON.parse(this.responseData), function (value) { return _.isEqual(expectedObject, value); }); } this.responseContainsValue = function (expectedValue) { return _.any(JSON.parse(this.responseData), function (item) { return item.value === expectedValue; }); }; callback(); };
const request = require('supertest') , {expect} = require('chai') , db = require('APP/db') , app = require('./start') , Order = db.model('orders') , User = db.model('users') , Glasses = db.model('glasses') /* global describe it before afterEach beforeEach */ describe('/api/orders', () => { before('Await database sync', () => db.didSync) // afterEach('Clear the tables', () => db.truncate({ cascade: true })) beforeEach('Create new associations', () => { Order.create({ glasses: [{}, {}, {}, {}] }) } ) describe('GET /', () => it('sends all orders', () => request(app) .get(`/api/orders`) .expect(200) .then(res => { expect(res.body.length).to.equal(1) expect(res.body[0].glasses.length).to.equal(4) }) )) describe('GET /color/:color', () => it('sends back all glasses of the color param', () => request(app) .get(`/api/glasses/color/black`) .expect(200) .then(res => { expect(res.body.length).to.equal(1) expect(res.body[0].color).to.equal('black') }) ) ) })
var b = require("ast-types").builders; module.exports = { // Config itemName: /(?:)/, itemType: 'Element', // Method init: element => { return { createHtmlElement: () => b.callExpression ( b.identifier ('jQuery'), [b.literal ('<' + element.nodeName + '>')]), addToParent: (parent, currentElement) => b.callExpression ( b.memberExpression ( parent, b.identifier ('append'), false), [currentElement]) }; } };
var breadcrumbs=[['-1',"",""],['2',"SOLUTION-WIDE PROPERTIES Reference","topic_0000000000000C16.html"],['1984',"Tlece.Recruitment.Models.Company Namespace","topic_0000000000000699.html"],['2061',"CompanyRoleDto Class","topic_00000000000006DC.html"],['2062',"Properties","topic_00000000000006DC_props--.html"],['2063',"CompanyId Property","topic_00000000000006DE.html"]];
const _ = require('lodash') const ApiFactory = require('../../../../services/api').default const { <%= moduleName_upperCase%>_FINDBYID_REQUEST_START, <%= moduleName_upperCase%>_FINDBYID_REQUEST_SUCCESS, <%= moduleName_upperCase%>_FINDBYID_REQUEST_FAILURE, } = require('../constants').default //findById export function findByIdRequestStart() { return { type: <%= moduleName_upperCase%>_FINDBYID_REQUEST_START } } export function findByIdRequestSuccess(json) { return { type: <%= moduleName_upperCase%>_FINDBYID_REQUEST_SUCCESS, payload: json } } export function findByIdRequestFailure(error) { return { type: <%= moduleName_upperCase%>_FINDBYID_REQUEST_FAILURE, payload: error } }
/** This test aims to show how the io_manager library should be used. It shows the initialization, some basic usage steps, and destruction of the library. **/ var utils = require('../utils/utils'); var testDeviceObject = utils.testDeviceObject; var testDeviceObjects = utils.testDeviceObjects; var qRunner = utils.qRunner; var qExec = utils.qExec; var pResults = utils.pResults; var q = require('q'); var constants = require('../../lib/common/constants'); var test_util = require('../utils/scanner_test_util'); var printAvailableDeviceData = test_util.printAvailableDeviceData; var testScanResults = test_util.testScanResults; var io_manager; var io_interface; // Managers var driver_controller; var device_controller; var file_io_controller; var logger_controller; var device; var deviceB; var capturedEvents = []; var getDeviceControllerEventListener = function(eventKey) { var deviceControllerEventListener = function(eventData) { // console.log('Captured an event', eventKey); capturedEvents.push({'eventName': eventKey, 'data': eventData}); }; return deviceControllerEventListener; }; var mockDevices = [{ 'deviceType': 'LJM_dtT7', 'connectionType': 'LJM_ctUSB', 'identifier': 'LJM_idANY', }, { 'deviceType': 'LJM_dtT7', 'connectionType': 'LJM_ctETHERNET', 'identifier': 'LJM_idANY', }]; exports.tests = { 'initialization': function(test) { // Require the io_manager library io_manager = require('../../lib/io_manager'); // Require the io_interface that gives access to the ljm driver, // device controller, logger, and file_io_controller objects. io_interface = io_manager.io_interface(); // Initialize the io_interface io_interface.initialize() .then(function(res) { // io_interface has initialized and is ready for use // Save local pointers to the created objects driver_controller = io_interface.getDriverController(); device_controller = io_interface.getDeviceController(); var eventKeys = Object.keys(constants.deviceControllerEvents); eventKeys.forEach(function(eventKey) { var eventName = constants.deviceControllerEvents[eventKey]; device_controller.on( eventName, getDeviceControllerEventListener(eventName) ); }); test.ok(true); test.done(); }, function(err) { test.ok(false, 'error initializing io_interface' + JSON.stringify(err)); test.done(); }); }, 'open mock device': function(test) { var params = mockDevices[0]; device_controller.openDevice(params) .then(function(newDevice) { device = newDevice; setTimeout(function() { if(capturedEvents.length != 1) { test.ok(false, 'unexpected number of events triggered.'); } else { test.ok(true); } test.done(); },50); }, function(err) { console.log("Error opening device", err); test.ok(false, 'failed to create new device object'); test.done(); }); }, 'get mock device attributes': function(test) { device.getDeviceAttributes() .then(function(res) { // Test to make sure that there are a few key attributes. var requiredAttributes = [ 'deviceType', 'connectionType', 'serialNumber', 'ipAddress', 'port', 'maxBytesPerMB', 'deviceTypeName', 'deviceTypeString', 'deviceClass', 'openParameters', 'subclass', 'isPro', 'productType' ]; var listToCheck = { 'ipAddress': '0.0.0.0', }; var givenAttributes = Object.keys(res); requiredAttributes.forEach(function(requiredAttribute) { var msg = 'Required key does not exist: ' + requiredAttribute; test.ok((givenAttributes.indexOf(requiredAttribute) >= 0), msg); }); var keys = Object.keys(listToCheck); keys.forEach(function(key) { test.strictEqual(res[key], listToCheck[key], 'unexpected mock device attribute value'); }); test.done(); }, function(err) { test.ok(false, 'read should not have returned an error: ' + JSON.stringify(err)); test.done(); }); }, 'open second device': function(test) { capturedEvents = []; // Configure the device so that its serial number is one of the mock // devices that gets found. var params = mockDevices[1]; device_controller.openDevice(params) .then(function(newDevice) { deviceB = newDevice; setTimeout(function() { if(capturedEvents.length != 1) { test.ok(false, 'unexpected number of events triggered.'); } else { test.ok(true); } test.done(); },50); }, function(err) { console.log("Error opening device", err); test.ok(false, 'failed to create new device object'); test.done(); }); }, 'get mock deviceB attributes': function(test) { deviceB.getDeviceAttributes() .then(function(res) { // Test to make sure that there are a few key attributes. var requiredAttributes = [ 'deviceType', 'connectionType', 'serialNumber', 'ipAddress', 'port', 'maxBytesPerMB', 'deviceTypeName', 'deviceTypeString', 'deviceClass', 'openParameters', 'subclass', 'isPro', 'productType' ]; var listToCheck = { }; var givenAttributes = Object.keys(res); requiredAttributes.forEach(function(requiredAttribute) { var msg = 'Required key does not exist: ' + requiredAttribute; test.ok((givenAttributes.indexOf(requiredAttribute) >= 0), msg); }); var keys = Object.keys(listToCheck); keys.forEach(function(key) { test.strictEqual(res[key], listToCheck[key], 'unexpected mock device attribute value'); }); test.done(); }, function(err) { test.ok(false, 'read should not have returned an error: ' + JSON.stringify(err)); test.done(); }); }, 'get number of devices': function(test) { device_controller.getNumDevices() .then(function(numDevices) { test.strictEqual(numDevices, 2, 'Unexpected number of already open devices'); test.done(); }); }, 'get device listing': function(test) { device_controller.getDeviceListing() .then(function(foundDevices) { test.strictEqual(foundDevices.length, 2, 'Unexpected number of already open devices'); // Save device data to the mockDevices object for testing & later operations foundDevices.forEach(function(device, i) { mockDevices[i].mockDeviceConfig = { 'serialNumber': device.serialNumber, 'DEVICE_NAME_DEFAULT': device.DEVICE_NAME_DEFAULT, 'ipAddress': device.ipAddress, }; }); test.done(); }); }, 'get devices': function(test) { device_controller.getDevices() .then(function(devices) { try { test.strictEqual(devices.length, 2, 'Unexpected number of already open devices'); testDeviceObjects(test, devices, mockDevices); // console.log('Device Objects', devices); test.done(); } catch(err) { console.log('err', err, err.stack); } }); }, 'get device sn: first device': function(test) { var options = { 'serialNumber':mockDevices[0].mockDeviceConfig.serialNumber, }; device_controller.getDevices(options) .then(function(devices) { try { test.strictEqual(devices.length, 1, 'Unexpected number of already open devices'); testDeviceObjects(test, devices, [mockDevices[0]]); test.done(); } catch(err) { console.log('err', err, err.stack); } }); }, 'get device sn: second device': function(test) { var options = { 'serialNumber':mockDevices[1].mockDeviceConfig.serialNumber, }; device_controller.getDevices(options) .then(function(devices) { try { test.strictEqual(devices.length, 1, 'Unexpected number of already open devices'); testDeviceObjects(test, devices, [mockDevices[1]]); test.done(); } catch(err) { console.log('err', err, err.stack); } }); }, 'get device data, sn': function(test) { var options = { 'serialNumber':mockDevices[1].mockDeviceConfig.serialNumber, }; device_controller.getDevice(options) .then(function(device) { try { testDeviceObject(test, device, mockDevices[1]); // console.log('device', device); test.done(); } catch(err) { console.log('err', err, err.stack); } }); }, 'close mock device': function(test) { capturedEvents = []; var options = { 'serialNumber':mockDevices[1].mockDeviceConfig.serialNumber, }; device_controller.getDevice(options) .then(device_controller.closeDeviceRef) // .then(function(device) { // console.log('Closing Device, sn:', device.savedAttributes.serialNumber); // return device.close(); // }) // device.close() .then(function(res) { setTimeout(function() { if(capturedEvents.length != 1) { test.ok(false, 'unexpected number of events triggered.'); } else { test.ok(true); } test.done(); },50); }, function(err) { console.log('Failed to close', err); test.ok(false); test.done(); }); }, 'get device data, sn -after close': function(test) { var options = { 'serialNumber':mockDevices[1].mockDeviceConfig.serialNumber, }; device_controller.getDevice(options) .then(function(device) { test.strictEqual(device, undefined, 'Device should not be found'); test.done(); }); }, 'get device data first device -after close': function(test) { var options = { 'serialNumber':mockDevices[0].mockDeviceConfig.serialNumber, }; device_controller.getDevice(options) .then(function(device) { try { testDeviceObject(test, device, mockDevices[0]); test.done(); } catch(err) { console.log('err', err, err.stack); } }); }, 'get number of devices -after close': function(test) { device_controller.getNumDevices() .then(function(numDevices) { test.strictEqual(numDevices, 1, 'Unexpected number of already open devices'); test.done(); }); }, 'get device listing -after close': function(test) { device_controller.getDeviceListing() .then(function(foundDevices) { test.strictEqual(foundDevices.length, 1, 'Unexpected number of already open devices'); test.done(); }); }, 'get devices -after close': function(test) { device_controller.getDevices() .then(function(devices) { try { test.strictEqual(devices.length, 1, 'Unexpected number of already open devices'); testDeviceObjects(test, devices, [mockDevices[0]]); test.done(); } catch(err) { console.log('err', err, err.stack); } }); }, 'close mock device (2)': function(test) { capturedEvents = []; var options = { 'serialNumber':mockDevices[0].mockDeviceConfig.serialNumber, }; device_controller.getDevice(options) .then(device_controller.closeDeviceRef) // .then(function(device) { // console.log('Closing Device, sn:', device.savedAttributes.serialNumber); // return device.close(); // }) // device.close() .then(function(res) { setTimeout(function() { if(capturedEvents.length != 1) { test.ok(false, 'unexpected number of events triggered.'); } else { test.ok(true); } test.done(); },50); }, function(err) { console.log('Failed to close', err); test.ok(false); test.done(); }); }, 'get device data, sn -after close (2)': function(test) { var options = { 'serialNumber':mockDevices[0].mockDeviceConfig.serialNumber, }; device_controller.getDevice(options) .then(function(device) { test.strictEqual(device, undefined, 'Device should not be found'); test.done(); }); }, 'get number of devices -after close (2)': function(test) { device_controller.getNumDevices() .then(function(numDevices) { test.strictEqual(numDevices, 0, 'Unexpected number of already open devices'); test.done(); }); }, 'get device listing -after close (2)': function(test) { device_controller.getDeviceListing() .then(function(foundDevices) { test.strictEqual(foundDevices.length, 0, 'Unexpected number of already open devices'); test.done(); }); }, 'get devices -after close (2)': function(test) { device_controller.getDevices() .then(function(devices) { try { test.strictEqual(devices.length, 0, 'Unexpected number of already open devices'); test.done(); } catch(err) { console.log('err', err, err.stack); } }); }, 'destruction': function(test) { setImmediate(function() { io_interface.destroy() .then(function(res) { // io_interface process has been shut down test.ok(true); test.done(); }, function(err) { test.ok(false, 'io_interface failed to shut down' + JSON.stringify(err)); test.done(); }); }); } };
var xtend = require('xtend') module.exports = function(opt) { opt = opt||{} var opacity = typeof opt.opacity === 'number' ? opt.opacity : 1 var alphaTest = typeof opt.alphaTest === 'number' ? opt.alphaTest : 0.06 var smooth = typeof opt.smooth === 'number' ? opt.smooth : 1/16 return xtend({ attributes: { zPos: { type: 'f', value: null }, word: { type: 'f', value: null } }, uniforms: { wordCount: { type: 'f', value: 1 }, origin: { type: 'v3', value: new THREE.Vector3() }, currentWord: { type: 'f', value: 0 }, opacity: { type: 'f', value: opacity }, smooth: { type: 'f', value: smooth }, map: { type: 't', value: opt.map || new THREE.Texture() }, color: { type: 'c', value: new THREE.Color(opt.color) } }, vertexShader: [ "precision mediump float;", "uniform mat4 modelViewMatrix;", "uniform mat4 projectionMatrix;", "attribute vec4 position;", "attribute vec2 uv;", "attribute float zPos;", "attribute float word;", "varying vec2 vUv;", "uniform float currentWord;", "uniform float wordCount;", "uniform vec3 origin;", "varying float vSelect;", "varying float vFade;", "void main() {", "vUv = uv;", "vec4 mvmpos = vec4( position.xy, zPos, 1.0 );", "vFade = clamp(length(mvmpos.xyz - origin.xyz) / 50.0, 0.0, 1.0);", "vFade = smoothstep(0.06, 0.15, vFade);", "vFade *= 0.5;", "float amt = abs(floor(word) - floor(currentWord));", // "if (word == currentWord) { vFade = 1.0; }", "vSelect = smoothstep(1.0, 0.0, amt);", "vFade = mix(vFade, 1.0, vSelect);", "gl_Position = projectionMatrix * modelViewMatrix * mvmpos;", "}" ].join("\n"), fragmentShader: [ "#extension GL_OES_standard_derivatives : enable", "precision mediump float;", "#define SQRT2 1.4142135623730951", "#define SQRT2_2 0.70710678118654757", "uniform float opacity;", "uniform vec3 color;", "uniform sampler2D map;", "uniform float smooth;", "varying float vSelect;", "varying float vFade;", "varying vec2 vUv;", "const vec2 shadowOffset = vec2(-1.0/512.0);", "const vec4 glowColor = vec4(vec3(0.1), 1.0);", "const float glowMin = 0.4;", "const float glowMax = 0.8;", "void main() {", "vec4 texColor = texture2D(map, vUv);", "float dst = texColor.a;", "float contrast = mix(0.1, 0.0, vSelect);", "float afwidth = contrast + length(vec2(dFdx(dst), dFdy(dst))) * SQRT2_2;", "float alpha = smoothstep(0.5 - afwidth, 0.5 + afwidth, dst);", "vec4 base = vec4(color, opacity * alpha * vFade);", // "float glowDst = texture2D(map, vUv + shadowOffset).a;", // "vec4 glow = glowColor * smoothstep(glowMin, glowMax, glowDst);", // "float mask = 1.0-alpha;", "gl_FragColor = base;", // THREE.ShaderChunk["alphatest_fragment"], "}" ].join("\n"), defines: { "USE_MAP": "", "ALPHATEST": Number(alphaTest || 0).toFixed(1) } }, opt) }
var app = require('express')(); var http = require('http').Server(app); var io = require('socket.io')(http); var nicknames = []; http.listen(3000, function(){ console.log('listening on *:3000'); }) app.get('/', function(req, res){ res.sendFile( __dirname + '/index.html'); }); io.on('connection', function(socket){ function updateUsernames() { io.emit('usernames', nicknames); } socket.on('chat message', function(data){ io.emit('chat message', {msg: data, nick: socket.nickname}); //io.broadcast.emit("chat message", msg); //sends message out to everyone except sender }); socket.on('new user', function(data, callback){ if(nicknames.indexOf(data) != -1){ callback(false); } else{ callback(true); socket.nickname = data; nicknames.push(socket.nickname); updateUsernames(); } }); socket.on('disconnect', function(data){ if(!socket.nickname) return; nicknames.splice(nicknames.indexOf(socket.nickname), 1); updateUsernames(); }); });
import fixtures from './spectreport-github.fixtures'; import path from 'path'; // Wrap all console logging within a function function trapConsole(func) { return function () { let oldConsole = console.log; let consoleLog = sinon.mock(); console.log = consoleLog; try { func.apply(func, arguments); } catch (e) { console.log = oldConsole; throw (e); } console.log = oldConsole; return consoleLog; }; } describe('Plugin - Github', () => { let options, reporter, plugin, usage, request, summary, netrc, error, done; before(() => { summary = sinon.mock().returns(fixtures.results.stats); reporter = { results: fixtures.results, summary: summary, constructor: fixtures.Spectreport }; options = fixtures.options; request = sinon.spy(function () { arguments[1](error, null, null); }); netrc = sinon.mock().returns(fixtures.netrc); done = sinon.spy(); // Rewire stub dependencies plugin = proxyquire(path.join(__dirname, 'spectreport-github.plugin'), { 'request': request, 'netrc': netrc }); // Trap the console on the plugin and the usage function usage = trapConsole(plugin.getUsage.bind(plugin)); plugin = trapConsole(plugin.bind(plugin)); }); describe('General', () => { beforeEach(() => { request.reset(); done.reset(); summary.reset(); netrc.reset(); error = undefined; }); it('should properly invoke the summary function', function () { plugin(options, reporter, done); expect(summary).to.have.been.calledOnce; }); it('should build the proper github url with user/pass', () => { options = fixtures.options; plugin(options, reporter, done); let call = request.args[0]; expect(call[0].method).to.eql('POST'); expect(call[0].uri).to.eql(fixtures.repoUrl); }); it('should not have the the auth header with user/pass', () => { options = fixtures.options; plugin(options, reporter, done); let call = request.args[0]; expect(call[0].headers).to.not.have.property('Authorization'); }); it('should call netrc correctly with default netrc', () => { options = fixtures.optionsNetrcDefault; netrc.returns(fixtures.netrcDefault); plugin(options, reporter, done); let call = netrc.args[0]; expect(call[0]).to.be.undefined; }); it('should build the proper github url with default netrc', () => { options = fixtures.optionsNetrcDefault; netrc.returns(fixtures.netrcDefault); plugin(options, reporter, done); let call = request.args[0]; expect(call[0].uri).to.eql(fixtures.repoUrlNetrcDefault); }); it('should call netrc correctly with specific netrc', () => { options = fixtures.optionsNetrc; netrc.returns(fixtures.netrc); plugin(options, reporter, done); let call = netrc.args[0]; expect(call[0]).to.eql(options.ghNetrc); }); it('should build the proper github url with specified netrc', () => { options = fixtures.optionsNetrc; netrc.returns(fixtures.netrc); plugin(options, reporter, done); let call = request.args[0]; expect(call[0].uri).to.eql(fixtures.repoUrlNetrc); }); it('should report error when no matching credentials in the netrc', () => { options = fixtures.optionsNetrc; netrc.returns({}); expect(plugin.bind(plugin, options, reporter)).to.throw(fixtures.noCredsError); }); it('should build the proper github url with API Key', () => { options = fixtures.optionsApiKey; plugin(options, reporter, done); let call = request.args[0]; expect(call[0].method).to.eql('POST'); expect(call[0].uri).to.eql(fixtures.repoUrlApiKey); }); it('should have the auth header with API Key', () => { options = fixtures.optionsApiKey; plugin(options, reporter, done); let call = request.args[0]; expect(call[0].headers).to.have.property('Authorization', 'token ' + fixtures.optionsApiKey.ghApiKey); }); it('should log to console on success', () => { let log = plugin(options, reporter, done); expect(log).to.have.been.calledWith(fixtures.consoleSuccess); }); it('should call done() method on success', () => { plugin(options, reporter, done); expect(done).to.have.been.calledOnce; }); it('should report error when no valid credentials supplied', () => { options = fixtures.optionsNoCreds; expect(plugin.bind(plugin, options, reporter)).to.throw(fixtures.noCredsError); }); it('should report error when the github api call fails', () => { options = fixtures.options; error = fixtures.githubError; expect(plugin.bind(plugin, options, reporter)).to.throw(fixtures.postError); }); }); describe('Success Report', () => { beforeEach(() => { request.reset(); done.reset(); summary.reset(); error = undefined; }); it('should output the expected body to github', () => { plugin(options, reporter, done); let call = request.args[0]; expect(call[0]).to.have.property('json').eql({body: fixtures.message}); }); it('should not send report on failOnly', () => { options.ghOnlyFail = true; plugin(options, reporter, done); expect(request).to.not.have.been.called; }); it('should not log to console on quiet', () => { options.ghQuiet = true; let log = plugin(options, reporter, done); expect(log).to.not.have.been.called; }); }); describe('Failure Report', () => { before(() => { summary = sinon.mock().returns(fixtures.resultsFailure.stats); reporter = { results: fixtures.resultsFailure, summary: summary, constructor: fixtures.Spectreport }; }); beforeEach(() => { request.reset(); done.reset(); summary.reset(); error = undefined; }); it('should output the expected body to github', () => { plugin(options, reporter, done); let call = request.args[0]; expect(call[0]).to.have.property('json').eql({body: fixtures.messageFailure}); }); it('should send report on failOnly', () => { options.ghOnlyFail = true; plugin(options, reporter, done); expect(request).to.have.been.calledOnce; }); it('should not log to console on quiet', () => { options.ghQuiet = true; let log = plugin(options, reporter, done); expect(log).to.not.have.been.called; }); }); describe('getUsage', () => { it('should log something to the console', () => { let log = usage(); expect(log).to.have.been.calledOnce; }); }); });
'use strict'; // karma.conf.js module.exports = function(config) { config.set({ browsers: ['Firefox'], frameworks: ['mocha', 'detectBrowsers'], detectBrowsers: { enabled: true, usePhantomJS: false, postDetection: function(availableBrowser) { // modify to enable additional browsers if available var runBrowsers = ['Firefox', 'Chrome']; var browsers = []; for(var i = 0; i < runBrowsers.length; i++) { if(~availableBrowser.indexOf(runBrowsers[i])) { browsers.push(runBrowsers[i]); } } return browsers; } }, singleRun: true, files: [ 'tests.js' ], plugins: [ 'karma-mocha', 'karma-chrome-launcher', 'karma-firefox-launcher', 'karma-detect-browsers' ] }); };
var scrollObject = require('./scrollObject'); module.exports = function(spec) { var that = new Group(); var WIDTH = 320; var HEIGHT = 272; var MAX_ARRAY = 2; var pict = spec.pict; var backGroundArray = new Array(MAX_ARRAY); (function() { for(var i=0; i<MAX_ARRAY; i++) { backGroundArray[i] = scrollObject({ pict : pict, width : WIDTH, height : HEIGHT }); backGroundArray[i].x = i * WIDTH; backGroundArray[i].y = 0; backGroundArray[i].scaleX = i%2===0 ? 1 : -1; that.addChild(backGroundArray[i]); } })() that.setSpeed = function(pSpeed){ for(var i=0; i<MAX_ARRAY; i++) { backGroundArray[i].setSpeed(pSpeed); } } that.setVisible = function(value){ for(var i=0; i<MAX_ARRAY; i++) { backGroundArray[i].visible = value; } } that.setOpacity = function(opacity) { for(var i=0; i<MAX_ARRAY; i++) { backGroundArray[i].opacity = opacity; } } return that; }
/** @typedef {import('./index').EventBridgeCloudWatchAlarmsEvent} EventBridgeCloudWatchAlarmsEvent */ module.exports = { /** * @param {EventBridgeCloudWatchAlarmsEvent} event * @returns {String} A hex color value */ value(event) { switch (event.detail.state.value) { case 'OK': return '#2eb886'; case 'ALARM': return '#a30200'; case 'INSUFFICIENT_DATA': return '#daa038'; default: return '#daa038'; } }, };
var Jquerypivot; (function (Jquerypivot) { (function (Lib) { var StringBuilder = (function () { function StringBuilder(value) { this.strings = ['']; this.append(value); } StringBuilder.prototype.append = function (value) { if (value !== null) { this.strings.push(value); } }; StringBuilder.prototype.clear = function () { this.strings.length = 1; }; StringBuilder.prototype.toString = function () { return this.strings.join(''); }; return StringBuilder; })(); Lib.StringBuilder = StringBuilder; function map(ar, fun, extra) { var i, len, res = [], item; if (ar) { { for (i = 0, len = ar.length; i < len; i += 1) { item = fun.call(extra, ar[i], i, ar); if (item !== null) { res.push(item); } } } return res; } } Lib.map = map; function find(ar, fun, extra) { var res; if (typeof (ar.filter) === 'function') { res = ar.filter(fun, extra); } else { res = Lib.map(ar, function (value, index, array) { return fun.call(extra, value, index, array) ? value : null; }, extra); } return res.length > 0 ? res[0] : null; } Lib.find = find; function exists(ar, fun, extra) { var i, len, item; if (ar) { if (typeof (ar.some) === 'function') { return ar.some(fun, extra); } else { for (i = 0, len = ar.length; i < len; i += 1) { if (fun.call(extra, ar[i], i, ar)) { return true; } } } } return false; } Lib.exists = exists; })(Jquerypivot.Lib || (Jquerypivot.Lib = {})); var Lib = Jquerypivot.Lib; })(Jquerypivot || (Jquerypivot = {})); var Jquerypivot; (function (Jquerypivot) { (function (_Adapter) { function sortgroupbys(rowA, rowB) { var a = +rowA.groupbyrank, b = +rowB.groupbyrank; return (a < b) ? -1 : (a > b) ? 1 : 0; } function trim(oIn) { if (typeof oIn === 'string' || oIn === null) { return $.trim(oIn); } else { return oIn; } } var TreeNode = (function () { function TreeNode() { this.children = []; this.pivotvalues = []; this.uniqueGroupByValuesLookup = {}; this.pivotResultValuesLookup = {}; } TreeNode.prototype.visible = function () { return this.parent === undefined || (!this.parent.collapsed && (!this.parent.visible || this.parent.visible())); }; return TreeNode; })(); _Adapter.TreeNode = TreeNode; var Adapter = (function () { function Adapter() { this.uniquePivotValuesLookup = {}; this.alGroupByCols = []; this.pivotCol = null; this.resultCol = []; this.bInvSort = false; this.tree = new TreeNode(); this.uniquePivotValues = []; this.dataid = null; this.sortPivotColumnHeaders = true; } Adapter.prototype.sortTree = function (treeNode) { var i, datatype; if (treeNode.children && treeNode.children.length > 0) { for (i = 0; i < treeNode.children.length; i += 1) { this.sortTree(treeNode.children[i]); } datatype = this.findCell(this.alGroupByCols, treeNode.children[0].colindex).datatype; treeNode.children.sort(this.getcomparer(this.bInvSort)[datatype]); } }; Adapter.prototype.findCell = function (arCells, colIndex) { return Jquerypivot.Lib.find(arCells, function (item, index) { return item.colindex == this; }, colIndex); }; Adapter.prototype.getcomparer = function (bInv) { function comp(f) { return function (rowA, rowB) { var out = (f(rowA.sortby) < f(rowB.sortby)) ? -1 : (f(rowA.sortby) > f(rowB.sortby)) ? 1 : 0; return bInv ? -out : out; }; } return { 'string': comp(function (s) { return s; }), 'number': comp(function (i) { return +i; }) }; }; Adapter.prototype.parseJSONsource = function (data) { var cellIndex, cellcount, rowIndex, rowcount, i, sourcecol, treecol, curNode, newObj, groupbyValue, groupbyText, sortbyValue, pivotValue, pivotSortBy, resultValues, newPivotValue, rowitem, row; this.dataid = data.dataid; for (cellIndex = 0, cellcount = data.columns.length; cellIndex < cellcount; cellIndex += 1) { sourcecol = data.columns[cellIndex]; treecol = { colvalue: sourcecol.colvalue, coltext: sourcecol.coltext, text: sourcecol.header || sourcecol.coltext || sourcecol.colvalue, colindex: cellIndex, datatype: sourcecol.datatype || 'string', sortbycol: sourcecol.sortbycol || sourcecol.coltext || sourcecol.colvalue, dataid: sourcecol.dataid || sourcecol.colvalue, groupbyrank: sourcecol.groupbyrank }; if (typeof (treecol.groupbyrank) === 'number' && isFinite(treecol.groupbyrank)) { this.alGroupByCols.push(treecol); } else if (sourcecol.pivot) { this.pivotCol = treecol; } else if (sourcecol.result) { this.resultCol.push(treecol); } } this.alGroupByCols.sort(sortgroupbys); for (rowIndex = 0, rowcount = data.rows.length; rowIndex < rowcount; rowIndex += 1) { row = data.rows[rowIndex]; curNode = this.tree; for (i = 0; i < this.alGroupByCols.length; i += 1) { groupbyValue = trim(row[this.alGroupByCols[i].colvalue]); groupbyText = row[this.alGroupByCols[i].coltext]; sortbyValue = trim(row[this.alGroupByCols[i].sortbycol]); newObj = curNode.uniqueGroupByValuesLookup[groupbyValue]; if (!newObj) { newObj = new TreeNode(); newObj.groupbyValue = groupbyValue; newObj.groupbyText = groupbyText; newObj.colindex = this.alGroupByCols[i].colindex; newObj.children = []; newObj.sortby = sortbyValue; newObj.parent = curNode; newObj.dataid = this.alGroupByCols[i].dataid; newObj.collapsed = true; newObj.groupbylevel = i; curNode.uniqueGroupByValuesLookup[groupbyValue] = newObj; curNode.children.push(newObj); } curNode = newObj; } pivotValue = trim(row[this.pivotCol.colvalue]); pivotSortBy = trim(row[this.pivotCol.sortbycol]); resultValues = []; for (i = 0; i < this.resultCol.length; i += 1) { resultValues.push(trim(row[this.resultCol[i].colvalue])); } newPivotValue = { pivotValue: pivotValue, resultValues: resultValues, sortby: pivotSortBy, dataid: this.pivotCol.dataid }; curNode.pivotvalues.push(newPivotValue); if (!this.uniquePivotValuesLookup.hasOwnProperty(pivotValue)) { this.uniquePivotValues.push(newPivotValue); this.uniquePivotValuesLookup[pivotValue] = null; } } this.sortTree(this.tree); if (this.sortPivotColumnHeaders) { this.uniquePivotValues.sort(this.getcomparer(this.bInvSort)[this.pivotCol.datatype]); } }; Adapter.prototype.parseFromHtmlTable = function (sourceTable) { var cellIndex, cellcount, rowIndex, rowcount, el, eltext, col, cells, row, data = { dataid: sourceTable.data('pivot-dataid'), columns: [], rows: [] }, rows = $('tbody > tr', sourceTable), columnNames = []; for (cellIndex = 0, cellcount = rows[0].cells.length; cellIndex < cellcount; cellIndex += 1) { el = $(rows[0].cells[cellIndex]); eltext = el.text(); col = { colvalue: el.data('pivot-colvalue') || eltext, coltext: el.data('pivot-coltext') || eltext, header: el.data('pivot-header') || el.text(), datatype: el.data('pivot-datatype'), sortbycol: el.data('pivot-sortbycol') || eltext, dataid: el.data('pivot-dataid'), groupbyrank: parseInt(el.data('pivot-groupbyrank'), 10), pivot: el.data('pivot-pivot'), result: el.data('pivot-result') }; data.columns.push(col); columnNames.push(eltext); } for (rowIndex = 1, rowcount = rows.length; rowIndex < rowcount; rowIndex += 1) { cells = rows[rowIndex].cells; row = {}; for (cellIndex = 0, cellcount = columnNames.length; cellIndex < cellcount; cellIndex += 1) { eltext = cells[cellIndex].innerHTML; row[columnNames[cellIndex]] = (data.columns[cellIndex].datatype === 'number') ? parseFloat(eltext) : eltext; } data.rows.push(row); } this.parseJSONsource(data); }; return Adapter; })(); _Adapter.Adapter = Adapter; })(Jquerypivot.Adapter || (Jquerypivot.Adapter = {})); var Adapter = Jquerypivot.Adapter; })(Jquerypivot || (Jquerypivot = {})); var Jquerypivot; (function (Jquerypivot) { (function (Pivot) { $ = jQuery; function calcsum(values) { var i, length; var total = 0.0; for (i = 0, length = values.length; i < length; i += 1) { total += values[i]; } return total; } function formatDK(num, decimals) { return this.formatLocale(num, decimals, '.', ','); } function formatUK(num, decimals) { return this.formatLocale(num, decimals, ',', '.'); } function formatLocale(num, decimals, kilosep, decimalsep) { var i, bNeg = num < 0, x = Math.round(num * Math.pow(10, decimals)), y = Math.abs(x).toString().split(''), z = y.length - decimals; if (z <= 0) { for (i = 0; i <= -z; i += 1) { y.unshift('0'); } z = 1; } if (decimals > 0) { y.splice(z, 0, decimalsep); } while (z > 3) { z -= 3; y.splice(z, 0, kilosep); } if (bNeg) { y.splice(0, 0, '-'); } return y.join(''); } var jqueryPivotOptions = (function () { function jqueryPivotOptions(source, bTotals, bCollapsible, aggregatefunc, formatFunc, parseNumFunc, onResultCellClicked, noGroupByText, noDataText, sortPivotColumnHeaders) { if (typeof source === "undefined") { source = null; } if (typeof bTotals === "undefined") { bTotals = true; } if (typeof bCollapsible === "undefined") { bCollapsible = true; } if (typeof aggregatefunc === "undefined") { aggregatefunc = calcsum; } if (typeof formatFunc === "undefined") { formatFunc = function (n) { return n === null ? null : n.toString(); }; } if (typeof parseNumFunc === "undefined") { parseNumFunc = function (n) { return +n; }; } if (typeof onResultCellClicked === "undefined") { onResultCellClicked = null; } if (typeof noGroupByText === "undefined") { noGroupByText = 'No value'; } if (typeof noDataText === "undefined") { noDataText = 'No data'; } if (typeof sortPivotColumnHeaders === "undefined") { sortPivotColumnHeaders = true; } this.source = source; this.bTotals = bTotals; this.bCollapsible = bCollapsible; this.aggregatefunc = aggregatefunc; this.formatFunc = formatFunc; this.parseNumFunc = parseNumFunc; this.onResultCellClicked = onResultCellClicked; this.noGroupByText = noGroupByText; this.noDataText = noDataText; this.sortPivotColumnHeaders = sortPivotColumnHeaders; } return jqueryPivotOptions; })(); Pivot.jqueryPivotOptions = jqueryPivotOptions; var resultCellClickedInfoPivotInfo = (function () { function resultCellClickedInfoPivotInfo(dataidPivot, pivotvalue, pivotsortvalue) { this.dataidPivot = dataidPivot; this.pivotvalue = pivotvalue; this.pivotsortvalue = pivotsortvalue; } return resultCellClickedInfoPivotInfo; })(); Pivot.resultCellClickedInfoPivotInfo = resultCellClickedInfoPivotInfo; var resultCellClickedInfoGroupByInfo = (function () { function resultCellClickedInfoGroupByInfo(dataidGroup, groupbyval) { this.dataidGroup = dataidGroup; this.groupbyval = groupbyval; } return resultCellClickedInfoGroupByInfo; })(); Pivot.resultCellClickedInfoGroupByInfo = resultCellClickedInfoGroupByInfo; var resultCellClickedInfoResultColInfo = (function () { function resultCellClickedInfoResultColInfo(colKeyName, colName) { this.colKeyName = colKeyName; this.colName = colName; } return resultCellClickedInfoResultColInfo; })(); Pivot.resultCellClickedInfoResultColInfo = resultCellClickedInfoResultColInfo; var resultCellClickedInfo = (function () { function resultCellClickedInfo(dataidTable, pivot, groups, resultcol) { this.dataidTable = dataidTable; this.pivot = pivot; this.groups = groups; this.resultcol = resultcol; } return resultCellClickedInfo; })(); Pivot.resultCellClickedInfo = resultCellClickedInfo; var resultCellInfo = (function () { function resultCellInfo(pivot, treeNode, resultcol) { this.pivot = pivot; this.treeNode = treeNode; this.resultcol = resultcol; } return resultCellInfo; })(); var groupbynodeStatus = (function () { function groupbynodeStatus(bDatabound, treeNode) { this.bDatabound = bDatabound; this.treeNode = treeNode; } return groupbynodeStatus; })(); var pivot = (function () { function pivot(suppliedoptions) { var _this = this; this.resultCellClicked = function (e) { var el = $(e.target), adapter = el.closest('table.pivot').data('jquery.pivot.adapter'), aGroupBys = [], data = el.data('def'), curNode = data.treeNode, dataObj; if (_this.opts.onResultCellClicked) { el.closest('table.pivot').find('.resultcell').removeClass('clickedResultCell'); el.addClass('clickedResultCell'); while (curNode.parent) { aGroupBys.unshift(new resultCellClickedInfoGroupByInfo(curNode.dataid, curNode.groupbyValue)); curNode = curNode.parent; } dataObj = new resultCellClickedInfo(adapter.dataid, new resultCellClickedInfoPivotInfo(data.pivot.dataid, data.pivot.pivotValue, data.pivot.sortby), aGroupBys, new resultCellClickedInfoResultColInfo(data.resultcol.dataid, data.resultcol.coltext)); _this.opts.onResultCellClicked(dataObj, el); } }; this.flattenFunc = function (index) { return function (item) { return item[index]; }; }; this.getResValues = function (treeNode, pivotValue) { var i, res = [], valsToAggregate = [], pivotResultValues; var parseNums = function (n) { return _this.opts.parseNumFunc(n); }; if (!treeNode.pivotResultValuesLookup.hasOwnProperty(pivotValue)) { if (_this.opts.aggregatefunc) { if (treeNode.pivotvalues.length > 0) { pivotResultValues = Jquerypivot.Lib.map(treeNode.pivotvalues || [], function (item, index) { return item.pivotValue === pivotValue ? item.resultValues : null; }); if (_this.opts.parseNumFunc) { for (i = 0; i < pivotResultValues.length; i += 1) { valsToAggregate.push(Jquerypivot.Lib.map(pivotResultValues[i], parseNums)); } } else { valsToAggregate = pivotResultValues; } } else if (_this.opts.bTotals) { for (i = 0; i < treeNode.children.length; i += 1) { valsToAggregate.push(_this.getResValues(treeNode.children[i], pivotValue)); } } for (i = 0; i < _this.adapter.resultCol.length; i += 1) { var resColVals = Jquerypivot.Lib.map(valsToAggregate, _this.flattenFunc(i)); res.push(_this.opts.aggregatefunc(resColVals)); } } else { res = null; } treeNode.pivotResultValuesLookup[pivotValue] = res; } return treeNode.pivotResultValuesLookup[pivotValue]; }; this.appendChildRows = function (treeNode, belowThisRow, adapter) { var i, j, col, col1, sb, item, itemtext, resCell, spanFoldUnfold, gbCols = adapter.alGroupByCols, pivotCols = adapter.uniquePivotValues, foldunfoldclass = _this.opts.bCollapsible ? 'foldunfold' : 'nonfoldunfold', foldunfoldclassSelector = '.' + foldunfoldclass, status, valsToSumOn = [], sums, aggregateValues = function (v) { return _this.opts.aggregatefunc(v); }, results; for (i = 0; i < treeNode.children.length; i += 1) { sb = new Jquerypivot.Lib.StringBuilder(); item = treeNode.children[i]; itemtext = (item.groupbyText === undefined || item.groupbyText === null || item.groupbyText === '&nbsp;' || item.groupbyText === '') ? _this.opts.noGroupByText : item.groupbyText; sb.append('<tr class="level'); sb.append(item.groupbylevel); sb.append('">'); for (col = 0; col < gbCols.length; col += 1) { sb.append('<th class="groupby level'); sb.append(col); sb.append('">'); if (gbCols[col].colindex === item.colindex) { if (item.children.length > 0) { sb.append('<span class="'); sb.append(foldunfoldclass); sb.append(' collapsed">'); sb.append(itemtext); sb.append(' </span>'); } else { sb.append(itemtext); } } else { sb.append(' '); } sb.append('</th>'); } sb.append('</tr>'); belowThisRow = $(sb.toString()).insertAfter(belowThisRow); belowThisRow.find(foldunfoldclassSelector).data('status', new groupbynodeStatus(false, item)); valsToSumOn = []; for (col1 = 0; col1 < pivotCols.length; col1 += 1) { results = _this.getResValues(item, pivotCols[col1].pivotValue); if (_this.opts.bTotals) { valsToSumOn.push(results); } sb.clear(); for (j = 0; j < results.length; j += 1) { sb.append('<td class="resultcell resultcell'); sb.append(j); sb.append('" title="'); sb.append(_this.adapter.resultCol[j].coltext); sb.append('">'); sb.append(_this.opts.formatFunc(results[j])); sb.append('</td>'); } resCell = $(sb.toString()).appendTo(belowThisRow); for (j = 0; j < results.length; j += 1) { resCell.eq(j).data('def', new resultCellInfo(pivotCols[col1], item, _this.adapter.resultCol[j])); } } if (_this.opts.bTotals) { sb.clear(); sums = []; for (j = 0; j < _this.adapter.resultCol.length; j += 1) { var resColVals = Jquerypivot.Lib.map(valsToSumOn, _this.flattenFunc(j)); sums.push(_this.opts.aggregatefunc(resColVals)); } for (j = 0; j < results.length; j += 1) { sb.append('<td class="total total'); sb.append(j); sb.append('" title="'); sb.append(_this.adapter.resultCol[j].coltext); sb.append('">'); sb.append(_this.opts.formatFunc(sums[j])); sb.append('</td>'); } $(sb.toString()).appendTo(belowThisRow); } if (!_this.opts.bCollapsible) { spanFoldUnfold = belowThisRow.find(foldunfoldclassSelector); if (spanFoldUnfold.length > 0) { status = spanFoldUnfold.removeClass('collapsed').data('status'); status.treeNode.collapsed = false; status.bDatabound = true; _this.appendChildRows(status.treeNode, belowThisRow, adapter); belowThisRow = belowThisRow.nextUntil('.total').last(); } } } }; this.makeCollapsed = function (adapter, $obj) { var i, j, col, $pivottable, aggVals = [], sb = new Jquerypivot.Lib.StringBuilder('<table class="pivot">'), gbCols = adapter.alGroupByCols, pivotCols = adapter.uniquePivotValues, results; _this.adapter = adapter; sb.append('<tr class="head">'); for (i = 0; i < gbCols.length; i += 1) { sb.append('<th class="groupby level'); sb.append(i); sb.append('">'); sb.append(gbCols[i].text); sb.append('</th>'); } for (i = 0; i < pivotCols.length; i += 1) { sb.append('<th class="pivotcol" colspan="'); sb.append(_this.adapter.resultCol.length); sb.append('">'); sb.append(pivotCols[i].pivotValue); sb.append('</th>'); } if (_this.opts.bTotals) { sb.append('<th class="total" colspan="'); sb.append(_this.adapter.resultCol.length); sb.append('">Total</th>'); } sb.append('</tr>'); if (_this.opts.bTotals) { sb.append('<tr class="total">'); sb.append('<th class="total" colspan="'); sb.append(gbCols.length); sb.append('">Total</th>'); for (col = 0; col < pivotCols.length; col += 1) { results = _this.getResValues(adapter.tree, pivotCols[col].pivotValue); if (_this.opts.bTotals) { aggVals.push(results); } for (j = 0; j < _this.adapter.resultCol.length; j += 1) { sb.append('<td class="coltotal total'); sb.append(j); sb.append('" title="'); sb.append(_this.adapter.resultCol[j].coltext); sb.append('">'); sb.append(_this.opts.formatFunc(results[j])); sb.append('</td>'); } } for (j = 0; j < _this.adapter.resultCol.length; j += 1) { var resColVals = Jquerypivot.Lib.map(aggVals, _this.flattenFunc(j)); sb.append('<td class="total total'); sb.append(j); sb.append('" title="'); sb.append(_this.adapter.resultCol[j].coltext); sb.append('">'); sb.append(_this.opts.formatFunc(_this.opts.aggregatefunc(resColVals))); sb.append('</td>'); } sb.append('</tr>'); } sb.append('</table>'); $obj.html(''); $pivottable = $(sb.toString()).appendTo($obj); $pivottable.data('jquery.pivot.adapter', adapter); _this.appendChildRows(adapter.tree, $('tr:first', $pivottable), adapter); }; this.foldunfoldElem = function (el) { var adapter = el.closest('table.pivot').data('jquery.pivot.adapter'), status = el.data('status'), parentRow = el.closest('tr'), visible = false, row, rowstatus, thisrowstatus; status.treeNode.collapsed = !status.treeNode.collapsed; if (status.treeNode.collapsed) { el.addClass('collapsed'); } else { el.removeClass('collapsed'); } if (!status.bDatabound) { _this.appendChildRows(status.treeNode, parentRow, adapter); status.bDatabound = true; } else { row = parentRow; rowstatus = status; while ((row = row.next()).length > 0) { thisrowstatus = row.find('.foldunfold').data('status'); if ((thisrowstatus && thisrowstatus.treeNode.groupbylevel <= status.treeNode.groupbylevel) || row.is('.total')) { break; } if (thisrowstatus) { rowstatus = thisrowstatus; visible = rowstatus.treeNode.visible(); } else { visible = rowstatus.treeNode.visible() && !rowstatus.treeNode.collapsed; } row.toggle(visible); } } }; this.foldunfold = function (e) { _this.foldunfoldElem($(e.target)); }; this.opts = $.extend({}, $.fn.pivot.defaults, suppliedoptions); } return pivot; })(); Pivot.pivot = pivot; $.fn.pivot = function (options) { var p = new pivot(options); return this.each(function () { var item = $(this), adapter = new Jquerypivot.Adapter.Adapter(), opts = p.opts; adapter.sortPivotColumnHeaders = opts.sortPivotColumnHeaders; item.empty(); if ((typeof opts.source === 'object' && opts.source.jquery) || opts.source.columns) { if (opts.source.jquery) { if (opts.source.find('tr').length > 0) { adapter.parseFromHtmlTable(opts.source); } } else { adapter.parseJSONsource(opts.source); } item.off('click.jquery.pivot'); item.on('click.jquery.pivot', '.pivot .foldunfold', p.foldunfold); if (opts.onResultCellClicked) { item.on('click.jquery.pivot', '.resultcell', p.resultCellClicked); } p.makeCollapsed(adapter, item); } if (item.html() === '') { item.html('<h1>' + opts.noDataText + '</h1>'); } }); }; $.fn.pivot.defaults = new jqueryPivotOptions(); $.fn.pivot.formatDK = formatDK; $.fn.pivot.formatUK = formatUK; $.fn.pivot.formatLocale = formatLocale; })(Jquerypivot.Pivot || (Jquerypivot.Pivot = {})); var Pivot = Jquerypivot.Pivot; })(Jquerypivot || (Jquerypivot = {})); //# sourceMappingURL=jquery.pivot.js.map
var fs = require('fs'), frisby = require('frisby'), ini = require('ini'); var config = ini.parse(fs.readFileSync('../config.ini', 'utf-8')); config.baseUrl = "http://localhost:8081/"; var logged = function(callback) { frisby.globalSetup({ request: { baseUri: config.baseUrl } }); frisby.create('Login') .post('auth', { username: config.auth.username, password: config.auth.password }) .expectStatus(200) .expectJSON({result: true}) .afterJSON(function(json) { frisby.globalSetup({ request: { headers: {"Auth-token": json['token']}, baseUri: config.baseUrl } }); callback(frisby); }).toss(); }; var unlogged = function(callback) { frisby.globalSetup({ request: { baseUri: config.baseUrl } }); callback(frisby); }; exports.logged = logged; exports.unlogged = unlogged; exports.BASE_URL = config.baseUrl; exports.USERNAME = config.auth.username; exports.PASSWORD = config.auth.password;
var Mongoose = require("mongoose"); var Module = function () { var _name = "Continents"; var _schema = new Mongoose.Schema({ name: String, region: { type: Mongoose.Schema.Types.ObjectId, ref: 'Regions' } }); return Mongoose.connection.models[_name] || Mongoose.model(_name, _schema); }; module.exports = Module();
module.exports.complement = require("./complement") module.exports.diff = require("./diff") module.exports.intersect = require("./intersect") module.exports.join = require("./join") module.exports.union = require("./union") module.exports.where = require("./where")
var searchData= [ ['concatenation_5fparser',['concatenation_parser',['../structthewizardplusplus_1_1wizard__parser_1_1parser_1_1concatenation__parser.html',1,'thewizardplusplus::wizard_parser::parser']]] ];
version https://git-lfs.github.com/spec/v1 oid sha256:a5f7e816007e246313c24f02bb520028b67f9669a6f59250dfb2ad055cd66f02 size 1812362
var InheritanceHelpers = Coool.traits.InheritanceHelpers; var Class = Coool.Class.extend({ traits : [InheritanceHelpers]}); QUnit.module("traits.InheritanceHelpers"); test("parent Class should be isAncestorOf() it's direct child", function() { var Parent = Class.extend({}); var Child = Parent.extend({}); assert.isTrue(Parent.isAncestorOf(Child)); }); test("indirect parent Class should also be isAncestorOf()", function() { var Parent = Class.extend({}); var Child = Parent.extend({}); var Grandchild = Child.extend({}); assert.isTrue(Parent.isAncestorOf(Grandchild)); }); test("child Class should not be isAncestorOf() it's parent", function() { var Parent = Class.extend({}); var Child = Parent.extend({}); assert.isFalse(Child.isAncestorOf(Parent)); }); test("a Class should not be isAncestorOf() itself", function() { var Demo = Class.extend({}); assert.isFalse(Demo.isAncestorOf(Demo)); }); test("unrelated Class should not be isAncestorOf() other class ", function() { var One = Class.extend({}); var Other = Class.extend({}); assert.isFalse(One.isAncestorOf(Other)); assert.isFalse(Other.isAncestorOf(One)); }); test("Class should not be isAncestorOf() undefined, null, or primitive", function() { var Demo = Class.extend({}); assert.isFalse(Demo.isAncestorOf(undefined)); assert.isFalse(Demo.isAncestorOf(null)); assert.isFalse(Demo.isAncestorOf(true)); assert.isFalse(Demo.isAncestorOf(0)); assert.isFalse(Demo.isAncestorOf("string")); });
/** * Users * Pokemon Showdown - http://pokemonshowdown.com/ * * Most of the communication with users happens here. * * There are two object types this file introduces: * User and Connection. * * A User object is a user, identified by username. A guest has a * username in the form "Guest 12". Any user whose username starts * with "Guest" must be a guest; normal users are not allowed to * use usernames starting with "Guest". * * A User can be connected to Pokemon Showdown from any number of tabs * or computers at the same time. Each connection is represented by * a Connection object. A user tracks its connections in * user.connections - if this array is empty, the user is offline. * * Get a user by username with Users.get * (scroll down to its definition for details) * * @license MIT license */ 'use strict'; const THROTTLE_DELAY = 600; const THROTTLE_BUFFER_LIMIT = 6; const THROTTLE_MULTILINE_WARN = 3; const THROTTLE_MULTILINE_WARN_STAFF = 6; const PERMALOCK_CACHE_TIME = 30 * 24 * 60 * 60 * 1000; const FS = require('./fs'); const Matchmaker = require('./ladders-matchmaker').matchmaker; let Users = module.exports = getUser; /********************************************************* * Users map *********************************************************/ let users = Users.users = new Map(); let prevUsers = Users.prevUsers = new Map(); let numUsers = 0; // Low-level functions for manipulating Users.users and Users.prevUsers // Keeping them all here makes it easy to ensure they stay consistent Users.move = function (user, newUserid) { if (user.userid === newUserid) return true; if (!user) return false; // doing it this way mathematically ensures no cycles prevUsers.delete(newUserid); prevUsers.set(user.userid, newUserid); users.delete(user.userid); user.userid = newUserid; users.set(newUserid, user); return true; }; Users.add = function (user) { if (user.userid) throw new Error(`Adding a user that already exists`); numUsers++; user.guestNum = numUsers; user.name = `Guest ${numUsers}`; user.userid = toId(user.name); if (users.has(user.userid)) throw new Error(`userid taken: ${user.userid}`); users.set(user.userid, user); }; Users.delete = function (user) { prevUsers.delete('guest' + user.guestNum); users.delete(user.userid); }; Users.merge = function (user1, user2) { prevUsers.delete(user2.userid); prevUsers.set(user1.userid, user2.userid); }; /** * Get a user. * * Usage: * Users.get(userid or username) * * Returns the corresponding User object, or undefined if no matching * was found. * * By default, this function will track users across name changes. * For instance, if "Some dude" changed their name to "Some guy", * Users.get("Some dude") will give you "Some guy"s user object. * * If this behavior is undesirable, use Users.getExact. */ function getUser(name, exactName) { if (!name || name === '!') return null; if (name && name.userid) return name; let userid = toId(name); let i = 0; if (!exactName) { while (userid && !users.has(userid) && i < 1000) { userid = prevUsers.get(userid); i++; } } return users.get(userid); } Users.get = getUser; /** * Get a user by their exact username. * * Usage: * Users.getExact(userid or username) * * Like Users.get, but won't track across username changes. * * Users.get(userid or username, true) is equivalent to * Users.getExact(userid or username). * The former is not recommended because it's less readable. */ let getExactUser = Users.getExact = function (name) { return getUser(name, true); }; /** * Get a list of all users matching a list of userids and ips. * * Usage: * Users.findUsers([userids], [ips]) * */ let findUsers = Users.findUsers = function (userids, ips, options) { let matches = []; if (options && options.forPunishment) ips = ips.filter(ip => !Punishments.sharedIps.has(ip)); users.forEach(user => { if (!(options && options.forPunishment) && !user.named && !user.connected) return; if (!(options && options.includeTrusted) && user.trusted) return; if (userids.includes(user.userid)) { matches.push(user); return; } for (let myIp of ips) { if (myIp in user.ips) { matches.push(user); return; } } }); return matches; }; /********************************************************* * User groups *********************************************************/ let usergroups = Users.usergroups = Object.create(null); function importUsergroups() { // can't just say usergroups = {} because it's exported for (let i in usergroups) delete usergroups[i]; FS('config/usergroups.csv').readTextIfExists().then(data => { for (const row of data.split("\n")) { if (!row) continue; let cells = row.split(","); usergroups[toId(cells[0])] = (cells[1] || Config.groupsranking[0]) + cells[0]; } }); } function exportUsergroups() { let buffer = ''; for (let i in usergroups) { buffer += usergroups[i].substr(1).replace(/,/g, '') + ',' + usergroups[i].charAt(0) + "\n"; } FS('config/usergroups.csv').write(buffer); } importUsergroups(); function cacheGroupData() { if (Config.groups) { // Support for old config groups format. // Should be removed soon. console.log( `You are using a deprecated version of user group specification in config.\n` + `Support for this will be removed soon.\n` + `Please ensure that you update your config.js to the new format (see config-example.js, line 220).\n` ); } else { Config.punishgroups = Object.create(null); Config.groups = Object.create(null); Config.groupsranking = []; } let groups = Config.groups; let punishgroups = Config.punishgroups; let cachedGroups = {}; function cacheGroup(sym, groupData) { if (cachedGroups[sym] === 'processing') return false; // cyclic inheritance. if (cachedGroups[sym] !== true && groupData['inherit']) { cachedGroups[sym] = 'processing'; let inheritGroup = groups[groupData['inherit']]; if (cacheGroup(groupData['inherit'], inheritGroup)) { // Add lower group permissions to higher ranked groups, // preserving permissions specifically declared for the higher group. for (let key in inheritGroup) { if (key in groupData) continue; groupData[key] = inheritGroup[key]; } } delete groupData['inherit']; } return (cachedGroups[sym] = true); } if (Config.grouplist) { // Using new groups format. let grouplist = Config.grouplist; let numGroups = grouplist.length; for (let i = 0; i < numGroups; i++) { let groupData = grouplist[i]; // punish groups if (groupData.punishgroup) { punishgroups[groupData.id] = groupData; continue; } groupData.rank = numGroups - i - 1; groups[groupData.symbol] = groupData; Config.groupsranking.unshift(groupData.symbol); } } for (let sym in groups) { let groupData = groups[sym]; cacheGroup(sym, groupData); } // hardcode default punishgroups. if (!punishgroups.locked) { punishgroups.locked = { name: 'Locked', id: 'locked', symbol: '‽', }; } if (!punishgroups.muted) { punishgroups.muted = { name: 'Muted', id: 'muted', symbol: '!', }; } } cacheGroupData(); Users.setOfflineGroup = function (name, group, forceTrusted) { if (!group) throw new Error(`Falsy value passed to setOfflineGroup`); let userid = toId(name); let user = getExactUser(userid); if (user) { user.setGroup(group, forceTrusted); return true; } if (group === Config.groupsranking[0] && !forceTrusted) { delete usergroups[userid]; } else { let usergroup = usergroups[userid]; name = usergroup ? usergroup.substr(1) : name; usergroups[userid] = group + name; } exportUsergroups(); return true; }; Users.isUsernameKnown = function (name) { let userid = toId(name); if (Users(userid)) return true; if (userid in usergroups) return true; for (let i = 0; i < Rooms.global.chatRooms.length; i++) { let curRoom = Rooms.global.chatRooms[i]; if (!curRoom.auth) continue; if (userid in curRoom.auth) return true; } return false; }; Users.isTrusted = function (name) { if (name.trusted) return name.trusted; let userid = toId(name); if (userid in usergroups) return userid; for (let i = 0; i < Rooms.global.chatRooms.length; i++) { let curRoom = Rooms.global.chatRooms[i]; if (!curRoom.isPrivate && !curRoom.isPersonal && curRoom.auth && userid in curRoom.auth && curRoom.auth[userid] !== '+') return userid; } return false; }; Users.importUsergroups = importUsergroups; Users.cacheGroupData = cacheGroupData; /********************************************************* * User and Connection classes *********************************************************/ let connections = Users.connections = new Map(); class Connection { constructor(id, worker, socketid, user, ip, protocol) { this.id = id; this.socketid = socketid; this.worker = worker; this.inRooms = new Set(); this.user = user; this.ip = ip || ''; this.protocol = protocol || ''; this.autojoin = ''; } sendTo(roomid, data) { if (roomid && roomid.id) roomid = roomid.id; if (roomid && roomid !== 'lobby') data = `>${roomid}\n${data}`; Sockets.socketSend(this.worker, this.socketid, data); Monitor.countNetworkUse(data.length); } send(data) { Sockets.socketSend(this.worker, this.socketid, data); Monitor.countNetworkUse(data.length); } destroy() { Sockets.socketDisconnect(this.worker, this.socketid); this.onDisconnect(); } onDisconnect() { connections.delete(this.id); if (this.user) this.user.onDisconnect(this); this.user = null; } popup(message) { this.send(`|popup|` + message.replace(/\n/g, '||')); } joinRoom(room) { if (this.inRooms.has(room.id)) return; this.inRooms.add(room.id); Sockets.channelAdd(this.worker, room.id, this.socketid); } leaveRoom(room) { if (this.inRooms.has(room.id)) { this.inRooms.delete(room.id); Sockets.channelRemove(this.worker, room.id, this.socketid); } } } // User class User { constructor(connection) { this.mmrCache = Object.create(null); this.guestNum = -1; this.name = ""; this.named = false; this.registered = false; this.userid = ''; this.group = Config.groupsranking[0]; let trainersprites = [1, 2, 101, 102, 169, 170, 265, 266]; this.avatar = trainersprites[Math.floor(Math.random() * trainersprites.length)]; this.connected = true; if (connection.user) connection.user = this; this.connections = [connection]; this.latestHost = ''; this.ips = Object.create(null); this.ips[connection.ip] = 1; // Note: Using the user's latest IP for anything will usually be // wrong. Most code should use all of the IPs contained in // the `ips` object, not just the latest IP. this.latestIp = connection.ip; this.locked = false; this.namelocked = false; this.prevNames = Object.create(null); this.inRooms = new Set(); // Set of roomids this.games = new Set(); // searches and challenges this.searching = Object.create(null); this.challengesFrom = {}; this.challengeTo = null; this.lastChallenge = 0; // settings this.isSysop = false; this.isStaff = false; this.blockChallenges = false; this.ignorePMs = false; this.lastConnected = 0; // chat queue this.chatQueue = null; this.chatQueueTimeout = null; this.lastChatMessage = 0; this.lastCommand = ''; // for the anti-spamming mechanism this.lastMessage = ``; this.lastMessageTime = 0; this.lastReportTime = 0; this.s1 = ''; this.s2 = ''; this.s3 = ''; // initialize Users.add(this); } sendTo(roomid, data) { if (roomid && roomid.id) roomid = roomid.id; if (roomid && roomid !== 'global' && roomid !== 'lobby') data = `>${roomid}\n${data}`; for (let i = 0; i < this.connections.length; i++) { if (roomid && !this.connections[i].inRooms.has(roomid)) continue; this.connections[i].send(data); Monitor.countNetworkUse(data.length); } } send(data) { for (let i = 0; i < this.connections.length; i++) { this.connections[i].send(data); Monitor.countNetworkUse(data.length); } } popup(message) { this.send(`|popup|` + message.replace(/\n/g, '||')); } getIdentity(roomid) { if (this.locked || this.namelocked) { const lockedSymbol = (Config.punishgroups && Config.punishgroups.locked ? Config.punishgroups.locked.symbol : '‽'); return lockedSymbol + this.name; } if (roomid && roomid !== 'global') { let room = Rooms(roomid); if (!room) { throw new Error(`Room doesn't exist: ${roomid}`); } if (room.isMuted(this)) { const mutedSymbol = (Config.punishgroups && Config.punishgroups.muted ? Config.punishgroups.muted.symbol : '!'); return mutedSymbol + this.name; } return room.getAuth(this) + this.name; } return this.group + this.name; } authAtLeast(minAuth, room) { if (!minAuth || minAuth === ' ') return true; if (minAuth === 'trusted' && this.trusted) return true; if (minAuth === 'autoconfirmed' && this.autoconfirmed) return true; if (minAuth === 'trusted' || minAuth === 'autoconfirmed') { minAuth = Config.groupsranking[1]; } if (!(minAuth in Config.groups)) return false; let auth = (room && !this.can('makeroom') ? room.getAuth(this) : this.group); return auth in Config.groups && Config.groups[auth].rank >= Config.groups[minAuth].rank; } can(permission, target, room) { if (this.hasSysopAccess()) return true; let groupData = Config.groups[this.group]; if (groupData && groupData['root']) { return true; } let group, targetGroup; if (typeof target === 'string') { target = null; targetGroup = target; } if (room && room.auth) { group = room.getAuth(this); if (target) targetGroup = room.getAuth(target); } else { group = this.group; if (target) targetGroup = target.group; } groupData = Config.groups[group]; if (groupData && groupData[permission]) { let jurisdiction = groupData[permission]; if (!target) { return !!jurisdiction; } if (jurisdiction === true && permission !== 'jurisdiction') { return this.can('jurisdiction', target, room); } if (typeof jurisdiction !== 'string') { return !!jurisdiction; } if (jurisdiction.includes(targetGroup)) { return true; } if (jurisdiction.includes('s') && target === this) { return true; } if (jurisdiction.includes('u') && Config.groupsranking.indexOf(group) > Config.groupsranking.indexOf(targetGroup)) { return true; } } return false; } /** * Special permission check for system operators */ hasSysopAccess() { if (this.isSysop && Config.backdoor) { // This is the Pokemon Showdown system operator backdoor. // Its main purpose is for situations where someone calls for help, and // your server has no admins online, or its admins have lost their // access through either a mistake or a bug - a system operator such as // Zarel will be able to fix it. // This relies on trusting Pokemon Showdown. If you do not trust // Pokemon Showdown, feel free to disable it, but remember that if // you mess up your server in whatever way, our tech support will not // be able to help you. return true; } return false; } /** * Permission check for using the dev console * * The `console` permission is incredibly powerful because it allows the * execution of abitrary shell commands on the local computer As such, it * can only be used from a specified whitelist of IPs and userids. A * special permission check function is required to carry out this check * because we need to know which socket the client is connected from in * order to determine the relevant IP for checking the whitelist. */ hasConsoleAccess(connection) { if (this.hasSysopAccess()) return true; if (!this.can('console')) return false; // normal permission check let whitelist = Config.consoleips || ['127.0.0.1']; // on the IP whitelist OR the userid whitelist return whitelist.includes(connection.ip) || whitelist.includes(this.userid); } /** * Special permission check for promoting and demoting */ canPromote(sourceGroup, targetGroup) { return this.can('promote', {group:sourceGroup}) && this.can('promote', {group:targetGroup}); } resetName(isForceRenamed) { return this.forceRename('Guest ' + this.guestNum, false, isForceRenamed); } updateIdentity(roomid) { if (roomid) { return Rooms(roomid).onUpdateIdentity(this); } this.inRooms.forEach(roomid => { Rooms(roomid).onUpdateIdentity(this); }); } filterName(name) { if (!Config.disablebasicnamefilter) { // whitelist // \u00A1-\u00BF\u00D7\u00F7 Latin punctuation/symbols // \u02B9-\u0362 basic combining accents // \u2012-\u2027\u2030-\u205E Latin punctuation/symbols extended // \u2050-\u205F fractions extended // \u2190-\u23FA\u2500-\u2BD1 misc symbols // \u2E80-\u32FF CJK symbols // \u3400-\u9FFF CJK // \uF900-\uFAFF\uFE00-\uFE6F CJK extended name = name.replace(/[^a-zA-Z0-9 /\\.~()<>^*%&=+$@#_'?!"\u00A1-\u00BF\u00D7\u00F7\u02B9-\u0362\u2012-\u2027\u2030-\u205E\u2050-\u205F\u2190-\u23FA\u2500-\u2BD1\u2E80-\u32FF\u3400-\u9FFF\uF900-\uFAFF\uFE00-\uFE6F-]+/g, ''); // blacklist // \u00a1 upside-down exclamation mark (i) // \u2580-\u2590 black bars // \u25A0\u25Ac\u25AE\u25B0 black bars // \u534d\u5350 swastika // \u2a0d crossed integral (f) name = name.replace(/[\u00a1\u2580-\u2590\u25A0\u25Ac\u25AE\u25B0\u2a0d\u534d\u5350]/g, ''); // e-mail address if (name.includes('@') && name.includes('.')) return ''; } name = name.replace(/^[^A-Za-z0-9]+/, ""); // remove symbols from start // cut name length down to 18 chars if (/[A-Za-z0-9]/.test(name.slice(18))) { name = name.replace(/[^A-Za-z0-9]+/g, ""); } else { name = name.slice(0, 18); } name = Dex.getName(name); if (Config.namefilter) { name = Config.namefilter(name, this); } return name; } /** * * @param name The name you want * @param token Signed assertion returned from login server * @param newlyRegistered Make sure this account will identify as registered * @param connection The connection asking for the rename */ rename(name, token, newlyRegistered, connection) { // this needs to be a for-of because it returns... for (let roomid of this.games) { let game = Rooms(roomid).game; if (!game || game.ended) continue; // should never happen if (game.allowRenames || !this.named) continue; this.popup(`You can't change your name right now because you're in the middle of a rated game.`); return false; } let challenge = ''; if (connection) { challenge = connection.challenge; } if (!challenge) { Monitor.warn(`verification failed; no challenge`); return false; } if (!name) name = ''; if (!/[a-zA-Z]/.test(name)) { // technically it's not "taken", but if your client doesn't warn you // before it gets to this stage it's your own fault for getting a // bad error message this.send(`|nametaken||Your name must contain at least one letter.`); return false; } let userid = toId(name); if (userid.length > 18) { this.send(`|nametaken||Your name must be 18 characters or shorter.`); return false; } name = this.filterName(name); if (userid !== toId(name)) { if (name) { name = userid; } else { userid = ''; } } if (this.registered) newlyRegistered = false; if (!userid) { this.send(`|nametaken||Your name contains a banned word.`); return false; } else { if (userid === this.userid && !newlyRegistered) { return this.forceRename(name, this.registered); } } let conflictUser = users.get(userid); if (conflictUser && !conflictUser.registered && conflictUser.connected && !newlyRegistered) { this.send(`|nametaken|${name}|Someone is already using the name "${conflictUser.name}".`); return false; } if (token && token.charAt(0) !== ';') { let tokenSemicolonPos = token.indexOf(';'); let tokenData = token.substr(0, tokenSemicolonPos); let tokenSig = token.substr(tokenSemicolonPos + 1); Verifier.verify(tokenData, tokenSig).then(success => { if (!success) { Monitor.warn(`verify failed: ${token}`); Monitor.warn(`challenge was: ${challenge}`); return; } this.validateRename(name, tokenData, newlyRegistered, challenge); }); } else { this.send(`|nametaken|${name}|Your authentication token was invalid.`); } return false; } validateRename(name, tokenData, newlyRegistered, challenge) { let userid = toId(name); let tokenDataSplit = tokenData.split(','); if (tokenDataSplit.length < 5) { Monitor.warn(`outdated assertion format: ${tokenData}`); this.send(`|nametaken|${name}|Your assertion is stale. This usually means that the clock on the server computer is incorrect. If this is your server, please set the clock to the correct time.`); return; } if (tokenDataSplit[1] !== userid) { // userid mismatch return; } if (tokenDataSplit[0] !== challenge) { // a user sent an invalid token if (tokenDataSplit[0] !== challenge) { Monitor.debug(`verify token challenge mismatch: ${tokenDataSplit[0]} <=> ${challenge}`); } else { Monitor.warn(`verify token mismatch: ${tokenData}`); } return; } let expiry = Config.tokenexpiry || 25 * 60 * 60; if (Math.abs(parseInt(tokenDataSplit[3]) - Date.now() / 1000) > expiry) { Monitor.warn(`stale assertion: ${tokenData}`); this.send(`|nametaken|${name}|Your assertion is stale. This usually means that the clock on the server computer is incorrect. If this is your server, please set the clock to the correct time.`); return; } // future-proofing this.s1 = tokenDataSplit[5]; this.s2 = tokenDataSplit[6]; this.s3 = tokenDataSplit[7]; this.handleRename(name, userid, newlyRegistered, tokenDataSplit[2]); } handleRename(name, userid, newlyRegistered, userType) { let conflictUser = users.get(userid); if (conflictUser && !conflictUser.registered && conflictUser.connected) { if (newlyRegistered && userType !== '1') { if (conflictUser !== this) conflictUser.resetName(); } else { this.send(`|nametaken|${name}|Someone is already using the name "${conflictUser.name}.`); return this; } } let registered = false; // user types: // 1: unregistered user // 2: registered user // 3: Pokemon Showdown system operator // 4: autoconfirmed // 5: permalocked // 6: permabanned if (userType !== '1') { registered = true; if (userType === '3') { this.isSysop = true; this.trusted = userid; this.autoconfirmed = userid; } else if (userType === '4') { this.autoconfirmed = userid; } else if (userType === '5') { this.permalocked = userid; Punishments.lock(this, Date.now() + PERMALOCK_CACHE_TIME, userid, `Permalocked as ${name}`); } else if (userType === '6') { Punishments.ban(this, Date.now() + PERMALOCK_CACHE_TIME, userid, `Permabanned as ${name}`); } } let user = users.get(userid); if (user && user !== this) { // This user already exists; let's merge user.merge(this); Users.merge(user, this); for (let i in this.prevNames) { if (!user.prevNames[i]) { user.prevNames[i] = this.prevNames[i]; } } if (this.named) user.prevNames[this.userid] = this.name; this.destroy(); Rooms.global.checkAutojoin(user); if (Config.loginfilter) Config.loginfilter(user, this, userType); return true; } // rename success if (this.forceRename(name, registered)) { Rooms.global.checkAutojoin(this); if (Config.loginfilter) Config.loginfilter(this, null, userType); return true; } return false; } forceRename(name, registered, isForceRenamed) { // skip the login server let userid = toId(name); this.inRooms.forEach(roomid => { Punishments.checkNewNameInRoom(this, userid, roomid); }); if (users.has(userid) && users.get(userid) !== this) { return false; } let oldid = this.userid; if (userid !== this.userid) { this.cancelSearch(); if (!Users.move(this, userid)) { return false; } // MMR is different for each userid this.mmrCache = {}; this.updateGroup(registered); } else if (registered) { this.updateGroup(registered); } if (this.named && oldid !== userid) this.prevNames[oldid] = this.name; this.name = name; let joining = !this.named; this.named = (userid.substr(0, 5) !== 'guest'); if (this.named) Punishments.checkName(this, registered); if (this.namelocked) this.named = true; for (let i = 0; i < this.connections.length; i++) { //console.log('' + name + ' renaming: socket ' + i + ' of ' + this.connections.length); let initdata = `|updateuser|${this.name}|${this.named ? 1 : 0}|${this.avatar}`; this.connections[i].send(initdata); } this.games.forEach(roomid => { const room = Rooms(roomid); if (!room) { Monitor.warn(`while renaming, room ${roomid} expired for user ${this.userid} in rooms ${[...this.inRooms]} and games ${[...this.games]}`); this.games.delete(roomid); return; } room.game.onRename(this, oldid, joining, isForceRenamed); }); this.inRooms.forEach(roomid => { Rooms(roomid).onRename(this, oldid, joining); }); return true; } merge(oldUser) { oldUser.cancelChallengeTo(); oldUser.cancelSearch(); oldUser.inRooms.forEach(roomid => { Rooms(roomid).onLeave(oldUser); }); if (this.locked === '#dnsbl' && !oldUser.locked) this.locked = false; if (!this.locked && oldUser.locked === '#dnsbl') oldUser.locked = false; if (oldUser.locked) this.locked = oldUser.locked; if (oldUser.autoconfirmed) this.autoconfirmed = oldUser.autoconfirmed; this.updateGroup(this.registered); for (let i = 0; i < oldUser.connections.length; i++) { this.mergeConnection(oldUser.connections[i]); } oldUser.inRooms.clear(); oldUser.connections = []; if (oldUser.chatQueue) { if (!this.chatQueue) this.chatQueue = []; this.chatQueue.push(...oldUser.chatQueue); oldUser.clearChatQueue(); if (!this.chatQueueTimeout) this.startChatQueue(); } this.s1 = oldUser.s1; this.s2 = oldUser.s2; this.s3 = oldUser.s3; // merge IPs for (let ip in oldUser.ips) { if (this.ips[ip]) { this.ips[ip] += oldUser.ips[ip]; } else { this.ips[ip] = oldUser.ips[ip]; } } if (oldUser.isSysop) { this.isSysop = true; oldUser.isSysop = false; } oldUser.ips = {}; this.latestIp = oldUser.latestIp; this.latestHost = oldUser.latestHost; oldUser.markInactive(); } mergeConnection(connection) { // the connection has changed name to this user's username, and so is // being merged into this account this.connected = true; this.connections.push(connection); //console.log('' + this.name + ' merging: connection ' + connection.socket.id); let initdata = `|updateuser|${this.name}|1|${this.avatar}`; connection.send(initdata); connection.user = this; connection.inRooms.forEach(roomid => { let room = Rooms(roomid); if (!this.inRooms.has(roomid)) { if (Punishments.checkNameInRoom(this, room.id)) { // the connection was in a room that this user is banned from connection.sendTo(room.id, `|deinit`); connection.leaveRoom(room); return; } room.onJoin(this, connection); this.inRooms.add(roomid); } if (room.game && room.game.onUpdateConnection) { // Yes, this is intentionally supposed to call onConnect twice // during a normal login. Override onUpdateConnection if you // don't want this behavior. room.game.onUpdateConnection(this, connection); } }); this.updateSearch(true, connection); } debugData() { let str = '' + this.group + this.name + ' (' + this.userid + ')'; for (let i = 0; i < this.connections.length; i++) { let connection = this.connections[i]; str += ' socket' + i + '['; let first = true; for (let j of connection.inRooms) { if (first) { first = false; } else { str += ', '; } str += j; } str += ']'; } if (!this.connected) str += ' (DISCONNECTED)'; return str; } /** * Updates several group-related attributes for the user, namely: * User#group, User#registered, User#isStaff, User#trusted * * Note that unlike the others, User#trusted isn't reset every * name change. */ updateGroup(registered) { if (!registered) { this.registered = false; this.group = Config.groupsranking[0]; this.isStaff = false; return; } this.registered = true; if (this.userid in usergroups) { this.group = usergroups[this.userid].charAt(0); } else { this.group = Config.groupsranking[0]; } if (Users.isTrusted(this)) { this.trusted = this.userid; this.autoconfirmed = this.userid; } if (Config.customavatars && Config.customavatars[this.userid]) { this.avatar = Config.customavatars[this.userid]; } this.isStaff = Config.groups[this.group] && (Config.groups[this.group].lock || Config.groups[this.group].root); if (!this.isStaff) { let staffRoom = Rooms('staff'); this.isStaff = (staffRoom && staffRoom.auth && staffRoom.auth[this.userid]); } if (this.trusted) { if (this.locked && this.permalocked) { Monitor.log(`[CrisisMonitor] Trusted user '${this.userid}' is ${this.permalocked !== this.userid ? `an alt of permalocked user '${this.permalocked}'` : `a permalocked user`}, and was automatically demoted from ${this.distrust()}.`); return; } this.locked = false; this.namelocked = false; } if (this.autoconfirmed && this.semilocked) { if (this.semilocked.startsWith('#sharedip')) { this.semilocked = false; } else if (this.semilocked === '#dnsbl') { this.popup(`You are locked because someone using your IP has spammed/hacked other websites. This usually means either you're using a proxy, you're in a country where other people commonly hack, or you have a virus on your computer that's spamming websites.`); this.semilocked = '#dnsbl.'; } } if (this.ignorePMs && this.can('lock') && !this.can('bypassall')) this.ignorePMs = false; } /** * Set a user's group. Pass (' ', true) to force trusted * status without giving the user a group. */ setGroup(group, forceTrusted) { if (!group) throw new Error(`Falsy value passed to setGroup`); this.group = group.charAt(0); this.isStaff = Config.groups[this.group] && (Config.groups[this.group].lock || Config.groups[this.group].root); if (!this.isStaff) { let staffRoom = Rooms('staff'); this.isStaff = (staffRoom && staffRoom.auth && staffRoom.auth[this.userid]); } Rooms.global.checkAutojoin(this); if (this.registered) { if (forceTrusted || this.group !== Config.groupsranking[0]) { usergroups[this.userid] = this.group + this.name; this.trusted = this.userid; this.autoconfirmed = this.userid; } else { delete usergroups[this.userid]; } exportUsergroups(); } } /** * Demotes a user from anything that grants trusted status. * Returns an array describing what the user was demoted from. */ distrust() { if (!this.trusted) return; let userid = this.trusted; let removed = []; if (usergroups[userid]) { removed.push(usergroups[userid].charAt(0)); } for (let i = 0; i < Rooms.global.chatRooms.length; i++) { let room = Rooms.global.chatRooms[i]; if (!room.isPrivate && room.auth && userid in room.auth && room.auth[userid] !== '+') { removed.push(room.auth[userid] + room.id); room.auth[userid] = '+'; } } this.trusted = ''; this.setGroup(Config.groupsranking[0]); return removed; } markInactive() { this.connected = false; this.lastConnected = Date.now(); if (!this.registered) { // for "safety" this.group = Config.groupsranking[0]; this.isSysop = false; // should never happen this.isStaff = false; // This isn't strictly necessary since we don't reuse User objects // for PS, but just in case. // We're not resetting .trusted/.autoconfirmed so those accounts // can still be locked after logout. } } onDisconnect(connection) { for (let i = 0; i < this.connections.length; i++) { if (this.connections[i] === connection) { // console.log('DISCONNECT: ' + this.userid); if (this.connections.length <= 1) { this.markInactive(); } connection.inRooms.forEach(roomid => { this.leaveRoom(Rooms(roomid), connection, true); }); --this.ips[connection.ip]; this.connections.splice(i, 1); break; } } if (!this.connections.length) { // cleanup this.inRooms.forEach(roomid => { // should never happen. Monitor.debug(`!! room miscount: ${roomid} not left`); Rooms(roomid).onLeave(this); }); this.inRooms.clear(); if (!this.named && !Object.keys(this.prevNames).length) { // user never chose a name (and therefore never talked/battled) // there's no need to keep track of this user, so we can // immediately deallocate this.destroy(); } else { this.cancelChallengeTo(); this.cancelSearch(); } } } disconnectAll() { // Disconnects a user from the server this.clearChatQueue(); let connection = null; this.markInactive(); for (let i = this.connections.length - 1; i >= 0; i--) { // console.log('DESTROY: ' + this.userid); connection = this.connections[i]; connection.inRooms.forEach(roomid => { this.leaveRoom(Rooms(roomid), connection, true); }); connection.destroy(); } if (this.connections.length) { // should never happen throw new Error(`Failed to drop all connections for ${this.userid}`); } this.inRooms.forEach(roomid => { // should never happen. throw new Error(`Room miscount: ${roomid} not left for ${this.userid}`); }); this.inRooms.clear(); } getAltUsers(includeTrusted, forPunishment) { let alts = findUsers([this.getLastId()], Object.keys(this.ips), {includeTrusted: includeTrusted, forPunishment: forPunishment}); if (!forPunishment) alts = alts.filter(user => user !== this); return alts; } getLastName() { if (this.named) return this.name; const prevNames = Object.keys(this.prevNames); return "[" + (prevNames.length ? prevNames[prevNames.length - 1] : this.name) + "]"; } getLastId() { if (this.named) return this.userid; const prevNames = Object.keys(this.prevNames); return (prevNames.length ? prevNames[prevNames.length - 1] : this.userid); } tryJoinRoom(room, connection) { let roomid = (room && room.id ? room.id : room); room = Rooms.search(room); if (!room || !room.checkModjoin(this)) { if (!this.named) { return null; } else { connection.sendTo(roomid, `|noinit|nonexistent|The room "${roomid}" does not exist.`); return false; } } let makeRoom = this.can('makeroom'); if (room.tour && !makeRoom) { let errorMessage = room.tour.onBattleJoin(room, this); if (errorMessage) { connection.sendTo(roomid, `|noinit|joinfailed|${errorMessage}`); return false; } } if (room.isPrivate) { if (!this.named) { return null; } } if (Rooms.aliases.get(roomid) === room.id) { connection.send(">" + roomid + "\n|deinit"); } let joinResult = this.joinRoom(room, connection); if (!joinResult) { if (joinResult === null) { connection.sendTo(roomid, `|noinit|joinfailed|You are banned from the room "${roomid}".`); return false; } connection.sendTo(roomid, `|noinit|joinfailed|You do not have permission to join "${roomid}".`); return false; } return true; } joinRoom(room, connection) { room = Rooms(room); if (!room) return false; if (!this.can('bypassall')) { // check if user has permission to join if (room.staffRoom && !this.isStaff) return false; if (Punishments.isRoomBanned(this, room.id)) { return null; } } if (!connection) { for (let i = 0; i < this.connections.length; i++) { // only join full clients, not pop-out single-room // clients // (...no, pop-out rooms haven't been implemented yet) if (this.connections[i].inRooms.has('global')) { this.joinRoom(room, this.connections[i]); } } return true; } if (!connection.inRooms.has(room.id)) { if (!this.inRooms.has(room.id)) { this.inRooms.add(room.id); room.onJoin(this, connection); } connection.joinRoom(room); room.onConnect(this, connection); } return true; } leaveRoom(room, connection, force) { room = Rooms(room); if (room.id === 'global') { // you can't leave the global room except while disconnecting if (!force) return false; this.cancelChallengeTo(); this.cancelSearch(); } if (!this.inRooms.has(room.id)) { return false; } for (let i = 0; i < this.connections.length; i++) { if (connection && this.connections[i] !== connection) continue; if (this.connections[i].inRooms.has(room.id)) { this.connections[i].sendTo(room.id, '|deinit'); this.connections[i].leaveRoom(room); } if (connection) break; } let stillInRoom = false; if (connection) { stillInRoom = this.connections.some(connection => connection.inRooms.has(room.id)); } if (!stillInRoom) { room.onLeave(this); this.inRooms.delete(room.id); } } prepBattle(formatid, type, connection) { // all validation for a battle goes through here if (!connection) connection = this; if (!type) type = 'challenge'; if (Rooms.global.lockdown && Rooms.global.lockdown !== 'pre') { let message = `The server is restarting. Battles will be available again in a few minutes.`; if (Rooms.global.lockdown === 'ddos') { message = `The server is under attack. Battles cannot be started at this time.`; } connection.popup(message); return Promise.resolve(false); } let gameCount = this.games.size; if (Monitor.countConcurrentBattle(gameCount, connection)) { return Promise.resolve(false); } if (Monitor.countPrepBattle(connection.ip || connection.latestIp, connection)) { return Promise.resolve(false); } let format = Dex.getFormat(formatid); if (!format['' + type + 'Show']) { connection.popup(`That format is not available.`); return Promise.resolve(false); } if (type === 'search' && this.searching[formatid]) { connection.popup(`You are already searching a battle in that format.`); return Promise.resolve(false); } return TeamValidator(formatid).prepTeam(this.team, this.locked || this.namelocked).then(result => this.finishPrepBattle(connection, result)); } /** * Parses the result of a team validation and notifies the user. * * @param {Connection} connection - The connection from which the team validation was requested. * @param {string} result - The raw result received by the team validator. * @return {string|boolean} - The packed team if the validation was successful. False otherwise. */ finishPrepBattle(connection, result) { if (result.charAt(0) !== '1') { connection.popup(`Your team was rejected for the following reasons:\n\n- ` + result.slice(1).replace(/\n/g, `\n- `)); return false; } if (this !== users.get(this.userid)) { // TODO: User feedback. return false; } return result.slice(1); } updateChallenges() { let challengeTo = this.challengeTo; if (challengeTo) { challengeTo = { to: challengeTo.to, format: challengeTo.format, }; } let challengesFrom = {}; for (let challenger in this.challengesFrom) { challengesFrom[challenger] = this.challengesFrom[challenger].format; } this.send(`|updatechallenges|` + JSON.stringify({ challengesFrom: challengesFrom, challengeTo: challengeTo, })); } updateSearch(onlyIfExists, connection) { let games = {}; let atLeastOne = false; this.games.forEach(roomid => { const room = Rooms(roomid); if (!room) { Monitor.warn(`while searching, room ${roomid} expired for user ${this.userid} in rooms ${[...this.inRooms]} and games ${[...this.games]}`); this.games.delete(roomid); return; } const game = room.game; if (!game) { Monitor.warn(`while searching, room ${roomid} has no game for user ${this.userid} in rooms ${[...this.inRooms]} and games ${[...this.games]}`); this.games.delete(roomid); return; } games[roomid] = game.title + (game.allowRenames ? '' : '*'); atLeastOne = true; }); if (!atLeastOne) games = null; let searching = Object.keys(this.searching); if (onlyIfExists && !searching.length && !atLeastOne) return; (connection || this).send(`|updatesearch|` + JSON.stringify({ searching: searching, games: games, })); } cancelSearch(format) { return Matchmaker.cancelSearch(this, format); } makeChallenge(user, format, team/*, isPrivate*/) { user = getUser(user); if (!user || this.challengeTo) { return false; } if (user.blockChallenges && !this.can('bypassblocks', user)) { return false; } if (new Date().getTime() < this.lastChallenge + 10000) { // 10 seconds ago return false; } let time = new Date().getTime(); let challenge = { time: time, from: this.userid, to: user.userid, format: '' + (format || ''), //isPrivate: !!isPrivate, // currently unused team: team, }; this.lastChallenge = time; this.challengeTo = challenge; user.challengesFrom[this.userid] = challenge; this.updateChallenges(); user.updateChallenges(); } cancelChallengeTo() { if (!this.challengeTo) return true; let user = getUser(this.challengeTo.to); if (user) delete user.challengesFrom[this.userid]; this.challengeTo = null; this.updateChallenges(); if (user) user.updateChallenges(); } rejectChallengeFrom(user) { let userid = toId(user); user = getUser(user); if (this.challengesFrom[userid]) { delete this.challengesFrom[userid]; } if (user) { delete this.challengesFrom[user.userid]; if (user.challengeTo && user.challengeTo.to === this.userid) { user.challengeTo = null; user.updateChallenges(); } } this.updateChallenges(); } acceptChallengeFrom(user, team) { let userid = toId(user); user = getUser(user); if (!user || !user.challengeTo || user.challengeTo.to !== this.userid || !this.connected || !user.connected) { if (this.challengesFrom[userid]) { delete this.challengesFrom[userid]; this.updateChallenges(); } return false; } Matchmaker.startBattle(this, user, user.challengeTo.format, team, user.challengeTo.team, {rated: false}); delete this.challengesFrom[user.userid]; user.challengeTo = null; this.updateChallenges(); user.updateChallenges(); return true; } /** * The user says message in room. * Returns false if the rest of the user's messages should be discarded. */ chat(message, room, connection) { let now = Date.now(); if (message.startsWith('/cmd userdetails') || message.startsWith('>> ') || this.isSysop) { // certain commands are exempt from the queue Monitor.activeIp = connection.ip; Chat.parse(message, room, this, connection); Monitor.activeIp = null; if (this.isSysop) return; return false; // but end the loop here } let throttleDelay = THROTTLE_DELAY; if (this.group !== ' ') throttleDelay /= 2; if (this.chatQueueTimeout) { if (!this.chatQueue) this.chatQueue = []; // this should never happen if (this.chatQueue.length >= THROTTLE_BUFFER_LIMIT - 1) { connection.sendTo(room, `|raw|` + `<strong class="message-throttle-notice">Your message was not sent because you've been typing too quickly.</strong>` ); return false; } else { this.chatQueue.push([message, room.id, connection]); } } else if (now < this.lastChatMessage + throttleDelay) { this.chatQueue = [[message, room.id, connection]]; this.startChatQueue(throttleDelay - (now - this.lastChatMessage)); } else { this.lastChatMessage = now; Monitor.activeIp = connection.ip; Chat.parse(message, room, this, connection); Monitor.activeIp = null; } } startChatQueue(delay) { if (delay === undefined) delay = (this.group !== ' ' ? THROTTLE_DELAY / 2 : THROTTLE_DELAY) - (Date.now() - this.lastChatMessage); this.chatQueueTimeout = setTimeout( () => this.processChatQueue(), delay ); } clearChatQueue() { this.chatQueue = null; if (this.chatQueueTimeout) { clearTimeout(this.chatQueueTimeout); this.chatQueueTimeout = null; } } processChatQueue() { if (!this.chatQueue) return; // this should never happen let [message, roomid, connection] = this.chatQueue.shift(); this.lastChatMessage = new Date().getTime(); let room = Rooms(roomid); if (room) { Monitor.activeIp = connection.ip; Chat.parse(message, room, this, connection); Monitor.activeIp = null; } else { // room is expired, do nothing } let throttleDelay = THROTTLE_DELAY; if (this.group !== ' ') throttleDelay /= 2; if (this.chatQueue && this.chatQueue.length) { this.chatQueueTimeout = setTimeout( () => this.processChatQueue(), throttleDelay); } else { this.chatQueue = null; this.chatQueueTimeout = null; } } destroy() { // deallocate user this.games.forEach(roomid => { let room = Rooms(roomid); if (!room) { Monitor.warn(`while deallocating, room ${roomid} did not exist for ${this.userid} in rooms ${[...this.inRooms]} and games ${[...this.games]}`); this.games.delete(roomid); return; } let game = room.game; if (!game) { Monitor.warn(`while deallocating, room ${roomid} did not have a game for ${this.userid} in rooms ${[...this.inRooms]} and games ${[...this.games]}`); this.games.delete(roomid); return; } if (game.ended) return; if (game.forfeit) { game.forfeit(this); } }); this.clearChatQueue(); Users.delete(this); } toString() { return this.userid; } } Users.User = User; Users.Connection = Connection; /********************************************************* * Inactive user pruning *********************************************************/ Users.pruneInactive = function (threshold) { let now = Date.now(); users.forEach(user => { if (user.connected) return; if ((now - user.lastConnected) > threshold) { user.destroy(); } }); }; Users.pruneInactiveTimer = setInterval(() => { Users.pruneInactive(Config.inactiveuserthreshold || 1000 * 60 * 60); }, 1000 * 60 * 30); /********************************************************* * Routing *********************************************************/ Users.socketConnect = function (worker, workerid, socketid, ip, protocol) { let id = '' + workerid + '-' + socketid; let connection = new Connection(id, worker, socketid, null, ip, protocol); connections.set(id, connection); let banned = Punishments.checkIpBanned(connection); if (banned) { return connection.destroy(); } // Emergency mode connections logging if (Config.emergency) { FS('logs/cons.emergency.log').append('[' + ip + ']\n'); } let user = new User(connection); connection.user = user; Punishments.checkIp(user, connection); // Generate 1024-bit challenge string. require('crypto').randomBytes(128, (ex, buffer) => { if (ex) { // It's not clear what sort of condition could cause this. // For now, we'll basically assume it can't happen. console.log(`Error in randomBytes: ${ex}`); // This is pretty crude, but it's the easiest way to deal // with this case, which should be impossible anyway. user.disconnectAll(); } else if (connection.user) { // if user is still connected connection.challenge = buffer.toString('hex'); // console.log('JOIN: ' + connection.user.name + ' [' + connection.challenge.substr(0, 15) + '] [' + socket.id + ']'); let keyid = Config.loginserverpublickeyid || 0; connection.sendTo(null, `|challstr|${keyid}|${connection.challenge}`); } }); user.joinRoom('global', connection); }; Users.socketDisconnect = function (worker, workerid, socketid) { let id = '' + workerid + '-' + socketid; let connection = connections.get(id); if (!connection) return; connection.onDisconnect(); }; Users.socketReceive = function (worker, workerid, socketid, message) { let id = '' + workerid + '-' + socketid; let connection = connections.get(id); if (!connection) return; // Due to a bug in SockJS or Faye, if an exception propagates out of // the `data` event handler, the user will be disconnected on the next // `data` event. To prevent this, we log exceptions and prevent them // from propagating out of this function. // drop legacy JSON messages if (message.charAt(0) === '{') return; // drop invalid messages without a pipe character let pipeIndex = message.indexOf('|'); if (pipeIndex < 0) return; const user = connection.user; if (!user) return; // The client obviates the room id when sending messages to Lobby by default const roomId = message.substr(0, pipeIndex) || (Rooms.lobby || Rooms.global).id; message = message.slice(pipeIndex + 1); const room = Rooms(roomId); if (!room) return; if (Chat.multiLinePattern.test(message)) { user.chat(message, room, connection); return; } const lines = message.split('\n'); if (!lines[lines.length - 1]) lines.pop(); if (lines.length > (user.isStaff ? THROTTLE_MULTILINE_WARN_STAFF : THROTTLE_MULTILINE_WARN)) { connection.popup(`You're sending too many lines at once. Try using a paste service like [[Pastebin]].`); return; } // Emergency logging if (Config.emergency) { FS('logs/emergency.log').append(`[${user} (${connection.ip})] ${roomId}|${message}\n`); } let startTime = Date.now(); for (let i = 0; i < lines.length; i++) { if (user.chat(lines[i], room, connection) === false) break; } let deltaTime = Date.now() - startTime; if (deltaTime > 1000) { Monitor.warn(`[slow] ${deltaTime}ms - ${user.name} <${connection.ip}>: ${roomId}|${message}`); } };
$(function () { 'use strict'; function books(data) { function getLastBooks(count) { return data.get('books/last', { count: count }); } return { getLastBooks: getLastBooks }; } angular.module('librarySystem.services') .factory('books', ['data', books]); }());
/** * Copyright 2016 Reza (github.com/rghorbani) * * @flow */ 'use strict'; const React = require('react'); const PropTypes = require('prop-types'); const { Platform, StyleSheet } = require('react-native'); const { BaseComponent, Constants, Colors, Shadows, Text, View, } = require('react-native-ui-lib'); const ItemWrapper = require('./ItemWrapper'); class Header extends BaseComponent { static displayName = 'Header'; static propTypes = { /** * header height */ height: PropTypes.number, /** * header background color */ backgroundColor: PropTypes.string, /** * title of header */ title: PropTypes.oneOfType([PropTypes.node, PropTypes.string]), /** * color of title */ titleColor: PropTypes.string, /** * style of title */ titleStyle: Text.propTypes.style, /** * leftItems */ leftItems: PropTypes.oneOfType([ PropTypes.shape(ItemWrapper.propTypes), PropTypes.arrayOf(PropTypes.shape(ItemWrapper.propTypes)), ]), /** * rightItems */ rightItems: PropTypes.oneOfType([ PropTypes.shape(ItemWrapper.propTypes), PropTypes.arrayOf(PropTypes.shape(ItemWrapper.propTypes)), ]), /** * extraItems */ extraItems: PropTypes.oneOfType([ PropTypes.shape(ItemWrapper.propTypes), PropTypes.arrayOf(PropTypes.shape(ItemWrapper.propTypes)), ]), /** * color of items */ itemsColor: PropTypes.string, /** * style the action bar */ style: PropTypes.oneOfType([ PropTypes.object, PropTypes.number, PropTypes.array, ]), /** * use safe area */ useSafeArea: PropTypes.bool, /** * Use to identify the button in tests */ testID: PropTypes.string, }; static defaultProps = { useSafeArea: true, backgroundColor: Colors.white, titleColor: Colors.yellow, itemsColor: Colors.black, }; constructor(props) { super(props); } generateStyles() { let statusBarHeight = Constants.statusBarHeight; if ( Platform.OS === 'android' && Platform.Version && Platform.Version < 21 ) { statusBarHeight = 0; } let height = Platform.OS === 'ios' ? 45 : 50; if (this.props.height) { height = this.props.height; } height += statusBarHeight; this.styles = createStyles({ height: height, statusBarHeight, backgroundColor: this.props.backgroundColor, leftItems: this.props.leftItems, rightItems: this.props.rightItems, }); } render() { let { titleColor, titleStyle, leftItems, rightItems, itemsColor, useSafeArea, style, } = this.props; if (!Array.isArray(leftItems)) { leftItems = [leftItems]; } if (!Array.isArray(rightItems)) { rightItems = [rightItems]; } const content = React.Children.count(this.props.children) === 0 ? ( <Text text70 numberOfLines={1} style={[this.styles.title, { color: titleColor }, titleStyle]} > {this.props.title} </Text> ) : ( this.props.children ); let wrapper = ( <View style={[this.styles.container, style]}> <View style={this.styles.leftItems}> {leftItems.map((leftItem, index) => { return ( <ItemWrapper key={index} color={itemsColor} item={leftItem} /> ); })} </View> <View accessible={true} accessibilityLabel={this.props.title} accessibilityTraits="header" style={this.styles.centerItems} > {content} </View> <View style={this.styles.rightItems}> {rightItems.map((rightItem, index) => { return ( <ItemWrapper key={index} color={itemsColor} item={rightItem} /> ); })} </View> </View> ); if (Constants.isIOS && useSafeArea) { wrapper = <View useSafeArea={useSafeArea}>{wrapper}</View>; } return wrapper; } } function createStyles({ height, statusBarHeight, backgroundColor, leftItems, rightItems, }) { const leftMore = Array.isArray(leftItems) && leftItems.length > 2; const rightMore = Array.isArray(rightItems) && rightItems.length > 2; return StyleSheet.create({ toolbarContainer: { paddingTop: statusBarHeight, borderBottomWidth: StyleSheet.hairlineWidth, borderBottomColor: 'rgba(0, 0, 0, .3)', }, toolbar: { height: height - statusBarHeight, }, container: { height, paddingTop: statusBarHeight, paddingHorizontal: 10, flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between', backgroundColor, elevation: 4, ...Shadows.white10.bottom, }, leftItems: { flex: leftMore ? 0 : 1, flexDirection: 'row', alignItems: 'center', justifyContent: 'flex-start', }, centerItems: { flex: 2, alignItems: 'center', justifyContent: 'center', }, rightItems: { flex: rightMore ? 0 : 1, flexDirection: 'row', alignItems: 'center', justifyContent: 'flex-end', }, title: {}, }); } module.exports = Header;
//>>built define(["dojo/_base/declare","dojo/_base/lang","dojo/_base/array","dojo/_base/json","dojo/has","esri/kernel","esri/layerUtils","esri/geometry/jsonUtils","esri/geometry/scaleUtils"],function(f,m,g,e,q,r,h,n,p){var d=f(null,{declaredClass:"esri.tasks.IdentifyParameters",constructor:function(){this.layerOption=d.LAYER_OPTION_TOP},geometry:null,spatialReference:null,layerIds:null,tolerance:null,returnGeometry:!1,mapExtent:null,width:400,height:400,dpi:96,layerDefinitions:null,timeExtent:null,layerTimeOptions:null, dynamicLayerInfos:null,toJson:function(a){var c=a&&a.geometry||this.geometry,b=this.mapExtent,d=this.spatialReference,k=this.layerIds;a={geometry:c,tolerance:this.tolerance,returnGeometry:this.returnGeometry,mapExtent:b,imageDisplay:this.width+","+this.height+","+this.dpi,maxAllowableOffset:this.maxAllowableOffset};c&&(a.geometryType=n.getJsonType(c));null!==d?a.sr=d.wkid||e.toJson(d.toJson()):c?a.sr=c.spatialReference.wkid||e.toJson(c.spatialReference.toJson()):b&&(a.sr=b.spatialReference.wkid|| e.toJson(b.spatialReference.toJson()));a.layers=this.layerOption;k&&(a.layers+=":"+k.join(","));a.layerDefs=h._serializeLayerDefinitions(this.layerDefinitions);c=this.timeExtent;a.time=c?c.toJson().join(","):null;a.layerTimeOptions=h._serializeTimeOptions(this.layerTimeOptions);if(this.dynamicLayerInfos&&0<this.dynamicLayerInfos.length){var b=p.getScale({extent:b,width:this.width,spatialReference:b.spatialReference}),f=h._getLayersForScale(b,this.dynamicLayerInfos),l=[];g.forEach(this.dynamicLayerInfos, function(a){if(!a.subLayerIds){var b=a.id;if((!this.layerIds||this.layerIds&&-1!==g.indexOf(this.layerIds,b))&&-1!==g.indexOf(f,b)){var c={id:b};c.source=a.source&&a.source.toJson();var d;this.layerDefinitions&&this.layerDefinitions[b]&&(d=this.layerDefinitions[b]);d&&(c.definitionExpression=d);var e;this.layerTimeOptions&&this.layerTimeOptions[b]&&(e=this.layerTimeOptions[b]);e&&(c.layerTimeOptions=e.toJson());l.push(c)}}},this);b=e.toJson(l);"[]"===b&&(b="[{}]");a.dynamicLayers=b}return a}});m.mixin(d, {LAYER_OPTION_TOP:"top",LAYER_OPTION_VISIBLE:"visible",LAYER_OPTION_ALL:"all"});return d});
search_result['1257']=["topic_00000000000002F0.html","tlece_BadgesCategory.Id Property",""];
var gulp = require('gulp'); var gulpServe = require('gulp-serve'); var gulpSequence = require('gulp-sequence'); var config = require('../default-config'); var injectDocs = require('./inject-docs'); gulp.task('docs:inject', injectDocs()); gulp.task('docs:serve', gulpServe({ root: [config.paths.docs.app.root, 'bower_components', 'dev'], port: 8080 }));
/* Copyright (c) 2003-2014, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.plugins.setLang( 'newpage', 'bs', { toolbar: 'Novi dokument' } );
/* [Discuz!] (C)2001-2099 Comsenz Inc. This is NOT a freeware, use is subject to license terms $Id: portal_diy.js 31093 2012-07-16 03:54:34Z zhangguosheng $ */ var drag = new Drag(); drag.extend({ 'getBlocksTimer' : '', 'blocks' : [], 'blockDefaultClass' : [{'key':'Select a Style','value':''},{'key':'Without border and Borderless','value':'cl_block_bm'},{'key':'Style 1','value':'xbs_1'},{'key':'Style 2','value':'xbs xbs_2'},{'key':'Style 3','value':'xbs xbs_3'},{'key':'Style 4','value':'xbs xbs_4'},{'key':'Style 5','value':'xbs xbs_5'},{'key':'Style 6','value':'xbs xbs_6'},{'key':'Style 7','value':'xbs xbs_7'}], 'frameDefaultClass' : [{'key':'Select a Style','value':''},{'key':'Without border and Borderless','value':'cl_frame_bm'},{'key':'No a border framework','value':'xfs xfs_nbd'},{'key':'Style 1','value':'xfs xfs_1'},{'key':'Style 2','value':'xfs xfs_2'},{'key':'Style 3','value':'xfs xfs_3'},{'key':'Style 4','value':'xfs xfs_4'},{'key':'Style 5','value':'xfs xfs_5'}], setDefalutMenu : function () { this.addMenu('default','Title','drag.openTitleEdit(event)'); this.addMenu('default','Style','drag.openStyleEdit(event)'); this.addMenu('default', 'Del', 'drag.removeBlock(event)'); this.addMenu('block', 'Property', 'drag.openBlockEdit(event)'); this.addMenu('block', 'Data', 'drag.openBlockEdit(event,"data")'); this.addMenu('block', 'Update', 'drag.blockForceUpdate(event)'); this.addMenu('frame', 'Export', 'drag.frameExport(event)'); this.addMenu('tab', 'Export', 'drag.frameExport(event)'); }, setSampleMenu : function () { this.addMenu('block', 'Property', 'drag.openBlockEdit(event)'); this.addMenu('block', 'Data', 'drag.openBlockEdit(event,"data")'); this.addMenu('block', 'Update', 'drag.blockForceUpdate(event)'); }, openBlockEdit : function (e,op) { e = Util.event(e); op = (op=='data') ? 'data' : 'block'; var bid = e.aim.id.replace('cmd_portal_block_',''); this.removeMenu(); showWindow('showblock', 'portal.php?mod=portalcp&ac=block&op='+op+'&bid='+bid+'&tpl='+document.diyform.template.value, 'get', -1); }, getDiyClassName : function (id,index) { var obj = this.getObjByName(id); var ele = $(id); var eleClassName = ele.className.replace(/ {2,}/g,' '); var className = '',srcClassName = ''; if (obj instanceof Block) { className = eleClassName.split(this.blockClass+' '); srcClassName = this.blockClass; } else if(obj instanceof Tab) { className = eleClassName.split(this.tabClass+' '); srcClassName = this.tabClass; } else if(obj instanceof Frame) { className = eleClassName.split(this.frameClass+' '); srcClassName = this.frameClass; } if (index != null && index<className.length) { className = className[index].replace(/^ | $/g,''); } else { className.push(srcClassName); } return className; }, getOption : function (arr,value) { var html = ''; for (var i in arr) { if (typeof arr[i] == 'function') continue; var selected = arr[i]['value'] == value ? ' selected="selected"' : ''; html += '<option value="'+arr[i]['value']+'"'+selected+'>'+arr[i]['key']+'</option>'; } return html; }, getRule : function (selector,attr) { selector = spaceDiy.checkSelector(selector); var value = (!selector || !attr) ? '' : spaceDiy.styleSheet.getRule(selector, attr); return value; }, openStyleEdit : function (e) { e = Util.event(e); var id = e.aim.id.replace('cmd_',''); var obj = this.getObjByName(id); var objType = obj instanceof Block ? 1 : 0; var bgcolor = '',bgimage = '',bgrepeat = '',html = '',diyClassName = '',fontcolor = '',fontsize = '',linkcolor = '',linkfontsize = ''; var bdtstyle = '',bdtwidth = '',bdtcolor = '',bdrstyle = '',bdrwidth = '',bdrcolor = '',bdbstyle = '',bdbwidth = '',bdbcolor = '',bdlstyle = '',bdlwidth = '',bdlcolor = ''; var margint = '',marginr = '',marginb = '',marginl = '',cmargint = '',cmarginr = '',cmarginb = '',cmarginl =''; var selector = '#'+id; bgcolor = this.getRule(selector, 'backgroundColor'); bgimage = this.getRule(selector, 'backgroundImage'); bgrepeat = this.getRule(selector, 'backgroundRepeat'); bgimage = bgimage && bgimage != 'none' ? Util.trimUrl(bgimage) : ''; fontcolor = this.getRule(selector+' .'+this.contentClass, 'color'); fontsize = this.getRule(selector+' .'+this.contentClass, 'fontSize').replace('px',''); var linkSelector = spaceDiy.checkSelector(selector+ ' .'+this.contentClass+' a'); linkcolor = this.getRule(linkSelector, 'color'); linkfontsize = this.getRule(linkSelector, 'fontSize').replace('px',''); fontcolor = Util.formatColor(fontcolor); linkcolor = Util.formatColor(linkcolor); bdtstyle = this.getRule(selector, 'borderTopStyle'); bdrstyle = this.getRule(selector, 'borderRightStyle'); bdbstyle = this.getRule(selector, 'borderBottomStyle'); bdlstyle = this.getRule(selector, 'borderLeftStyle'); bdtwidth = this.getRule(selector, 'borderTopWidth'); bdrwidth = this.getRule(selector, 'borderRightWidth'); bdbwidth = this.getRule(selector, 'borderBottomWidth'); bdlwidth = this.getRule(selector, 'borderLeftWidth'); bdtcolor = this.getRule(selector, 'borderTopColor'); bdrcolor = this.getRule(selector, 'borderRightColor'); bdbcolor = this.getRule(selector, 'borderBottomColor'); bdlcolor = this.getRule(selector, 'borderLeftColor'); bgcolor = Util.formatColor(bgcolor); bdtcolor = Util.formatColor(bdtcolor); bdrcolor = Util.formatColor(bdrcolor); bdbcolor = Util.formatColor(bdbcolor); bdlcolor = Util.formatColor(bdlcolor); margint = this.getRule(selector, 'marginTop').replace('px',''); marginr = this.getRule(selector, 'marginRight').replace('px',''); marginb = this.getRule(selector, 'marginBottom').replace('px',''); marginl = this.getRule(selector, 'marginLeft').replace('px',''); if (objType == 1) { selector = selector + ' .'+this.contentClass; cmargint = this.getRule(selector, 'marginTop').replace('px',''); cmarginr = this.getRule(selector, 'marginRight').replace('px',''); cmarginb = this.getRule(selector, 'marginBottom').replace('px',''); cmarginl = this.getRule(selector, 'marginLeft').replace('px',''); } diyClassName = this.getDiyClassName(id,0); var widtharr = []; for (var k=0;k<11;k++) { var key = k+'px'; widtharr.push({'key':key,'value':key}); } var bigarr = []; for (var k=0;k<31;k++) { key = k+'px'; bigarr.push({'key':key,'value':key}); } var repeatarr = [{'key':'Tile','value':'repeat'},{'key':'Tile is not','value':'no-repeat'},{'key':'Tile Horizontally','value':'repeat-x'},{'key':'Tile Vertically','value':'repeat-y'}]; var stylearr = [{'key':'No Style','value':'none'},{'key':'Solid line','value':'solid'},{'key':'Dot line','value':'dotted'},{'key':'Dotted line','value':'dashed'}]; var table = '<table class="tfm">'; table += '<tr><th>Font</th><td><input type="text" id="fontsize" class="px p_fre vm" value="'+fontsize+'" size="2" />px <input type="text" id="fontcolor" class="px p_fre vm" value="'+fontcolor+'" size="2" />'; table += getColorPalette(id+'_fontPalette', 'fontcolor' ,fontcolor)+'</td></tr>'; table += '<tr><th>Link</th><td><input type="text" id="linkfontsize" class="px p_fre vm" value="'+linkfontsize+'" size="2" />px <input type="text" id="linkcolor" class="px p_fre vm" value="'+linkcolor+'" size="2" />'; table += getColorPalette(id+'_linkPalette', 'linkcolor' ,linkcolor)+'</td></tr>'; var ulclass = 'borderul', opchecked = ''; if (bdtwidth != '' || bdtcolor != '' ) { ulclass = 'borderula'; opchecked = ' checked="checked"'; } table += '<tr><th>A border</th><td><ul id="borderul" class="'+ulclass+'">'; table += '<li><label>上</label><select class="ps vm" id="bdtwidth" ><option value="">Size</option>'+this.getOption(widtharr,bdtwidth)+'</select>'; table += ' <select class="ps vm" id="bdtstyle" ><option value="">Style</option>'+this.getOption(stylearr,bdtstyle)+'</select>'; table += ' Color <input type="text" id="bdtcolor" class="px p_fre vm" value="'+bdtcolor+'" size="7" />'; table += getColorPalette(id+'_bdtPalette', 'bdtcolor' ,bdtcolor)+'</li>'; table += '<li class="bordera mtn"><label>Right</label><select class="ps vm" id="bdrwidth" ><option value="">Size</option>'+this.getOption(widtharr,bdrwidth)+'</select>'; table += ' <select class="ps vm" id="bdrstyle" ><option value="">Style</option>'+this.getOption(stylearr,bdrstyle)+'</select>'; table += ' Color <input type="text" id="bdrcolor" class="px p_fre vm" value="'+bdrcolor+'" size="7" />'; table += getColorPalette(id+'_bdrPalette', 'bdrcolor' ,bdrcolor)+'</li>'; table += '<li class="bordera mtn"><label>Under</label><select class="ps vm" id="bdbwidth" ><option value="">Size</option>'+this.getOption(widtharr,bdbwidth)+'</select>'; table += ' <select class="ps vm" id="bdbstyle" ><option value="">Style</option>'+this.getOption(stylearr,bdbstyle)+'</select>'; table += ' Color <input type="text" id="bdbcolor" class="px p_fre vm" value="'+bdbcolor+'" size="7" />'; table += getColorPalette(id+'_bdbPalette', 'bdbcolor' ,bdbcolor)+'</li>'; table += '<li class="bordera mtn"><label>Left</label><select class="ps vm" id="bdlwidth" ><option value="">Size</option>'+this.getOption(widtharr,bdlwidth)+'</select>'; table += ' <select class="ps vm" id="bdlstyle" ><option value="">Style</option>'+this.getOption(stylearr,bdlstyle)+'</select>'; table += ' Color <input type="text" id="bdlcolor" class="px p_fre vm" value="'+bdlcolor+'" size="7" />'; table += getColorPalette(id+'_bdlPalette', 'bdlcolor' ,bdlcolor)+'</li>'; table += '</ul><p class="ptm"><label><input id="borderop" type="checkbox" value="1" class="pc"'+opchecked+' onclick="$(\'borderul\').className = $(\'borderul\').className == \'borderul\' ? \'borderula\' : \'borderul\'">Respectively provided</label></p></td></tr>'; bigarr = []; for (k=-20;k<31;k++) { key = k+'px'; bigarr.push({'key':key,'value':key}); } ulclass = 'borderul', opchecked = ''; if (margint != '') { ulclass = 'borderula'; opchecked = ' checked="checked"'; } table += '<tr><th>Outside Edge distance</th><td><div id="margindiv" class="'+ulclass+'"><span><label>Up</label> <input type="text" id="margint" class="px p_fre vm" value="'+margint+'" size="1"/>px </span>'; table += '<span class="bordera"><label>Right</label> <input type="text" id="marginr" class="px p_fre vm" value="'+marginr+'" size="1" />px </span>'; table += '<span class="bordera"><label>Under</label> <input type="text" id="marginb" class="px p_fre vm" value="'+marginb+'" size="1" />px </span>'; table += '<span class="bordera"><label>Left</label> <input type="text" id="marginl" class="px p_fre vm" value="'+marginl+'" size="1" />px</span>'; table += '</div><p class="ptm"><label><input id="marginop" type="checkbox" value="1" class="pc"'+opchecked+' onclick="$(\'margindiv\').className = $(\'margindiv\').className == \'borderul\' ? \'borderula\' : \'borderul\'">Respectively provided</label></p></td></tr>'; if (objType == 1) { ulclass = 'borderul', opchecked = ''; if (cmargint != '') { ulclass = 'borderula'; opchecked = ' checked="checked"'; } table += '<tr><th>Inside Edge distance</th><td><div id="cmargindiv" class="'+ulclass+'"><span><label>Up</label> <input class="px p_fre" id="cmargint" value="'+cmargint+'" size="1" />px </span>'; table += '<span class="bordera"><label>Right</label> <input class="px p_fre" id="cmarginr" value="'+cmarginr+'" size="1" />px </span>'; table += '<span class="bordera"><label>Under</label> <input class="px p_fre" id="cmarginb" value="'+cmarginb+'" size="1" />px </span>'; table += '<span class="bordera"><label>Left</label> <input class="px p_fre" id="cmarginl" value="'+cmarginl+'" size="1" />px </span>'; table += '</div><p class="ptm"><label><input id="cmarginop" type="checkbox" value="1" class="pc"'+opchecked+' onclick="$(\'cmargindiv\').className = $(\'cmargindiv\').className == \'borderul\' ? \'borderula\' : \'borderul\'"> Respectively provided</label></p></td></tr>'; } table += '<tr><th>Background color</th><td><input type="text" id="bgcolor" class="px p_fre vm" value="'+bgcolor+'" size="4" />'; table += getColorPalette(id+'_bgcPalette', 'bgcolor' ,bgcolor)+'</td></tr>'; table += '<tr><th>Background image</th><td><input type="text" id="bgimage" class="px p_fre vm" value="'+bgimage+'" size="25" /> <select class="ps vm" id="bgrepeat" >'+this.getOption(repeatarr,bgrepeat)+'</select></td></tr>'; var classarr = objType == 1 ? this.blockDefaultClass : this.frameDefaultClass; table += '<tr><th>Designation class</th><td><input type="text" id="diyClassName" class="px p_fre" value="'+diyClassName+'" size="8" /> <select class="ps vm" id="bgrepeat" onchange="$(\'diyClassName\').value=this.value;" >'+this.getOption(classarr, diyClassName)+'</select></td></tr>'; table += '</table>'; var wname = objType ? 'Module' : 'Frame'; html = '<div class="c diywin" style="width:450px;position:relative;">'+table+'</div>'; var h = '<h3 class="flb"><em>Edit '+wname+' Style</em><span><a href="javascript:;" class="flbc" onclick="drag.closeStyleEdit(\''+id+'\');return false;" title="Close">\n\ Close</a></span></h3>'; var f = '<p class="o pns"><button onclick="drag.saveStyle(\''+id+'\');drag.closeStyleEdit(\''+id+'\');" class="pn pnc" value="true">\n\ <strong>Confirm</strong></button><button onclick="drag.closeStyleEdit(\''+id+'\')" class="pn" value="true"><strong>Cancel</strong></button></p>'; this.removeMenu(e); showWindow('eleStyle',h + html + f, 'html', 0); }, closeStyleEdit : function (id) { this.deleteFrame([id+'_bgcPalette',id+'_bdtPalette',id+'_bdrPalette',id+'_bdbPalette',id+'_bdlPalette',id+'_fontPalette',id+'_linkPalette']); hideWindow('eleStyle'); }, saveStyle : function (id) { var className = this.getDiyClassName(id); var diyClassName = $('diyClassName').value; $(id).className = diyClassName+' '+className[2]+' '+className[1]; var obj = this.getObjByName(id); var objType = obj instanceof Block ? 1 : 0; if (objType == 1) this.saveBlockClassName(id,diyClassName); var selector = '#'+id; var random = Math.random(); spaceDiy.setStyle(selector, 'background-color', $('bgcolor').value, random); var bgimage = $('bgimage').value && $('bgimage') != 'none' ? Util.url($('bgimage').value) : ''; var bgrepeat = bgimage ? $('bgrepeat').value : ''; if ($('bgcolor').value != '' && bgimage == '') bgimage = 'none'; spaceDiy.setStyle(selector, 'background-image', bgimage, random); spaceDiy.setStyle(selector, 'background-repeat', bgrepeat, random); spaceDiy.setStyle(selector+' .'+this.contentClass, 'color', $('fontcolor').value, random); spaceDiy.setStyle(selector+' .'+this.contentClass, 'font-size', this.formatValue('fontsize'), random); spaceDiy.setStyle(spaceDiy.checkSelector(selector+' .'+this.contentClass+' a'), 'color', $('linkcolor').value, random); var linkfontsize = parseInt($('linkfontsize').value); linkfontsize = isNaN(linkfontsize) ? '' : linkfontsize+'px'; spaceDiy.setStyle(spaceDiy.checkSelector(selector+' .'+this.contentClass+' a'), 'font-size', this.formatValue('linkfontsize'), random); if ($('borderop').checked) { var bdtwidth = $('bdtwidth').value,bdrwidth = $('bdrwidth').value,bdbwidth = $('bdbwidth').value,bdlwidth = $('bdlwidth').value; var bdtstyle = $('bdtstyle').value,bdrstyle = $('bdrstyle').value,bdbstyle = $('bdbstyle').value,bdlstyle = $('bdlstyle').value; var bdtcolor = $('bdtcolor').value,bdrcolor = $('bdrcolor').value,bdbcolor = $('bdbcolor').value,bdlcolor = $('bdlcolor').value; } else { bdlwidth = bdbwidth = bdrwidth = bdtwidth = $('bdtwidth').value; bdlstyle = bdbstyle = bdrstyle = bdtstyle = $('bdtstyle').value; bdlcolor = bdbcolor = bdrcolor = bdtcolor = $('bdtcolor').value; } spaceDiy.setStyle(selector, 'border', '', random); spaceDiy.setStyle(selector, 'border-top-width', bdtwidth, random); spaceDiy.setStyle(selector, 'border-right-width', bdrwidth, random); spaceDiy.setStyle(selector, 'border-bottom-width', bdbwidth, random); spaceDiy.setStyle(selector, 'border-left-width', bdlwidth, random); spaceDiy.setStyle(selector, 'border-top-style', bdtstyle, random); spaceDiy.setStyle(selector, 'border-right-style', bdrstyle, random); spaceDiy.setStyle(selector, 'border-bottom-style', bdbstyle, random); spaceDiy.setStyle(selector, 'border-left-style', bdlstyle, random); spaceDiy.setStyle(selector, 'border-top-color', bdtcolor, random); spaceDiy.setStyle(selector, 'border-right-color', bdrcolor, random); spaceDiy.setStyle(selector, 'border-bottom-color', bdbcolor, random); spaceDiy.setStyle(selector, 'border-left-color', bdlcolor, random); if ($('marginop').checked) { var margint = this.formatValue('margint'),marginr = this.formatValue('marginr'), marginb = this.formatValue('marginb'), marginl = this.formatValue('marginl'); } else { marginl = marginb = marginr = margint = this.formatValue('margint'); } spaceDiy.setStyle(selector, 'margin-top',margint, random); spaceDiy.setStyle(selector, 'margin-right', marginr, random); spaceDiy.setStyle(selector, 'margin-bottom', marginb, random); spaceDiy.setStyle(selector, 'margin-left', marginl, random); if (objType == 1) { if ($('cmarginop').checked) { var cmargint = this.formatValue('cmargint'),cmarginr = this.formatValue('cmarginr'), cmarginb = this.formatValue('cmarginb'), cmarginl = this.formatValue('cmarginl'); } else { cmarginl = cmarginb = cmarginr = cmargint = this.formatValue('cmargint'); } selector = selector + ' .'+this.contentClass; spaceDiy.setStyle(selector, 'margin-top', cmargint, random); spaceDiy.setStyle(selector, 'margin-right', cmarginr, random); spaceDiy.setStyle(selector, 'margin-bottom', cmarginb, random); spaceDiy.setStyle(selector, 'margin-left', cmarginl, random); } this.setClose(); }, formatValue : function(id) { var value = ''; if ($(id)) { value = parseInt($(id).value); value = isNaN(value) ? '' : value+'px'; } return value; }, saveBlockClassName : function(id,className){ if (!$('saveblockclassname')){ var dom = document.createElement('div'); dom.innerHTML = '<form id="saveblockclassname" method="post" action=""><input type="hidden" name="classname" value="" />\n\ <input type="hidden" name="formhash" value="'+document.diyform.formhash.value+'" /><input type="hidden" name="saveclassnamesubmit" value="true"/></form>'; $('append_parent').appendChild(dom.childNodes[0]); } $('saveblockclassname').action = 'portal.php?mod=portalcp&ac=block&op=saveblockclassname&bid='+id.replace('portal_block_',''); document.forms.saveblockclassname.classname.value = className; ajaxpost('saveblockclassname','ajaxwaitid'); }, closeTitleEdit : function (fid) { this.deleteFrame(fid+'bgPalette_0'); for (var i = 0 ; i<=10; i++) { this.deleteFrame(fid+'Palette_'+i); } hideWindow('frameTitle'); }, openTitleEdit : function (e) { if (typeof e == 'object') { e = Util.event(e); var fid = e.aim.id.replace('cmd_',''); } else { fid = e; } var obj = this.getObjByName(fid); var titlename = obj instanceof Block ? 'Module' : 'Frame'; var repeatarr = [{'key':'Tile','value':'repeat'},{'key':'Tile is not','value':'no-repeat'},{'key':'Tile Horizontally','value':'repeat-x'},{'key':'Tile Vertically','value':'repeat-y'}]; var len = obj.titles.length; var bgimage = obj.titles.style && obj.titles.style['background-image'] ? obj.titles.style['background-image'] : ''; bgimage = bgimage != 'none' ? Util.trimUrl(bgimage) : ''; var bgcolor = obj.titles.style && obj.titles.style['background-color'] ? obj.titles.style['background-color'] : ''; bgcolor = Util.formatColor(bgcolor); var bgrepeat = obj.titles.style && obj.titles.style['background-repeat'] ? obj.titles.style['background-repeat'] : ''; var common = '<table class="tfm">'; common += '<tr><th>Background image:</th><td><input type="text" id="titleBgImage" class="px p_fre" value="'+bgimage+'" /> <select class="ps vm" id="titleBgRepeat" >'+this.getOption(repeatarr,bgrepeat)+'</select></td></tr>'; common += '<tr><th>Background color:</th><td><input type="text" id="titleBgColor" class="px p_fre" value="'+bgcolor+'" size="7" />'; common += getColorPalette(fid+'bgPalette_0', 'titleBgColor' ,bgcolor)+'</td></tr>'; if (obj instanceof Tab) { var switchArr = [{'key':'Click','value':'click'},{'key':'Glide','value':'mouseover'}]; var switchType = obj.titles['switchType'] ? obj.titles['switchType'][0] : 'click'; common += '<tr><th>Switch Type:</th><td><select class="ps" id="switchType" >'+this.getOption(switchArr,switchType)+'</select></td></tr>'; } common += '</table><hr class="l">'; var li = ''; li += '<div id="titleInput_0"><table class="tfm"><tr><th>'+titlename+' Title:</th><td><input type="text" id="titleText_0" class="px p_fre" value="`title`" /></td></tr>'; li += '<tr><th>Link:</th><td><input type="text" id="titleLink_0" class="px p_fre" value="`link`" /></td></tr>'; li += '<tr><th>Image:</th><td><input type="text" id="titleSrc_0" class="px p_fre" value="`src`" /></td></tr>'; li += '<tr><th>Location:</th><td><select id="titleFloat_0" class="ps vm"><option value="" `left`>Left</option><option value="right" `right`>Right</option></select>'; li += '&nbsp;&nbsp;Offset of: <input type="text" id="titleMargin_0" class="px p_fre vm" value="`margin`" size="2" />px</td></tr>'; li += '<tr><th>Font:</th><td><select class="ps vm" id="titleSize_0" ><option value="">Size</option>`size`</select>'; li += '&nbsp;&nbsp;Color: <input type="text" id="titleColor_0" class="px p_fre vm" value="`color`" size="4" />'; li += getColorPalette(fid+'Palette_0', 'titleColor_0' ,'`color`'); li += '</td></tr><tr><td colspan="2"><hr class="l"></td></tr></table></div>'; var html = ''; if (obj.titles['first']) { html = this.getTitleHtml(obj, 'first', li); } for (var i = 0; i < len; i++ ) { html += this.getTitleHtml(obj, i, li); } if (!html) { var bigarr = []; for (var k=7;k<27;k++) { var key = k+'px'; bigarr.push({'key':key,'value':key}); } var ssize = this.getOption(bigarr,ssize); html = li.replace('`size`', ssize).replace(/`\w+`/g, ''); } var c = len + 1; html = '<div class="c diywin" style="width:450px;height:400px; overflow:auto;"><table cellspacing="0" cellpadding="0" class="tfm pns"><tr><th></th><td><button type="button" id="addTitleInput" class="pn" onclick="drag.addTitleInput('+c+');"><em>Add new title</em></button></td></tr></table><div id="titleEdit">'+html+common+'</div></div>'; var h = '<h3 class="flb"><em>Edit '+titlename+' Title</em><span><a href="javascript:;" class="flbc" onclick="drag.closeTitleEdit(\''+fid+'\');return false;" title="Close">\n\ Close</a></span></h3>'; var f = '<p class="o pns"><button onclick="drag.saveTitleEdit(\''+fid+'\');drag.closeTitleEdit(\''+fid+'\');" class="pn pnc" value="true">\n\ <strong>Confirm</strong></button><button onclick="drag.closeTitleEdit(\''+fid+'\')" class="pn" value="true"><strong>Cancel</strong></button></p>'; this.removeMenu(e); showWindow('frameTitle',h + html + f, 'html', 0); }, getTitleHtml : function (obj, i, li) { var shtml = '',stitle = '',slink = '',sfloat = '',ssize = '',scolor = '',margin = '',src = ''; var c = i == 'first' ? '0' : i+1; stitle = obj.titles[i]['text'] ? obj.titles[i]['text'] : ''; slink = obj.titles[i]['href'] ? obj.titles[i]['href'] : ''; sfloat = obj.titles[i]['float'] ? obj.titles[i]['float'] : ''; margin = obj.titles[i]['margin'] ? obj.titles[i]['margin'] : ''; ssize = obj.titles[i]['font-size'] ? obj.titles[i]['font-size']+'px' : ''; scolor = obj.titles[i]['color'] ? obj.titles[i]['color'] : ''; src = obj.titles[i]['src'] ? obj.titles[i]['src'] : ''; var bigarr = []; for (var k=7;k<27;k++) { var key = k+'px'; bigarr.push({'key':key,'value':key}); } ssize = this.getOption(bigarr,ssize); shtml = li.replace(/_0/g, '_' + c).replace('`title`', stitle).replace('`link`', slink).replace('`size`', ssize).replace('`src`',src); var left = sfloat == '' ? 'selected' : ''; var right = sfloat == 'right' ? 'selected' : ''; scolor = Util.formatColor(scolor); shtml = shtml.replace(/`color`/g, scolor).replace('`left`', left).replace('`right`', right).replace('`margin`', margin); return shtml; }, addTitleInput : function (c) { if (c > 10) return false; var pre = $('titleInput_'+(c-1)); var dom = document.createElement('div'); dom.className = 'tfm'; var exp = new RegExp('_'+(c-1), 'g'); dom.id = 'titleInput_'+c; dom.innerHTML = pre.innerHTML.replace(exp, '_'+c); Util.insertAfter(dom, pre); $('addTitleInput').onclick = function () {drag.addTitleInput(c+1)}; }, saveTitleEdit : function (fid) { var obj = this.getObjByName(fid); var ele = $(fid); var children = ele.childNodes; var title = first = ''; var hastitle = 0; var c = 0; for (var i in children) { if (typeof children[i] == 'object' && Util.hasClass(children[i], this.titleClass)) { title = children[i]; break; } } if (title) { var arrDel = []; for (var i in title.childNodes) { if (typeof title.childNodes[i] == 'object' && Util.hasClass(title.childNodes[i], this.titleTextClass)) { first = title.childNodes[i]; this._createTitleHtml(first, c); if (first.innerHTML != '') hastitle = 1; } else if (typeof title.childNodes[i] == 'object' && !Util.hasClass(title.childNodes[i], this.moveableObject)) { arrDel.push(title.childNodes[i]); } } for (var i = 0; i < arrDel.length; i++) { title.removeChild(arrDel[i]); } } else { var titleClassName = ''; if(obj instanceof Tab) { titleClassName = 'tab-'; } else if(obj instanceof Frame) { titleClassName = 'frame-'; } else if(obj instanceof Block) { titleClassName = 'block'; } title = document.createElement('div'); title.className = titleClassName + 'title' + ' '+ this.titleClass; ele.insertBefore(title,ele.firstChild); } if (!first) { var first = document.createElement('span'); first.className = this.titleTextClass; this._createTitleHtml(first, c); if (first.innerHTML != '') { title.insertBefore(first, title.firstChild); hastitle = 1; } } while ($('titleText_'+(++c))) { var dom = document.createElement('span'); dom.className = 'subtitle'; this._createTitleHtml(dom, c); if (dom.innerHTML != '') { if (dom.innerHTML) Util.insertAfter(dom, first); first = dom; hastitle = 1; } } var titleBgImage = $('titleBgImage').value; titleBgImage = titleBgImage && titleBgImage != 'none' ? Util.url(titleBgImage) : ''; if ($('titleBgColor').value != '' && titleBgImage == '') titleBgImage = 'none'; title.style['backgroundImage'] = titleBgImage; if (titleBgImage) { title.style['backgroundRepeat'] = $('titleBgRepeat').value; } title.style['backgroundColor'] = $('titleBgColor').value; if ($('switchType')) { title.switchType = []; title.switchType[0] = $('switchType').value ? $('switchType').value : 'click'; title.setAttribute('switchtype',title.switchType[0]); } obj.titles = []; if (hastitle == 1) { this._initTitle(obj,title); } else { if (!(obj instanceof Tab)) title.parentNode.removeChild(title); title = ''; this.initPosition(); } if (obj instanceof Block) this.saveBlockTitle(fid,title); this.setClose(); }, _createTitleHtml : function (ele,tid) { var html = '',img = ''; tid = '_' + tid ; var ttext = $('titleText'+tid).value; var tlink = $('titleLink'+tid).value; var tfloat = $('titleFloat'+tid).value; var tmargin_ = tfloat != '' ? tfloat : 'left'; var tmargin = $('titleMargin'+tid).value; var tsize = $('titleSize'+tid).value; var tcolor = $('titleColor'+tid).value; var src = $('titleSrc'+tid).value; var divStyle = 'float:'+tfloat+';margin-'+tmargin_+':'+tmargin+'px;font-size:'+tsize; var aStyle = 'color:'+tcolor+' !important;'; if (src) { img = '<img class="vm" src="'+src+'" alt="'+ttext+'" />'; } if (ttext || img) { if (tlink) { Util.setStyle(ele, divStyle); html = '<a href='+tlink+' target="_blank" style="'+aStyle+'">'+img+ttext+'</a>'; } else { Util.setStyle(ele, divStyle+';'+aStyle); html = img+ttext; } } ele.innerHTML = html; return true; }, saveBlockTitle : function (id,title) { if (!$('saveblocktitle')){ var dom = document.createElement('div'); dom.innerHTML = '<form id="saveblocktitle" method="post" action=""><input type="hidden" name="title" value="" />\n\ <input type="hidden" name="formhash" value="'+document.diyform.formhash.value+'" /><input type="hidden" name="savetitlesubmit" value="true"/></form>'; $('append_parent').appendChild(dom.childNodes[0]); } $('saveblocktitle').action = 'portal.php?mod=portalcp&ac=block&op=saveblocktitle&bid='+id.replace('portal_block_',''); var html = !title ? '' : title.outerHTML; document.forms.saveblocktitle.title.value = html; ajaxpost('saveblocktitle','ajaxwaitid'); }, removeBlock : function (e, flag) { if ( typeof e !== 'string') { e = Util.event(e); var id = e.aim.id.replace('cmd_',''); } else { var id = e; } if ($(id) == null) return false; var obj = this.getObjByName(id); if (!flag) { if (!confirm('Are you sure you want to delete it, can not be recovered after deletion')) return false; } if (obj instanceof Block) { this.delBlock(id); } else if (obj instanceof Frame) { this.delFrame(obj); } $(id).parentNode.removeChild($(id)); var content = $(id+'_content'); if(content) { content.parentNode.removeChild(content); } this.setClose(); this.initPosition(); this.initChkBlock(); }, delBlock : function (bid) { spaceDiy.removeCssSelector('#'+bid); this.stopSlide(bid); }, delFrame : function (frame) { spaceDiy.removeCssSelector('#'+frame.name); for (var i in frame['columns']) { if (frame['columns'][i] instanceof Column) { var children = frame['columns'][i]['children']; for (var j in children) { if (children[j] instanceof Frame) { this.delFrame(children[j]); } else if (children[j] instanceof Block) { this.delBlock(children[j]['name']); } } } } this.setClose(); }, initChkBlock : function (data) { if (typeof name == 'undefined' || data == null ) data = this.data; if ( data instanceof Frame) { this.initChkBlock(data['columns']); } else if (data instanceof Block) { var el = $('chk'+data.name); if (el != null) el.checked = true; } else if (typeof data == 'object') { for (var i in data) { this.initChkBlock(data[i]); } } }, getBlockData : function (blockname) { var bid = this.dragObj.id; var eleid = bid; if (bid.indexOf('portal_block_') != -1) { eleid = 0; }else { bid = 0; } showWindow('showblock', 'portal.php?mod=portalcp&ac=block&op=block&classname='+blockname+'&bid='+bid+'&eleid='+eleid+'&tpl='+document.diyform.template.value,'get',-1); drag.initPosition(); this.fn = ''; return true; }, stopSlide : function (id) { if (typeof slideshow == 'undefined' || typeof slideshow.entities == 'undefined') return false; var slidebox = $C('slidebox',$(id)); if(slidebox && slidebox.length > 0) { if(slidebox[0].id) { var timer = slideshow.entities[slidebox[0].id].timer; if(timer) clearTimeout(timer); slideshow.entities[slidebox[0].id] = ''; } } }, blockForceUpdate : function (e,all) { if ( typeof e !== 'string') { e = Util.event(e); var id = e.aim.id.replace('cmd_',''); } else { var id = e; } if ($(id) == null) return false; var bid = id.replace('portal_block_', ''); var bcontent = $(id+'_content'); if (!bcontent) { bcontent = document.createElement('div'); bcontent.id = id+'_content'; bcontent.className = this.contentClass; } this.stopSlide(id); var height = Util.getFinallyStyle(bcontent, 'height'); bcontent.style.lineHeight = height == 'auto' ? '' : (height == '0px' ? '20px' : height); var boldcontent = bcontent.innerHTML; bcontent.innerHTML = '<center>Loading Content...</center>'; var x = new Ajax(); x.get('portal.php?mod=portalcp&ac=block&op=getblock&forceupdate=1&inajax=1&bid='+bid+'&tpl='+document.diyform.template.value, function(s) { if(s.indexOf('errorhandle_') != -1) { bcontent.innerHTML = boldcontent; runslideshow(); showDialog('Sorry, you do not have permission to add or edit module', 'alert'); doane(); } else { var obj = document.createElement('div'); obj.innerHTML = s; bcontent.parentNode.removeChild(bcontent); $(id).innerHTML = obj.childNodes[0].innerHTML; evalscript(s); if(s.indexOf('runslideshow()') != -1) {runslideshow();} drag.initPosition(); if (all) {drag.getBlocks();} } }); }, frameExport : function (e) { var flag = true; if (drag.isChange) { flag = confirm('You have done modified, Please save and then do export. Otherwise, the exported data will not include you of the changes made.'); } if (flag) { if ( typeof e == 'object') { e = Util.event(e); var frame = e.aim.id.replace('cmd_',''); } else { frame = e == undefined ? '' : e; } if (!$('frameexport')){ var dom = document.createElement('div'); dom.innerHTML = '<form id="frameexport" method="post" action="" target="_blank"><input type="hidden" name="frame" value="" />\n\ <input type="hidden" name="tpl" value="'+document.diyform.template.value+'" />\n\ <input type="hidden" name="tpldirectory" value="'+document.diyform.tpldirectory.value+'" />\n\ <input type="hidden" name="diysign" value="'+document.diyform.diysign.value+'" />\n\ <input type="hidden" name="formhash" value="'+document.diyform.formhash.value+'" /><input type="hidden" name="exportsubmit" value="true"/></form>'; $('append_parent').appendChild(dom.childNodes[0]); } $('frameexport').action = 'portal.php?mod=portalcp&ac=diy&op=export'; document.forms.frameexport.frame.value = frame; document.forms.frameexport.submit(); } doane(); }, openFrameImport : function (type) { type = type || 0; showWindow('showimport','portal.php?mod=portalcp&ac=diy&op=import&tpl='+document.diyform.template.value+'&tpldirectory='+document.diyform.tpldirectory.value+'&diysign='+document.diyform.diysign.value+'&type='+type, 'get'); }, endBlockForceUpdateBatch : function () { if($('allupdate')) { $('allupdate').innerHTML = 'The operation is completed.'; $('fwin_dialog_submit').style.display = ''; $('fwin_dialog_cancel').style.display = 'none'; } this.initPosition(); }, getBlocks : function () { if (this.blocks.length == 0) { this.endBlockForceUpdateBatch(); } if (this.blocks.length > 0) { var cur = this.blocksLen - this.blocks.length; if($('allupdate')) { $('allupdate').innerHTML = 'Total <span style="color:blue">'+this.blocksLen+'</span> Modules are being updated first <span style="color:red">'+cur+'</span> , Has been completed <span style="color:red">'+(parseInt(cur / this.blocksLen * 100)) + '%</span>'; var bid = 'portal_block_'+this.blocks.pop(); this.blockForceUpdate(bid,true); } } }, blockForceUpdateBatch : function (blocks) { if (blocks) { this.blocks = blocks; } else { this.initPosition(); this.blocks = this.allBlocks; } this.blocksLen = this.blocks.length; showDialog('<div id="allupdate" style="width:350px;line-height:28px;">To begin the update...</div>','confirm','Module data is updated', '', true, 'drag.endBlockForceUpdateBatch()'); var wait = function() { if($('fwin_dialog_submit')) { $('fwin_dialog_submit').style.display = 'none'; $('fwin_dialog_cancel').className = 'pn pnc'; setTimeout(function(){drag.getBlocks()},500); } else { setTimeout(wait,100); } }; wait(); doane(); }, clearAll : function () { if (confirm('You sure you want to empty the page where DIY data unrecoverable empty')) { for (var i in this.data) { for (var j in this.data[i]) { if (typeof(this.data[i][j]) == 'object' && this.data[i][j].name.indexOf('_temp')<0) { this.delFrame(this.data[i][j]); $(this.data[i][j].name).parentNode.removeChild($(this.data[i][j].name)); } } } this.initPosition(); this.setClose(); } doane(); }, createObj : function (e,objType,contentType) { if (objType == 'block' && !this.checkHasFrame()) {alert("Tip: Not found framework, please add the framework.");spaceDiy.getdiy('frame');return false;} e = Util.event(e); if(e.which != 1 ) {return false;} var html = '',offWidth = 0; if (objType == 'frame') { html = this.getFrameHtml(contentType); offWidth = 600; } else if (objType == 'block') { html = this.getBlockHtml(contentType); offWidth = 200; this.fn = function (e) {drag.getBlockData(contentType);}; } else if (objType == 'tab') { html = this.getTabHtml(contentType); offWidth = 300; } var ele = document.createElement('div'); ele.innerHTML = html; ele = ele.childNodes[0]; document.body.appendChild(ele); this.dragObj = this.overObj = ele; if (!this.getTmpBoxElement()) return false; var scroll = Util.getScroll(); this.dragObj.style.position = 'absolute'; this.dragObj.style.left = e.clientX + scroll.l - 60 + "px"; this.dragObj.style.top = e.clientY + scroll.t - 10 + "px"; this.dragObj.style.width = offWidth + 'px'; this.dragObj.style.cursor = 'move'; this.dragObj.lastMouseX = e.clientX; this.dragObj.lastMouseY = e.clientY; Util.insertBefore(this.tmpBoxElement,this.overObj); Util.addClass(this.dragObj,this.moving); this.dragObj.style.zIndex = 500 ; this.scroll = Util.getScroll(); this.newFlag = true; var _method = this; document.onscroll = function(){Drag.prototype.resetObj.call(_method, e);}; window.onscroll = function(){Drag.prototype.resetObj.call(_method, e);}; document.onmousemove = function (e){Drag.prototype.drag.call(_method, e);}; document.onmouseup = function (e){Drag.prototype.dragEnd.call(_method, e);}; }, getFrameHtml : function (type) { var id = 'frame'+Util.getRandom(6); var className = [this.frameClass,this.moveableObject].join(' '); className = className + ' cl frame-' + type; var str = '<div id="'+id+'" class="'+className+'">'; str += '<div id="'+id+'_title" class="'+this.titleClass+' '+this.frameTitleClass+'"><span class="'+this.titleTextClass+'">'+type+' Frame</span></div>'; var cols = type.split('-'); var clsl='',clsc='',clsr=''; clsl = ' frame-'+type+'-l'; clsc = ' frame-'+type+'-c'; clsr = ' frame-'+type+'-r'; var len = cols.length; if (len == 1) { str += '<div id="'+id+'_left" class="'+this.moveableColumn+clsc+'"></div>'; } else if (len == 2) { str += '<div id="'+id+'_left" class="'+this.moveableColumn+clsl+ '"></div>'; str += '<div id="'+id+'_center" class="'+this.moveableColumn+clsr+ '"></div>'; } else if (len == 3) { str += '<div id="'+id+'_left" class="'+this.moveableColumn+clsl+'"></div>'; str += '<div id="'+id+'_center" class="'+this.moveableColumn+clsc+'"></div>'; str += '<div id="'+id+'_right" class="'+this.moveableColumn+clsr+'"></div>'; } str += '</div>'; return str; }, getTabHtml : function () { var id = 'tab'+Util.getRandom(6); var className = [this.tabClass,this.moveableObject].join(' '); className = className + ' cl'; var titleClassName = [this.tabTitleClass, this.titleClass, this.moveableColumn, 'cl'].join(' '); var str = '<div id="'+id+'" class="'+className+'">'; str += '<div id="'+id+'_title" class="'+titleClassName+'"><span class="'+this.titleTextClass+'">tab tag</span></div>'; str += '<div id="'+id+'_content" class="'+this.tabContentClass+'"></div>'; str += '</div>'; return str; }, getBlockHtml : function () { var id = 'block'+Util.getRandom(6); var str = '<div id="'+id+'" class="block move-span"></div>'; str += '</div>'; return str; }, setClose : function () { if(this.sampleMode) { return true; } else { if (!this.isChange) { window.onbeforeunload = function() { return 'Your data has been modified, the exit will not be able to save your changes.'; }; } this.isChange = true; spaceDiy.enablePreviewButton(); } }, clearClose : function () { this.isChange = false; this.isClearClose = true; window.onbeforeunload = function () {}; }, goonDIY : function () { if ($('prefile').value == '1') { showDialog('<div style="line-height:28px;">Press the Continue button will open a temporary data and DIY, <br />Press the Delete button will delete the temporary data.</div>','confirm','Whether to continue the temporary data DIY?', function(){location.replace(location.href+'&preview=yes');}, true, 'spaceDiy.cancelDIY()', '', 'Continue', 'Del'); } else if (location.search.indexOf('preview=yes') > -1) { spaceDiy.enablePreviewButton(); } else { spaceDiy.disablePreviewButton(); } setInterval(function(){spaceDiy.save('savecache', 1);},180000); } }); var spaceDiy = new DIY(); spaceDiy.extend({ save : function (optype,rejs) { optype = typeof optype == 'undefined' ? '' : optype; if (optype == 'savecache' && !drag.isChange) {return false;} var tplpre = document.diyform.template.value.split(':'); if (!optype) { if (['portal/portal_topic_content', 'portal/list', 'portal/view'].indexOf(tplpre[0]) == -1) { if (document.diyform.template.value.indexOf(':') > -1 && !document.selectsave) { var schecked = '',dchecked = ''; if (document.diyform.savemod.value == '1') { dchecked = ' checked'; } else { schecked = ' checked'; } showDialog('<form name="selectsave" action="" method="get"><label><input type="radio" value="0" name="savemod"'+schecked+' />Apply to such page</label>\n\ <label><input type="radio" value="1" name="savemod"'+dchecked+' />This page applies only to</label></form>','notice', '', spaceDiy.save); return false; } if (document.selectsave) { if (document.selectsave.savemod[0].checked) { document.diyform.savemod.value = document.selectsave.savemod[0].value; } else { document.diyform.savemod.value = document.selectsave.savemod[1].value; } } } else { document.diyform.savemod.value = 1; } } else if (optype == 'savecache') { if (!drag.isChange) return false; this.checkPreview_form(); document.diyform.rejs.value = rejs ? 0 : 1; } else if (optype =='preview') { if (drag.isChange) { optype = 'savecache'; } else { this.checkPreview_form(); $('preview_form').submit(); return false; } } document.diyform.action = document.diyform.action.replace(/[&|\?]inajax=1/, ''); document.diyform.optype.value = optype; document.diyform.spacecss.value = spaceDiy.getSpacecssStr(); document.diyform.style.value = spaceDiy.style; document.diyform.layoutdata.value = drag.getPositionStr(); document.diyform.gobackurl.value = spaceDiy.cancelDiyUrl(); drag.clearClose(); if (optype == 'savecache') { document.diyform.handlekey.value = 'diyform'; ajaxpost('diyform','ajaxwaitid','ajaxwaitid','onerror'); } else { saveUserdata('diy_advance_mode', ''); document.diyform.submit(); } }, checkPreview_form : function () { if (!$('preview_form')) { var dom = document.createElement('div'); var search = ''; var sarr = location.search.replace('?','').split('&'); for (var i = 0;i<sarr.length;i++){ var kv = sarr[i].split('='); if (kv.length>1 && kv[0] != 'diy') { search += '<input type="hidden" value="'+kv[1]+'" name="'+kv[0]+'" />'; } } search += '<input type="hidden" value="yes" name="preview" />'; dom.innerHTML = '<form action="'+location.href+'" target="_bloak" method="get" id="preview_form">'+search+'</form>'; var form = dom.getElementsByTagName('form'); $('append_parent').appendChild(form[0]); } }, cancelDiyUrl : function () { return location.href.replace(/[\?|\&]diy\=yes/g,'').replace(/[\?|\&]preview=yes/,''); }, cancel : function () { saveUserdata('diy_advance_mode', ''); if (drag.isClearClose) { showDialog('<div style="line-height:28px;">Whether to retain the temporary data?<br />Press the OK button will retain temporary data, press the Cancel button will delete the temporary data.</div>','confirm','Retain temporary data', function(){location.href = spaceDiy.cancelDiyUrl();}, true, function(){window.onunload=function(){spaceDiy.cancelDIY()};location.href = spaceDiy.cancelDiyUrl();}); } else { location.href = this.cancelDiyUrl(); } }, recover : function() { if (confirm('Are you sure you want to revert to the previous version saved it?')) { drag.clearClose(); document.diyform.recover.value = '1'; document.diyform.gobackurl.value = location.href.replace(/(\?diy=yes)|(\&diy=yes)/,'').replace(/[\?|\&]preview=yes/,''); document.diyform.submit(); } doane(); }, enablePreviewButton : function () { if ($('preview')){ $('preview').className = ''; if(drag.isChange) { $('diy_preview').onclick = function () {spaceDiy.save('savecache');return false;}; } else { $('diy_preview').onclick = function () {spaceDiy.save('preview');return false;}; } Util.show($('savecachemsg')) } }, disablePreviewButton : function () { if ($('preview')) { $('preview').className = 'unusable'; $('diy_preview').onclick = function () {return false;}; } }, cancelDIY : function () { this.disablePreviewButton(); document.diyform.optype.value = 'canceldiy'; var x = new Ajax(); x.post($('diyform').action+'&inajax=1','optype=canceldiy&diysubmit=1&template='+document.diyform.template.value+'&savemod='+document.diyform.savemod.value+'&formhash='+document.diyform.formhash.value+'&tpldirectory='+document.diyform.tpldirectory.value+'&diysign='+document.diyform.diysign.value,function(s){}); }, switchBlockclass : function(blockclass) { var navs = $('contentblockclass_nav').getElementsByTagName('a'); var contents = $('contentblockclass').getElementsByTagName('ul'); for(var i=0; i<navs.length; i++) { if(navs[i].id=='bcnav_'+blockclass) { navs[i].className = 'a'; } else { navs[i].className = ''; } } for(var i=0; i<contents.length; i++) { if(contents[i].id=='contentblockclass_'+blockclass) { contents[i].style.display = ''; } else { contents[i].style.display = 'none'; } } }, getdiy : function (type) { if (type) { var nav = $('controlnav').children; for (var i in nav) { if (nav[i].className == 'current') { nav[i].className = ''; var contentid = 'content'+nav[i].id.replace('nav', ''); if ($(contentid)) $(contentid).style.display = 'none'; } } $('nav'+type).className = 'current'; if (type == 'start' || type == 'frame') { $('content'+type).style.display = 'block'; return true; } if(type == 'blockclass' && $('content'+type).innerHTML !='') { $('content'+type).style.display = 'block'; return true; } var para = '&op='+type; if (arguments.length > 1) { for (var i = 1; i < arguments.length; i++) { para += '&' + arguments[i] + '=' + arguments[++i]; } } var ajaxtarget = type == 'diy' ? 'diyimages' : ''; var x = new Ajax(); x.showId = ajaxtarget; x.get('portal.php?mod=portalcp&ac=diy'+para+'&inajax=1&ajaxtarget='+ajaxtarget,function(s, x) { if (s) { if (typeof cpb_frame == 'object' && !BROWSER.ie) {delete cpb_frame;} if (!$('content'+type)) { var dom = document.createElement('div'); dom.id = 'content'+type; $('controlcontent').appendChild(dom); } $('content'+type).innerHTML = s; $('content'+type).style.display = 'block'; if (type == 'diy') { spaceDiy.setCurrentDiy(spaceDiy.currentDiy); if (spaceDiy.styleSheet.rules.length > 0) { Util.show('recover_button'); } } var evaled = false; if(s.indexOf('ajaxerror') != -1) { evalscript(s); evaled = true; } if(!evaled && (typeof ajaxerror == 'undefined' || !ajaxerror)) { if(x.showId) { ajaxupdateevents($(x.showId)); } } if(!evaled) evalscript(s); } }); } } }); spaceDiy.init(1); function succeedhandle_diyform (url, message, values) { if (values['rejs'] == '1') { document.diyform.rejs.value = ''; parent.$('preview_form').submit(); } spaceDiy.enablePreviewButton(); return false; }
var Logger = require('content-logger'); var contentLogger = Logger.create( { prototype: { init: function() { this.testStats = { failures: 0 }; this.on( 'add', function(error) { if (error.type !== 'ignored') { this.testStats.failures++; } } ); } } } ); module.exports = new contentLogger();
import React from 'react'; import ReactDOM from 'react-dom'; import './styles/style.scss'; import CountupBlock from 'components/countup_block'; ReactDOM.render( <CountupBlock />, document.getElementById('app'), );
(function(){ var canvasWidth = 800; var canvasHeight = 800; var sideLength = canvasWidth; var generationsCount = 6; var colorsCount = 100; var svgContainer = d3.select("body").append("svg") .attr("width", canvasWidth) .attr("height", canvasHeight); var color = d3.scaleLinear().domain([1,colorsCount]) .interpolate(d3.interpolateHcl) .range([d3.rgb("#007AFF"), d3.rgb('#FFF500')]); var curve = new Curve(sideLength, generationsCount); var lines = curve.getLines(); lines.forEach((l, index) => l.draw(color(index%colorsCount))); function Curve(sideLength, generationsCount) { var point1 = { x: 0, y: sideLength/3}; var point2 = { x: sideLength, y: sideLength/3}; function getLines() { return generateSide(point1, point2); } function generateSide(start, end) { var line = new Line(start, end); var lines = getNextGeneration([line]); for(var j=2; j<=generationsCount; j++) { lines = getNextGeneration(lines); } return lines; } function getNextGeneration(lines) { var nextGeneration = []; for(var i = 0, length = lines.length; i < length; i++) { var l = lines[i]; let a = l.kochA(); let b = l.kochB(); let c = l.kochC(); let d = l.kochD(); let e = l.kochE(); nextGeneration.push(new Line(a, b)); nextGeneration.push(new Line(b, c)); nextGeneration.push(new Line(c, d)); nextGeneration.push(new Line(d, e)); } return nextGeneration; } return { getLines: getLines } } function Line(start, end) { var start = start; var end = end; function draw(color) { svgContainer.append("line") .style("stroke", color) .attr("x1", start.x) .attr("y1", start.y) .attr("x2", end.x) .attr("y2", end.y); } function kochA() { return start; } function kochB() { return { x: start.x + (end.x - start.x)/3, y: start.y + (end.y - start.y)/3 }; } function kochC() { i=1; var length = Math.sqrt(Math.pow(start.x - end.x,2) + Math.pow(start.y - end.y,2)); var height = length/(2*Math.sqrt(3)); var sina = (end.y - start.y)/length; var cosa = (end.x - start.x)/length; return { x: (end.x + start.x)/2 + height * i * sina, y: (end.y + start.y)/2 - height * i * cosa }; } function kochD() { return { x: start.x + (end.x - start.x)*2/3, y: start.y + (end.y - start.y)*2/3 }; } function kochE() { return end; } function getTan(degrees) { return Math.tan(degrees * Math.PI/180); } return { draw: draw, kochA: kochA, kochB: kochB, kochC: kochC, kochD: kochD, kochE: kochE } } })(); // http://natureofcode.com/book/chapter-8-fractals/
alert("Hola mUNDO");
'use strict'; var EventEmitter = require('events'), net = require('net'); // see: arpa/telnet.h const IAC = 255; const DONT = 254; const DO = 253; const WONT = 252; const WILL = 251; const SB = 250; const SE = 240; const GA = 249; const EOR = 239; const OPT_ECHO = 1; const OPT_EOR = 25; /** * The following is an intentionally dismissive telnet parser, * it basically ignores anything the client tells it to do. Its * only purpose is to know how to parse negotiations and swallow * them. It can, however, issue commands such as toggling echo */ class TelnetStream extends EventEmitter { constructor(opts) { super(); this.isTTY = true; this.env = {}; this.stream = null; this.maxInputLength = opts.maxInputLength || 512; this.echoing = true; this.gaMode = null; } get readable() { return this.stream.readable; } get writable() { return this.stream.writable; } address() { return this.stream && this.stream.address(); } end(string, enc) { this.stream.end(string, enc); } write(data, encoding) { if (!Buffer.isBuffer(data)) { data = new Buffer(data, encoding); } // escape IACs by duplicating let iacs = 0; for (const val of data.values()) { if (val === IAC) { iacs++; } } if (iacs) { let b = new Buffer(data.length + iacs); for (let i = 0, j = 0; i < data.length; i++) { b[j++] = data[i]; if (data[i] === IAC) { b[j++] = IAC; } } } try { if (!this.stream.ended && !this.stream.finished) { this.stream.write(data); } } catch (e) { console.log(e); } } setEncoding(encoding) { this.stream.setEncoding(encoding); } pause() { this.stream.pause(); } resume() { this.stream.resume(); } destroy() { this.stream.destroy(); } /** * Execute a telnet command * @param {number} willingness DO/DONT/WILL/WONT * @param {number|Array} command Option to do/don't do or subsequence as array */ telnetCommand(willingness, command) { let seq = [IAC, willingness]; if (Array.isArray(command)) { seq.push.apply(seq, command); } else { seq.push(command); } this.stream.write(new Buffer(seq)); } toggleEcho() { this.echoing = !this.echoing; this.telnetCommand(this.echoing ? WONT : WILL, OPT_ECHO); } goAhead() { if (!this.gaMode) { return; } this.stream.write(new Buffer([IAC, this.gaMode])); } attach(connection) { this.stream = connection; let inputbuf = new Buffer(this.maxInputLength); let inputlen = 0; connection.on('error', err => console.error('Telnet Stream Error: ', err)); this.stream.write("\r\n"); connection.on('data', (databuf) => { databuf.copy(inputbuf, inputlen); inputlen += databuf.length; // immediately start consuming data if we begin receiving normal data // instead of telnet negotiation if (connection.fresh && databuf[0] !== IAC) { connection.fresh = false; } databuf = inputbuf.slice(0, inputlen); // fresh makes sure that even if we haven't gotten a newline but the client // sent us some initial negotiations to still interpret them if (!databuf.toString().match(/[\r\n]/) && !connection.fresh) { return; } // If multiple commands were sent \r\n separated in the same packet process // them separately. Some client auto-connect features do this let bucket = []; for (let i = 0; i < inputlen; i++) { if (databuf[i] !== 10) { // \n bucket.push(databuf[i]); } else { this.input(Buffer.from(bucket)); bucket = []; } } if (bucket.length) { this.input(Buffer.from(bucket)); } inputbuf = new Buffer(this.maxInputLength); inputlen = 0; }); connection.on('close', _ => { this.emit('close'); }); } /** * Parse telnet input stream, swallowing any negotiations * and emitting clean, fresh data * * @param {Buffer} inputbuf */ input(inputbuf) { // strip any negotiations let cleanbuf = Buffer.alloc(inputbuf.length); let i = 0; let cleanlen = 0; while (i < inputbuf.length) { if (inputbuf[i] !== IAC) { cleanbuf[cleanlen++] = inputbuf[i++]; continue; } // We don't actually negotiate, we don't care what the clients will or wont do // so just swallow everything inside an IAC sequence // i += (number of bytes including IAC) const cmd = inputbuf[i + 1]; const opt = inputbuf[i + 2]; switch (cmd) { case DO: switch (opt) { case OPT_EOR: this.gaMode = EOR; break; default: this.telnetCommand(WONT, opt); break; } i += 3; break; case DONT: switch (opt) { case OPT_EOR: this.gaMode = GA; break; } i += 3; break; case WILL: /* falls through */ case WONT: i += 3; break; case SB: // swallow subnegotiations i += 2; let sublen = 0; while (inputbuf[i++] !== SE) {sublen++;} break; default: i += 2; break; } } if (this.stream.fresh) { this.stream.fresh = false; return; } // OLD // this.emit('data', cleanbuf.slice(0, cleanlen - 1)); this.emit('data', cleanbuf.slice(0, cleanlen)); } } class TelnetServer { /** * @param {object} streamOpts options for the stream @see TelnetStream * @param {function} listener connected callback */ constructor(streamOpts, listener) { this.netServer = net.createServer({}, (connection) => { connection.fresh = true; var stream = new TelnetStream(streamOpts); stream.attach(connection); stream.telnetCommand(WILL, OPT_EOR); this.netServer.emit('connected', stream); }); this.netServer.on('connected', listener); this.netServer.on('error', error => { console.error('Error: ', error); console.error('Stack Trace: ', error.stack); }); this.netServer.on('uncaughtException', error => { console.error('Uncaught Error: ', error); console.error('Stack Trace: ', error.stack); }); } } exports.TelnetServer = TelnetServer; // vim:ts=2:sw=2:et:
export const reverseString = (input) => { return input.split("").reverse().join(""); };
function HTTPGET(url) { var req = new XMLHttpRequest(); req.open("GET", url, false); req.send(null); return req.responseText; } var getData = function() { //Get weather info var response = HTTPGET("http://192.168.1.95:8085/telemachus/datalink?vertaltitude=v.altitude&gforce=v.geeForce&paused=p.paused&shipname=v.body&periapsis=o.PeA&apoapsis=o.ApA"); //Convert to JSON var json = JSON.parse(response); //Extract the data var altitude = Math.round(json.vertaltitude); var apoapsis = Math.round(json.apoapsis); var periapsis = Math.round(json.periapsis); var shipname = json.shipname; //Construct a key-value dictionary var dict = {"KEY_NAME" : shipname, "KEY_ALT": altitude, "KEY_APO" : apoapsis, "KEY_PER" : periapsis}; //Send data to watch for display Pebble.sendAppMessage(dict); console.log("SENT THE DATA!"); }; Pebble.addEventListener("ready", function(e) { //App is ready to receive JS messages getData(); } ); Pebble.addEventListener("appmessage", function(e) { //Watch wants new data! getData(); } ); Pebble.addEventListener("showConfiguration", function() { console.log("Showing configuration"); Pebble.openURL('http://largepixelcollider.net/kerbalwatch/configurable.html'); });
/* Copyright (c) 2003-2014, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.plugins.setLang( 'liststyle', 'fr', { armenian: 'Numération arménienne', bulletedTitle: 'Propriétés de la liste à puces', circle: 'Cercle', decimal: 'Décimal (1, 2, 3, etc.)', decimalLeadingZero: 'Décimal précédé par un 0 (01, 02, 03, etc.)', disc: 'Disque', georgian: 'Numération géorgienne (an, ban, gan, etc.)', lowerAlpha: 'Alphabétique minuscules (a, b, c, d, e, etc.)', lowerGreek: 'Grec minuscule (alpha, beta, gamma, etc.)', lowerRoman: 'Nombres romains minuscules (i, ii, iii, iv, v, etc.)', none: 'Aucun', notset: '<Non défini>', numberedTitle: 'Propriétés de la liste numérotée', square: 'Carré', start: 'Début', type: 'Type', upperAlpha: 'Alphabétique majuscules (A, B, C, D, E, etc.)', upperRoman: 'Nombres romains majuscules (I, II, III, IV, V, etc.)', validateStartNumber: 'Le premier élément de la liste doit être un nombre entier.' } );
/** * @license Highstock JS v10.0.0 (2022-03-07) * @module highcharts/modules/datagrouping * @requires highcharts * * Data grouping module * * (c) 2010-2021 Torstein Hønsi * * License: www.highcharts.com/license */ 'use strict'; import dataGrouping from '../../Extensions/DataGrouping.js'; export default dataGrouping;
var selectedDate = (function () { var keyFormat = "YYYY-MM-DD"; var getAsKey = function () { return Session.get("selectedDate"); }; var getAsMoment = function () { return moment.utc(getAsKey(), keyFormat); }; var getFormatted = function () { var localFormat = i18n.getDateFormat(); return getAsMoment().format(localFormat); }; var getTomorrowAsMoment = function () { return getAsMoment().add("days", 1); }; var getTomorrowAsKey = function () { return getTomorrowAsMoment().format(keyFormat); }; var getTomorrowFormatted = function () { var localFormat = i18n.getDateFormat(); return getTomorrowAsMoment().format(localFormat); }; var setAsMoment = function (asMoment) { Session.set("selectedDate", asMoment.format(keyFormat)); }; setAsMoment(moment()); return { keyFormat: keyFormat, getAsKey: getAsKey, getFormatted: getFormatted, getTomorrowAsKey: getTomorrowAsKey, getTomorrowFormatted: getTomorrowFormatted, setAsMoment: setAsMoment }; }());
/* * Module dependencies. */ global.__base = __dirname + '/'; if (process.argv[2] === undefined) { process.argv[2] = 'development'; } var codeprez = require('./lib'), /** * Expose `codeprez()`. */ exports = module.exports = new codeprez();
var disconnectcount = 0, count = 0; function removeClasses(index, klass) { return klass.replace(/(^|\s)+dot\s+/, ''); } function checkDisconnects() { if (disconnectcount > 4) changeStatus("yellow", true); } function changeStatus(color, isWarning) { console.debug("Changing status to " + color, isWarning); var dot = $('.dot').removeClass(removeClasses); dot.addClass('dot dot-' + color); if (!isWarning) checkDisconnects(); } function generateDefaultData(amount, min, max) { var data = []; var today = new Date().getTime() / 1000; var start = today - (24 * 3600); var step = (today - start) / amount; //console.log(step); for (i = 0; i < amount; i++) { count++; data.push({time: start + (step * (i)), y: Math.floor((Math.random() * (30 - 10 + count)) + (10 + count))}) } //console.log(data); count = 0; return data; }
Package.describe({ name: 'babrahams:constellation', version: '0.1.6', summary: 'A curated set of packages for Constellation', git: 'https://github.com/JackAdams/constellation-distro.git', documentation: 'README.md', debugOnly: true }); Package.onUse(function(api) { api.versionsFrom('1.1'); api.use('constellation:console@1.2.1'); api.use('babrahams:temple@0.3.2'); api.use('constellation:subscriptions@0.3.1'); api.use('constellation:session@0.3.2'); api.use('constellation:autopublish@0.3.4'); api.use('constellation:tiny@0.3.1'); api.use('constellation:position@0.3.2'); api.use('lai:ddp-inspector@1.1.6'); api.imply('constellation:console'); }); Package.onTest(function(api) { api.use('tinytest'); });
var http = require("http-get"), url = require("url"), path = require("path"), fs = require("fs"), util = require('util'); var Log = require('../../utils/Log.js'); var FileUtils = require('../../utils/File.js'); var YouTubeDownload = require('../../download/YouTubeDownload.js'); var LinkResolver = require('../../download/LinkResolver.js'); var FileInfo = require('../../download/FileInfo.js'); var QueueProcessor = require('../QueueProcessor.js'); function DownloadController() { var self = this; var AssetMetadataCustomRules = require('../../discovery/AssetMetadataCustomRules.js'); /** configuration for task */ this.config = {}; /** downloaded assets */ this.media = []; /** * start loading our asset queue * @param assets */ this.process = function(data, callback) { this.config = data; this.callback = callback; this._ytdl = new YouTubeDownload(this.config); this._resolve = new LinkResolver(this.config); this._dlresolve = new FileInfo(); this._resolve.on(LinkResolver.prototype.LINK_RESOLVED, this._onLinkResolved); this._dlresolve.on(FileInfo.prototype.FILE_RESOLVED, this._onFileResolved); this._ytdl.on(YouTubeDownload.prototype.FINISH, this._onFileDownloaded); if (!this.config.assetslist || this.config.assetslist.length == 0) { Log.prototype.log(DownloadController.prototype.classDescription, "No assets to download"); this.callback.apply(); return; } this.queueProcessor = new QueueProcessor(this.onComplete, this.onProcessItem); this.queueProcessor.process(this.config.assetslist); } /** * process complete * @private */ this.onComplete = function() { self.callback.apply(self, [ [ {file: self.config.output, data: JSON.stringify(self.media, null, '\t')}, {file: self.config.removalListFile, data: JSON.stringify(self.config.removalList, null, '\t')}] ]); } /** * load next asset */ this.onProcessItem = function(item) { // no media URL - load next if (!item.media) { Log.prototype.log(DownloadController.prototype.classDescription, "Media not found"); if (self.queueProcessor.currentItem.media) { self.config.removalList.push({ media: item.media, reason: "media not found"}); } self.queueProcessor.next(self.queueProcessor); return; } Log.prototype.addLineBreak(); Log.prototype.log(DownloadController.prototype.classDescription, "Starting - " + item.source + " :: " + item.media); Log.prototype.log(DownloadController.prototype.classDescription, "Resolving link " + item.media + " of type " + item.publisher); self._resolve.resolve(item.publisher, item.media); } /** * on link resolved * @param info * @private */ this._onLinkResolved = function(error, info) { if (error) { Log.prototype.log(DownloadController.prototype.classDescription, error + " Link Cannot be Resolved for " + self.queueProcessor.currentItem.media); if (self.queueProcessor.currentItem.media) { self.config.removalList.push({ media: self.queueProcessor.currentItem.media, reason: "link not resolved"}); } self.queueProcessor.next(self.queueProcessor); return; } AssetMetadataCustomRules.prototype.apply(self.queueProcessor.currentItem, info, DownloadController.prototype.className); Log.prototype.log(DownloadController.prototype.classDescription, "URL resolved to " + self.queueProcessor.currentItem.media); self._checkUnique(); } /** * on file resolved * @param info * @private */ this._onFileResolved = function(info) { if (!info.duration) { self.queueProcessor.currentItem.downloadError = true; self.config.removalList.push({ media: self.queueProcessor.currentItem.media, reason: "not a media file"}); Log.prototype.error(DownloadController.prototype.classDescription, "Found file that doesn't appear to be a media file: " + self.queueProcessor.currentItem.media); self.queueProcessor.next(self.queueProcessor); return; } AssetMetadataCustomRules.prototype.apply(self.queueProcessor.currentItem, info, DownloadController.prototype.className); self.queueProcessor.next(self.queueProcessor); } /** * check file uniqueness * @param err * @param stats */ this._checkUnique = function() { if (FileUtils.prototype.getMediaFileRef(self.config.mediaDirectory + path.sep + self.queueProcessor.currentItem.filename)) { self.queueProcessor.currentItem.filename = FileUtils.prototype.convertPathToFilename( FileUtils.prototype.getMediaFileRef(self.config.mediaDirectory + path.sep + self.queueProcessor.currentItem.filename)); Log.prototype.log(DownloadController.prototype.classDescription, "File exists - " + self.queueProcessor.currentItem.filename); self.media.push(self.queueProcessor.currentItem); self._dlresolve.resolve(self.queueProcessor.currentItem.publisher, self.config.mediaDirectory + path.sep + self.queueProcessor.currentItem.filename); } else { Log.prototype.log(DownloadController.prototype.classDescription, "Now Downloading " + self.queueProcessor.currentItem.media); if (self.queueProcessor.currentItem.publisher == "youtube" || self.queueProcessor.currentItem.publisher == "vimeo") { self._ytdl.download(self.queueProcessor.currentItem.media, self.queueProcessor.currentItem.filename, self.config.mediaDirectory); } else { http.get({url:self.queueProcessor.currentItem.media}, self.config.mediaDirectory + path.sep + self.queueProcessor.currentItem.filename, self._onFileDownloaded); } } } /** * on file downloaded * @param error * @param response */ this._onFileDownloaded = function(error, response) { // use Youtube info data to populate asset info if (self.queueProcessor.currentItem.publisher == "youtube" || self.queueProcessor.currentItem.publisher == "vimeo") { AssetMetadataCustomRules.prototype.apply(self.queueProcessor.currentItem, response, DownloadController.prototype.className); } if (error) { Log.prototype.error(DownloadController.prototype.classDescription, "File Error: " + error); self.config.removalList.push({ media: self.queueProcessor.currentItem.media, reason: "file error"}); self.queueProcessor.currentItem.downloadError = true; } else { Log.prototype.log(DownloadController.prototype.classDescription, "Finished - " + self.queueProcessor.currentItem.filename); self.media.push(self.queueProcessor.currentItem); } self._dlresolve.resolve(self.queueProcessor.currentItem.publisher, self.config.mediaDirectory + path.sep + self.queueProcessor.currentItem.filename); } } DownloadController.prototype.className = "DownloadController"; DownloadController.prototype.classDescription = "Download Media"; exports = module.exports = DownloadController;
'use strict'; /* jasmine specs for controllers go here */ /* todo describe('controllers', function(){ beforeEach(module('myApp.controllers')); it('should ....', inject(function($controller) { //spec body var myCtrl1 = $controller('MyCtrl1', { $scope: {} }); expect(myCtrl1).toBeDefined(); })); it('should ....', inject(function($controller) { //spec body var myCtrl2 = $controller('MyCtrl2', { $scope: {} }); expect(myCtrl2).toBeDefined(); })); }); */
var Mongoose = require('mongoose'); var Schema = Mongoose.Schema, ObjectId = Schema.ObjectId; // Start of Friends n Food var UserSchema = new Mongoose.Schema({ "name": String, "email": String, "password": String, "imageUrl": String, "attendence": Number, "aamount": Number, "rating": Number, "ramount": Number, "location": ObjectId, // default location preferences "calendar": ObjectId, // default calendar preferences "okayFriends": Boolean, "okayFOF": Boolean, "okayAny": Boolean, "needFriend": Boolean }); exports.User = Mongoose.model('User', UserSchema); /* var CalendarSchema = new Mongoose.Schema({ "matched": Boolean, "time": Date, "location": ObjectId }); exports.Calendar = Mongoose.model('Calendar', CalendarSchema); */ var EventSchema = new Mongoose.Schema({ "person1": ObjectId, "person2": ObjectId, "person3": ObjectId, "person4": ObjectId, "time": Date, "location": String }); exports.Event = Mongoose.model('Event', EventSchema); var CalSchema = new Mongoose.Schema({ "cval1": Number, "cval2start": Number, "cval2end": Number, "day": Date, "user": ObjectId, "isDefault": Boolean, "event": ObjectId, "people": Number, // number of people "status": Number, // 0 - searching, 1 - found "location": String // where to eat }); exports.Cal = Mongoose.model('Cal', CalSchema); var MessageSchema = new Mongoose.Schema({ "sender": ObjectId, "event": ObjectId, "message": String, "time": Date }); exports.Message = Mongoose.model('Message', MessageSchema); var RecentSchema = new Mongoose.Schema({ "owner": ObjectId, "message": String, "link": String, "onclick": String, "time": Date }); exports.Recent = Mongoose.model('Recent', RecentSchema); var FriendSchema = new Mongoose.Schema({ "person": ObjectId, "friend": ObjectId, "status": Number, "last": Date // last time eaten together }); exports.Friend = Mongoose.model('Friend', FriendSchema); var LocationSchema = new Mongoose.Schema({ "d1": Boolean, "d2": Boolean, "d3": Boolean, "d4": Boolean, "d5": Boolean, "d6": Boolean, "d7": Boolean, "d8": Boolean, "d9": Boolean, "d10": Boolean, "d11": Boolean, "n1": Boolean, "n2": Boolean, "n3": Boolean, "n4": Boolean, "n5": Boolean, "n6": Boolean, "n7": Boolean, "n8": Boolean, "n9": Boolean, "n10": Boolean, "n11": Boolean, "n12": Boolean, "n13": Boolean, "n14": Boolean, "n15": Boolean }); exports.Location = Mongoose.model('Location', LocationSchema); // Depreciated var ProjectSchema = new Mongoose.Schema({ // fields are defined here "title": String, "date": String, "summary": String, "image": String }); exports.Project = Mongoose.model('Project', ProjectSchema); var TaskSchema = new Mongoose.Schema({ "title": String, "location": String, "difficulty": String, "duration": Number, "category": String, "status": String, "owner": ObjectId }); exports.Task = Mongoose.model('Task', TaskSchema);
/* global describe, it */ (function() { 'use strict'; var expect = require('chai').expect; var aftershave = require('../src/aftershave.js'); function _run(template, args, expected, context) { var actual = aftershave.render(template, args, context); expect(actual).to.equal(expected); } describe('Testing Aftershave.render', function() { it('should work alone', function() { _run('<h1>Hello</h1>', {}, '<h1>Hello</h1>'); }); it('should work with variables', function() { _run('<h1>Hello {{ name }}!</h1>', {name: 'Craig'}, '<h1>Hello Craig!</h1>'); }); it('should work with variables with no spaces', function() { _run('<h1>Hello {{name}}!</h1>', {name: 'Craig'}, '<h1>Hello Craig!</h1>'); }); it('should work with if statements', function() { _run('<h1>Hello {% if (name) %}{{ name }}{% else %}Person{% end %}!</h1>', {}, '<h1>Hello Person!</h1>'); _run('<h1>Hello {% if (name) %}{{ name }}{% else %}Person{% end %}!</h1>', {name: 'Craig'}, '<h1>Hello Craig!</h1>'); // try endif _run('<h1>Hello {% if (name) %}{{ name }}{% else %}Person{% endif %}!</h1>', {}, '<h1>Hello Person!</h1>'); // try punctuation _run('<h1>Hello {% if (name): %}{{ name }}{% else: %}Person{% endif; %}!</h1>', {}, '<h1>Hello Person!</h1>'); }); it('should work with if/elseif/else statements', function() { _run('{% if (test == 5) %}Hi{% elseif (test + 1 == 5) %}Hii{% else %}Hiii{% end %}', {}, 'Hiii'); _run('{% if (test == 5) %}Hi{% else if (test + 1 == 5) %}Hii{% else %}Hiii{% end %}', {test: 4}, 'Hii'); _run('{% if (test == 5) %}Hi{% else if (test + 1 == 5) %}Hii{% else %}Hiii{% end %}', {test: 5}, 'Hi'); }); it('should work with for loops', function() { var template = '<ul>{% for (var i = 0; i < fruits.length; i++) %}<li>{{ fruits[i] }}</li>{% end %}</ul>'; var args = {fruits: ['Blueberry', 'Banana', 'Strawberry', 'Pumpkin']}; var result = '<ul><li>Blueberry</li><li>Banana</li><li>Strawberry</li><li>Pumpkin</li></ul>'; _run(template, args, result); // try endfor template = '<ul>{% for (var i = 0; i < fruits.length; i++) %}<li>{{ fruits[i] }}</li>{% endfor %}</ul>'; _run(template, args, result); }); it('should allow you to run any javascript', function() { // alphabetize the fruits in the view! var template = '{% fruits.sort() %}<ul>{% for (var i = 0; i < fruits.length; i++) %}<li>{{ fruits[i] }}</li>{% end %}</ul>'; var args = {fruits: ['Blueberry', 'Banana', 'Strawberry', 'Pumpkin']}; var result = '<ul><li>Banana</li><li>Blueberry</li><li>Pumpkin</li><li>Strawberry</li></ul>'; _run(template, args, result); }); it('should work with switch statements', function() { var template = '{% switch (fruit) %}{% case "Blueberry" %}Muffin{% break %}{% case "Banana" %}Split{% break %}{% default %}Nothing{% break %}{% end %}'; var args = {}; var result = 'Nothing'; _run(template, args, result); args = {fruit: 'Blueberry'}; result = 'Muffin'; _run(template, args, result); args = {fruit: 'Banana'}; result = 'Split'; _run(template, args, result); }); it('should let you render other views', function() { var context = { render : function(view) { return "<footer>View is " + view + "</footer>"; } }; var template = '<h1>Hello</h1>{% render("footer") %}'; var args = {}; _run(template, args, '<h1>Hello</h1><footer>View is footer</footer>', context); }); it('should strip extension when rendering other views', function() { var context = { render : function(view) { return "<footer>View is " + view + "</footer>"; } }; var template = '<h1>Hello</h1>{% render("footer.html") %}'; var args = {}; _run(template, args, '<h1>Hello</h1><footer>View is footer</footer>', context); }); it('should let you escape variables', function() { var context = { escape: function(string) { return 'Escaped: ' + string; } }; var template = '<title>{% escape(title) %}</title>'; var args = {title: 'Whatever'}; _run(template, args, '<title>Escaped: Whatever</title>', context); }); it('should let you use helper functions', function() { var context = { helpers: { capitalize: function(string) { return string.toUpperCase(); } } }; var template = '<title>{% capitalize(title) %}</title>'; var args = {title: 'Whatever'}; _run(template, args, '<title>WHATEVER</title>', context); }); it('should not render "undefined" if helper returns undefined', function() { var context = { helpers: { addJavascript: function() {} } }; var template = '{% addJavascript("file.js") %}'; _run(template, {}, '', context); }); it('should let you extend other templates', function() { var master = '<h1>{{ title }}</h1><p>{{ content }}</p>'; var child = '{% extends master %}{% block title %}Hello!{% end %} {% block content %}This is a sentence.{% end %}'; var context = { render: function(name, args) { if (name == 'master') { return aftershave.render(master, args); } } }; _run(child, {}, '<h1>Hello!</h1><p>This is a sentence.</p>', context); // extend instead of extends child = '{% extend master %}{% block title %}Hello!{% end %} {% block content %}This is a sentence.{% end %}'; _run(child, {}, '<h1>Hello!</h1><p>This is a sentence.</p>', context); // dynamic title child = '{% extend master %}{% block title %}{{ title }}{% end %} {% block content %}This is a sentence.{% end %}'; _run(child, {title: 'Dynamic!'}, '<h1>Dynamic!</h1><p>This is a sentence.</p>', context); }); it('should let you extend with default blocks', function() { var master = '<title>{% block title %}Default Title{% end %}</title>'; var child = '{% extends master %}'; var context = { render: function(name, args) { if (name == 'master') { return aftershave.render(master, args); } } }; _run(child, {}, '<title>Default Title</title>', context); child = '{% extends master %}{% block title %}New Title{% end %}'; _run(child, {}, '<title>New Title</title>', context); // if else statement child = '{% extend master %}{% block title %}{% if (one) %}One.{% else %}Two.{% end %}{% end %}'; _run(child, {one: true}, '<title>One.</title>', context); }); it('should allow other variable definitions', function() { _run('{% var name = "John"; %}{% if (passedName) { name = passedName; } %}<h1>{{ name }}</h1>', {}, '<h1>John</h1>'); _run('{% var name = "John"; %}{% if (passedName) { name = passedName; } %}<h1>{{ name }}</h1>', {passedName: 'Craig'}, '<h1>Craig</h1>'); }); it('should strip html comments', function() { _run('<!-- some comment -->\n<div class="hello">Hello</div>', {}, '<div class="hello">Hello</div>'); }); it('should preserve whitespace on a single line', function() { _run('<form method="post" action="/" class="sign-in{% if (error) %} error{% end %}">', {error: true}, '<form method="post" action="/" class="sign-in error">'); }); it('should allow native javascript functions', function() { _run('Url is http://something.com/?email={{ encodeURIComponent(email) }}', {email: 'whatever@something.com'}, 'Url is http://something.com/?email=whatever%40something.com'); _run('Url is http://something.com/?email={% encodeURIComponent(email) %}', {email: 'whatever@something.com'}, 'Url is http://something.com/?email=whatever%40something.com'); }); it('should allow native javascript objects', function() { _run('Look at the json: {{ JSON.stringify(something) }}', {something: {test: 123}}, 'Look at the json: {"test":123}'); }); it('should pass args to parent template', function() { var master = '<h1>{% if (currentUser) %}Logged In as {{ currentUser.name }}{% else %}Logged Out{% end %}</h1><p>{{ content }}</p>'; var child = '{% extends master %}{% block content %}Content goes here.{% end %}'; var context = { render: function(name, args) { if (name == 'master') { return aftershave.render(master, args); } } }; _run(child, {currentUser: {name: 'Craig'}}, '<h1>Logged In as Craig</h1><p>Content goes here.</p>', context); }); it('should allow console logs', function() { _run('{% console.log(something) %}', {something: true}, ''); }); it('should not have undefined variables with child templates', function() { var master = '{% block content %}{% end %}'; var child = '{% extends master %}{% block content %}{% if (results) %}<h1>Search Results</h1>{% else %}<h1>No Results</h1>{% end %}{% end %}'; var context = { render: function(name, args) { if (name == 'master') { return aftershave.render(master, args); } } }; _run(child, {results: false}, '<h1>No Results</h1>', context); }); it('should allow directories in partial views', function() { var template = '{% render(\'helper/tip.phtml\', {message: message}) %}'; var context = { render: function(name, args) { if (name == 'helper/tip') { return args.message; } } }; _run(template, {message: 'Hello!'}, 'Hello!', context); }); it('should allow partial view rendering from variables', function() { var template = '<p>{% var name = "something"; %}{% render(name) %}</p>'; var context = { render: function(name) { if (name == 'something') { return 'Test View!'; } } }; _run(template, {}, '<p>Test View!</p>', context); }); it('should allow partial view rendering from functions', function() { var template = '<p>{% render(getViewToRender()) %}</p>'; var context = { helpers: { getViewToRender: function() { return 'test'; } }, render: function(name) { if (name == 'test') { return 'Test View!'; } } }; _run(template, {}, '<p>Test View!</p>', context); }); it('should use helpers inside of an if statement', function() { var template = '{% if (showTip("something")) %}<div class="tip">This is a tip</div>{% end %}'; var context = { helpers: { showTip: function () { return true; } } }; _run(template, {}, '<div class="tip">This is a tip</div>', context); }); it('should use args if args is specified explicitly', function() { var template = '{% if (args.showTip("something")) %}<div class="tip">This is a tip</div>{% end %}'; _run(template, {showTip: function() {return true;}}, '<div class="tip">This is a tip</div>'); }); it('should allow in expressions', function() { var someData = {1: 'one', 2: 'two'}; var template = '<ul>{% for (var key in data) %}<li>{{ data[key] }}{% end %}</ul>'; _run(template, {data: someData}, '<ul><li>one<li>two</ul>'); }); it('levels should be correct inside blocks', function() { var master = '{% block content %}{% end %}'; var context = { render: function(name, args) { if (name == 'master') { return aftershave.render(master, args); } } }; var child = '{% extends master %}{% block content %}{% if (first) %}<ul>{% for (var key in data) %}<li>{{ data[key] }}</li>{% end %}</ul>{% elseif (second) %}<ul>{% for (var i = 0; i < data.length; i++) %}<li>{{ data[i] }}</li>{% end %}</ul>{% else %}third{% end %}{% end %}'; var someData = {1: 'one', 2: 'two'}; var otherData = ['first', 'second']; _run(child, {first: true, data: someData}, '<ul><li>one</li><li>two</li></ul>', context); _run(child, {second: true, data: otherData}, '<ul><li>first</li><li>second</li></ul>', context); _run(child, {}, 'third', context); }); it('Should not prepend "args" to passed objects', function() { var context = { helpers: { something: function(name) { return name; } } }; var template = '{% something(name, {first: 1, second: 2}) %}'; var args = {name: 'Craig'}; _run(template, args, 'Craig', context); }); it('Should correctly pull multiple arguments from passed args', function() { var context = { helpers: { contrastColor: function(color1, color2, flag) { if (flag) { return 'First: ' + color1 + ', Second: ' + color2; } return ''; }, lighten: function(color) { if (color == '#000') { return '#111'; } } } }; var args = {color: '#000', flag: true}; var template = '{% contrastColor(lighten(color), color, flag) %}'; _run(template, args, 'First: #111, Second: #000', context); }); it('Should still use helper functions and args in variable declarations', function() { var context = { helpers: { contrastColor: function(foreground, background) { if (background === '#333') { return '#fff'; } }, lighten: function() { return '#333'; } } }; var template = '{% var checkmarkColor = contrastColor(color, lighten(color, 30)); %}{{ checkmarkColor }}'; _run(template, {color: '#000'}, '#fff', context); }); }); }) ();
 $(function() { if(get_menu_param("id")) { // 编辑状态 $.getJSON( "ajax_library_get?id=" + get_menu_param("id") + "&random=" + Math.random(), function(data) { $("#title").html("修改数据"); // 保存在book表中 $("#picture").val(data.data.book_picture); $("#picture").ckeditor(); $("#content").val(data.data.book_content); $('#content').ckeditor(); $("#btn_submit").val("更新"); } ); } else { $("#picture").ckeditor(); $('#content').ckeditor(); } $("#btn_submit").click(function() { var picture = $("#picture").val(); var content = $("#content").val(); var msg = ""; if(picture == "") msg += "封面图不能为空\n"; if(msg != "") alert(msg); else { var type = get_menu_param("type"); var obj = null; if(get_menu_param("id")) { var id = get_menu_param("id"); // 添加数据 obj = { id: id, bookPicture: picture, content: content, type: type, random: Math.random() }; } else { // 更新数据 obj = { bookPicture: picture, content: content, type: type, random: Math.random() }; } $.post( "ajax_library_add", obj, function(data) { if(!get_menu_param("id")) $("#menu_param").val("type:" + get_menu_param("type")); else { var page = 1; if(get_menu_param("page")) page = get_menu_param("page"); $("#menu_param").val("type:" + get_menu_param("type") + ",page:" + page); } $("#center-column").load("../../static/admin/admin_templates/library_list.html?random=" + Math.random()); }, "json" ); } }); $("#btn_back").click(function() { $("#center-column").load("../../static/admin/admin_templates/library_list.html?random=" + Math.random()); }); });
(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('@angular/core'), require('@angular/common'), require('primeng/dom')) : typeof define === 'function' && define.amd ? define('primeng/dragdrop', ['exports', '@angular/core', '@angular/common', 'primeng/dom'], factory) : (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory((global.primeng = global.primeng || {}, global.primeng.dragdrop = {}), global.ng.core, global.ng.common, global.primeng.dom)); }(this, (function (exports, i0, common, dom) { 'use strict'; function _interopNamespace(e) { if (e && e.__esModule) return e; var n = Object.create(null); if (e) { Object.keys(e).forEach(function (k) { if (k !== 'default') { var d = Object.getOwnPropertyDescriptor(e, k); Object.defineProperty(n, k, d.get ? d : { enumerable: true, get: function () { return e[k]; } }); } }); } n['default'] = e; return Object.freeze(n); } var i0__namespace = /*#__PURE__*/_interopNamespace(i0); var Draggable = /** @class */ (function () { function Draggable(el, zone) { this.el = el; this.zone = zone; this.onDragStart = new i0.EventEmitter(); this.onDragEnd = new i0.EventEmitter(); this.onDrag = new i0.EventEmitter(); } Object.defineProperty(Draggable.prototype, "pDraggableDisabled", { get: function () { return this._pDraggableDisabled; }, set: function (_pDraggableDisabled) { this._pDraggableDisabled = _pDraggableDisabled; if (this._pDraggableDisabled) { this.unbindMouseListeners(); } else { this.el.nativeElement.draggable = true; this.bindMouseListeners(); } }, enumerable: false, configurable: true }); Draggable.prototype.ngAfterViewInit = function () { if (!this.pDraggableDisabled) { this.el.nativeElement.draggable = true; this.bindMouseListeners(); } }; Draggable.prototype.bindDragListener = function () { var _this = this; if (!this.dragListener) { this.zone.runOutsideAngular(function () { _this.dragListener = _this.drag.bind(_this); _this.el.nativeElement.addEventListener('drag', _this.dragListener); }); } }; Draggable.prototype.unbindDragListener = function () { var _this = this; if (this.dragListener) { this.zone.runOutsideAngular(function () { _this.el.nativeElement.removeEventListener('drag', _this.dragListener); _this.dragListener = null; }); } }; Draggable.prototype.bindMouseListeners = function () { var _this = this; if (!this.mouseDownListener && !this.mouseUpListener) { this.zone.runOutsideAngular(function () { _this.mouseDownListener = _this.mousedown.bind(_this); _this.mouseUpListener = _this.mouseup.bind(_this); _this.el.nativeElement.addEventListener('mousedown', _this.mouseDownListener); _this.el.nativeElement.addEventListener('mouseup', _this.mouseUpListener); }); } }; Draggable.prototype.unbindMouseListeners = function () { var _this = this; if (this.mouseDownListener && this.mouseUpListener) { this.zone.runOutsideAngular(function () { _this.el.nativeElement.removeEventListener('mousedown', _this.mouseDownListener); _this.el.nativeElement.removeEventListener('mouseup', _this.mouseUpListener); _this.mouseDownListener = null; _this.mouseUpListener = null; }); } }; Draggable.prototype.drag = function (event) { this.onDrag.emit(event); }; Draggable.prototype.dragStart = function (event) { if (this.allowDrag() && !this.pDraggableDisabled) { if (this.dragEffect) { event.dataTransfer.effectAllowed = this.dragEffect; } event.dataTransfer.setData('text', this.scope); this.onDragStart.emit(event); this.bindDragListener(); } else { event.preventDefault(); } }; Draggable.prototype.dragEnd = function (event) { this.onDragEnd.emit(event); this.unbindDragListener(); }; Draggable.prototype.mousedown = function (event) { this.handle = event.target; }; Draggable.prototype.mouseup = function (event) { this.handle = null; }; Draggable.prototype.allowDrag = function () { if (this.dragHandle && this.handle) return dom.DomHandler.matches(this.handle, this.dragHandle); else return true; }; Draggable.prototype.ngOnDestroy = function () { this.unbindDragListener(); this.unbindMouseListeners(); }; return Draggable; }()); Draggable.ɵfac = i0__namespace.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "12.0.4", ngImport: i0__namespace, type: Draggable, deps: [{ token: i0__namespace.ElementRef }, { token: i0__namespace.NgZone }], target: i0__namespace.ɵɵFactoryTarget.Directive }); Draggable.ɵdir = i0__namespace.ɵɵngDeclareDirective({ minVersion: "12.0.0", version: "12.0.4", type: Draggable, selector: "[pDraggable]", inputs: { scope: ["pDraggable", "scope"], dragEffect: "dragEffect", dragHandle: "dragHandle", pDraggableDisabled: "pDraggableDisabled" }, outputs: { onDragStart: "onDragStart", onDragEnd: "onDragEnd", onDrag: "onDrag" }, host: { listeners: { "dragstart": "dragStart($event)", "dragend": "dragEnd($event)" } }, ngImport: i0__namespace }); i0__namespace.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "12.0.4", ngImport: i0__namespace, type: Draggable, decorators: [{ type: i0.Directive, args: [{ selector: '[pDraggable]' }] }], ctorParameters: function () { return [{ type: i0__namespace.ElementRef }, { type: i0__namespace.NgZone }]; }, propDecorators: { scope: [{ type: i0.Input, args: ['pDraggable'] }], dragEffect: [{ type: i0.Input }], dragHandle: [{ type: i0.Input }], onDragStart: [{ type: i0.Output }], onDragEnd: [{ type: i0.Output }], onDrag: [{ type: i0.Output }], pDraggableDisabled: [{ type: i0.Input }], dragStart: [{ type: i0.HostListener, args: ['dragstart', ['$event']] }], dragEnd: [{ type: i0.HostListener, args: ['dragend', ['$event']] }] } }); var Droppable = /** @class */ (function () { function Droppable(el, zone) { this.el = el; this.zone = zone; this.onDragEnter = new i0.EventEmitter(); this.onDragLeave = new i0.EventEmitter(); this.onDrop = new i0.EventEmitter(); } Droppable.prototype.ngAfterViewInit = function () { if (!this.pDroppableDisabled) { this.bindDragOverListener(); } }; Droppable.prototype.bindDragOverListener = function () { var _this = this; if (!this.dragOverListener) { this.zone.runOutsideAngular(function () { _this.dragOverListener = _this.dragOver.bind(_this); _this.el.nativeElement.addEventListener('dragover', _this.dragOverListener); }); } }; Droppable.prototype.unbindDragOverListener = function () { var _this = this; if (this.dragOverListener) { this.zone.runOutsideAngular(function () { _this.el.nativeElement.removeEventListener('dragover', _this.dragOverListener); _this.dragOverListener = null; }); } }; Droppable.prototype.dragOver = function (event) { event.preventDefault(); }; Droppable.prototype.drop = function (event) { if (this.allowDrop(event)) { dom.DomHandler.removeClass(this.el.nativeElement, 'p-draggable-enter'); event.preventDefault(); this.onDrop.emit(event); } }; Droppable.prototype.dragEnter = function (event) { event.preventDefault(); if (this.dropEffect) { event.dataTransfer.dropEffect = this.dropEffect; } dom.DomHandler.addClass(this.el.nativeElement, 'p-draggable-enter'); this.onDragEnter.emit(event); }; Droppable.prototype.dragLeave = function (event) { event.preventDefault(); dom.DomHandler.removeClass(this.el.nativeElement, 'p-draggable-enter'); this.onDragLeave.emit(event); }; Droppable.prototype.allowDrop = function (event) { var dragScope = event.dataTransfer.getData('text'); if (typeof (this.scope) == "string" && dragScope == this.scope) { return true; } else if (this.scope instanceof Array) { for (var j = 0; j < this.scope.length; j++) { if (dragScope == this.scope[j]) { return true; } } } return false; }; Droppable.prototype.ngOnDestroy = function () { this.unbindDragOverListener(); }; return Droppable; }()); Droppable.ɵfac = i0__namespace.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "12.0.4", ngImport: i0__namespace, type: Droppable, deps: [{ token: i0__namespace.ElementRef }, { token: i0__namespace.NgZone }], target: i0__namespace.ɵɵFactoryTarget.Directive }); Droppable.ɵdir = i0__namespace.ɵɵngDeclareDirective({ minVersion: "12.0.0", version: "12.0.4", type: Droppable, selector: "[pDroppable]", inputs: { scope: ["pDroppable", "scope"], pDroppableDisabled: "pDroppableDisabled", dropEffect: "dropEffect" }, outputs: { onDragEnter: "onDragEnter", onDragLeave: "onDragLeave", onDrop: "onDrop" }, host: { listeners: { "drop": "drop($event)", "dragenter": "dragEnter($event)", "dragleave": "dragLeave($event)" } }, ngImport: i0__namespace }); i0__namespace.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "12.0.4", ngImport: i0__namespace, type: Droppable, decorators: [{ type: i0.Directive, args: [{ selector: '[pDroppable]' }] }], ctorParameters: function () { return [{ type: i0__namespace.ElementRef }, { type: i0__namespace.NgZone }]; }, propDecorators: { scope: [{ type: i0.Input, args: ['pDroppable'] }], pDroppableDisabled: [{ type: i0.Input }], dropEffect: [{ type: i0.Input }], onDragEnter: [{ type: i0.Output }], onDragLeave: [{ type: i0.Output }], onDrop: [{ type: i0.Output }], drop: [{ type: i0.HostListener, args: ['drop', ['$event']] }], dragEnter: [{ type: i0.HostListener, args: ['dragenter', ['$event']] }], dragLeave: [{ type: i0.HostListener, args: ['dragleave', ['$event']] }] } }); var DragDropModule = /** @class */ (function () { function DragDropModule() { } return DragDropModule; }()); DragDropModule.ɵfac = i0__namespace.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "12.0.4", ngImport: i0__namespace, type: DragDropModule, deps: [], target: i0__namespace.ɵɵFactoryTarget.NgModule }); DragDropModule.ɵmod = i0__namespace.ɵɵngDeclareNgModule({ minVersion: "12.0.0", version: "12.0.4", ngImport: i0__namespace, type: DragDropModule, declarations: [Draggable, Droppable], imports: [common.CommonModule], exports: [Draggable, Droppable] }); DragDropModule.ɵinj = i0__namespace.ɵɵngDeclareInjector({ minVersion: "12.0.0", version: "12.0.4", ngImport: i0__namespace, type: DragDropModule, imports: [[common.CommonModule]] }); i0__namespace.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "12.0.4", ngImport: i0__namespace, type: DragDropModule, decorators: [{ type: i0.NgModule, args: [{ imports: [common.CommonModule], exports: [Draggable, Droppable], declarations: [Draggable, Droppable] }] }] }); /** * Generated bundle index. Do not edit. */ exports.DragDropModule = DragDropModule; exports.Draggable = Draggable; exports.Droppable = Droppable; Object.defineProperty(exports, '__esModule', { value: true }); }))); //# sourceMappingURL=primeng-dragdrop.umd.js.map
/** * Tom Select v2.0.0-rc.2 * Licensed under the Apache License, Version 2.0 (the "License"); */ import TomSelect from '../../tom-select.js'; /** * Plugin: "input_autogrow" (Tom Select) * * 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. * */ TomSelect.define('no_active_items', function () { this.hook('instead', 'setActiveItem', () => {}); this.hook('instead', 'selectAll', () => {}); }); //# sourceMappingURL=plugin.js.map
/* Tabulator v4.5.0 (c) Oliver Folkerd */ var Persistence = function Persistence(table) { this.table = table; //hold Tabulator object this.mode = ""; this.id = ""; // this.persistProps = ["field", "width", "visible"]; this.defWatcherBlock = false; this.config = {}; this.readFunc = false; this.writeFunc = false; }; // Test for whether localStorage is available for use. Persistence.prototype.localStorageTest = function () { var testKey = "_tabulator_test"; try { window.localStorage.setItem(testKey, testKey); window.localStorage.removeItem(testKey); return true; } catch (e) { return false; } }; //setup parameters Persistence.prototype.initialize = function () { //determine persistent layout storage type var mode = this.table.options.persistenceMode, id = this.table.options.persistenceID, retreivedData; this.mode = mode !== true ? mode : this.localStorageTest() ? "local" : "cookie"; if (this.table.options.persistenceReaderFunc) { if (typeof this.table.options.persistenceReaderFunc === "function") { this.readFunc = this.table.options.persistenceReaderFunc; } else { if (this.readers[this.table.options.persistenceReaderFunc]) { this.readFunc = this.readers[this.table.options.persistenceReaderFunc]; } else { console.warn("Persistence Read Error - invalid reader set", this.table.options.persistenceReaderFunc); } } } else { if (this.readers[this.mode]) { this.readFunc = this.readers[this.mode]; } else { console.warn("Persistence Read Error - invalid reader set", this.mode); } } if (this.table.options.persistenceWriterFunc) { if (typeof this.table.options.persistenceWriterFunc === "function") { this.writeFunc = this.table.options.persistenceWriterFunc; } else { if (this.readers[this.table.options.persistenceWriterFunc]) { this.writeFunc = this.readers[this.table.options.persistenceWriterFunc]; } else { console.warn("Persistence Write Error - invalid reader set", this.table.options.persistenceWriterFunc); } } } else { if (this.writers[this.mode]) { this.writeFunc = this.writers[this.mode]; } else { console.warn("Persistence Write Error - invalid writer set", this.mode); } } //set storage tag this.id = "tabulator-" + (id || this.table.element.getAttribute("id") || ""); this.config = { sort: this.table.options.persistence === true || this.table.options.persistence.sort, filter: this.table.options.persistence === true || this.table.options.persistence.filter, group: this.table.options.persistence === true || this.table.options.persistence.group, page: this.table.options.persistence === true || this.table.options.persistence.page, columns: this.table.options.persistence === true ? ["title", "width", "visible"] : this.table.options.persistence.columns }; //load pagination data if needed if (this.config.page) { retreivedData = this.retreiveData("page"); if (retreivedData) { if (typeof retreivedData.paginationSize !== "undefined" && (this.config.page === true || this.config.page.size)) { this.table.options.paginationSize = retreivedData.paginationSize; } if (typeof retreivedData.paginationInitialPage !== "undefined" && (this.config.page === true || this.config.page.page)) { this.table.options.paginationInitialPage = retreivedData.paginationInitialPage; } } } //load group data if needed if (this.config.group) { retreivedData = this.retreiveData("group"); if (retreivedData) { if (typeof retreivedData.groupBy !== "undefined" && (this.config.group === true || this.config.group.groupBy)) { this.table.options.groupBy = retreivedData.groupBy; } if (typeof retreivedData.groupStartOpen !== "undefined" && (this.config.group === true || this.config.group.groupStartOpen)) { this.table.options.groupStartOpen = retreivedData.groupStartOpen; } if (typeof retreivedData.groupHeader !== "undefined" && (this.config.group === true || this.config.group.groupHeader)) { this.table.options.groupHeader = retreivedData.groupHeader; } } } }; Persistence.prototype.initializeColumn = function (column) { var self = this, def, keys; if (this.config.columns) { this.defWatcherBlock = true; def = column.getDefinition(); keys = this.config.columns === true ? Object.keys(def) : this.config.columns; keys.forEach(function (key) { var props = Object.getOwnPropertyDescriptor(def, key); var value = def[key]; Object.defineProperty(def, key, { set: function set(newValue) { value = newValue; if (!self.defWatcherBlock) { self.save("columns"); } if (props.set) { props.set(newValue); } }, get: function get() { if (props.get) { props.get(); } return value; } }); }); this.defWatcherBlock = false; } }; //load saved definitions Persistence.prototype.load = function (type, current) { var data = this.retreiveData(type); if (current) { data = data ? this.mergeDefinition(current, data) : current; } return data; }; //retreive data from memory Persistence.prototype.retreiveData = function (type) { return this.readFunc ? this.readFunc(this.id, type) : false; }; //merge old and new column definitions Persistence.prototype.mergeDefinition = function (oldCols, newCols) { var self = this, output = []; // oldCols = oldCols || []; newCols = newCols || []; newCols.forEach(function (column, to) { var from = self._findColumn(oldCols, column), keys; if (from) { if (self.config.columns === true) { keys = Object.keys(from); keys.push("width"); } else { keys = self.config.columns; } keys.forEach(function (key) { if (typeof column[key] !== "undefined") { from[key] = column[key]; } }); if (from.columns) { from.columns = self.mergeDefinition(from.columns, column.columns); } output.push(from); } }); oldCols.forEach(function (column, i) { var from = self._findColumn(newCols, column); if (!from) { if (output.length > i) { output.splice(i, 0, column); } else { output.push(column); } } }); return output; }; //find matching columns Persistence.prototype._findColumn = function (columns, subject) { var type = subject.columns ? "group" : subject.field ? "field" : "object"; return columns.find(function (col) { switch (type) { case "group": return col.title === subject.title && col.columns.length === subject.columns.length; break; case "field": return col.field === subject.field; break; case "object": return col === subject; break; } }); }; //save data Persistence.prototype.save = function (type) { var data = {}; switch (type) { case "columns": data = this.parseColumns(this.table.columnManager.getColumns()); break; case "filter": data = this.table.modules.filter.getFilters(); break; case "sort": data = this.validateSorters(this.table.modules.sort.getSort()); break; case "group": data = this.getGroupConfig(); break; case "page": data = this.getPageConfig(); break; } if (this.writeFunc) { this.writeFunc(this.id, type, data); } }; //ensure sorters contain no function data Persistence.prototype.validateSorters = function (data) { data.forEach(function (item) { item.column = item.field; delete item.field; }); return data; }; Persistence.prototype.getGroupConfig = function () { if (this.config.group) { if (this.config.group === true || this.config.group.groupBy) { data.groupBy = this.table.options.groupBy; } if (this.config.group === true || this.config.group.groupStartOpen) { data.groupStartOpen = this.table.options.groupStartOpen; } if (this.config.group === true || this.config.group.groupHeader) { data.groupHeader = this.table.options.groupHeader; } } return data; }; Persistence.prototype.getPageConfig = function () { var data = {}; if (this.config.page) { if (this.config.page === true || this.config.page.size) { data.paginationSize = this.table.modules.page.getPageSize(); } if (this.config.page === true || this.config.page.page) { data.paginationInitialPage = this.table.modules.page.getPage(); } } return data; }; //parse columns for data to store Persistence.prototype.parseColumns = function (columns) { var self = this, definitions = []; columns.forEach(function (column) { var defStore = {}, colDef = column.getDefinition(), keys; if (column.isGroup) { defStore.title = colDef.title; defStore.columns = self.parseColumns(column.getColumns()); } else { defStore.field = column.getField(); if (self.config.columns === true) { keys = Object.keys(colDef); keys.push("width"); } else { keys = self.config.columns; } keys.forEach(function (key) { switch (key) { case "width": defStore.width = column.getWidth(); break; case "visible": defStore.visible = column.visible; break; default: defStore[key] = colDef[key]; } }); } definitions.push(defStore); }); return definitions; }; // read peristence information from storage Persistence.prototype.readers = { local: function local(id, type) { var data = localStorage.getItem(id + "-" + type); return data ? JSON.parse(data) : false; }, cookie: function cookie(id, type) { var cookie = document.cookie, key = id + "-" + type, cookiePos = cookie.indexOf(key + "="), end; //if cookie exists, decode and load column data into tabulator if (cookiePos > -1) { cookie = cookie.substr(cookiePos); end = cookie.indexOf(";"); if (end > -1) { cookie = cookie.substr(0, end); } data = cookie.replace(key + "=", ""); } return data ? JSON.parse(data) : false; } }; //write persistence information to storage Persistence.prototype.writers = { local: function local(id, type, data) { localStorage.setItem(id + "-" + type, JSON.stringify(data)); }, cookie: function cookie(id, type, data) { var expireDate = new Date(); expireDate.setDate(expireDate.getDate() + 10000); document.cookie = id + "_" + type + "=" + JSON.stringify(data) + "; expires=" + expireDate.toUTCString(); } }; Tabulator.prototype.registerModule("persistence", Persistence);
/*! * OOUI v0.40.0 * https://www.mediawiki.org/wiki/OOUI * * Copyright 2011–2020 OOUI Team and other contributors. * Released under the MIT license * http://oojs.mit-license.org * * Date: 2020-07-30T22:39:58Z */ ( function ( OO ) { 'use strict'; /** * Toolbars are complex interface components that permit users to easily access a variety * of {@link OO.ui.Tool tools} (e.g., formatting commands) and actions, which are additional * commands that are part of the toolbar, but not configured as tools. * * Individual tools are customized and then registered with a * {@link OO.ui.ToolFactory tool factory}, which creates the tools on demand. Each tool has a * symbolic name (used when registering the tool), a title (e.g., ‘Insert image’), and an icon. * * Individual tools are organized in {@link OO.ui.ToolGroup toolgroups}, which can be * {@link OO.ui.MenuToolGroup menus} of tools, {@link OO.ui.ListToolGroup lists} of tools, or a * single {@link OO.ui.BarToolGroup bar} of tools. The arrangement and order of the toolgroups is * customized when the toolbar is set up. Tools can be presented in any order, but each can only * appear once in the toolbar. * * The toolbar can be synchronized with the state of the external "application", like a text * editor's editing area, marking tools as active/inactive (e.g. a 'bold' tool would be shown as * active when the text cursor was inside bolded text) or enabled/disabled (e.g. a table caption * tool would be disabled while the user is not editing a table). A state change is signalled by * emitting the {@link #event-updateState 'updateState' event}, which calls Tools' * {@link OO.ui.Tool#onUpdateState onUpdateState method}. * * The following is an example of a basic toolbar. * * @example * // Example of a toolbar * // Create the toolbar * var toolFactory = new OO.ui.ToolFactory(); * var toolGroupFactory = new OO.ui.ToolGroupFactory(); * var toolbar = new OO.ui.Toolbar( toolFactory, toolGroupFactory ); * * // We will be placing status text in this element when tools are used * var $area = $( '<p>' ).text( 'Toolbar example' ); * * // Define the tools that we're going to place in our toolbar * * // Create a class inheriting from OO.ui.Tool * function SearchTool() { * SearchTool.super.apply( this, arguments ); * } * OO.inheritClass( SearchTool, OO.ui.Tool ); * // Each tool must have a 'name' (used as an internal identifier, see later) and at least one * // of 'icon' and 'title' (displayed icon and text). * SearchTool.static.name = 'search'; * SearchTool.static.icon = 'search'; * SearchTool.static.title = 'Search...'; * // Defines the action that will happen when this tool is selected (clicked). * SearchTool.prototype.onSelect = function () { * $area.text( 'Search tool clicked!' ); * // Never display this tool as "active" (selected). * this.setActive( false ); * }; * SearchTool.prototype.onUpdateState = function () {}; * // Make this tool available in our toolFactory and thus our toolbar * toolFactory.register( SearchTool ); * * // Register two more tools, nothing interesting here * function SettingsTool() { * SettingsTool.super.apply( this, arguments ); * } * OO.inheritClass( SettingsTool, OO.ui.Tool ); * SettingsTool.static.name = 'settings'; * SettingsTool.static.icon = 'settings'; * SettingsTool.static.title = 'Change settings'; * SettingsTool.prototype.onSelect = function () { * $area.text( 'Settings tool clicked!' ); * this.setActive( false ); * }; * SettingsTool.prototype.onUpdateState = function () {}; * toolFactory.register( SettingsTool ); * * // Register two more tools, nothing interesting here * function StuffTool() { * StuffTool.super.apply( this, arguments ); * } * OO.inheritClass( StuffTool, OO.ui.Tool ); * StuffTool.static.name = 'stuff'; * StuffTool.static.icon = 'ellipsis'; * StuffTool.static.title = 'More stuff'; * StuffTool.prototype.onSelect = function () { * $area.text( 'More stuff tool clicked!' ); * this.setActive( false ); * }; * StuffTool.prototype.onUpdateState = function () {}; * toolFactory.register( StuffTool ); * * // This is a PopupTool. Rather than having a custom 'onSelect' action, it will display a * // little popup window (a PopupWidget). * function HelpTool( toolGroup, config ) { * OO.ui.PopupTool.call( this, toolGroup, $.extend( { popup: { * padded: true, * label: 'Help', * head: true * } }, config ) ); * this.popup.$body.append( '<p>I am helpful!</p>' ); * } * OO.inheritClass( HelpTool, OO.ui.PopupTool ); * HelpTool.static.name = 'help'; * HelpTool.static.icon = 'help'; * HelpTool.static.title = 'Help'; * toolFactory.register( HelpTool ); * * // Finally define which tools and in what order appear in the toolbar. Each tool may only be * // used once (but not all defined tools must be used). * toolbar.setup( [ * { * // 'bar' tool groups display tools' icons only, side-by-side. * type: 'bar', * include: [ 'search', 'help' ] * }, * { * // 'list' tool groups display both the titles and icons, in a dropdown list. * type: 'list', * indicator: 'down', * label: 'More', * include: [ 'settings', 'stuff' ] * } * // Note how the tools themselves are toolgroup-agnostic - the same tool can be displayed * // either in a 'list' or a 'bar'. There is a 'menu' tool group too, not showcased here, * // since it's more complicated to use. (See the next example snippet on this page.) * ] ); * * // Create some UI around the toolbar and place it in the document * var frame = new OO.ui.PanelLayout( { * expanded: false, * framed: true * } ); * var contentFrame = new OO.ui.PanelLayout( { * expanded: false, * padded: true * } ); * frame.$element.append( * toolbar.$element, * contentFrame.$element.append( $area ) * ); * $( document.body ).append( frame.$element ); * * // Here is where the toolbar is actually built. This must be done after inserting it into the * // document. * toolbar.initialize(); * toolbar.emit( 'updateState' ); * * The following example extends the previous one to illustrate 'menu' toolgroups and the usage of * {@link #event-updateState 'updateState' event}. * * @example * // Create the toolbar * var toolFactory = new OO.ui.ToolFactory(); * var toolGroupFactory = new OO.ui.ToolGroupFactory(); * var toolbar = new OO.ui.Toolbar( toolFactory, toolGroupFactory ); * * // We will be placing status text in this element when tools are used * var $area = $( '<p>' ).text( 'Toolbar example' ); * * // Define the tools that we're going to place in our toolbar * * // Create a class inheriting from OO.ui.Tool * function SearchTool() { * SearchTool.super.apply( this, arguments ); * } * OO.inheritClass( SearchTool, OO.ui.Tool ); * // Each tool must have a 'name' (used as an internal identifier, see later) and at least one * // of 'icon' and 'title' (displayed icon and text). * SearchTool.static.name = 'search'; * SearchTool.static.icon = 'search'; * SearchTool.static.title = 'Search...'; * // Defines the action that will happen when this tool is selected (clicked). * SearchTool.prototype.onSelect = function () { * $area.text( 'Search tool clicked!' ); * // Never display this tool as "active" (selected). * this.setActive( false ); * }; * SearchTool.prototype.onUpdateState = function () {}; * // Make this tool available in our toolFactory and thus our toolbar * toolFactory.register( SearchTool ); * * // Register two more tools, nothing interesting here * function SettingsTool() { * SettingsTool.super.apply( this, arguments ); * this.reallyActive = false; * } * OO.inheritClass( SettingsTool, OO.ui.Tool ); * SettingsTool.static.name = 'settings'; * SettingsTool.static.icon = 'settings'; * SettingsTool.static.title = 'Change settings'; * SettingsTool.prototype.onSelect = function () { * $area.text( 'Settings tool clicked!' ); * // Toggle the active state on each click * this.reallyActive = !this.reallyActive; * this.setActive( this.reallyActive ); * // To update the menu label * this.toolbar.emit( 'updateState' ); * }; * SettingsTool.prototype.onUpdateState = function () {}; * toolFactory.register( SettingsTool ); * * // Register two more tools, nothing interesting here * function StuffTool() { * StuffTool.super.apply( this, arguments ); * this.reallyActive = false; * } * OO.inheritClass( StuffTool, OO.ui.Tool ); * StuffTool.static.name = 'stuff'; * StuffTool.static.icon = 'ellipsis'; * StuffTool.static.title = 'More stuff'; * StuffTool.prototype.onSelect = function () { * $area.text( 'More stuff tool clicked!' ); * // Toggle the active state on each click * this.reallyActive = !this.reallyActive; * this.setActive( this.reallyActive ); * // To update the menu label * this.toolbar.emit( 'updateState' ); * }; * StuffTool.prototype.onUpdateState = function () {}; * toolFactory.register( StuffTool ); * * // This is a PopupTool. Rather than having a custom 'onSelect' action, it will display a * // little popup window (a PopupWidget). 'onUpdateState' is also already implemented. * function HelpTool( toolGroup, config ) { * OO.ui.PopupTool.call( this, toolGroup, $.extend( { popup: { * padded: true, * label: 'Help', * head: true * } }, config ) ); * this.popup.$body.append( '<p>I am helpful!</p>' ); * } * OO.inheritClass( HelpTool, OO.ui.PopupTool ); * HelpTool.static.name = 'help'; * HelpTool.static.icon = 'help'; * HelpTool.static.title = 'Help'; * toolFactory.register( HelpTool ); * * // Finally define which tools and in what order appear in the toolbar. Each tool may only be * // used once (but not all defined tools must be used). * toolbar.setup( [ * { * // 'bar' tool groups display tools' icons only, side-by-side. * type: 'bar', * include: [ 'search', 'help' ] * }, * { * // 'menu' tool groups display both the titles and icons, in a dropdown menu. * // Menu label indicates which items are selected. * type: 'menu', * indicator: 'down', * include: [ 'settings', 'stuff' ] * } * ] ); * * // Create some UI around the toolbar and place it in the document * var frame = new OO.ui.PanelLayout( { * expanded: false, * framed: true * } ); * var contentFrame = new OO.ui.PanelLayout( { * expanded: false, * padded: true * } ); * frame.$element.append( * toolbar.$element, * contentFrame.$element.append( $area ) * ); * $( document.body ).append( frame.$element ); * * // Here is where the toolbar is actually built. This must be done after inserting it into the * // document. * toolbar.initialize(); * toolbar.emit( 'updateState' ); * * @class * @extends OO.ui.Element * @mixins OO.EventEmitter * @mixins OO.ui.mixin.GroupElement * * @constructor * @param {OO.ui.ToolFactory} toolFactory Factory for creating tools * @param {OO.ui.ToolGroupFactory} toolGroupFactory Factory for creating toolgroups * @param {Object} [config] Configuration options * @cfg {boolean} [actions] Add an actions section to the toolbar. Actions are commands that are * included in the toolbar, but are not configured as tools. By default, actions are displayed on * the right side of the toolbar. * @cfg {string} [position='top'] Whether the toolbar is positioned above ('top') or below * ('bottom') content. * @cfg {jQuery} [$overlay] An overlay for the popup. * See <https://www.mediawiki.org/wiki/OOUI/Concepts#Overlays>. */ OO.ui.Toolbar = function OoUiToolbar( toolFactory, toolGroupFactory, config ) { // Allow passing positional parameters inside the config object if ( OO.isPlainObject( toolFactory ) && config === undefined ) { config = toolFactory; toolFactory = config.toolFactory; toolGroupFactory = config.toolGroupFactory; } // Configuration initialization config = config || {}; // Parent constructor OO.ui.Toolbar.super.call( this, config ); // Mixin constructors OO.EventEmitter.call( this ); OO.ui.mixin.GroupElement.call( this, config ); // Properties this.toolFactory = toolFactory; this.toolGroupFactory = toolGroupFactory; this.groupsByName = {}; this.activeToolGroups = 0; this.tools = {}; this.position = config.position || 'top'; this.$bar = $( '<div>' ); this.$actions = $( '<div>' ); this.$popups = $( '<div>' ); this.initialized = false; this.narrowThreshold = null; this.onWindowResizeHandler = this.onWindowResize.bind( this ); this.$overlay = ( config.$overlay === true ? OO.ui.getDefaultOverlay() : config.$overlay ) || this.$element; // Events this.$element .add( this.$bar ).add( this.$group ).add( this.$actions ) .on( 'mousedown keydown', this.onPointerDown.bind( this ) ); // Initialization this.$group.addClass( 'oo-ui-toolbar-tools' ); if ( config.actions ) { this.$bar.append( this.$actions.addClass( 'oo-ui-toolbar-actions' ) ); } this.$popups.addClass( 'oo-ui-toolbar-popups' ); this.$bar .addClass( 'oo-ui-toolbar-bar' ) .append( this.$group, '<div style="clear:both"></div>' ); // Possible classes: oo-ui-toolbar-position-top, oo-ui-toolbar-position-bottom this.$element .addClass( 'oo-ui-toolbar oo-ui-toolbar-position-' + this.position ) .append( this.$bar ); this.$overlay.append( this.$popups ); }; /* Setup */ OO.inheritClass( OO.ui.Toolbar, OO.ui.Element ); OO.mixinClass( OO.ui.Toolbar, OO.EventEmitter ); OO.mixinClass( OO.ui.Toolbar, OO.ui.mixin.GroupElement ); /* Events */ /** * @event updateState * * An 'updateState' event must be emitted on the Toolbar (by calling * `toolbar.emit( 'updateState' )`) every time the state of the application using the toolbar * changes, and an update to the state of tools is required. * * @param {...Mixed} data Application-defined parameters */ /** * @event active * * An 'active' event is emitted when the number of active toolgroups increases from 0, or * returns to 0. * * @param {boolean} There are active toolgroups in this toolbar */ /* Methods */ /** * Get the tool factory. * * @return {OO.ui.ToolFactory} Tool factory */ OO.ui.Toolbar.prototype.getToolFactory = function () { return this.toolFactory; }; /** * Get the toolgroup factory. * * @return {OO.Factory} Toolgroup factory */ OO.ui.Toolbar.prototype.getToolGroupFactory = function () { return this.toolGroupFactory; }; /** * Handles mouse down events. * * @private * @param {jQuery.Event} e Mouse down event * @return {undefined|boolean} False to prevent default if event is handled */ OO.ui.Toolbar.prototype.onPointerDown = function ( e ) { var $closestWidgetToEvent = $( e.target ).closest( '.oo-ui-widget' ), $closestWidgetToToolbar = this.$element.closest( '.oo-ui-widget' ); if ( !$closestWidgetToEvent.length || $closestWidgetToEvent[ 0 ] === $closestWidgetToToolbar[ 0 ] ) { return false; } }; /** * Handle window resize event. * * @private * @param {jQuery.Event} e Window resize event */ OO.ui.Toolbar.prototype.onWindowResize = function () { this.$element.add( this.$popups ).toggleClass( 'oo-ui-toolbar-narrow', this.$bar[ 0 ].clientWidth <= this.getNarrowThreshold() ); }; /** * Get the (lazily-computed) width threshold for applying the oo-ui-toolbar-narrow * class. * * @private * @return {number} Width threshold in pixels */ OO.ui.Toolbar.prototype.getNarrowThreshold = function () { if ( this.narrowThreshold === null ) { this.narrowThreshold = this.$group[ 0 ].offsetWidth + this.$actions[ 0 ].offsetWidth; } return this.narrowThreshold; }; /** * Sets up handles and preloads required information for the toolbar to work. * This must be called after it is attached to a visible document and before doing anything else. */ OO.ui.Toolbar.prototype.initialize = function () { if ( !this.initialized ) { this.initialized = true; $( this.getElementWindow() ).on( 'resize', this.onWindowResizeHandler ); this.onWindowResize(); } }; /** * Set up the toolbar. * * The toolbar is set up with a list of toolgroup configurations that specify the type of * toolgroup ({@link OO.ui.BarToolGroup bar}, {@link OO.ui.MenuToolGroup menu}, or * {@link OO.ui.ListToolGroup list}) to add and which tools to include, exclude, promote, or demote * within that toolgroup. Please see {@link OO.ui.ToolGroup toolgroups} for more information about * including tools in toolgroups. * * @param {Object.<string,Array>} groups List of toolgroup configurations * @param {string} [groups.name] Symbolic name for this toolgroup * @param {string} [groups.type] Toolgroup type, should exist in the toolgroup factory * @param {Array|string} [groups.include] Tools to include in the toolgroup * @param {Array|string} [groups.exclude] Tools to exclude from the toolgroup * @param {Array|string} [groups.promote] Tools to promote to the beginning of the toolgroup * @param {Array|string} [groups.demote] Tools to demote to the end of the toolgroup */ OO.ui.Toolbar.prototype.setup = function ( groups ) { var i, len, type, toolGroup, groupConfig, items = [], defaultType = 'bar'; // Cleanup previous groups this.reset(); // Build out new groups for ( i = 0, len = groups.length; i < len; i++ ) { groupConfig = groups[ i ]; if ( groupConfig.include === '*' ) { // Apply defaults to catch-all groups if ( groupConfig.type === undefined ) { groupConfig.type = 'list'; } if ( groupConfig.label === undefined ) { groupConfig.label = OO.ui.msg( 'ooui-toolbar-more' ); } } // Check type has been registered type = this.getToolGroupFactory().lookup( groupConfig.type ) ? groupConfig.type : defaultType; toolGroup = this.getToolGroupFactory().create( type, this, groupConfig ); items.push( toolGroup ); this.groupsByName[ groupConfig.name ] = toolGroup; toolGroup.connect( this, { active: 'onToolGroupActive' } ); } this.addItems( items ); }; /** * Handle active events from tool groups * * @param {boolean} active Tool group has become active, inactive if false * @fires active */ OO.ui.Toolbar.prototype.onToolGroupActive = function ( active ) { if ( active ) { this.activeToolGroups++; if ( this.activeToolGroups === 1 ) { this.emit( 'active', true ); } } else { this.activeToolGroups--; if ( this.activeToolGroups === 0 ) { this.emit( 'active', false ); } } }; /** * Get a toolgroup by name * * @param {string} name Group name * @return {OO.ui.ToolGroup|null} Tool group, or null if none found by that name */ OO.ui.Toolbar.prototype.getToolGroupByName = function ( name ) { return this.groupsByName[ name ] || null; }; /** * Remove all tools and toolgroups from the toolbar. */ OO.ui.Toolbar.prototype.reset = function () { var i, len; this.groupsByName = {}; this.tools = {}; for ( i = 0, len = this.items.length; i < len; i++ ) { this.items[ i ].destroy(); } this.clearItems(); }; /** * Destroy the toolbar. * * Destroying the toolbar removes all event handlers and DOM elements that constitute the toolbar. * Call this method whenever you are done using a toolbar. */ OO.ui.Toolbar.prototype.destroy = function () { $( this.getElementWindow() ).off( 'resize', this.onWindowResizeHandler ); this.reset(); this.$element.remove(); }; /** * Check if the tool is available. * * Available tools are ones that have not yet been added to the toolbar. * * @param {string} name Symbolic name of tool * @return {boolean} Tool is available */ OO.ui.Toolbar.prototype.isToolAvailable = function ( name ) { return !this.tools[ name ]; }; /** * Prevent tool from being used again. * * @param {OO.ui.Tool} tool Tool to reserve */ OO.ui.Toolbar.prototype.reserveTool = function ( tool ) { this.tools[ tool.getName() ] = tool; }; /** * Allow tool to be used again. * * @param {OO.ui.Tool} tool Tool to release */ OO.ui.Toolbar.prototype.releaseTool = function ( tool ) { delete this.tools[ tool.getName() ]; }; /** * Get accelerator label for tool. * * The OOUI library does not contain an accelerator system, but this is the hook for one. To * use an accelerator system, subclass the toolbar and override this method, which is meant to * return a label that describes the accelerator keys for the tool passed (by symbolic name) to * the method. * * @param {string} name Symbolic name of tool * @return {string|undefined} Tool accelerator label if available */ OO.ui.Toolbar.prototype.getToolAccelerator = function () { return undefined; }; /** * Tools, together with {@link OO.ui.ToolGroup toolgroups}, constitute * {@link OO.ui.Toolbar toolbars}. * Each tool is configured with a static name, title, and icon and is customized with the command * to carry out when the tool is selected. Tools must also be registered with a * {@link OO.ui.ToolFactory tool factory}, which creates the tools on demand. * * Every Tool subclass must implement two methods: * * - {@link #onUpdateState} * - {@link #onSelect} * * Tools are added to toolgroups ({@link OO.ui.ListToolGroup ListToolGroup}, * {@link OO.ui.BarToolGroup BarToolGroup}, or {@link OO.ui.MenuToolGroup MenuToolGroup}), which * determine how the tool is displayed in the toolbar. See {@link OO.ui.Toolbar toolbars} for an * example. * * For more information, please see the [OOUI documentation on MediaWiki][1]. * [1]: https://www.mediawiki.org/wiki/OOUI/Toolbars * * @abstract * @class * @extends OO.ui.Widget * @mixins OO.ui.mixin.IconElement * @mixins OO.ui.mixin.FlaggedElement * @mixins OO.ui.mixin.TabIndexedElement * * @constructor * @param {OO.ui.ToolGroup} toolGroup * @param {Object} [config] Configuration options * @cfg {string|Function} [title] Title text or a function that returns text. If this config is * omitted, the value of the {@link #static-title static title} property is used. * * The title is used in different ways depending on the type of toolgroup that contains the tool. * The title is used as a tooltip if the tool is part of a {@link OO.ui.BarToolGroup bar} * toolgroup, or as the label text if the tool is part of a {@link OO.ui.ListToolGroup list} or * {@link OO.ui.MenuToolGroup menu} toolgroup. * * For bar toolgroups, a description of the accelerator key is appended to the title if an * accelerator key is associated with an action by the same name as the tool and accelerator * functionality has been added to the application. * To add accelerator key functionality, you must subclass OO.ui.Toolbar and override the * {@link OO.ui.Toolbar#getToolAccelerator getToolAccelerator} method. */ OO.ui.Tool = function OoUiTool( toolGroup, config ) { // Allow passing positional parameters inside the config object if ( OO.isPlainObject( toolGroup ) && config === undefined ) { config = toolGroup; toolGroup = config.toolGroup; } // Configuration initialization config = config || {}; // Parent constructor OO.ui.Tool.super.call( this, config ); // Properties this.toolGroup = toolGroup; this.toolbar = this.toolGroup.getToolbar(); this.active = false; this.$title = $( '<span>' ); this.$accel = $( '<span>' ); this.$link = $( '<a>' ); this.title = null; this.checkIcon = new OO.ui.IconWidget( { icon: 'check', classes: [ 'oo-ui-tool-checkIcon' ] } ); // Mixin constructors OO.ui.mixin.IconElement.call( this, config ); OO.ui.mixin.FlaggedElement.call( this, config ); OO.ui.mixin.TabIndexedElement.call( this, $.extend( { $tabIndexed: this.$link }, config ) ); // Events this.toolbar.connect( this, { updateState: 'onUpdateState' } ); // Initialization this.$title.addClass( 'oo-ui-tool-title' ); this.$accel .addClass( 'oo-ui-tool-accel' ) .prop( { // This may need to be changed if the key names are ever localized, // but for now they are essentially written in English dir: 'ltr', lang: 'en' } ); this.$link .addClass( 'oo-ui-tool-link' ) .append( this.checkIcon.$element, this.$icon, this.$title, this.$accel ) .attr( 'role', 'button' ); // Don't show keyboard shortcuts on mobile as users are unlikely to have // a physical keyboard, and likely to have limited screen space. if ( !OO.ui.isMobile() ) { this.$link.append( this.$accel ); } this.$element .data( 'oo-ui-tool', this ) .addClass( 'oo-ui-tool' ) .addClass( 'oo-ui-tool-name-' + this.constructor.static.name.replace( /^([^/]+)\/([^/]+).*$/, '$1-$2' ) ) .toggleClass( 'oo-ui-tool-with-label', this.constructor.static.displayBothIconAndLabel ) .append( this.$link ); this.setTitle( config.title || this.constructor.static.title ); }; /* Setup */ OO.inheritClass( OO.ui.Tool, OO.ui.Widget ); OO.mixinClass( OO.ui.Tool, OO.ui.mixin.IconElement ); OO.mixinClass( OO.ui.Tool, OO.ui.mixin.FlaggedElement ); OO.mixinClass( OO.ui.Tool, OO.ui.mixin.TabIndexedElement ); /* Static Properties */ /** * @static * @inheritdoc */ OO.ui.Tool.static.tagName = 'span'; /** * Symbolic name of tool. * * The symbolic name is used internally to register the tool with a * {@link OO.ui.ToolFactory ToolFactory}. It can also be used when adding tools to toolgroups. * * @abstract * @static * @inheritable * @property {string} */ OO.ui.Tool.static.name = ''; /** * Symbolic name of the group. * * The group name is used to associate tools with each other so that they can be selected later by * a {@link OO.ui.ToolGroup toolgroup}. * * @abstract * @static * @inheritable * @property {string} */ OO.ui.Tool.static.group = ''; /** * Tool title text or a function that returns title text. The value of the static property is * overridden if the #title config option is used. * * @abstract * @static * @inheritable * @property {string|Function} */ OO.ui.Tool.static.title = ''; /** * Display both icon and label when the tool is used in a {@link OO.ui.BarToolGroup bar} toolgroup. * Normally only the icon is displayed, or only the label if no icon is given. * * @static * @inheritable * @property {boolean} */ OO.ui.Tool.static.displayBothIconAndLabel = false; /** * Add tool to catch-all groups automatically. * * A catch-all group, which contains all tools that do not currently belong to a toolgroup, * can be included in a toolgroup using the wildcard selector, an asterisk (*). * * @static * @inheritable * @property {boolean} */ OO.ui.Tool.static.autoAddToCatchall = true; /** * Add tool to named groups automatically. * * By default, tools that are configured with a static ‘group’ property are added * to that group and will be selected when the symbolic name of the group is specified (e.g., when * toolgroups include tools by group name). * * @static * @property {boolean} * @inheritable */ OO.ui.Tool.static.autoAddToGroup = true; /** * Check if this tool is compatible with given data. * * This is a stub that can be overridden to provide support for filtering tools based on an * arbitrary piece of information (e.g., where the cursor is in a document). The implementation * must also call this method so that the compatibility check can be performed. * * @static * @inheritable * @param {Mixed} data Data to check * @return {boolean} Tool can be used with data */ OO.ui.Tool.static.isCompatibleWith = function () { return false; }; /* Methods */ /** * Handle the toolbar state being updated. This method is called when the * {@link OO.ui.Toolbar#event-updateState 'updateState' event} is emitted on the * {@link OO.ui.Toolbar Toolbar} that uses this tool, and should set the state of this tool * depending on application state (usually by calling #setDisabled to enable or disable the tool, * or #setActive to mark is as currently in-use or not). * * This is an abstract method that must be overridden in a concrete subclass. * * @method * @protected * @abstract */ OO.ui.Tool.prototype.onUpdateState = null; /** * Handle the tool being selected. This method is called when the user triggers this tool, * usually by clicking on its label/icon. * * This is an abstract method that must be overridden in a concrete subclass. * * @method * @protected * @abstract */ OO.ui.Tool.prototype.onSelect = null; /** * Check if the tool is active. * * Tools become active when their #onSelect or #onUpdateState handlers change them to appear pressed * with the #setActive method. Additional CSS is applied to the tool to reflect the active state. * * @return {boolean} Tool is active */ OO.ui.Tool.prototype.isActive = function () { return this.active; }; /** * Make the tool appear active or inactive. * * This method should be called within #onSelect or #onUpdateState event handlers to make the tool * appear pressed or not. * * @param {boolean} state Make tool appear active */ OO.ui.Tool.prototype.setActive = function ( state ) { this.active = !!state; this.$element.toggleClass( 'oo-ui-tool-active', this.active ); this.updateThemeClasses(); }; /** * Set the tool #title. * * @param {string|Function} title Title text or a function that returns text * @chainable * @return {OO.ui.Tool} The tool, for chaining */ OO.ui.Tool.prototype.setTitle = function ( title ) { this.title = OO.ui.resolveMsg( title ); this.updateTitle(); return this; }; /** * Get the tool #title. * * @return {string} Title text */ OO.ui.Tool.prototype.getTitle = function () { return this.title; }; /** * Get the tool's symbolic name. * * @return {string} Symbolic name of tool */ OO.ui.Tool.prototype.getName = function () { return this.constructor.static.name; }; /** * Update the title. */ OO.ui.Tool.prototype.updateTitle = function () { var titleTooltips = this.toolGroup.constructor.static.titleTooltips, accelTooltips = this.toolGroup.constructor.static.accelTooltips, accel = this.toolbar.getToolAccelerator( this.constructor.static.name ), tooltipParts = []; this.$title.text( this.title ); this.$accel.text( accel ); if ( titleTooltips && typeof this.title === 'string' && this.title.length ) { tooltipParts.push( this.title ); } if ( accelTooltips && typeof accel === 'string' && accel.length ) { tooltipParts.push( accel ); } if ( tooltipParts.length ) { this.$link.attr( 'title', tooltipParts.join( ' ' ) ); } else { this.$link.removeAttr( 'title' ); } }; /** * @inheritdoc OO.ui.mixin.IconElement */ OO.ui.Tool.prototype.setIcon = function ( icon ) { // Mixin method OO.ui.mixin.IconElement.prototype.setIcon.call( this, icon ); this.$element.toggleClass( 'oo-ui-tool-with-icon', !!this.icon ); return this; }; /** * Destroy tool. * * Destroying the tool removes all event handlers and the tool’s DOM elements. * Call this method whenever you are done using a tool. */ OO.ui.Tool.prototype.destroy = function () { this.toolbar.disconnect( this ); this.$element.remove(); }; /** * ToolGroups are collections of {@link OO.ui.Tool tools} that are used in a * {@link OO.ui.Toolbar toolbar}. * The type of toolgroup ({@link OO.ui.ListToolGroup list}, {@link OO.ui.BarToolGroup bar}, or * {@link OO.ui.MenuToolGroup menu}) to which a tool belongs determines how the tool is arranged * and displayed in the toolbar. Toolgroups themselves are created on demand with a * {@link OO.ui.ToolGroupFactory toolgroup factory}. * * Toolgroups can contain individual tools, groups of tools, or all available tools, as specified * using the `include` config option. See OO.ui.ToolFactory#extract on documentation of the format. * The options `exclude`, `promote`, and `demote` support the same formats. * * See {@link OO.ui.Toolbar toolbars} for a full example. For more information about toolbars in * general, please see the [OOUI documentation on MediaWiki][1]. * * [1]: https://www.mediawiki.org/wiki/OOUI/Toolbars * * @abstract * @class * @extends OO.ui.Widget * @mixins OO.ui.mixin.GroupElement * * @constructor * @param {OO.ui.Toolbar} toolbar * @param {Object} [config] Configuration options * @cfg {Array|string} [include] List of tools to include in the toolgroup, see above. * @cfg {Array|string} [exclude] List of tools to exclude from the toolgroup, see above. * @cfg {Array|string} [promote] List of tools to promote to the beginning of the toolgroup, * see above. * @cfg {Array|string} [demote] List of tools to demote to the end of the toolgroup, see above. * This setting is particularly useful when tools have been added to the toolgroup * en masse (e.g., via the catch-all selector). */ OO.ui.ToolGroup = function OoUiToolGroup( toolbar, config ) { // Allow passing positional parameters inside the config object if ( OO.isPlainObject( toolbar ) && config === undefined ) { config = toolbar; toolbar = config.toolbar; } // Configuration initialization config = config || {}; // Parent constructor OO.ui.ToolGroup.super.call( this, config ); // Mixin constructors OO.ui.mixin.GroupElement.call( this, config ); // Properties this.toolbar = toolbar; this.tools = {}; this.pressed = null; this.autoDisabled = false; this.include = config.include || []; this.exclude = config.exclude || []; this.promote = config.promote || []; this.demote = config.demote || []; this.onDocumentMouseKeyUpHandler = this.onDocumentMouseKeyUp.bind( this ); // Events this.$group.on( { mousedown: this.onMouseKeyDown.bind( this ), mouseup: this.onMouseKeyUp.bind( this ), keydown: this.onMouseKeyDown.bind( this ), keyup: this.onMouseKeyUp.bind( this ), focus: this.onMouseOverFocus.bind( this ), blur: this.onMouseOutBlur.bind( this ), mouseover: this.onMouseOverFocus.bind( this ), mouseout: this.onMouseOutBlur.bind( this ) } ); this.toolbar.getToolFactory().connect( this, { register: 'onToolFactoryRegister' } ); this.aggregate( { disable: 'itemDisable' } ); this.connect( this, { itemDisable: 'updateDisabled', disable: 'onDisable' } ); // Initialization this.$group.addClass( 'oo-ui-toolGroup-tools' ); this.$element .addClass( 'oo-ui-toolGroup' ) .append( this.$group ); this.onDisable( this.isDisabled() ); this.populate(); }; /* Setup */ OO.inheritClass( OO.ui.ToolGroup, OO.ui.Widget ); OO.mixinClass( OO.ui.ToolGroup, OO.ui.mixin.GroupElement ); /* Events */ /** * @event update */ /** * @event active * * An 'active' event is emitted when any popup is shown/hidden. * * @param {boolean} The popup is visible */ /* Static Properties */ /** * Show labels in tooltips. * * @static * @inheritable * @property {boolean} */ OO.ui.ToolGroup.static.titleTooltips = false; /** * Show acceleration labels in tooltips. * * Note: The OOUI library does not include an accelerator system, but does contain * a hook for one. To use an accelerator system, subclass the {@link OO.ui.Toolbar toolbar} and * override the {@link OO.ui.Toolbar#getToolAccelerator getToolAccelerator} method, which is * meant to return a label that describes the accelerator keys for a given tool (e.g., Control+M * key combination). * * @static * @inheritable * @property {boolean} */ OO.ui.ToolGroup.static.accelTooltips = false; /** * Automatically disable the toolgroup when all tools are disabled * * @static * @inheritable * @property {boolean} */ OO.ui.ToolGroup.static.autoDisable = true; /** * @abstract * @static * @inheritable * @property {string} */ OO.ui.ToolGroup.static.name = null; /* Methods */ /** * @inheritdoc */ OO.ui.ToolGroup.prototype.isDisabled = function () { return this.autoDisabled || OO.ui.ToolGroup.super.prototype.isDisabled.apply( this, arguments ); }; /** * @inheritdoc */ OO.ui.ToolGroup.prototype.updateDisabled = function () { var i, item, allDisabled = true; if ( this.constructor.static.autoDisable ) { for ( i = this.items.length - 1; i >= 0; i-- ) { item = this.items[ i ]; if ( !item.isDisabled() ) { allDisabled = false; break; } } this.autoDisabled = allDisabled; } OO.ui.ToolGroup.super.prototype.updateDisabled.apply( this, arguments ); }; /** * Handle disable events. * * @protected * @param {boolean} isDisabled */ OO.ui.ToolGroup.prototype.onDisable = function ( isDisabled ) { this.$group.toggleClass( 'oo-ui-toolGroup-disabled-tools', isDisabled ); this.$group.toggleClass( 'oo-ui-toolGroup-enabled-tools', !isDisabled ); }; /** * Handle mouse down and key down events. * * @protected * @param {jQuery.Event} e Mouse down or key down event * @return {undefined|boolean} False to prevent default if event is handled */ OO.ui.ToolGroup.prototype.onMouseKeyDown = function ( e ) { if ( !this.isDisabled() && ( e.which === OO.ui.MouseButtons.LEFT || e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER ) ) { this.pressed = this.findTargetTool( e ); if ( this.pressed ) { this.pressed.setActive( true ); this.getElementDocument().addEventListener( 'mouseup', this.onDocumentMouseKeyUpHandler, true ); this.getElementDocument().addEventListener( 'keyup', this.onDocumentMouseKeyUpHandler, true ); return false; } } }; /** * Handle document mouse up and key up events. * * @protected * @param {MouseEvent|KeyboardEvent} e Mouse up or key up event */ OO.ui.ToolGroup.prototype.onDocumentMouseKeyUp = function ( e ) { this.getElementDocument().removeEventListener( 'mouseup', this.onDocumentMouseKeyUpHandler, true ); this.getElementDocument().removeEventListener( 'keyup', this.onDocumentMouseKeyUpHandler, true ); // onMouseKeyUp may be called a second time, depending on where the mouse is when the button is // released, but since `this.pressed` will no longer be true, the second call will be ignored. this.onMouseKeyUp( e ); }; /** * Handle mouse up and key up events. * * @protected * @param {MouseEvent|KeyboardEvent} e Mouse up or key up event */ OO.ui.ToolGroup.prototype.onMouseKeyUp = function ( e ) { var tool = this.findTargetTool( e ); if ( !this.isDisabled() && this.pressed && this.pressed === tool && ( e.which === OO.ui.MouseButtons.LEFT || e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER ) ) { this.pressed.onSelect(); this.pressed = null; e.preventDefault(); e.stopPropagation(); } this.pressed = null; }; /** * Handle mouse over and focus events. * * @protected * @param {jQuery.Event} e Mouse over or focus event */ OO.ui.ToolGroup.prototype.onMouseOverFocus = function ( e ) { var tool = this.findTargetTool( e ); if ( this.pressed && this.pressed === tool ) { this.pressed.setActive( true ); } }; /** * Handle mouse out and blur events. * * @protected * @param {jQuery.Event} e Mouse out or blur event */ OO.ui.ToolGroup.prototype.onMouseOutBlur = function ( e ) { var tool = this.findTargetTool( e ); if ( this.pressed && this.pressed === tool ) { this.pressed.setActive( false ); } }; /** * Get the closest tool to a jQuery.Event. * * Only tool links are considered, which prevents other elements in the tool such as popups from * triggering tool group interactions. * * @private * @param {jQuery.Event} e * @return {OO.ui.Tool|null} Tool, `null` if none was found */ OO.ui.ToolGroup.prototype.findTargetTool = function ( e ) { var tool, $item = $( e.target ).closest( '.oo-ui-tool-link' ); if ( $item.length ) { tool = $item.parent().data( 'oo-ui-tool' ); } return tool && !tool.isDisabled() ? tool : null; }; /** * Handle tool registry register events. * * If a tool is registered after the group is created, we must repopulate the list to account for: * * - a tool being added that may be included * - a tool already included being overridden * * @protected * @param {string} name Symbolic name of tool */ OO.ui.ToolGroup.prototype.onToolFactoryRegister = function () { this.populate(); }; /** * Get the toolbar that contains the toolgroup. * * @return {OO.ui.Toolbar} Toolbar that contains the toolgroup */ OO.ui.ToolGroup.prototype.getToolbar = function () { return this.toolbar; }; /** * Add and remove tools based on configuration. */ OO.ui.ToolGroup.prototype.populate = function () { var i, len, name, tool, toolFactory = this.toolbar.getToolFactory(), names = {}, add = [], remove = [], list = this.toolbar.getToolFactory().getTools( this.include, this.exclude, this.promote, this.demote ); // Build a list of needed tools for ( i = 0, len = list.length; i < len; i++ ) { name = list[ i ]; if ( // Tool exists toolFactory.lookup( name ) && // Tool is available or is already in this group ( this.toolbar.isToolAvailable( name ) || this.tools[ name ] ) ) { // Hack to prevent infinite recursion via ToolGroupTool. We need to reserve the tool // before creating it, but we can't call reserveTool() yet because we haven't created // the tool. this.toolbar.tools[ name ] = true; tool = this.tools[ name ]; if ( !tool ) { // Auto-initialize tools on first use this.tools[ name ] = tool = toolFactory.create( name, this ); tool.updateTitle(); } this.toolbar.reserveTool( tool ); add.push( tool ); names[ name ] = true; } } // Remove tools that are no longer needed for ( name in this.tools ) { if ( !names[ name ] ) { this.tools[ name ].destroy(); this.toolbar.releaseTool( this.tools[ name ] ); remove.push( this.tools[ name ] ); delete this.tools[ name ]; } } if ( remove.length ) { this.removeItems( remove ); } // Update emptiness state if ( add.length ) { this.$element.removeClass( 'oo-ui-toolGroup-empty' ); } else { this.$element.addClass( 'oo-ui-toolGroup-empty' ); } // Re-add tools (moving existing ones to new locations) this.addItems( add ); // Disabled state may depend on items this.updateDisabled(); }; /** * Destroy toolgroup. */ OO.ui.ToolGroup.prototype.destroy = function () { var name; this.clearItems(); this.toolbar.getToolFactory().disconnect( this ); for ( name in this.tools ) { this.toolbar.releaseTool( this.tools[ name ] ); this.tools[ name ].disconnect( this ).destroy(); delete this.tools[ name ]; } this.$element.remove(); }; /** * A ToolFactory creates tools on demand. All tools ({@link OO.ui.Tool Tools}, * {@link OO.ui.PopupTool PopupTools}, and {@link OO.ui.ToolGroupTool ToolGroupTools}) must be * registered with a tool factory. Tools are registered by their symbolic name. See * {@link OO.ui.Toolbar toolbars} for an example. * * For more information about toolbars in general, please see the * [OOUI documentation on MediaWiki][1]. * * [1]: https://www.mediawiki.org/wiki/OOUI/Toolbars * * @class * @extends OO.Factory * @constructor */ OO.ui.ToolFactory = function OoUiToolFactory() { // Parent constructor OO.ui.ToolFactory.super.call( this ); }; /* Setup */ OO.inheritClass( OO.ui.ToolFactory, OO.Factory ); /* Methods */ /** * Get tools from the factory. * * @param {Array|string} [include] Included tools, see #extract for format * @param {Array|string} [exclude] Excluded tools, see #extract for format * @param {Array|string} [promote] Promoted tools, see #extract for format * @param {Array|string} [demote] Demoted tools, see #extract for format * @return {string[]} List of tools */ OO.ui.ToolFactory.prototype.getTools = function ( include, exclude, promote, demote ) { var i, len, included, promoted, demoted, auto = [], used = {}; // Collect included and not excluded tools included = OO.simpleArrayDifference( this.extract( include ), this.extract( exclude ) ); // Promotion promoted = this.extract( promote, used ); demoted = this.extract( demote, used ); // Auto for ( i = 0, len = included.length; i < len; i++ ) { if ( !used[ included[ i ] ] ) { auto.push( included[ i ] ); } } return promoted.concat( auto ).concat( demoted ); }; /** * Get a flat list of names from a list of names or groups. * * Normally, `collection` is an array of tool specifications. Tools can be specified in the * following ways: * * - To include an individual tool, use the symbolic name: `{ name: 'tool-name' }` or `'tool-name'`. * - To include all tools in a group, use the group name: `{ group: 'group-name' }`. (To assign the * tool to a group, use OO.ui.Tool.static.group.) * * Alternatively, to include all tools that are not yet assigned to any other toolgroup, use the * catch-all selector `'*'`. * * If `used` is passed, tool names that appear as properties in this object will be considered * already assigned, and will not be returned even if specified otherwise. The tool names extracted * by this function call will be added as new properties in the object. * * @private * @param {Array|string} collection List of tools, see above * @param {Object} [used] Object containing information about used tools, see above * @return {string[]} List of extracted tool names */ OO.ui.ToolFactory.prototype.extract = function ( collection, used ) { var i, len, item, name, tool, names = []; collection = !Array.isArray( collection ) ? [ collection ] : collection; for ( i = 0, len = collection.length; i < len; i++ ) { item = collection[ i ]; if ( item === '*' ) { for ( name in this.registry ) { tool = this.registry[ name ]; if ( // Only add tools by group name when auto-add is enabled tool.static.autoAddToCatchall && // Exclude already used tools ( !used || !used[ name ] ) ) { names.push( name ); if ( used ) { used[ name ] = true; } } } } else { // Allow plain strings as shorthand for named tools if ( typeof item === 'string' ) { item = { name: item }; } if ( OO.isPlainObject( item ) ) { if ( item.group ) { for ( name in this.registry ) { tool = this.registry[ name ]; if ( // Include tools with matching group tool.static.group === item.group && // Only add tools by group name when auto-add is enabled tool.static.autoAddToGroup && // Exclude already used tools ( !used || !used[ name ] ) ) { names.push( name ); if ( used ) { used[ name ] = true; } } } // Include tools with matching name and exclude already used tools } else if ( item.name && ( !used || !used[ item.name ] ) ) { names.push( item.name ); if ( used ) { used[ item.name ] = true; } } } } } return names; }; /** * ToolGroupFactories create {@link OO.ui.ToolGroup toolgroups} on demand. The toolgroup classes * must specify a symbolic name and be registered with the factory. The following classes are * registered by default: * * - {@link OO.ui.BarToolGroup BarToolGroups} (‘bar’) * - {@link OO.ui.MenuToolGroup MenuToolGroups} (‘menu’) * - {@link OO.ui.ListToolGroup ListToolGroups} (‘list’) * * See {@link OO.ui.Toolbar toolbars} for an example. * * For more information about toolbars in general, please see the * [OOUI documentation on MediaWiki][1]. * * [1]: https://www.mediawiki.org/wiki/OOUI/Toolbars * * @class * @extends OO.Factory * @constructor */ OO.ui.ToolGroupFactory = function OoUiToolGroupFactory() { var i, l, defaultClasses; // Parent constructor OO.Factory.call( this ); defaultClasses = this.constructor.static.getDefaultClasses(); // Register default toolgroups for ( i = 0, l = defaultClasses.length; i < l; i++ ) { this.register( defaultClasses[ i ] ); } }; /* Setup */ OO.inheritClass( OO.ui.ToolGroupFactory, OO.Factory ); /* Static Methods */ /** * Get a default set of classes to be registered on construction. * * @return {Function[]} Default classes */ OO.ui.ToolGroupFactory.static.getDefaultClasses = function () { return [ OO.ui.BarToolGroup, OO.ui.ListToolGroup, OO.ui.MenuToolGroup ]; }; /** * Popup tools open a popup window when they are selected from the {@link OO.ui.Toolbar toolbar}. * Each popup tool is configured with a static name, title, and icon, as well with as any popup * configurations. Unlike other tools, popup tools do not require that developers specify an * #onSelect or #onUpdateState method, as these methods have been implemented already. * * // Example of a popup tool. When selected, a popup tool displays * // a popup window. * function HelpTool( toolGroup, config ) { * OO.ui.PopupTool.call( this, toolGroup, $.extend( { popup: { * padded: true, * label: 'Help', * head: true * } }, config ) ); * this.popup.$body.append( '<p>I am helpful!</p>' ); * }; * OO.inheritClass( HelpTool, OO.ui.PopupTool ); * HelpTool.static.name = 'help'; * HelpTool.static.icon = 'help'; * HelpTool.static.title = 'Help'; * toolFactory.register( HelpTool ); * * For an example of a toolbar that contains a popup tool, see {@link OO.ui.Toolbar toolbars}. * For more information about toolbars in general, please see the * [OOUI documentation on MediaWiki][1]. * * [1]: https://www.mediawiki.org/wiki/OOUI/Toolbars * * @abstract * @class * @extends OO.ui.Tool * @mixins OO.ui.mixin.PopupElement * * @constructor * @param {OO.ui.ToolGroup} toolGroup * @param {Object} [config] Configuration options */ OO.ui.PopupTool = function OoUiPopupTool( toolGroup, config ) { // Allow passing positional parameters inside the config object if ( OO.isPlainObject( toolGroup ) && config === undefined ) { config = toolGroup; toolGroup = config.toolGroup; } // Parent constructor OO.ui.PopupTool.super.call( this, toolGroup, config ); // Mixin constructors OO.ui.mixin.PopupElement.call( this, config ); // Events this.popup.connect( this, { toggle: 'onPopupToggle' } ); // Initialization this.popup.setAutoFlip( false ); this.popup.setPosition( toolGroup.getToolbar().position === 'bottom' ? 'above' : 'below' ); this.$element.addClass( 'oo-ui-popupTool' ); this.popup.$element.addClass( 'oo-ui-popupTool-popup' ); this.toolbar.$popups.append( this.popup.$element ); }; /* Setup */ OO.inheritClass( OO.ui.PopupTool, OO.ui.Tool ); OO.mixinClass( OO.ui.PopupTool, OO.ui.mixin.PopupElement ); /* Methods */ /** * Handle the tool being selected. * * @inheritdoc */ OO.ui.PopupTool.prototype.onSelect = function () { if ( !this.isDisabled() ) { this.popup.toggle(); } return false; }; /** * Handle the toolbar state being updated. * * @inheritdoc */ OO.ui.PopupTool.prototype.onUpdateState = function () { }; /** * Handle popup visibility being toggled. * * @param {boolean} isVisible */ OO.ui.PopupTool.prototype.onPopupToggle = function ( isVisible ) { this.setActive( isVisible ); this.toolGroup.emit( 'active', isVisible ); }; /** * A ToolGroupTool is a special sort of tool that can contain other {@link OO.ui.Tool tools} * and {@link OO.ui.ToolGroup toolgroups}. The ToolGroupTool was specifically designed to be used * inside a {@link OO.ui.BarToolGroup bar} toolgroup to provide access to additional tools from * the bar item. Included tools will be displayed in a dropdown {@link OO.ui.ListToolGroup list} * when the ToolGroupTool is selected. * * // Example: ToolGroupTool with two nested tools, 'setting1' and 'setting2', * // defined elsewhere. * * function SettingsTool() { * SettingsTool.super.apply( this, arguments ); * }; * OO.inheritClass( SettingsTool, OO.ui.ToolGroupTool ); * SettingsTool.static.name = 'settings'; * SettingsTool.static.title = 'Change settings'; * SettingsTool.static.groupConfig = { * icon: 'settings', * label: 'ToolGroupTool', * include: [ 'setting1', 'setting2' ] * }; * toolFactory.register( SettingsTool ); * * For more information, please see the [OOUI documentation on MediaWiki][1]. * * Please note that this implementation is subject to change per [T74159] [2]. * * [1]: https://www.mediawiki.org/wiki/OOUI/Toolbars#ToolGroupTool * [2]: https://phabricator.wikimedia.org/T74159 * * @abstract * @class * @extends OO.ui.Tool * * @constructor * @param {OO.ui.ToolGroup} toolGroup * @param {Object} [config] Configuration options */ OO.ui.ToolGroupTool = function OoUiToolGroupTool( toolGroup, config ) { // Allow passing positional parameters inside the config object if ( OO.isPlainObject( toolGroup ) && config === undefined ) { config = toolGroup; toolGroup = config.toolGroup; } // Parent constructor OO.ui.ToolGroupTool.super.call( this, toolGroup, config ); // Properties this.innerToolGroup = this.createGroup( this.constructor.static.groupConfig ); // Events this.innerToolGroup.connect( this, { disable: 'onToolGroupDisable', // Re-emit active events from the innerToolGroup on the parent toolGroup active: this.toolGroup.emit.bind( this.toolGroup, 'active' ) } ); // Initialization this.$link.remove(); this.$element .addClass( 'oo-ui-toolGroupTool' ) .append( this.innerToolGroup.$element ); }; /* Setup */ OO.inheritClass( OO.ui.ToolGroupTool, OO.ui.Tool ); /* Static Properties */ /** * Toolgroup configuration. * * The toolgroup configuration consists of the tools to include, as well as an icon and label * to use for the bar item. Tools can be included by symbolic name, group, or with the * wildcard selector. Please see {@link OO.ui.ToolGroup toolgroup} for more information. * * @property {Object.<string,Array>} */ OO.ui.ToolGroupTool.static.groupConfig = {}; /* Methods */ /** * Handle the tool being selected. * * @inheritdoc */ OO.ui.ToolGroupTool.prototype.onSelect = function () { this.innerToolGroup.setActive( !this.innerToolGroup.active ); return false; }; /** * Synchronize disabledness state of the tool with the inner toolgroup. * * @private * @param {boolean} disabled Element is disabled */ OO.ui.ToolGroupTool.prototype.onToolGroupDisable = function ( disabled ) { this.setDisabled( disabled ); }; /** * Handle the toolbar state being updated. * * @inheritdoc */ OO.ui.ToolGroupTool.prototype.onUpdateState = function () { this.setActive( false ); }; /** * Build a {@link OO.ui.ToolGroup toolgroup} from the specified configuration. * * @param {Object.<string,Array>} group Toolgroup configuration. Please see * {@link OO.ui.ToolGroup toolgroup} for more information. * @return {OO.ui.ListToolGroup} */ OO.ui.ToolGroupTool.prototype.createGroup = function ( group ) { if ( group.include === '*' ) { // Apply defaults to catch-all groups if ( group.label === undefined ) { group.label = OO.ui.msg( 'ooui-toolbar-more' ); } } return this.toolbar.getToolGroupFactory().create( 'list', this.toolbar, group ); }; /** * BarToolGroups are one of three types of {@link OO.ui.ToolGroup toolgroups} that are used to * create {@link OO.ui.Toolbar toolbars} (the other types of groups are * {@link OO.ui.MenuToolGroup MenuToolGroup} and {@link OO.ui.ListToolGroup ListToolGroup}). * The {@link OO.ui.Tool tools} in a BarToolGroup are displayed by icon in a single row. The * title of the tool is displayed when users move the mouse over the tool. * * BarToolGroups are created by a {@link OO.ui.ToolGroupFactory tool group factory} when the toolbar * is set up. * * @example * // Example of a BarToolGroup with two tools * var toolFactory = new OO.ui.ToolFactory(); * var toolGroupFactory = new OO.ui.ToolGroupFactory(); * var toolbar = new OO.ui.Toolbar( toolFactory, toolGroupFactory ); * * // We will be placing status text in this element when tools are used * var $area = $( '<p>' ).text( 'Example of a BarToolGroup with two tools.' ); * * // Define the tools that we're going to place in our toolbar * * // Create a class inheriting from OO.ui.Tool * function SearchTool() { * SearchTool.super.apply( this, arguments ); * } * OO.inheritClass( SearchTool, OO.ui.Tool ); * // Each tool must have a 'name' (used as an internal identifier, see later) and at least one * // of 'icon' and 'title' (displayed icon and text). * SearchTool.static.name = 'search'; * SearchTool.static.icon = 'search'; * SearchTool.static.title = 'Search...'; * // Defines the action that will happen when this tool is selected (clicked). * SearchTool.prototype.onSelect = function () { * $area.text( 'Search tool clicked!' ); * // Never display this tool as "active" (selected). * this.setActive( false ); * }; * SearchTool.prototype.onUpdateState = function () {}; * // Make this tool available in our toolFactory and thus our toolbar * toolFactory.register( SearchTool ); * * // This is a PopupTool. Rather than having a custom 'onSelect' action, it will display a * // little popup window (a PopupWidget). * function HelpTool( toolGroup, config ) { * OO.ui.PopupTool.call( this, toolGroup, $.extend( { popup: { * padded: true, * label: 'Help', * head: true * } }, config ) ); * this.popup.$body.append( '<p>I am helpful!</p>' ); * } * OO.inheritClass( HelpTool, OO.ui.PopupTool ); * HelpTool.static.name = 'help'; * HelpTool.static.icon = 'help'; * HelpTool.static.title = 'Help'; * toolFactory.register( HelpTool ); * * // Finally define which tools and in what order appear in the toolbar. Each tool may only be * // used once (but not all defined tools must be used). * toolbar.setup( [ * { * // 'bar' tool groups display tools by icon only * type: 'bar', * include: [ 'search', 'help' ] * } * ] ); * * // Create some UI around the toolbar and place it in the document * var frame = new OO.ui.PanelLayout( { * expanded: false, * framed: true * } ); * var contentFrame = new OO.ui.PanelLayout( { * expanded: false, * padded: true * } ); * frame.$element.append( * toolbar.$element, * contentFrame.$element.append( $area ) * ); * $( document.body ).append( frame.$element ); * * // Here is where the toolbar is actually built. This must be done after inserting it into the * // document. * toolbar.initialize(); * * For more information about how to add tools to a bar tool group, please see * {@link OO.ui.ToolGroup toolgroup}. * For more information about toolbars in general, please see the * [OOUI documentation on MediaWiki][1]. * * [1]: https://www.mediawiki.org/wiki/OOUI/Toolbars * * @class * @extends OO.ui.ToolGroup * * @constructor * @param {OO.ui.Toolbar} toolbar * @param {Object} [config] Configuration options */ OO.ui.BarToolGroup = function OoUiBarToolGroup( toolbar, config ) { // Allow passing positional parameters inside the config object if ( OO.isPlainObject( toolbar ) && config === undefined ) { config = toolbar; toolbar = config.toolbar; } // Parent constructor OO.ui.BarToolGroup.super.call( this, toolbar, config ); // Initialization this.$element.addClass( 'oo-ui-barToolGroup' ); this.$group.addClass( 'oo-ui-barToolGroup-tools' ); }; /* Setup */ OO.inheritClass( OO.ui.BarToolGroup, OO.ui.ToolGroup ); /* Static Properties */ /** * @static * @inheritdoc */ OO.ui.BarToolGroup.static.titleTooltips = true; /** * @static * @inheritdoc */ OO.ui.BarToolGroup.static.accelTooltips = true; /** * @static * @inheritdoc */ OO.ui.BarToolGroup.static.name = 'bar'; /** * PopupToolGroup is an abstract base class used by both {@link OO.ui.MenuToolGroup MenuToolGroup} * and {@link OO.ui.ListToolGroup ListToolGroup} to provide a popup (an overlaid menu or list of * tools with an optional icon and label). This class can be used for other base classes that * also use this functionality. * * @abstract * @class * @extends OO.ui.ToolGroup * @mixins OO.ui.mixin.IconElement * @mixins OO.ui.mixin.IndicatorElement * @mixins OO.ui.mixin.LabelElement * @mixins OO.ui.mixin.TitledElement * @mixins OO.ui.mixin.FlaggedElement * @mixins OO.ui.mixin.ClippableElement * @mixins OO.ui.mixin.FloatableElement * @mixins OO.ui.mixin.TabIndexedElement * * @constructor * @param {OO.ui.Toolbar} toolbar * @param {Object} [config] Configuration options * @cfg {string} [header] Text to display at the top of the popup */ OO.ui.PopupToolGroup = function OoUiPopupToolGroup( toolbar, config ) { // Allow passing positional parameters inside the config object if ( OO.isPlainObject( toolbar ) && config === undefined ) { config = toolbar; toolbar = config.toolbar; } // Configuration initialization config = $.extend( { indicator: config.indicator === undefined ? ( toolbar.position === 'bottom' ? 'up' : 'down' ) : config.indicator }, config ); // Parent constructor OO.ui.PopupToolGroup.super.call( this, toolbar, config ); // Properties this.active = false; this.dragging = false; // Don't conflict with parent method of the same name this.onPopupDocumentMouseKeyUpHandler = this.onPopupDocumentMouseKeyUp.bind( this ); this.$handle = $( '<span>' ); // Mixin constructors OO.ui.mixin.IconElement.call( this, config ); OO.ui.mixin.IndicatorElement.call( this, config ); OO.ui.mixin.LabelElement.call( this, config ); OO.ui.mixin.TitledElement.call( this, config ); OO.ui.mixin.FlaggedElement.call( this, config ); OO.ui.mixin.ClippableElement.call( this, $.extend( { $clippable: this.$group }, config ) ); OO.ui.mixin.FloatableElement.call( this, $.extend( { $floatable: this.$group, $floatableContainer: this.$handle, hideWhenOutOfView: false, verticalPosition: this.toolbar.position === 'bottom' ? 'above' : 'below' }, config ) ); OO.ui.mixin.TabIndexedElement.call( this, $.extend( { $tabIndexed: this.$handle }, config ) ); // Events this.$handle.on( { keydown: this.onHandleMouseKeyDown.bind( this ), keyup: this.onHandleMouseKeyUp.bind( this ), mousedown: this.onHandleMouseKeyDown.bind( this ), mouseup: this.onHandleMouseKeyUp.bind( this ) } ); // Initialization this.$handle .addClass( 'oo-ui-popupToolGroup-handle' ) .attr( 'role', 'button' ) .attr( 'aria-expanded', 'false' ) .append( this.$icon, this.$label, this.$indicator ); // If the pop-up should have a header, add it to the top of the toolGroup. // Note: If this feature is useful for other widgets, we could abstract it into an // OO.ui.HeaderedElement mixin constructor. if ( config.header !== undefined ) { this.$group .prepend( $( '<span>' ) .addClass( 'oo-ui-popupToolGroup-header' ) .text( config.header ) ); } this.$element .addClass( 'oo-ui-popupToolGroup' ) .prepend( this.$handle ); this.$group.addClass( 'oo-ui-popupToolGroup-tools' ); this.toolbar.$popups.append( this.$group ); }; /* Setup */ OO.inheritClass( OO.ui.PopupToolGroup, OO.ui.ToolGroup ); OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.mixin.IconElement ); OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.mixin.IndicatorElement ); OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.mixin.LabelElement ); OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.mixin.TitledElement ); OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.mixin.FlaggedElement ); OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.mixin.ClippableElement ); OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.mixin.FloatableElement ); OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.mixin.TabIndexedElement ); /* Methods */ /** * @inheritdoc */ OO.ui.PopupToolGroup.prototype.setDisabled = function () { // Parent method OO.ui.PopupToolGroup.super.prototype.setDisabled.apply( this, arguments ); if ( this.isDisabled() && this.isElementAttached() ) { this.setActive( false ); } }; /** * Handle document mouse up and key up events. * * @protected * @param {MouseEvent|KeyboardEvent} e Mouse up or key up event */ OO.ui.PopupToolGroup.prototype.onPopupDocumentMouseKeyUp = function ( e ) { var $target = $( e.target ); // Only deactivate when clicking outside the dropdown element if ( $target.closest( '.oo-ui-popupToolGroup' )[ 0 ] === this.$element[ 0 ] ) { return; } if ( $target.closest( '.oo-ui-popupToolGroup-tools' )[ 0 ] === this.$group[ 0 ] ) { return; } this.setActive( false ); }; /** * @inheritdoc */ OO.ui.PopupToolGroup.prototype.onMouseKeyUp = function ( e ) { // Only close toolgroup when a tool was actually selected if ( !this.isDisabled() && this.pressed && this.pressed === this.findTargetTool( e ) && ( e.which === OO.ui.MouseButtons.LEFT || e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER ) ) { this.setActive( false ); } return OO.ui.PopupToolGroup.super.prototype.onMouseKeyUp.call( this, e ); }; /** * @inheritdoc */ OO.ui.PopupToolGroup.prototype.onMouseKeyDown = function ( e ) { var $focused, $firstFocusable, $lastFocusable; // Shift-Tab on the first tool in the group jumps to the handle. // Tab on the last tool in the group jumps to the next group. if ( !this.isDisabled() && e.which === OO.ui.Keys.TAB ) { // We can't use this.items because ListToolGroup inserts the extra fake // expand/collapse tool. $focused = $( document.activeElement ); $firstFocusable = OO.ui.findFocusable( this.$group ); if ( $focused[ 0 ] === $firstFocusable[ 0 ] && e.shiftKey ) { this.$handle.trigger( 'focus' ); return false; } $lastFocusable = OO.ui.findFocusable( this.$group, true ); if ( $focused[ 0 ] === $lastFocusable[ 0 ] && !e.shiftKey ) { // Focus this group's handle and let the browser's tab handling happen // (no 'return false'). // This way we don't have to fiddle with other ToolGroups' business, or worry what to do // if the next group is not a PopupToolGroup or doesn't exist at all. this.$handle.trigger( 'focus' ); // Close the popup so that we don't move back inside it (if this is the last group). this.setActive( false ); } } return OO.ui.PopupToolGroup.super.prototype.onMouseKeyDown.call( this, e ); }; /** * Handle mouse up and key up events. * * @protected * @param {jQuery.Event} e Mouse up or key up event * @return {undefined|boolean} False to prevent default if event is handled */ OO.ui.PopupToolGroup.prototype.onHandleMouseKeyUp = function ( e ) { if ( !this.isDisabled() && ( e.which === OO.ui.MouseButtons.LEFT || e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER ) ) { return false; } }; /** * Handle mouse down and key down events. * * @protected * @param {jQuery.Event} e Mouse down or key down event * @return {undefined|boolean} False to prevent default if event is handled */ OO.ui.PopupToolGroup.prototype.onHandleMouseKeyDown = function ( e ) { var $focusable; if ( !this.isDisabled() ) { // Tab on the handle jumps to the first tool in the group (if the popup is open). if ( e.which === OO.ui.Keys.TAB && !e.shiftKey ) { $focusable = OO.ui.findFocusable( this.$group ); if ( $focusable.length ) { $focusable.trigger( 'focus' ); return false; } } if ( e.which === OO.ui.MouseButtons.LEFT || e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER ) { this.setActive( !this.active ); return false; } } }; /** * Check if the tool group is active. * * @return {boolean} Tool group is active */ OO.ui.PopupToolGroup.prototype.isActive = function () { return this.active; }; /** * Switch into 'active' mode. * * When active, the popup is visible. A mouseup event anywhere in the document will trigger * deactivation. * * @param {boolean} value The active state to set * @fires active */ OO.ui.PopupToolGroup.prototype.setActive = function ( value ) { var containerWidth, containerLeft; value = !!value; if ( this.active !== value ) { this.active = value; if ( value ) { this.getElementDocument().addEventListener( 'mouseup', this.onPopupDocumentMouseKeyUpHandler, true ); this.getElementDocument().addEventListener( 'keyup', this.onPopupDocumentMouseKeyUpHandler, true ); this.$clippable.css( 'left', '' ); this.$element.addClass( 'oo-ui-popupToolGroup-active' ); this.$group.addClass( 'oo-ui-popupToolGroup-active-tools' ); this.$handle.attr( 'aria-expanded', true ); this.togglePositioning( true ); this.toggleClipping( true ); // Try anchoring the popup to the left first this.setHorizontalPosition( 'start' ); if ( this.isClippedHorizontally() || this.isFloatableOutOfView() ) { // Anchoring to the left caused the popup to clip, so anchor it to the // right instead. this.setHorizontalPosition( 'end' ); } if ( this.isClippedHorizontally() || this.isFloatableOutOfView() ) { // Anchoring to the right also caused the popup to clip, so just make it fill the // container. containerWidth = this.$clippableScrollableContainer.width(); containerLeft = this.$clippableScrollableContainer[ 0 ] === document.documentElement ? 0 : this.$clippableScrollableContainer.offset().left; this.toggleClipping( false ); this.setHorizontalPosition( 'start' ); this.$clippable.css( { 'margin-left': -( this.$element.offset().left - containerLeft ), width: containerWidth } ); } } else { this.getElementDocument().removeEventListener( 'mouseup', this.onPopupDocumentMouseKeyUpHandler, true ); this.getElementDocument().removeEventListener( 'keyup', this.onPopupDocumentMouseKeyUpHandler, true ); this.$element.removeClass( 'oo-ui-popupToolGroup-active' ); this.$group.removeClass( 'oo-ui-popupToolGroup-active-tools' ); this.$handle.attr( 'aria-expanded', false ); this.togglePositioning( false ); this.toggleClipping( false ); } this.emit( 'active', this.active ); this.updateThemeClasses(); } }; /** * ListToolGroups are one of three types of {@link OO.ui.ToolGroup toolgroups} that are used to * create {@link OO.ui.Toolbar toolbars} (the other types of groups are * {@link OO.ui.MenuToolGroup MenuToolGroup} and {@link OO.ui.BarToolGroup BarToolGroup}). * The {@link OO.ui.Tool tools} in a ListToolGroup are displayed by label in a dropdown menu. * The title of the tool is used as the label text. The menu itself can be configured with a label, * icon, indicator, header, and title. * * ListToolGroups can be configured to be expanded and collapsed. Collapsed lists will have a * ‘More’ option that users can select to see the full list of tools. If a collapsed toolgroup is * expanded, a ‘Fewer’ option permits users to collapse the list again. * * ListToolGroups are created by a {@link OO.ui.ToolGroupFactory toolgroup factory} when the * toolbar is set up. The factory requires the ListToolGroup's symbolic name, 'list', which is * specified along with the other configurations. For more information about how to add tools to a * ListToolGroup, please see {@link OO.ui.ToolGroup toolgroup}. * * @example * // Example of a ListToolGroup * var toolFactory = new OO.ui.ToolFactory(); * var toolGroupFactory = new OO.ui.ToolGroupFactory(); * var toolbar = new OO.ui.Toolbar( toolFactory, toolGroupFactory ); * * // Configure and register two tools * function SettingsTool() { * SettingsTool.super.apply( this, arguments ); * } * OO.inheritClass( SettingsTool, OO.ui.Tool ); * SettingsTool.static.name = 'settings'; * SettingsTool.static.icon = 'settings'; * SettingsTool.static.title = 'Change settings'; * SettingsTool.prototype.onSelect = function () { * this.setActive( false ); * }; * SettingsTool.prototype.onUpdateState = function () {}; * toolFactory.register( SettingsTool ); * // Register two more tools, nothing interesting here * function StuffTool() { * StuffTool.super.apply( this, arguments ); * } * OO.inheritClass( StuffTool, OO.ui.Tool ); * StuffTool.static.name = 'stuff'; * StuffTool.static.icon = 'search'; * StuffTool.static.title = 'Change the world'; * StuffTool.prototype.onSelect = function () { * this.setActive( false ); * }; * StuffTool.prototype.onUpdateState = function () {}; * toolFactory.register( StuffTool ); * toolbar.setup( [ * { * // Configurations for list toolgroup. * type: 'list', * label: 'ListToolGroup', * icon: 'ellipsis', * title: 'This is the title, displayed when user moves the mouse over the list ' + * 'toolgroup', * header: 'This is the header', * include: [ 'settings', 'stuff' ], * allowCollapse: ['stuff'] * } * ] ); * * // Create some UI around the toolbar and place it in the document * var frame = new OO.ui.PanelLayout( { * expanded: false, * framed: true * } ); * frame.$element.append( * toolbar.$element * ); * $( document.body ).append( frame.$element ); * // Build the toolbar. This must be done after the toolbar has been appended to the document. * toolbar.initialize(); * * For more information about toolbars in general, please see the * [OOUI documentation on MediaWiki][1]. * * [1]: https://www.mediawiki.org/wiki/OOUI/Toolbars * * @class * @extends OO.ui.PopupToolGroup * * @constructor * @param {OO.ui.Toolbar} toolbar * @param {Object} [config] Configuration options * @cfg {Array} [allowCollapse] Allow the specified tools to be collapsed. By default, collapsible * tools will only be displayed if users click the ‘More’ option displayed at the bottom of the * list. If the list is expanded, a ‘Fewer’ option permits users to collapse the list again. * Any tools that are included in the toolgroup, but are not designated as collapsible, will always * be displayed. * To open a collapsible list in its expanded state, set #expanded to 'true'. * @cfg {Array} [forceExpand] Expand the specified tools. All other tools will be designated as * collapsible. Unless #expanded is set to true, the collapsible tools will be collapsed when the * list is first opened. * @cfg {boolean} [expanded=false] Expand collapsible tools. This config is only relevant if tools * have been designated as collapsible. When expanded is set to true, all tools in the group will * be displayed when the list is first opened. Users can collapse the list with a ‘Fewer’ option at * the bottom. */ OO.ui.ListToolGroup = function OoUiListToolGroup( toolbar, config ) { // Allow passing positional parameters inside the config object if ( OO.isPlainObject( toolbar ) && config === undefined ) { config = toolbar; toolbar = config.toolbar; } // Configuration initialization config = config || {}; // Properties (must be set before parent constructor, which calls #populate) this.allowCollapse = config.allowCollapse; this.forceExpand = config.forceExpand; this.expanded = config.expanded !== undefined ? config.expanded : false; this.collapsibleTools = []; // Parent constructor OO.ui.ListToolGroup.super.call( this, toolbar, config ); // Initialization this.$element.addClass( 'oo-ui-listToolGroup' ); this.$group.addClass( 'oo-ui-listToolGroup-tools' ); }; /* Setup */ OO.inheritClass( OO.ui.ListToolGroup, OO.ui.PopupToolGroup ); /* Static Properties */ /** * @static * @inheritdoc */ OO.ui.ListToolGroup.static.name = 'list'; /* Methods */ /** * @inheritdoc */ OO.ui.ListToolGroup.prototype.populate = function () { var i, len, allowCollapse = []; OO.ui.ListToolGroup.super.prototype.populate.call( this ); // Update the list of collapsible tools if ( this.allowCollapse !== undefined ) { allowCollapse = this.allowCollapse; } else if ( this.forceExpand !== undefined ) { allowCollapse = OO.simpleArrayDifference( Object.keys( this.tools ), this.forceExpand ); } this.collapsibleTools = []; for ( i = 0, len = allowCollapse.length; i < len; i++ ) { if ( this.tools[ allowCollapse[ i ] ] !== undefined ) { this.collapsibleTools.push( this.tools[ allowCollapse[ i ] ] ); } } // Keep at the end, even when tools are added this.$group.append( this.getExpandCollapseTool().$element ); this.getExpandCollapseTool().toggle( this.collapsibleTools.length !== 0 ); this.updateCollapsibleState(); }; /** * Get the expand/collapse tool for this group * * @return {OO.ui.Tool} Expand collapse tool */ OO.ui.ListToolGroup.prototype.getExpandCollapseTool = function () { var ExpandCollapseTool; if ( this.expandCollapseTool === undefined ) { ExpandCollapseTool = function () { ExpandCollapseTool.super.apply( this, arguments ); }; OO.inheritClass( ExpandCollapseTool, OO.ui.Tool ); ExpandCollapseTool.prototype.onSelect = function () { this.toolGroup.expanded = !this.toolGroup.expanded; this.toolGroup.updateCollapsibleState(); this.setActive( false ); }; ExpandCollapseTool.prototype.onUpdateState = function () { // Do nothing. Tool interface requires an implementation of this function. }; ExpandCollapseTool.static.name = 'more-fewer'; this.expandCollapseTool = new ExpandCollapseTool( this ); } return this.expandCollapseTool; }; /** * @inheritdoc */ OO.ui.ListToolGroup.prototype.onMouseKeyUp = function ( e ) { // Do not close the popup when the user wants to show more/fewer tools if ( $( e.target ).closest( '.oo-ui-tool-name-more-fewer' ).length && ( e.which === OO.ui.MouseButtons.LEFT || e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER ) ) { // HACK: Prevent the popup list from being hidden. Skip the PopupToolGroup implementation // (which hides the popup list when a tool is selected) and call ToolGroup's implementation // directly. return OO.ui.ListToolGroup.super.super.prototype.onMouseKeyUp.call( this, e ); } else { return OO.ui.ListToolGroup.super.prototype.onMouseKeyUp.call( this, e ); } }; OO.ui.ListToolGroup.prototype.updateCollapsibleState = function () { var i, icon, len; if ( this.toolbar.position !== 'bottom' ) { icon = this.expanded ? 'collapse' : 'expand'; } else { icon = this.expanded ? 'expand' : 'collapse'; } this.getExpandCollapseTool() .setIcon( icon ) .setTitle( OO.ui.msg( this.expanded ? 'ooui-toolgroup-collapse' : 'ooui-toolgroup-expand' ) ); for ( i = 0, len = this.collapsibleTools.length; i < len; i++ ) { this.collapsibleTools[ i ].toggle( this.expanded ); } // Re-evaluate clipping, because our height has changed this.clip(); }; /** * MenuToolGroups are one of three types of {@link OO.ui.ToolGroup toolgroups} that are used to * create {@link OO.ui.Toolbar toolbars} (the other types of groups are * {@link OO.ui.BarToolGroup BarToolGroup} and {@link OO.ui.ListToolGroup ListToolGroup}). * MenuToolGroups contain selectable {@link OO.ui.Tool tools}, which are displayed by label in a * dropdown menu. The tool's title is used as the label text, and the menu label is updated to * reflect which tool or tools are currently selected. If no tools are selected, the menu label * is empty. The menu can be configured with an indicator, icon, title, and/or header. * * MenuToolGroups are created by a {@link OO.ui.ToolGroupFactory tool group factory} when the * toolbar is set up. * * @example * // Example of a MenuToolGroup * var toolFactory = new OO.ui.ToolFactory(); * var toolGroupFactory = new OO.ui.ToolGroupFactory(); * var toolbar = new OO.ui.Toolbar( toolFactory, toolGroupFactory ); * * // We will be placing status text in this element when tools are used * var $area = $( '<p>' ).text( 'An example of a MenuToolGroup. Select a tool from the ' * + 'dropdown menu.' ); * * // Define the tools that we're going to place in our toolbar * * function SettingsTool() { * SettingsTool.super.apply( this, arguments ); * this.reallyActive = false; * } * OO.inheritClass( SettingsTool, OO.ui.Tool ); * SettingsTool.static.name = 'settings'; * SettingsTool.static.icon = 'settings'; * SettingsTool.static.title = 'Change settings'; * SettingsTool.prototype.onSelect = function () { * $area.text( 'Settings tool clicked!' ); * // Toggle the active state on each click * this.reallyActive = !this.reallyActive; * this.setActive( this.reallyActive ); * // To update the menu label * this.toolbar.emit( 'updateState' ); * }; * SettingsTool.prototype.onUpdateState = function () {}; * toolFactory.register( SettingsTool ); * * function StuffTool() { * StuffTool.super.apply( this, arguments ); * this.reallyActive = false; * } * OO.inheritClass( StuffTool, OO.ui.Tool ); * StuffTool.static.name = 'stuff'; * StuffTool.static.icon = 'ellipsis'; * StuffTool.static.title = 'More stuff'; * StuffTool.prototype.onSelect = function () { * $area.text( 'More stuff tool clicked!' ); * // Toggle the active state on each click * this.reallyActive = !this.reallyActive; * this.setActive( this.reallyActive ); * // To update the menu label * this.toolbar.emit( 'updateState' ); * }; * StuffTool.prototype.onUpdateState = function () {}; * toolFactory.register( StuffTool ); * * // Finally define which tools and in what order appear in the toolbar. Each tool may only be * // used once (but not all defined tools must be used). * toolbar.setup( [ * { * type: 'menu', * header: 'This is the (optional) header', * title: 'This is the (optional) title', * include: [ 'settings', 'stuff' ] * } * ] ); * * // Create some UI around the toolbar and place it in the document * var frame = new OO.ui.PanelLayout( { * expanded: false, * framed: true * } ); * var contentFrame = new OO.ui.PanelLayout( { * expanded: false, * padded: true * } ); * frame.$element.append( * toolbar.$element, * contentFrame.$element.append( $area ) * ); * $( document.body ).append( frame.$element ); * * // Here is where the toolbar is actually built. This must be done after inserting it into the * // document. * toolbar.initialize(); * toolbar.emit( 'updateState' ); * * For more information about how to add tools to a MenuToolGroup, please see * {@link OO.ui.ToolGroup toolgroup}. * For more information about toolbars in general, please see the * [OOUI documentation on MediaWiki] [1]. * * [1]: https://www.mediawiki.org/wiki/OOUI/Toolbars * * @class * @extends OO.ui.PopupToolGroup * * @constructor * @param {OO.ui.Toolbar} toolbar * @param {Object} [config] Configuration options */ OO.ui.MenuToolGroup = function OoUiMenuToolGroup( toolbar, config ) { // Allow passing positional parameters inside the config object if ( OO.isPlainObject( toolbar ) && config === undefined ) { config = toolbar; toolbar = config.toolbar; } // Configuration initialization config = config || {}; // Parent constructor OO.ui.MenuToolGroup.super.call( this, toolbar, config ); // Events this.toolbar.connect( this, { updateState: 'onUpdateState' } ); // Initialization this.$element.addClass( 'oo-ui-menuToolGroup' ); this.$group.addClass( 'oo-ui-menuToolGroup-tools' ); }; /* Setup */ OO.inheritClass( OO.ui.MenuToolGroup, OO.ui.PopupToolGroup ); /* Static Properties */ /** * @static * @inheritdoc */ OO.ui.MenuToolGroup.static.name = 'menu'; /* Methods */ /** * Handle the toolbar state being updated. * * When the state changes, the title of each active item in the menu will be joined together and * used as a label for the group. The label will be empty if none of the items are active. * * @private */ OO.ui.MenuToolGroup.prototype.onUpdateState = function () { var name, labelTexts = []; for ( name in this.tools ) { if ( this.tools[ name ].isActive() ) { labelTexts.push( this.tools[ name ].getTitle() ); } } this.setLabel( labelTexts.join( ', ' ) || ' ' ); }; }( OO ) ); //# sourceMappingURL=oojs-ui-toolbars.js.map.json
'use strict'; describe('VBoxLayout', ()=>{ it('should construct a BoxLayout with VERTICAL orientation', ()=>{ let w1 = new ST.Widgets.Panel(); w1.layout = new ST.Layouts.VBoxLayout(w1); expect(w1.layout.orientation).to.equal(ST.VERTICAL); }); });
import { select as d3_select } from 'd3-selection'; import { svgIcon, svgTagClasses } from '../svg'; import { utilFunctor } from '../util'; export function uiPresetIcon(context) { var preset, geometry, sizeClass = 'medium'; function isSmall() { return sizeClass === 'small'; } function presetIcon(selection) { selection.each(render); } function getIcon(p, geom) { if (isSmall() && p.isFallback && p.isFallback()) return 'iD-icon-' + p.id; else if (p.icon) return p.icon; else if (geom === 'line') return 'iD-other-line'; else if (geom === 'vertex') return p.isFallback() ? '' : 'temaki-vertex'; else if (isSmall() && geom === 'point') return ''; else return 'maki-marker-stroked'; } function renderPointBorder(enter) { var w = 40, h = 40; enter = enter .append('svg') .attr('class', 'preset-icon-fill preset-icon-point-border') .attr('width', w) .attr('height', h) .attr('viewBox', '0 0 ' + w + ' ' + h); enter.append('path') .attr('transform', 'translate(11.5, 8)') .attr('d', 'M 17,8 C 17,13 11,21 8.5,23.5 C 6,21 0,13 0,8 C 0,4 4,-0.5 8.5,-0.5 C 13,-0.5 17,4 17,8 z'); } function renderCircleFill(fillEnter) { var w = 60, h = 60, d = 40; fillEnter = fillEnter .append('svg') .attr('class', 'preset-icon-fill preset-icon-fill-vertex') .attr('width', w) .attr('height', h) .attr('viewBox', '0 0 ' + w + ' ' + h); fillEnter.append('circle') .attr('cx', w/2) .attr('cy', h/2) .attr('r', d/2); } function renderSquareFill(fillEnter) { var d = isSmall() ? 40 : 60; var w = d, h = d, l = d*2/3, c1 = (w-l)/2, c2 = c1 + l; fillEnter = fillEnter .append('svg') .attr('class', 'preset-icon-fill preset-icon-fill-area') .attr('width', w) .attr('height', h) .attr('viewBox', '0 0 ' + w + ' ' + h); var data = 'M' + c1 + ' ' + c1 + ' L' + c1 + ' ' + c2 + ' L' + c2 + ' ' + c2 + ' L' + c2 + ' ' + c1 + ' Z'; fillEnter.append('path') .attr('d', data) .attr('class', 'line area fill'); fillEnter.append('path') .attr('d', data) .attr('class', 'line area stroke'); var r = 2.5; var coordinates = [c1, c2]; for (var xIndex in coordinates) { for (var yIndex in coordinates) { fillEnter.append('circle') .attr('class', 'vertex') .attr('cx', coordinates[xIndex]) .attr('cy', coordinates[yIndex]) .attr('r', r); } } if (!isSmall()) { var midCoordinates = [[c1, w/2], [c2, w/2], [h/2, c1], [h/2, c2]]; for (var index in midCoordinates) { var loc = midCoordinates[index]; fillEnter.append('circle') .attr('class', 'midpoint') .attr('cx', loc[0]) .attr('cy', loc[1]) .attr('r', 1.25); } } } function renderLine(lineEnter) { var d = isSmall() ? 40 : 60; // draw the line parametrically var w = d, h = d, y = Math.round(d*0.72), l = Math.round(d*0.6), r = 2.5; var x1 = (w - l)/2, x2 = x1 + l; lineEnter = lineEnter .append('svg') .attr('class', 'preset-icon-line') .attr('width', w) .attr('height', h) .attr('viewBox', '0 0 ' + w + ' ' + h); ['casing', 'stroke'].forEach(function(klass) { lineEnter.append('path') .attr('d', 'M' + x1 + ' ' + y + ' L' + x2 + ' ' + y) .attr('class', 'line ' + klass); }); [[x1 - 1, y], [x2 + 1, y]].forEach(function(loc) { lineEnter.append('circle') .attr('class', 'vertex') .attr('cx', loc[0]) .attr('cy', loc[1]) .attr('r', r); }); } function renderRoute(routeEnter) { var d = isSmall() ? 40 : 60; // draw the route parametrically var w = d, h = d, y1 = Math.round(d*0.80), y2 = Math.round(d*0.68), l = Math.round(d*0.6), r = 2; var x1 = (w - l)/2, x2 = x1 + l/3, x3 = x2 + l/3, x4 = x3 + l/3; routeEnter = routeEnter .append('svg') .attr('class', 'preset-icon-route') .attr('width', w) .attr('height', h) .attr('viewBox', '0 0 ' + w + ' ' + h); ['casing', 'stroke'].forEach(function(klass) { routeEnter.append('path') .attr('d', 'M' + x1 + ' ' + y1 + ' L' + x2 + ' ' + y2) .attr('class', 'segment0 line ' + klass); routeEnter.append('path') .attr('d', 'M' + x2 + ' ' + y2 + ' L' + x3 + ' ' + y1) .attr('class', 'segment1 line ' + klass); routeEnter.append('path') .attr('d', 'M' + x3 + ' ' + y1 + ' L' + x4 + ' ' + y2) .attr('class', 'segment2 line ' + klass); }); [[x1, y1], [x2, y2], [x3, y1], [x4, y2]].forEach(function(loc) { routeEnter.append('circle') .attr('class', 'vertex') .attr('cx', loc[0]) .attr('cy', loc[1]) .attr('r', r); }); } var routeSegements = { bicycle: ['highway/cycleway', 'highway/cycleway', 'highway/cycleway'], bus: ['highway/unclassified', 'highway/secondary', 'highway/primary'], detour: ['highway/tertiary', 'highway/residential', 'highway/unclassified'], ferry: ['route/ferry', 'route/ferry', 'route/ferry'], foot: ['highway/footway', 'highway/footway', 'highway/footway'], hiking: ['highway/path', 'highway/path', 'highway/path'], horse: ['highway/bridleway', 'highway/bridleway', 'highway/bridleway'], light_rail: ['railway/light_rail', 'railway/light_rail', 'railway/light_rail'], monorail: ['railway/monorail', 'railway/monorail', 'railway/monorail'], pipeline: ['man_made/pipeline', 'man_made/pipeline', 'man_made/pipeline'], piste: ['piste/downhill', 'piste/hike', 'piste/nordic'], power: ['power/line', 'power/line', 'power/line'], road: ['highway/secondary', 'highway/primary', 'highway/trunk'], subway: ['railway/subway', 'railway/subway', 'railway/subway'], train: ['railway/rail', 'railway/rail', 'railway/rail'], tram: ['railway/tram', 'railway/tram', 'railway/tram'], waterway: ['waterway/stream', 'waterway/stream', 'waterway/stream'] }; function render() { var p = preset.apply(this, arguments); var isFallback = isSmall() && p.isFallback && p.isFallback(); var geom = geometry ? geometry.apply(this, arguments) : null; if (geom === 'relation' && p.tags && ((p.tags.type === 'route' && p.tags.route && routeSegements[p.tags.route]) || p.tags.type === 'waterway')) { geom = 'route'; } var imageURL = p.imageURL; var picon = imageURL ? null : getIcon(p, geom); var isMaki = picon && /^maki-/.test(picon); var isTemaki = picon && /^temaki-/.test(picon); var isFa = picon && /^fa[srb]-/.test(picon); var isTnp = picon && /^tnp-/.test(picon); var isiDIcon = picon && !(isMaki || isTemaki || isFa || isTnp); var isCategory = !p.setTags; var drawPoint = picon && geom === 'point' && isSmall() && !isFallback; var drawVertex = picon !== null && geom === 'vertex' && (!isSmall() || !isFallback); var drawLine = picon && geom === 'line' && !isFallback && !isCategory; var drawArea = picon && geom === 'area' && !isFallback; var drawRoute = picon && geom === 'route'; var isFramed = (drawVertex || drawArea || drawLine || drawRoute); var tags = !isCategory ? p.setTags({}, geom) : {}; for (var k in tags) { if (tags[k] === '*') { tags[k] = 'yes'; } } var tagClasses = svgTagClasses().getClassesString(tags, ''); var selection = d3_select(this); var container = selection.selectAll('.preset-icon-container') .data([0]); container = container.enter() .append('div') .attr('class', 'preset-icon-container ' + sizeClass) .merge(container); container.classed('fallback', isFallback); var imageIcon = container.selectAll('img.image-icon') .data(imageURL ? [0] : []); imageIcon.exit() .remove(); imageIcon = imageIcon.enter() .append('img') .attr('class', 'image-icon') .merge(imageIcon); imageIcon .attr('src', imageURL); var pointBorder = container.selectAll('.preset-icon-point-border') .data(drawPoint ? [0] : []); pointBorder.exit() .remove(); var pointBorderEnter = pointBorder.enter(); renderPointBorder(pointBorderEnter); pointBorder = pointBorderEnter.merge(pointBorder); var vertexFill = container.selectAll('.preset-icon-fill-vertex') .data(drawVertex ? [0] : []); vertexFill.exit() .remove(); var vertexFillEnter = vertexFill.enter(); renderCircleFill(vertexFillEnter); vertexFill = vertexFillEnter.merge(vertexFill); var fill = container.selectAll('.preset-icon-fill-area') .data(drawArea ? [0] : []); fill.exit() .remove(); var fillEnter = fill.enter(); renderSquareFill(fillEnter); fill = fillEnter.merge(fill); fill.selectAll('path.stroke') .attr('class', 'area stroke ' + tagClasses); fill.selectAll('path.fill') .attr('class', 'area fill ' + tagClasses); var line = container.selectAll('.preset-icon-line') .data(drawLine ? [0] : []); line.exit() .remove(); var lineEnter = line.enter(); renderLine(lineEnter); line = lineEnter.merge(line); line.selectAll('path.stroke') .attr('class', 'line stroke ' + tagClasses); line.selectAll('path.casing') .attr('class', 'line casing ' + tagClasses); var route = container.selectAll('.preset-icon-route') .data(drawRoute ? [0] : []); route.exit() .remove(); var routeEnter = route.enter(); renderRoute(routeEnter); route = routeEnter.merge(route); if (drawRoute) { var routeType = p.tags.type === 'waterway' ? 'waterway' : p.tags.route; var segmentPresetIDs = routeSegements[routeType]; for (var segmentIndex in segmentPresetIDs) { var segmentPreset = context.presets().item(segmentPresetIDs[segmentIndex]); var segmentTagClasses = svgTagClasses().getClassesString(segmentPreset.tags, ''); route.selectAll('path.stroke.segment' + segmentIndex) .attr('class', 'segment' + segmentIndex + ' line stroke ' + segmentTagClasses); route.selectAll('path.casing.segment' + segmentIndex) .attr('class', 'segment' + segmentIndex + ' line casing ' + segmentTagClasses); } } var icon = container.selectAll('.preset-icon') .data(picon ? [0] : []); icon.exit() .remove(); icon = icon.enter() .append('div') .attr('class', 'preset-icon') .call(svgIcon('')) .merge(icon); icon .attr('class', 'preset-icon ' + (geom ? geom + '-geom' : '')) .classed('framed', isFramed) .classed('preset-icon-iD', isiDIcon); icon.selectAll('svg') .attr('class', function() { return 'icon ' + picon + ' ' + (!isiDIcon && geom !== 'line' ? '' : tagClasses); }); icon.selectAll('use') .attr('href', '#' + picon + (isMaki ? (isSmall() && geom === 'point' ? '-11' : '-15') : '')); } presetIcon.preset = function(val) { if (!arguments.length) return preset; preset = utilFunctor(val); return presetIcon; }; presetIcon.geometry = function(val) { if (!arguments.length) return geometry; geometry = utilFunctor(val); return presetIcon; }; presetIcon.sizeClass = function(val) { if (!arguments.length) return sizeClass; sizeClass = val; return presetIcon; }; return presetIcon; }
function loadAndBind(name, file) { module.exports[name] = require(__dirname+'/'+file); }; loadAndBind('registerUser', 'register_user.js'); loadAndBind('listUsers', 'list_users.js'); loadAndBind('listUserExternalAccounts', 'list_user_external_accounts.js'); loadAndBind('addExternalAccount', 'add_external_account.js'); loadAndBind('fundHotWallet', 'fund_hot_wallet.js'); loadAndBind('setHotWallet', 'set_hot_wallet.js'); loadAndBind('listWithdrawals', 'list_withdrawals.js'); loadAndBind('listIncomingPayments', 'list_incoming_payments.js'); loadAndBind('clearWithdrawal', 'clear_withdrawal.js'); loadAndBind('recordDeposit', 'record_deposit.js'); loadAndBind('listDeposits', 'list_deposits.js'); loadAndBind('listOutgoingPayments', 'list_outgoing_payments.js'); loadAndBind('startGateway', 'start_gateway.js'); loadAndBind('stopGateway', 'stop_gateway.js'); loadAndBind('restartGateway', 'restart_gateway.js'); loadAndBind('setColdWallet', 'set_cold_wallet.js'); loadAndBind('addCurrency', 'add_currency.js'); loadAndBind('setLastPaymentHash', 'set_last_payment_hash.js'); loadAndBind('setKey', 'set_key.js'); loadAndBind('getKey', 'get_key.js'); loadAndBind('getTrustLines', 'get_trust_lines.js'); loadAndBind('setTrustLine', 'set_trust.js'); loadAndBind('refundColdWallet', 'refund_cold_wallet.js'); loadAndBind('listCurrencies', 'list_currencies.js'); loadAndBind('listProcesses', 'list_processes.js'); loadAndBind('activateUser', 'activate_user.js'); loadAndBind('deactivateUser', 'deactivate_user.js'); loadAndBind('listFailedPayments', 'list_failed_payments.js'); loadAndBind('retryFailedPayment', 'retry_failed_payment.js'); loadAndBind('listCleared', 'list_cleared.js');
function AudioLine(manager){ this._init(manager); } AudioLine.prototype.constructor = AudioLine; AudioLine.prototype._init = function(manager){ this.manager = manager; this.available = true; this.audio = null; this.htmlAudio = null; this.webAudio = null; this.loop = false; this.paused = false; this.callback = null; this.muted = false; this.startTime = 0; this.lastPauseTime = 0; this.offsetTime = 0; if(!this.manager.context){ this.htmlAudio = new Audio(); this.htmlAudio.addEventListener('ended', this._onEnd.bind(this)); } }; AudioLine.prototype.reset = function(){ this.available = true; this.audio = null; this.loop = false; this.callback = null; this.paused = false; this.muted = false; this.webAudio = null; this.startTime = 0; this.lastPauseTime = 0; this.offsetTime = 0; return this; }; AudioLine.prototype.setAudio = function(audio, loop, callback){ if(typeof loop === "function"){ callback = loop; loop = false; } this.audio = audio; this.available = false; this.loop = loop; this.callback = callback; return this; }; AudioLine.prototype.play = function(pause){ if(!pause && this.isPaused)return this; if(this.manager.context){ this.webAudio = this.manager.context.createBufferSource(); this.webAudio.start = this.webAudio.start || this.webAudio.noteOn; this.webAudio.stop = this.webAudio.stop || this.webAudio.noteOff; this.webAudio.buffer = this.audio.source; this.webAudio.loop = this.loop || this.audio.loop; this.startTime = this.manager.context.currentTime; this.webAudio.onended = this._onEnd.bind(this); this.webAudio.gainNode = this.manager.createGainNode(); this.webAudio.gainNode.value = (this.audio.muted || this.muted) ? 0 : this.audio.volume; this.webAudio.gainNode.connect(this.manager.gainNode); this.webAudio.connect(this.webAudio.gainNode); this.webAudio.start(0, (pause) ? this.lastPauseTime : null); }else{ var audio = this.htmlAudio; audio.src = (this.audio.source.src !== "") ? this.audio.source.src : this.audio.source.children[0].src; audio.preload = "auto"; audio.volume = (this.audio.muted || this.muted) ? 0 : this.audio.volume; audio.load(); audio.play(); } return this; }; AudioLine.prototype.mute = function(){ this.muted = true; if(this.manager.context){ this.webAudio.gainNode.gain.value = 0; }else{ if(this.htmlAudio){ this.htmlAudio.volume = 0; } } return this; }; AudioLine.prototype.unmute = function(){ this.muted = false; if(this.manager.context){ this.webAudio.gainNode.gain.value = this.audio.volume; }else{ if(this.htmlAudio){ this.htmlAudio.volume = this.audio.volume; } } return this; }; AudioLine.prototype.stop = function(){ if(this.manager.context){ this.webAudio.stop(0); }else{ this.htmlAudio.pause(); this.htmlAudio.currentTime = 0; } this.reset(); return this; }; AudioLine.prototype.pause = function(){ if(this.manager.context){ this.offsetTime += this.manager.context.currentTime - this.startTime; this.lastPauseTime = this.offsetTime%this.webAudio.buffer.duration; this.webAudio.stop(0); }else{ this.htmlAudio.pause(); } this.paused = true; return this; }; AudioLine.prototype.resume = function(){ if(this.paused){ if(this.manager.context){ this.play(true); }else{ this.htmlAudio.play(); } this.paused = false; } return this; }; AudioLine.prototype._onEnd = function(){ if(this.callback){ this.callback(this.manager, this.audio); } if(!this.manager.context){ if(this.loop || this.audio.loop){ this.htmlAudio.currentTime = 0; this.htmlAudio.play(); }else{ this.reset(); } }else if(this.manager.context && !this.paused){ this.reset(); } }; module.exports = AudioLine;
import React from "react"; let Method = ({ response }) => ( <div>Please do not contact us by {response.params.method}</div> ); export default Method;
/* global module:false */ module.exports = function (grunt) { // Project configuration. grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), watch: { options: { livereload: true, }, html: { files: ['*.html', 'step*/*.html'], tasks: [] } }, connect: { server: { options: { open: true, port: 9001, base: '.', livereload: true, } } } }); // Load grunt watch grunt.loadNpmTasks('grunt-contrib-watch'); // Load grunt connect grunt.loadNpmTasks('grunt-contrib-connect'); grunt.registerTask('serve', ['connect', 'watch']) };
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <React.Fragment><path fill="none" d="M0 0h24v24H0V0z" /><path d="M9.12 14.47V9.53H8.09v2.88L6.03 9.53H5v4.94h1.03v-2.88l2.1 2.88zM13.24 10.57V9.53h-3.3v4.94h3.3v-1.03h-2.06v-.91h2.06v-1.04h-2.06v-.92zM14.06 9.53v4.12c0 .45.37.82.82.82h3.29c.45 0 .82-.37.82-.82V9.53h-1.03v3.71h-.92v-2.89h-1.03v2.9h-.93V9.53h-1.02z" /><g><path d="M4 6h16v12H4z" opacity=".3" /><path d="M20 4H4c-1.11 0-1.99.89-1.99 2L2 18c0 1.11.89 2 2 2h16c1.11 0 2-.89 2-2V6c0-1.11-.89-2-2-2zm0 14H4V6h16v12z" /></g></React.Fragment> , 'FiberNewTwoTone');
alert("hello :-)");
_papersheet= $(".papersheet"); _trigger= $(".papersheet__trigger"); _trigger.click(anchorsOnOff); function anchorsOnOff() { if (_papersheet.hasClass("opened")) { $(this).parent(".papersheet").stop().removeClass("opened"); $(this).children("i").stop().removeClass("lf-close").toggleClass( "lf-tip" ); } else { $(this).parent(".papersheet").stop().addClass("opened"); $(this).children("i").stop().removeClass("lf-tip").addClass( "lf-close" ); } } var annotationsCont = $(".annotationsCont"); var papersheet = $(".papersheet"); var annotationsAnim = $(".annotationsAnim"); var annotationsOn = $(".annotationsOn"); var annotationsOff = $(".annotationsOff"); function eachRandom() { papersheet.each(function( index ) { var randomAnim = Math.max( 1.0, Math.random(index) * 2 ) ; $( this ).css("-webkit-animation-duration", randomAnim +"s"); }) } $(document).ready(function() { var annotationstop = 100; var annotationsOP = 1; var annotationsAnimShow; annotationsOn.click(function () { TweenMax.to(annotationsAnim,1,{opacity:1} ); annotationsAnimShow = TweenMax.from(annotationsAnim,2,{top:-annotationstop,opacity:1,ease:Power2.easeInOut}); }) annotationsOff.click(function () { TweenMax.to(annotationsAnim,2,{top:-annotationstop,opacity:1,ease:Power2.easeInOut} ); TweenMax.to(annotationsAnim,1,{opacity:0,delay:1} ); /*annotationsAnimShow.reverse();*/ }) });
"use strict"; var core_1 = require('@angular/core'); exports.FirebaseUrl = new core_1.OpaqueToken('FirebaseUrl'); exports.FirebaseRef = new core_1.OpaqueToken('FirebaseRef'); exports.FirebaseAuthConfig = new core_1.OpaqueToken('FirebaseAuthConfig'); //# sourceMappingURL=tokens.js.map
import { createStructuredSelector } from 'reselect'; const currencySelector = state => state.account.get('currency'); const balanceSelector = state => +state.account.get('balance'); export default createStructuredSelector({ currency: currencySelector, balance: balanceSelector, });
file:/home/charlike/dev/glob-fs/fixtures/a/u9.js
import { helper as FromNowHelper } from "./-from-now"; import Moment from "moment"; export const helper = FromNowHelper.extend({ _compute( params, hash ) { return new Moment( params[0] ).fromNow( hash.suffix || params[1] ); } });
import { DDPRateLimiter } from 'meteor/ddp-rate-limiter'; // 依名稱對個別 method 做額外限制 export function limitMethod(name, number = 20, interval = 60000) { const type = 'method'; DDPRateLimiter.addRule( { type, name, clientAddress }, number, interval ); } // 依名稱對個別 subscription 做額外限制 export function limitSubscription(name, number = 20, interval = 60000) { const type = 'subscription'; DDPRateLimiter.addRule( { type, name, clientAddress }, number, interval ); } function clientAddress() { return true; } export function limitGlobalMethod(name, number = 1, interval = 60000) { const type = 'method'; DDPRateLimiter.addRule( { type, name }, number, interval ); }
var Stream = require('stream') var splicer = require('labeled-stream-splicer') var parse = require('./parse') var split = require('split2') var JSONStream = require('JSONStream') module.exports = log function log() { var stream = splicer.obj([ 'split', [split()], 'parse', [parse()], 'format', [JSONStream.stringify()], ]) stream.plugin = function (fn) { fn(this) return this } return stream } if (require.main === module) { var spawn = require('child_process').spawn spawn('git', ['log']).stdout .pipe( log() .plugin(author) .plugin(date) .plugin(formatter) ) .pipe(process.stdout) } function formatter(pipeline) { pipeline.get('format').splice(0, 1, Stream.Transform({ objectMode: true, transform: function (row, enc, next) { this.push([ row.author.name, 'has commit', row.commit.slice(0, 7), 'at', row.date.toISOString().slice(0, 10) ].join(' ')) this.push('\n') next() }, })) } function author(pipeline) { pipeline.get('parse').push(Stream.Transform({ objectMode: true, transform: function (row, enc, next) { var author = row.author row.author = {} var matched = author.match(/<(.*)>/) if (matched) { row.author.email = matched[1] row.author.name = author.slice(0, author.indexOf('<')).trim() } else { row.author.name = author } next(null, row) }, })) } function date(pipeline) { pipeline.get('parse').push(Stream.Transform({ objectMode: true, transform: function (row, enc, next) { row.date = new Date(row.date) next(null, row) }, })) }
/*Game.addToManifest({ end_prototype: "sprites/quote/end_prototype.png", gunshot: "sounds/gunshot.mp3" }); function Scene_EndPrototype(){ var self = this; Scene.call(self); // Layers, yo. var q1 = MakeSprite("blackout"); var q2 = MakeSprite("end_prototype"); // BANG Game.sounds.gunshot.play(); // Add 'em in. q2.alpha = 0; Game.stage.addChild(q1); Game.stage.addChild(q2); // TWEEN ANIM Tween_get(q2) .wait(_s(BEAT*3.5)) .to({alpha:1}, _s(BEAT), Ease.quadInOut); }*/
var data = [{img:"http://s.amazeui.org/media/i/demos/bing-1.jpg",desc:'<div class="am-slider-content"><h2 class="am-slider-title">远方 有一个地方 那里种有我们的梦想</h2><p>内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内</p></div><a class="am-slider-more">了解更多</a>'},{img:"http://s.amazeui.org/media/i/demos/bing-2.jpg",desc:'<div class="am-slider-content"><h2 class="am-slider-title">某天 也许会相遇 相遇在这个好地方</h2><p>内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内</p></div><a class="am-slider-more">了解更多</a>'},{img:"http://s.amazeui.org/media/i/demos/bing-3.jpg",desc:'<div class="am-slider-content"><h2 class="am-slider-title">不要太担心 只因为我相信 终会走过这条遥远的道路</h2><p>内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内</p></div><a class="am-slider-more">了解更多</a>'},{img:"http://s.amazeui.org/media/i/demos/bing-4.jpg",desc:'<div class="am-slider-content"><h2 class="am-slider-title">OH PARA PARADISE 是否那么重要 你是否那么地遥远</h2><p>内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内</p></div><a class="am-slider-more">了解更多</a>'}]; var sliderIntance = ( <Slider theme="d2"> {data.map(function(item, k) { return ( <Slider.Item key={k}> <img src={item.img} /> <div className="am-slider-desc" dangerouslySetInnerHTML={{__html: item.desc}} /> </Slider.Item> ); })} </Slider>); ReactDOM.render(sliderIntance, mountNode);
'use strict'; import $ from 'jquery'; import { onLoad } from './foundation.core.utils'; import { Keyboard } from './foundation.util.keyboard'; import { onImagesLoaded } from './foundation.util.imageLoader'; import { Plugin } from './foundation.core.plugin'; /** * Tabs module. * @module foundation.tabs * @requires foundation.util.keyboard * @requires foundation.util.imageLoader if tabs contain images */ class Tabs extends Plugin { /** * Creates a new instance of tabs. * @class * @name Tabs * @fires Tabs#init * @param {jQuery} element - jQuery object to make into tabs. * @param {Object} options - Overrides to the default plugin settings. */ _setup(element, options) { this.$element = element; this.options = $.extend({}, Tabs.defaults, this.$element.data(), options); this.className = 'Tabs'; // ie9 back compat this._init(); Keyboard.register('Tabs', { 'ENTER': 'open', 'SPACE': 'open', 'ARROW_RIGHT': 'next', 'ARROW_UP': 'previous', 'ARROW_DOWN': 'next', 'ARROW_LEFT': 'previous' // 'TAB': 'next', // 'SHIFT_TAB': 'previous' }); } /** * Initializes the tabs by showing and focusing (if autoFocus=true) the preset active tab. * @private */ _init() { var _this = this; this._isInitializing = true; this.$element.attr({'role': 'tablist'}); this.$tabTitles = this.$element.find(`.${this.options.linkClass}`); this.$tabContent = $(`[data-tabs-content="${this.$element[0].id}"]`); this.$tabTitles.each(function(){ var $elem = $(this), $link = $elem.find('a'), isActive = $elem.hasClass(`${_this.options.linkActiveClass}`), hash = $link.attr('data-tabs-target') || $link[0].hash.slice(1), linkId = $link[0].id ? $link[0].id : `${hash}-label`, $tabContent = $(`#${hash}`); $elem.attr({'role': 'presentation'}); $link.attr({ 'role': 'tab', 'aria-controls': hash, 'aria-selected': isActive, 'id': linkId, 'tabindex': isActive ? '0' : '-1' }); $tabContent.attr({ 'role': 'tabpanel', 'aria-labelledby': linkId }); // Save up the initial hash to return to it later when going back in history if (isActive) { _this._initialAnchor = `#${hash}`; } if(!isActive) { $tabContent.attr('aria-hidden', 'true'); } if(isActive && _this.options.autoFocus){ _this.onLoadListener = onLoad($(window), function() { $('html, body').animate({ scrollTop: $elem.offset().top }, _this.options.deepLinkSmudgeDelay, () => { $link.focus(); }); }); } }); if(this.options.matchHeight) { var $images = this.$tabContent.find('img'); if ($images.length) { onImagesLoaded($images, this._setHeight.bind(this)); } else { this._setHeight(); } } // Current context-bound function to open tabs on page load or history hashchange this._checkDeepLink = () => { var anchor = window.location.hash; if (!anchor.length) { // If we are still initializing and there is no anchor, then there is nothing to do if (this._isInitializing) return; // Otherwise, move to the initial anchor if (this._initialAnchor) anchor = this._initialAnchor; } var $anchor = anchor && $(anchor); var $link = anchor && this.$element.find('[href$="'+anchor+'"]'); // Whether the anchor element that has been found is part of this element var isOwnAnchor = !!($anchor.length && $link.length); // If there is an anchor for the hash, select it if ($anchor && $anchor.length && $link && $link.length) { this.selectTab($anchor, true); } // Otherwise, collapse everything else { this._collapse(); } if (isOwnAnchor) { // Roll up a little to show the titles if (this.options.deepLinkSmudge) { var offset = this.$element.offset(); $('html, body').animate({ scrollTop: offset.top }, this.options.deepLinkSmudgeDelay); } /** * Fires when the plugin has deeplinked at pageload * @event Tabs#deeplink */ this.$element.trigger('deeplink.zf.tabs', [$link, $anchor]); } } //use browser to open a tab, if it exists in this tabset if (this.options.deepLink) { this._checkDeepLink(); } this._events(); this._isInitializing = false; } /** * Adds event handlers for items within the tabs. * @private */ _events() { this._addKeyHandler(); this._addClickHandler(); this._setHeightMqHandler = null; if (this.options.matchHeight) { this._setHeightMqHandler = this._setHeight.bind(this); $(window).on('changed.zf.mediaquery', this._setHeightMqHandler); } if(this.options.deepLink) { $(window).on('hashchange', this._checkDeepLink); } } /** * Adds click handlers for items within the tabs. * @private */ _addClickHandler() { var _this = this; this.$element .off('click.zf.tabs') .on('click.zf.tabs', `.${this.options.linkClass}`, function(e){ e.preventDefault(); e.stopPropagation(); _this._handleTabChange($(this)); }); } /** * Adds keyboard event handlers for items within the tabs. * @private */ _addKeyHandler() { var _this = this; this.$tabTitles.off('keydown.zf.tabs').on('keydown.zf.tabs', function(e){ if (e.which === 9) return; var $element = $(this), $elements = $element.parent('ul').children('li'), $prevElement, $nextElement; $elements.each(function(i) { if ($(this).is($element)) { if (_this.options.wrapOnKeys) { $prevElement = i === 0 ? $elements.last() : $elements.eq(i-1); $nextElement = i === $elements.length -1 ? $elements.first() : $elements.eq(i+1); } else { $prevElement = $elements.eq(Math.max(0, i-1)); $nextElement = $elements.eq(Math.min(i+1, $elements.length-1)); } return; } }); // handle keyboard event with keyboard util Keyboard.handleKey(e, 'Tabs', { open: function() { $element.find('[role="tab"]').focus(); _this._handleTabChange($element); }, previous: function() { $prevElement.find('[role="tab"]').focus(); _this._handleTabChange($prevElement); }, next: function() { $nextElement.find('[role="tab"]').focus(); _this._handleTabChange($nextElement); }, handled: function() { e.stopPropagation(); e.preventDefault(); } }); }); } /** * Opens the tab `$targetContent` defined by `$target`. Collapses active tab. * @param {jQuery} $target - Tab to open. * @param {boolean} historyHandled - browser has already handled a history update * @fires Tabs#change * @function */ _handleTabChange($target, historyHandled) { // With `activeCollapse`, if the target is the active Tab, collapse it. if ($target.hasClass(`${this.options.linkActiveClass}`)) { if(this.options.activeCollapse) { this._collapse(); } return; } var $oldTab = this.$element. find(`.${this.options.linkClass}.${this.options.linkActiveClass}`), $tabLink = $target.find('[role="tab"]'), target = $tabLink.attr('data-tabs-target'), anchor = target && target.length ? `#${target}` : $tabLink[0].hash, $targetContent = this.$tabContent.find(anchor); //close old tab this._collapseTab($oldTab); //open new tab this._openTab($target); //either replace or update browser history if (this.options.deepLink && !historyHandled) { if (this.options.updateHistory) { history.pushState({}, '', anchor); } else { history.replaceState({}, '', anchor); } } /** * Fires when the plugin has successfully changed tabs. * @event Tabs#change */ this.$element.trigger('change.zf.tabs', [$target, $targetContent]); //fire to children a mutation event $targetContent.find("[data-mutate]").trigger("mutateme.zf.trigger"); } /** * Opens the tab `$targetContent` defined by `$target`. * @param {jQuery} $target - Tab to open. * @function */ _openTab($target) { var $tabLink = $target.find('[role="tab"]'), hash = $tabLink.attr('data-tabs-target') || $tabLink[0].hash.slice(1), $targetContent = this.$tabContent.find(`#${hash}`); $target.addClass(`${this.options.linkActiveClass}`); $tabLink.attr({ 'aria-selected': 'true', 'tabindex': '0' }); $targetContent .addClass(`${this.options.panelActiveClass}`).removeAttr('aria-hidden'); } /** * Collapses `$targetContent` defined by `$target`. * @param {jQuery} $target - Tab to collapse. * @function */ _collapseTab($target) { var $target_anchor = $target .removeClass(`${this.options.linkActiveClass}`) .find('[role="tab"]') .attr({ 'aria-selected': 'false', 'tabindex': -1 }); $(`#${$target_anchor.attr('aria-controls')}`) .removeClass(`${this.options.panelActiveClass}`) .attr({ 'aria-hidden': 'true' }) } /** * Collapses the active Tab. * @fires Tabs#collapse * @function */ _collapse() { var $activeTab = this.$element.find(`.${this.options.linkClass}.${this.options.linkActiveClass}`); if ($activeTab.length) { this._collapseTab($activeTab); /** * Fires when the plugin has successfully collapsed tabs. * @event Tabs#collapse */ this.$element.trigger('collapse.zf.tabs', [$activeTab]); } } /** * Public method for selecting a content pane to display. * @param {jQuery | String} elem - jQuery object or string of the id of the pane to display. * @param {boolean} historyHandled - browser has already handled a history update * @function */ selectTab(elem, historyHandled) { var idStr; if (typeof elem === 'object') { idStr = elem[0].id; } else { idStr = elem; } if (idStr.indexOf('#') < 0) { idStr = `#${idStr}`; } var $target = this.$tabTitles.has(`[href$="${idStr}"]`); this._handleTabChange($target, historyHandled); }; /** * Sets the height of each panel to the height of the tallest panel. * If enabled in options, gets called on media query change. * If loading content via external source, can be called directly or with _reflow. * If enabled with `data-match-height="true"`, tabs sets to equal height * @function * @private */ _setHeight() { var max = 0, _this = this; // Lock down the `this` value for the root tabs object this.$tabContent .find(`.${this.options.panelClass}`) .css('height', '') .each(function() { var panel = $(this), isActive = panel.hasClass(`${_this.options.panelActiveClass}`); // get the options from the parent instead of trying to get them from the child if (!isActive) { panel.css({'visibility': 'hidden', 'display': 'block'}); } var temp = this.getBoundingClientRect().height; if (!isActive) { panel.css({ 'visibility': '', 'display': '' }); } max = temp > max ? temp : max; }) .css('height', `${max}px`); } /** * Destroys an instance of tabs. * @fires Tabs#destroyed */ _destroy() { this.$element .find(`.${this.options.linkClass}`) .off('.zf.tabs').hide().end() .find(`.${this.options.panelClass}`) .hide(); if (this.options.matchHeight) { if (this._setHeightMqHandler != null) { $(window).off('changed.zf.mediaquery', this._setHeightMqHandler); } } if (this.options.deepLink) { $(window).off('hashchange', this._checkDeepLink); } if (this.onLoadListener) { $(window).off(this.onLoadListener); } } } Tabs.defaults = { /** * Link the location hash to the active pane. * Set the location hash when the active pane changes, and open the corresponding pane when the location changes. * @option * @type {boolean} * @default false */ deepLink: false, /** * If `deepLink` is enabled, adjust the deep link scroll to make sure the top of the tab panel is visible * @option * @type {boolean} * @default false */ deepLinkSmudge: false, /** * If `deepLinkSmudge` is enabled, animation time (ms) for the deep link adjustment * @option * @type {number} * @default 300 */ deepLinkSmudgeDelay: 300, /** * If `deepLink` is enabled, update the browser history with the open tab * @option * @type {boolean} * @default false */ updateHistory: false, /** * Allows the window to scroll to content of active pane on load. * Not recommended if more than one tab panel per page. * @option * @type {boolean} * @default false */ autoFocus: false, /** * Allows keyboard input to 'wrap' around the tab links. * @option * @type {boolean} * @default true */ wrapOnKeys: true, /** * Allows the tab content panes to match heights if set to true. * @option * @type {boolean} * @default false */ matchHeight: false, /** * Allows active tabs to collapse when clicked. * @option * @type {boolean} * @default false */ activeCollapse: false, /** * Class applied to `li`'s in tab link list. * @option * @type {string} * @default 'tabs-title' */ linkClass: 'tabs-title', /** * Class applied to the active `li` in tab link list. * @option * @type {string} * @default 'is-active' */ linkActiveClass: 'is-active', /** * Class applied to the content containers. * @option * @type {string} * @default 'tabs-panel' */ panelClass: 'tabs-panel', /** * Class applied to the active content container. * @option * @type {string} * @default 'is-active' */ panelActiveClass: 'is-active' }; export {Tabs};
(function (angular, location) { "use strict"; //created socialPluginWidget module angular .module('socialPluginFilters', []) .filter('convertTimeFormat', [function () { return function (time) { var formattedTime = time; if (time && time.indexOf('a few seconds ago') != -1) { formattedTime = formattedTime.replace('a few seconds ago', 'just now'); } else if(time && time.indexOf('in a few seconds') != -1) { formattedTime = formattedTime.replace('in a few seconds', 'just now'); } else if(time && time.indexOf('a second ago') != -1) { formattedTime = formattedTime.replace('a second ago', '1s'); } else if(time && time.indexOf(' seconds ago') != -1) { formattedTime = formattedTime.replace('seconds ago', 's'); } else if(time && time.indexOf('a minute ago') != -1) { formattedTime = formattedTime.replace('a minute ago', '1m'); } else if(time && time.indexOf(' minutes ago') != -1) { formattedTime = formattedTime.replace('minutes ago', 'm'); } else if(time && time.indexOf('an hour ago') != -1) { formattedTime = formattedTime.replace('an hour ago', '1h'); } else if(time && time.indexOf(' hours ago') != -1) { formattedTime = formattedTime.replace('hours ago', 'h'); } else if(time && time.indexOf('a day ago') != -1) { formattedTime = formattedTime.replace('a day ago', '1d'); } else if(time && time.indexOf(' days ago') != -1) { formattedTime = formattedTime.replace('days ago', 'd'); } else if(time && time.indexOf('a month ago') != -1) { formattedTime = formattedTime.replace('a month ago', '1m'); } else if(time && time.indexOf(' months ago') != -1) { formattedTime = formattedTime.replace('months ago', 'm'); } else if(time && time.indexOf('a year ago') != -1) { formattedTime = formattedTime.replace('a year ago', '1y'); } else if(time && time.indexOf(' years ago') != -1) { formattedTime = formattedTime.replace('years ago', 'y'); } return formattedTime; }; }]) .filter('resizeImage', [function () { filter.$stateful = true; function filter(url, width, height) { var _imgUrl; if (!_imgUrl) { buildfire.imageLib.local.resizeImage(url, { width: width, height: height }, function (err, imgUrl) { _imgUrl = imgUrl; }); } return _imgUrl; } return filter; }]) .filter('cropImage', [function () { filter.$stateful = true; function filter(url, width, height) { var _imgUrl; if (!_imgUrl) { buildfire.imageLib.local.cropImage(url, { width: width, height: height }, function (err, imgUrl) { _imgUrl = imgUrl; }); } return _imgUrl; } return filter; }]) .filter('newLine', ['$sce', function ($sce) { return function (html) { if (html) { html = html.replace(/\n/g, '<br />'); return $sce.trustAsHtml(html); } else { return ""; } }; }]) })(window.angular, window.location);
var collection_1 = require('angular2/src/facade/collection'); var DomViewContainer = (function () { function DomViewContainer() { // The order in this list matches the DOM order. this.views = []; } DomViewContainer.prototype.contentTagContainers = function () { return this.views; }; DomViewContainer.prototype.nodes = function () { var r = []; for (var i = 0; i < this.views.length; ++i) { r = collection_1.ListWrapper.concat(r, this.views[i].rootNodes); } return r; }; return DomViewContainer; })(); exports.DomViewContainer = DomViewContainer; exports.__esModule = true; //# sourceMappingURL=view_container.js.map
(function(UI){ "use strict"; var toggles = []; UI.component('toggle', { defaults: { target : false, cls : 'uk-hidden', animation : false, duration : 200 }, boot: function(){ // init code UI.ready(function(context) { UI.$("[data-uk-toggle]", context).each(function() { var ele = UI.$(this); if (!ele.data("toggle")) { var obj = UI.toggle(ele, UI.Utils.options(ele.attr("data-uk-toggle"))); } }); setTimeout(function(){ toggles.forEach(function(toggle){ toggle.getToggles(); }); }, 0); }); }, init: function() { var $this = this; this.aria = (this.options.cls.indexOf('uk-hidden') !== -1); this.on("click", function(e) { if ($this.element.is('a[href="#"]')) { e.preventDefault(); } $this.toggle(); }); toggles.push(this); }, toggle: function() { this.getToggles(); if(!this.totoggle.length) return; if (this.options.animation && UI.support.animation) { var $this = this, animations = this.options.animation.split(','); if (animations.length == 1) { animations[1] = animations[0]; } animations[0] = animations[0].trim(); animations[1] = animations[1].trim(); this.totoggle.css('animation-duration', this.options.duration+'ms'); this.totoggle.each(function(){ var ele = UI.$(this); if (ele.hasClass($this.options.cls)) { ele.toggleClass($this.options.cls); UI.Utils.animate(ele, animations[0]).then(function(){ ele.css('animation-duration', ''); UI.Utils.checkDisplay(ele); }); } else { UI.Utils.animate(this, animations[1]+' uk-animation-reverse').then(function(){ ele.toggleClass($this.options.cls).css('animation-duration', ''); UI.Utils.checkDisplay(ele); }); } }); } else { this.totoggle.toggleClass(this.options.cls); UI.Utils.checkDisplay(this.totoggle); } this.updateAria(); }, getToggles: function() { this.totoggle = this.options.target ? UI.$(this.options.target):[]; this.updateAria(); }, updateAria: function() { if (this.aria && this.totoggle.length) { this.totoggle.not('[aria-hidden]').each(function(){ UI.$(this).attr('aria-hidden', UI.$(this).hasClass('uk-hidden')); }); } } }); })(UIkit);
/*! * UI development toolkit for HTML5 (OpenUI5) * (c) Copyright 2009-2017 SAP SE or an SAP affiliate company. * Licensed under the Apache License, Version 2.0 - see LICENSE.txt. */ sap.ui.define(['./Date','sap/ui/core/format/DateFormat'],function(D,a){"use strict";var b=D.extend("sap.ui.model.type.DateTime",{constructor:function(){D.apply(this,arguments);this.sName="DateTime";}});b.prototype._createFormats=function(){this.oOutputFormat=a.getDateTimeInstance(this.oFormatOptions);if(this.oFormatOptions.source){this.oInputFormat=a.getDateTimeInstance(this.oFormatOptions.source);}};return b;});
$(function($) { $.ventoonirico = {}; $.ventoonirico.user = null; $.ventoonirico.urlPrefix = window.location.pathname.substring(1); $.ventoonirico.Game = Backbone.RelationalModel.extend({ urlRoot: $.ventoonirico.urlPrefix + '/api/games', relations: [ { type: Backbone.HasOne, key: 'desire', relatedModel: '$.ventoonirico.Desire', includeInJSON: 'id' } ], createDesire: function(user) { var desire = new $.ventoonirico.Desire({owner: user, game: this}); desire.save(); this.set('desire', desire); }, removeDesire: function() { var desire = this.get('desire'); this.set('desire', false); desire.destroy(); }, }); $.ventoonirico.GameCollection = Backbone.Collection.extend({ url: $.ventoonirico.urlPrefix + '/api/games', model: $.ventoonirico.Game }); $.ventoonirico.Desire = Backbone.RelationalModel.extend({ urlRoot: $.ventoonirico.urlPrefix + '/api/desires', relations: [ { type: Backbone.HasOne, key: 'game', relatedModel: '$.ventoonirico.Game', includeInJSON: 'id' }, { type: Backbone.HasOne, key: 'owner', relatedModel: '$.ventoonirico.User', includeInJSON: 'id' }, { type: Backbone.HasMany, key: 'joins', relatedModel: '$.ventoonirico.Join', collectionType: '$.ventoonirico.JoinCollection' } ], addJoin: function(user) { var join = new $.ventoonirico.Join({user: user, desire: this}); join.save(); this.get('joins').add(join); }, removeJoin: function(user) { var joins = this.get('joins'); var i=0; while (i<joins.length) { var join = joins.at(i); if (join.get('user').id == user.id) { join.destroy(); joins.remove(join); this.set('joins',joins); break; } i++; } } }); $.ventoonirico.DesireCollection = Backbone.Collection.extend({ url: $.ventoonirico.urlPrefix + '/api/desires', model: $.ventoonirico.Desire }); $.ventoonirico.Join = Backbone.RelationalModel.extend({ urlRoot: $.ventoonirico.urlPrefix + '/api/joins', relations: [ { type: Backbone.HasOne, key: 'user', relatedModel: '$.ventoonirico.User', includeInJSON: 'id' }, { type: Backbone.HasOne, key: 'desire', relatedModel: '$.ventoonirico.Desire', includeInJSON: 'id' } ] }); $.ventoonirico.JoinCollection = Backbone.Collection.extend({ model: $.ventoonirico.Join }); $.ventoonirico.User = Backbone.RelationalModel.extend({ urlRoot: $.ventoonirico.urlPrefix + '/api/users' }); $.ventoonirico.CurrentUser = $.ventoonirico.User.extend({ url: $.ventoonirico.urlPrefix + '/api/user', isLogged: function() { return this.get('id'); } }); $.ventoonirico.UserCollection = Backbone.Collection.extend({ model: $.ventoonirico.User }); $.ventoonirico.GameCountView = Backbone.View.extend({ initialize: function() { this.listenTo(this.model, 'sync', this.render); }, template: _.template($('#game-count').html()), render: function() { this.$el.html(this.template({count: this.model.length})); return this; }, }); $.ventoonirico.GameListView = Backbone.View.extend({ initialize: function() { this.listenTo(this.model, 'sync', this.render); }, template: _.template($('#game-list').html()), render: function() { this.$el.parents().find(".loading").hide(); this.$el.html(this.template(this.model)); this.model.forEach(this.renderGame); return this; }, renderGame: function(game) { var gameView = new $.ventoonirico.GameView({ model: game }); this.$('table.game-list').append(gameView.render().el); } }); $.ventoonirico.GameView = Backbone.View.extend({ tagName: 'tr', initialize: function() { this.listenTo(this.model, 'change', this.render); }, template: _.template($('#game').html()), render: function() { this.setElement(this.template({game: this.model.toJSON()})); var gameStatusView = new $.ventoonirico.GameStatusView({ el: this.$el.find(".game-status"), model: { game: this.model, user: $.ventoonirico.user } }); return this; } }); $.ventoonirico.GameStatusView = Backbone.View.extend({ initialize: function() { this.listenTo(this.model.game, 'change', this.render); this.listenTo(this.model.user, 'change', this.render); this.render() }, events: { "click .desire-create": "createDesire", "click .desire-remove": "removeDesire", }, render: function() { var desire = this.model.game.get('desire'); if (!desire) { if (this.model.user.isLogged()) { this.template = _.template($('#game-status-user-nodesire').html()), this.$el.html(this.template(this.model)); return this; } else { this.template = _.template($('#game-status-nouser-nodesire').html()), this.$el.html(this.template({})); return this; } } var desireView = new $.ventoonirico.DesireView({ model: { user: this.model.user, game: this.model.game, desire: desire } }); this.$el.html(desireView.el); }, createDesire: function() { this.model.game.createDesire(this.model.user); return false; }, removeDesire: function() { this.model.game.removeDesire(); return false; } }); $.ventoonirico.DesireView = Backbone.View.extend({ initialize: function() { // this.listenTo(this.model.desire, 'change', this.render); this.listenTo(this.model.desire, 'add:joins', this.render); this.listenTo(this.model.desire, 'remove:joins', this.render); this.setElement($('#game-status-desire').html()); this.render(); }, events: { "click .join-add": "addJoin", "click .join-remove": "removeJoin" }, render: function() { var user = this.model.user; var game = this.model.game; var desire = this.model.game.get('desire'); this.$el.html(_.template($('#game-status-desire-player_main').html(), {user: user, owner: desire.get('owner')})); var joins = desire.get('joins'); var users = new $.ventoonirico.UserCollection([desire.get('owner')]); for(var i=0; i<game.get('maxPlayers')-1; i++) { var join = joins.at(i); if ( join) { var guest = users.get(join.get('user')) != undefined; users.push(join.get('user')); this.$el.append(_.template($('#game-status-desire-player_joined').html(), {user: user, join: join, guest:guest})); } else { this.$el.append(_.template($('#game-status-desire-player_nobody').html(), {user: user})); } } return this; }, addJoin: function() { this.model.desire.addJoin(this.model.user); return false; }, removeJoin: function() { this.model.desire.removeJoin(this.model.user); return false; } }); $.ventoonirico.DesiredGameListView = Backbone.View.extend({ initialize: function() { this.listenTo(this.model, 'sync', this.render); }, template: _.template($('#desired-game-list').html()), render: function() { var desiredGames = this.model.filter(function(game){ return (game.get('desire') != null) }); this.$el.parents().find(".loading").hide(); this.$el.html(this.template(desiredGames)); desiredGames.forEach(this.renderGame); return this; }, renderGame: function(game) { var desiredGameView = new $.ventoonirico.DesiredGameView({ model: game }); this.$('div.desired-game-list').append(desiredGameView.render().el); } }); $.ventoonirico.DesiredGameView = Backbone.View.extend({ tagName: 'div', initialize: function() { this.listenTo(this.model, 'change', this.render); }, template: _.template($('#desired-game').html()), render: function() { this.setElement(this.template({game: this.model.toJSON()})); var gameStatusView = new $.ventoonirico.GameStatusView({ el: this.$el.find(".game-status"), model: { game: this.model, user: $.ventoonirico.user } }); return this; } }); $.ventoonirico.IndexView = Backbone.View.extend({ el: $("#app"), template: _.template($('#games').html()), events: { }, initialize: function() { this.render(); }, render: function() { this.$el.html(this.template({})); var gameCollection = new $.ventoonirico.GameCollection(); var gameCountView = new $.ventoonirico.GameCountView({'model': gameCollection}); var desiredGameListView = new $.ventoonirico.DesiredGameListView({'model': gameCollection}); var gameListView = new $.ventoonirico.GameListView({'model': gameCollection}); this.$("#game-list").append(gameListView.el); this.$("#desired-game-list").append(desiredGameListView.el); this.$("#game-count").append(gameCountView.el); gameCollection.fetch(); $.ventoonirico.user.fetch(); }, }); $.ventoonirico.user = null; $.ventoonirico.Router = Backbone.Router.extend({ routes: function(){ var routes = new Array(); routes[$.ventoonirico.urlPrefix + ""] = "index"; return routes; }, initialize: function() { $.ventoonirico.user = new $.ventoonirico.CurrentUser(); }, index: function() { var indexView = new $.ventoonirico.IndexView({}); } }); $.ventoonirico.app = null; $.ventoonirico.bootstrap = function() { $.ventoonirico.app = new $.ventoonirico.Router(); Backbone.history.start({ pushState: true }); }; $.ventoonirico.bootstrap(); }(jQuery));
import _ from 'lodash'; const operators = { '===': (l, r) => _.isEqual(l, r), // allow comparing by value '!==': (l, r) => !_.isEqual(l, r), '<': (l, r) => l < r, '>': (l, r) => l > r, '<=': (l, r) => l <= r, '>=': (l, r) => l >= r, typeof: (l, r) => typeof l == r, regex: (l, r) => !!(new RegExp(r)).exec(l), empty: l => isEmpty(l), 'not-empty': l => !isEmpty(l), truthy: l => !!l, falsy: l => !!!l, 'length-equals': (l, r) => _.size(l) === r, 'length-less-than': (l, r) => _.size(l) < r, 'length-greater-than': (l, r) => _.size(l) > r }; /** * determine if a field is empty * @param {*} val * @return {Boolean} */ export function isEmpty(val) { // eslint-disable-line if (_.isArray(val)) { // an array is empty if it has no items, if all of the items are considered empty, or if the item contains props that are considered empty // (e.g. complex-list items) return _.isEmpty(val) || _.every(val, item => _.isObject(item) ? _.every(item, itemVal => isEmpty(itemVal)) : isEmpty(item)); } else if (_.isObject(val)) { // an object is empty if it's empty or all its props are falsy (e.g. checkbox-group) return _.isEmpty(val) || _.every(val, prop => !prop); } else if (_.isString(val)) { return val.length === 0; // emptystring is empty } else if (_.isNull(val) || _.isUndefined(val) || _.isNaN(val)) { return true; // null, undefined, and NaN are empty } else { // numbers, booleans, etc are never empty return false; } } /** * compare a field's data to a value * @param {*} data from a field * @param {string} [operator] * @param {*} [value] * @return {boolean} */ export function compare({ data, operator, value }) { if (!operator && typeof value === 'undefined') { // if neither operator or value are specified, default to // checking if field has a value return !isEmpty(data); } else if (!operator && typeof value !== 'undefined') { // if no operator (but there is a value!), default to equal return operators['==='](data, value); } else if (operators[operator]) { // if there's an operator, use it (value may be undefined, e.g. when using the 'truthy'/'empty'/etc operators) return operators[operator](data, value); } else { throw new Error(`Unknown operator: ${operator}`); } }
goog.provide('tictactoe.GameView'); goog.require('lime.Scene'); goog.require('lime.Layer'); goog.require('lime.Sprite'); goog.require('lime.Button'); goog.require('lime.RoundedRect'); goog.require('lime.Circle'); goog.require('lime.Label'); goog.require('lime.animation.Resize'); goog.require('lime.animation.FadeTo'); goog.require('lime.animation.Sequence'); goog.require('lime.animation.ColorTo'); /** * @constructor */ tictactoe.GameView = function() { 'use strict'; var that = this; lime.Scene.call(this); if (tictactoe.configs.useCanvas) { this.setRenderer(lime.Renderer.CANVAS); } this.leftPlayerName = new lime.Label('') .setFontSize(18) .setFontColor('#336633') .setSize(25, 14) .setPosition(66, 41) .setAnchorPoint(0, 1) .setAlign('left'); this.appendChild(this.leftPlayerName); this.rightPlayerName = new lime.Label('') .setFontSize(18) .setFontColor('#336633') .setSize(150, 14) .setPosition(244, 41) .setAnchorPoint(1, 1) .setAlign('right'); this.appendChild(this.rightPlayerName); this.leftPlayerRank = new lime.Label('') .setFontSize(15) .setFontColor('#514f4b') .setSize(85, 14) .setPosition(66, 57) .setAnchorPoint(0, 1) .setAlign('left'); this.appendChild(this.leftPlayerRank); this.rightPlayerRank = new lime.Label('') .setFontSize(15) .setFontColor('#514f4b') .setSize(85, 14) .setPosition(244, 57) .setAnchorPoint(1, 1) .setAlign('right'); this.appendChild(this.rightPlayerRank); this.leftPlayerProgress = new lime.Sprite() .setSize(54, 54) .setPosition(33, 42); this.appendChild(this.leftPlayerProgress); this.rightPlayerProgress = new lime.Sprite() .setSize(54, 54) .setPosition(277, 42); this.appendChild(this.rightPlayerProgress); this.leftPlayerAvatar = new lime.Circle() .setSize(40, 40) .setPosition(33, 42); this.appendChild(this.leftPlayerAvatar); this.rightPlayerAvatar = new lime.Circle() .setSize(40, 40) .setPosition(277, 42); this.appendChild(this.rightPlayerAvatar); this.leftAvatarOverlay = new lime.Circle() .setSize(40, 40) .setPosition(33, 42) .setFill('#000000') .setOpacity(0); this.appendChild(this.leftAvatarOverlay); this.rightAvatarOverlay = new lime.Circle() .setSize(40, 40) .setPosition(277, 42) .setFill('#000000') .setOpacity(0); this.appendChild(this.rightAvatarOverlay); this.leftTimer = new lime.Label('') .setFontSize(28) .setFontColor('#00ff00') .setSize(40, 40) .setPosition(33, 45) .setOpacity(0); this.appendChild(this.leftTimer); this.rightTimer = new lime.Label('') .setFontSize(28) .setFontColor('#00ff00') .setSize(40, 40) .setPosition(277, 45) .setOpacity(0); this.appendChild(this.rightTimer); this.winnerIndicator = new lime.Sprite() .setSize(20, 20) .setFill('img/header-crown' + tictactoe.configs.retinaPrefix + '.png') .setHidden(true); this.appendChild(this.winnerIndicator); var grid = new lime.Layer().setPosition(154, 275); grid.appendChild(this.buildRoundedLine(266, 4, '#94d4ed').setPosition(0, -45)); grid.appendChild(this.buildRoundedLine(266, 4, '#94d4ed').setPosition(0, 44)); grid.appendChild(this.buildRoundedLine(266, 4, '#94d4ed').setPosition(-44, 0).setRotation(90)); grid.appendChild(this.buildRoundedLine(266, 4, '#94d4ed').setPosition(45, 0).setRotation(90)); this.appendChild(grid); this.gameboard = new lime.Layer(); this.gameboard.gamePosition = []; var onClick = function(e) { //https://github.com/digitalfruit/limejs/pull/108 if(e.event === undefined) { that.handleClick(this.posX, this.posY); } }; for (var i = 0; i < 3; i++) { this.gameboard.gamePosition[i] = []; for (var j = 0; j < 3; j++) { this.gameboard.gamePosition[i][j] = new lime.Button( new lime.Sprite().setSize(86, 86), //.setFill('#ff0000').setOpacity(0.5).setStroke(1,'#000000'), new lime.Sprite().setSize(86, 86)).setPosition(64 + i * 90, 184 + j * 90); this.gameboard.gamePosition[i][j].posX = i; this.gameboard.gamePosition[i][j].posY = j; goog.events.listen(this.gameboard.gamePosition[i][j], lime.Button.Event.CLICK, onClick); this.gameboard.appendChild(this.gameboard.gamePosition[i][j]); } } this.victoryline = this.buildRoundedLine(12, 12, '#f09600').setOpacity(0.3).setHidden(true); this.gameboard.appendChild(this.victoryline); this.appendChild(this.gameboard); //pages shadow this.appendChild(new lime.Sprite() .setSize(312, 26) .setPosition(156, 554) .setFill('img/notepad-pages-shadow' + tictactoe.configs.retinaPrefix + '.png')); }; goog.inherits(tictactoe.GameView, lime.Scene); tictactoe.GameView.prototype.handleClick = function(posX, posY) { 'use strict'; this.lastTimeLeft = this.timeLeft; tictactoe.gameController.dispatchEvent({ type: 'move', posX: posX, posY: posY }); }; tictactoe.GameView.prototype.buildRoundedLine = function(width, lineWidth, fill) { 'use strict'; return new lime.RoundedRect() .setSize(width, lineWidth) .setRadius(lineWidth / 2) .setFill(fill); }; tictactoe.GameView.prototype.prepareGame = function(player, opponent, deviceType) { 'use strict'; this.player = player; this.opponent = opponent; this.useFirstSymbol = tictactoe.configs.allwaysUseSameSymbol ? true : player.id < opponent.id; this.leftPlayerName.setText('Me'); if (typeof player.user.ranking !== 'undefined') { this.leftPlayerRank.setText('#' + player.user.ranking); } else { this.leftPlayerRank.setText('--'); } this.leftPlayerAvatar.setFill(player.user.avatar); if(opponent.user.nickname.length > 9) { this.rightPlayerName.setText(opponent.user.nickname.slice(0, 8) + '…'); } else { this.rightPlayerName.setText(opponent.user.nickname); } if (typeof opponent.user.ranking !== 'undefined') { this.rightPlayerRank.setText('#' + opponent.user.ranking); } else { this.rightPlayerRank.setText('--'); } this.rightPlayerAvatar.setFill(opponent.user.avatar); //draw progress bars var canvas = document.createElement('canvas'), context = canvas.getContext('2d'), startAngle = Math.PI / 2 * 3, width = tictactoe.configs.retinaImages ? 108 : 54, radius = tictactoe.configs.retinaImages ? 50 : 25, lineWidth = tictactoe.configs.retinaImages ? 8 : 4; canvas.width = width; canvas.height = width; context.lineWidth = lineWidth; if (player.user.progress !== 0) { context.beginPath(); context.arc(width / 2, width / 2, radius, startAngle, player.user.progress - Math.PI / 2, false); context.strokeStyle = '#6c6'; context.stroke(); } context.beginPath(); context.arc(width / 2, width / 2, radius, player.user.progress - Math.PI / 2, startAngle, false); context.strokeStyle = '#d5d5d5'; context.stroke(); this.leftPlayerProgress.setFill(canvas.toDataURL()); context.clearRect(0,0,canvas.width,canvas.height); context.lineWidth = lineWidth; if (opponent.user.progress !== 0) { context.beginPath(); context.arc(width / 2, width / 2, radius, startAngle, opponent.user.progress - Math.PI / 2, false); context.strokeStyle = '#6c6'; context.stroke(); } context.beginPath(); context.arc(width / 2, width / 2, radius, opponent.user.progress - Math.PI / 2, startAngle, false); context.strokeStyle = '#d5d5d5'; context.stroke(); this.rightPlayerProgress.setFill(canvas.toDataURL()); if (deviceType === 'TV') { this.cursorPos = [1, 1]; this.cursor = new lime.Layer().setAnchorPoint(0.5, 0.5).setHidden(true); var cursorElements = []; cursorElements.push(new lime.Sprite().setSize(7, 25).setPosition(-36.5, -26.5)); cursorElements.push(new lime.Sprite().setSize(7, 25).setPosition(36.5, -26.5)); cursorElements.push(new lime.Sprite().setSize(7, 25).setPosition(-36.5, 26.5)); cursorElements.push(new lime.Sprite().setSize(7, 25).setPosition(36.5, 26.5)); cursorElements.push(new lime.Sprite().setSize(25, 7).setPosition(-26.5, -36.5)); cursorElements.push(new lime.Sprite().setSize(25, 7).setPosition(26.5, -36.5)); cursorElements.push(new lime.Sprite().setSize(25, 7).setPosition(-26.5, 36.5)); cursorElements.push(new lime.Sprite().setSize(25, 7).setPosition(26.5, 36.5)); this.cursor.setColor = function(color) { for (var i = cursorElements.length - 1; i >= 0; i--) { cursorElements[i].setFill(color); } return this; }; for (var i = cursorElements.length - 1; i >= 0; i--) { this.cursor.appendChild(cursorElements[i]); } this.appendChild(this.cursor); } else { this.menuButton = new lime.Button( new lime.Sprite().setFill('img/game-button-options-0' + tictactoe.configs.retinaPrefix + '.png').setSize(65, 47).setAnchorPoint(0, 0), new lime.Sprite().setFill('img/game-button-options-1' + tictactoe.configs.retinaPrefix + '.png').setSize(65, 47).setAnchorPoint(0, 0)) .setPosition(238, 473); goog.events.listen(this.menuButton, lime.Button.Event.CLICK, function(e) { //https://github.com/digitalfruit/limejs/pull/108 if(e.event === undefined) { tictactoe.gameController.dispatchEvent({ type: 'showMenu' }); } }); this.appendChild(this.menuButton); } }; tictactoe.GameView.prototype.startGame = function(playerToStart, moveTimeout) { 'use strict'; this.timeout = moveTimeout / 1000; this.switchPlayer(playerToStart); }; tictactoe.GameView.prototype.doMove = function(currentPlayer, posX, posY) { 'use strict'; var piece, bar1, bar2; if ((currentPlayer && this.useFirstSymbol) || (!currentPlayer && !this.useFirstSymbol)) { piece = new lime.Layer().setAnchorPoint(0.5, 0.5); bar1 = this.buildRoundedLine(55, 12, '#514f4b').setRotation(45); bar2 = this.buildRoundedLine(55, 12, '#514f4b').setRotation(-45); piece.appendChild(bar1); piece.appendChild(bar2); piece.setFill = function(fill) { bar1.setFill(fill); bar2.setFill(fill); return this; }; } else { piece = new lime.Circle().setSize(55 / 1.15, 55 / 1.15).setStroke(10, '#514f4b'); piece.setFill = function(fill) { return this.setStroke(10, fill); }; } this.lastPiece = piece; if (typeof this.gameboard.gamePosition[posX][posY].piece !== 'undefined') { //to undo moves on the same cell this.gameboard.gamePosition[posX][posY].lastPiece = this.gameboard.gamePosition[posX][posY].piece; } this.gameboard.gamePosition[posX][posY].piece = piece; this.gameboard.gamePosition[posX][posY].appendChild(piece); if (typeof this.cursor !== 'undefined') { this.cursor.setHidden(true); } }; tictactoe.GameView.prototype.undoLastMove = function(posX, posY) { 'use strict'; this.gameboard.gamePosition[posX][posY].piece = this.gameboard.gamePosition[posX][posY].lastPiece; this.gameboard.gamePosition[posX][posY].removeChild(this.lastPiece); return this.lastTimeLeft; }; tictactoe.GameView.prototype.endGame = function(currentPlayer, endCondition) { 'use strict'; var animation, pieces; this.leftTimer.setHidden(true); this.rightTimer.setHidden(true); clearInterval(this.intervalId); if (currentPlayer) { this.rightAvatarOverlay.setHidden(true); } else { this.leftAvatarOverlay.setHidden(true); } if (endCondition !== 9) { switch (endCondition) { //vertical line case 0: case 1: case 2: this.victoryline.setAnchorPoint(1, 0.5) .setRotation(90) .setPosition(64 + 90 * endCondition, 153); pieces = [ this.gameboard.gamePosition[endCondition][0].piece, this.gameboard.gamePosition[endCondition][1].piece, this.gameboard.gamePosition[endCondition][2].piece ]; animation = new lime.animation.Resize(241, 12).setEasing(lime.animation.Easing.LINEAR); break; //hotizontal line case 3: case 4: case 5: this.victoryline.setAnchorPoint(0, 0.5).setPosition(33, 184 + 90 * (endCondition - 3)); pieces = [ this.gameboard.gamePosition[0][endCondition - 3].piece, this.gameboard.gamePosition[1][endCondition - 3].piece, this.gameboard.gamePosition[2][endCondition - 3].piece ]; animation = new lime.animation.Resize(241, 12).setEasing(lime.animation.Easing.LINEAR); break; //diagonal line case 6: case 7: if (endCondition === 6) { this.victoryline.setAnchorPoint(0, 0.5) .setRotation(-45) .setPosition(44, 164); pieces = [ this.gameboard.gamePosition[0][0].piece, this.gameboard.gamePosition[1][1].piece, this.gameboard.gamePosition[2][2].piece ]; } else { this.victoryline.setAnchorPoint(1, 0.5) .setRotation(-135) .setPosition(44, 384); pieces = [ this.gameboard.gamePosition[0][2].piece, this.gameboard.gamePosition[1][1].piece, this.gameboard.gamePosition[2][0].piece ]; } animation = new lime.animation.Resize(311, 12).setEasing(lime.animation.Easing.LINEAR); break; //board full case 8: this.fadePlayerIndicators(true, true); this.fadePlayerIndicators(false, true); if (currentPlayer) { this.leftAvatarOverlay.setHidden(true); } else { this.rightAvatarOverlay.setHidden(true); } return; } this.victoryline.setHidden(false); setTimeout(function() { pieces[0].setFill('#f09600'); }, 100); setTimeout(function() { pieces[1].setFill('#f09600'); }, 500); setTimeout(function() { pieces[2].setFill('#f09600'); }, 900); this.victoryline.runAction(animation); } this.fadePlayerIndicators(true, true); this.fadePlayerIndicators(false, true); if (currentPlayer) { this.leftPlayerName.setFontColor('#f09600'); this.winnerIndicator.setPosition(33, 42).setHidden(false); } else { this.rightPlayerName.setFontColor('#f09600'); this.winnerIndicator.setPosition(277, 42).setHidden(false); } }; tictactoe.GameView.prototype.switchPlayer = function(currentPlayer, optTime) { 'use strict'; var that = this, timer, colorStep1, colorStep2; clearInterval(this.intervalId); if (typeof this.timerColorAnim !== 'undefined') { this.timerColorAnim.stop(); } if (typeof optTime !== 'undefined') { this.timeLeft = optTime; } else { this.timeLeft = this.timeout; } colorStep2 = this.timeLeft / 3; colorStep1 = colorStep2 * 2; if (currentPlayer) { timer = this.leftTimer; this.fadePlayerIndicators(true, true); this.fadePlayerIndicators(false, false); } else { timer = this.rightTimer; this.fadePlayerIndicators(true, false); this.fadePlayerIndicators(false, true); } timer.setText(this.timeLeft).setFontColor('#00ff00'); this.intervalId = setInterval(function() { timer.setText(--that.timeLeft); switch (that.timeLeft) { case colorStep1: that.timerColorAnim = new lime.animation.ColorTo('#ffff00') .setTargetComponent(lime.animation.ColorTo.Target.FONT).setDuration(3); timer.runAction(that.timerColorAnim); break; case colorStep2: that.timerColorAnim = new lime.animation.ColorTo('#ff0000') .setTargetComponent(lime.animation.ColorTo.Target.FONT).setDuration(3); timer.runAction(that.timerColorAnim); break; case 0: clearInterval(that.intervalId); break; } }, 1000); if (currentPlayer && typeof this.cursor !== 'undefined') { this.moveCursor(); this.cursor.setHidden(false); } }; tictactoe.GameView.prototype.fadePlayerIndicators = function(currentPlayer, show) { 'use strict'; var nameAnim = new lime.animation.FadeTo(show ? 1 : 0.33).setDuration(0.5), overlayAnim = new lime.animation.FadeTo(show ? 0.72 : 0).setDuration(0.5), timerAnim = new lime.animation.FadeTo(show ? 1 : 0).setDuration(0.5); if (currentPlayer) { nameAnim.addTarget(this.leftPlayerName); nameAnim.addTarget(this.leftPlayerRank); nameAnim.addTarget(this.leftPlayerAvatar); nameAnim.addTarget(this.leftPlayerProgress); overlayAnim.addTarget(this.leftAvatarOverlay); timerAnim.addTarget(this.leftTimer); } else { nameAnim.addTarget(this.rightPlayerName); nameAnim.addTarget(this.rightPlayerRank); nameAnim.addTarget(this.rightPlayerAvatar); nameAnim.addTarget(this.rightPlayerProgress); overlayAnim.addTarget(this.rightAvatarOverlay); timerAnim.addTarget(this.rightTimer); } nameAnim.play(); overlayAnim.play(); timerAnim.play(); }; tictactoe.GameView.prototype.moveCursor = function(direction) { 'use strict'; switch (direction) { case 'left': if (this.cursorPos[0] > 0) { this.cursorPos[0]--; } break; case 'right': if (this.cursorPos[0] < 2) { this.cursorPos[0]++; } break; case 'up': if (this.cursorPos[1] > 0) { this.cursorPos[1]--; } break; case 'down': if (this.cursorPos[1] < 2) { this.cursorPos[1]++; } break; } if (typeof this.gameboard.gamePosition[this.cursorPos[0]][this.cursorPos[1]].piece === 'undefined') { this.cursor.setColor('#52504C'); } else { this.cursor.setColor('#FF5638'); } this.cursor.setPosition(64 + this.cursorPos[0] * 90, 184 + this.cursorPos[1] * 90); };
import React from 'react'; import {children, optional, once} from '../Composite'; import Label from '../Label'; import Input from '../Input'; import InputAreaWithLabelComposite from '../Composite/InputAreaWithLabelComposite/InputAreaWithLabelComposite'; const TextField = ({...props, children}) => ( <InputAreaWithLabelComposite {...props}> {children} </InputAreaWithLabelComposite> ); TextField.propTypes = { children: children(optional(Label), once(Input)) }; TextField.displayName = 'TextField'; export default TextField;
/** * jqPlot * Pure JavaScript plotting plugin using jQuery * * Version: 1.0.0b2_r1012 * * Copyright (c) 2009-2011 Chris Leonello * jqPlot is currently available for use in all personal or commercial projects * under both the MIT (http://www.opensource.org/licenses/mit-license.php) and GPL * version 2.0 (http://www.gnu.org/licenses/gpl-2.0.html) licenses. This means that you can * choose the license that best suits your project and use it accordingly. * * Although not required, the author would appreciate an email letting him * know of any substantial use of jqPlot. You can reach the author at: * chris at jqplot dot com or see http://www.jqplot.com/info.php . * * If you are feeling kind and generous, consider supporting the project by * making a donation at: http://www.jqplot.com/donate.php . * * sprintf functions contained in jqplot.sprintf.js by Ash Searle: * * version 2007.04.27 * author Ash Searle * http://hexmen.com/blog/2007/03/printf-sprintf/ * http://hexmen.com/js/sprintf.js * The author (Ash Searle) has placed this code in the public domain: * "This code is unrestricted: you are free to use it however you like." * */ (function ($) { /** * Class: $.jqplot.PointLabels * Plugin for putting labels at the data points. * * To use this plugin, include the js * file in your source: * * > <script type="text/javascript" src="plugins/jqplot.pointLabels.js"></script> * * By default, the last value in the data ponit array in the data series is used * for the label. For most series renderers, extra data can be added to the * data point arrays and the last value will be used as the label. * * For instance, * this series: * * > [[1,4], [3,5], [7,2]] * * Would, by default, use the y values in the labels. * Extra data can be added to the series like so: * * > [[1,4,'mid'], [3 5,'hi'], [7,2,'low']] * * And now the point labels would be 'mid', 'low', and 'hi'. * * Options to the point labels and a custom labels array can be passed into the * "pointLabels" option on the series option like so: * * > series:[{pointLabels:{ * > labels:['mid', 'hi', 'low'], * > location:'se', * > ypadding: 12 * > } * > }] * * A custom labels array in the options takes precendence over any labels * in the series data. If you have a custom labels array in the options, * but still want to use values from the series array as labels, set the * "labelsFromSeries" option to true. * * By default, html entities (<, >, etc.) are escaped in point labels. * If you want to include actual html markup in the labels, * set the "escapeHTML" option to false. * */ $.jqplot.PointLabels = function (options) { // Group: Properties // // prop: show // show the labels or not. this.show = $.jqplot.config.enablePlugins; // prop: location // compass location where to position the label around the point. // 'n', 'ne', 'e', 'se', 's', 'sw', 'w', 'nw' this.location = 'n'; // prop: labelsFromSeries // true to use labels within data point arrays. this.labelsFromSeries = false; // prop: seriesLabelIndex // array index for location of labels within data point arrays. // if null, will use the last element of the data point array. this.seriesLabelIndex = null; // prop: labels // array of arrays of labels, one array for each series. this.labels = []; // actual labels that will get displayed. // needed to preserve user specified labels in labels array. this._labels = []; // prop: stackedValue // true to display value as stacked in a stacked plot. // no effect if labels is specified. this.stackedValue = false; // prop: ypadding // vertical padding in pixels between point and label this.ypadding = 6; // prop: xpadding // horizontal padding in pixels between point and label this.xpadding = 6; // prop: escapeHTML // true to escape html entities in the labels. // If you want to include markup in the labels, set to false. this.escapeHTML = true; // prop: edgeTolerance // Number of pixels that the label must be away from an axis // boundary in order to be drawn. Negative values will allow overlap // with the grid boundaries. this.edgeTolerance = -5; // prop: formatter // A class of a formatter for the tick text. sprintf by default. this.formatter = $.jqplot.DefaultTickFormatter; // prop: formatString // string passed to the formatter. this.formatString = ''; // prop: hideZeros // true to not show a label for a value which is 0. this.hideZeros = false; this._elems = []; $.extend(true, this, options); }; var locations = ['nw', 'n', 'ne', 'e', 'se', 's', 'sw', 'w']; var locationIndicies = {'nw': 0, 'n': 1, 'ne': 2, 'e': 3, 'se': 4, 's': 5, 'sw': 6, 'w': 7}; var oppositeLocations = ['se', 's', 'sw', 'w', 'nw', 'n', 'ne', 'e']; // called with scope of a series $.jqplot.PointLabels.init = function (target, data, seriesDefaults, opts, plot) { var options = $.extend(true, {}, seriesDefaults, opts); options.pointLabels = options.pointLabels || {}; if (this.renderer.constructor === $.jqplot.BarRenderer && this.barDirection === 'horizontal' && !options.pointLabels.location) { options.pointLabels.location = 'e'; } // add a pointLabels attribute to the series plugins this.plugins.pointLabels = new $.jqplot.PointLabels(options.pointLabels); this.plugins.pointLabels.setLabels.call(this); }; // called with scope of series $.jqplot.PointLabels.prototype.setLabels = function () { var p = this.plugins.pointLabels; var labelIdx; if (p.seriesLabelIndex != null) { labelIdx = p.seriesLabelIndex; } else if (this.renderer.constructor === $.jqplot.BarRenderer && this.barDirection === 'horizontal') { labelIdx = 0; } else { labelIdx = (this._plotData.length === 0) ? 0 : this._plotData[0].length - 1; } p._labels = []; if (p.labels.length === 0 || p.labelsFromSeries) { if (p.stackedValue) { if (this._plotData.length && this._plotData[0].length) { // var idx = p.seriesLabelIndex || this._plotData[0].length -1; for (var i = 0; i < this._plotData.length; i++) { p._labels.push(this._plotData[i][labelIdx]); } } } else { var d = this._plotData; if (this.renderer.constructor === $.jqplot.BarRenderer && this.waterfall) { d = this._data; } if (d.length && d[0].length) { // var idx = p.seriesLabelIndex || d[0].length -1; for (var i = 0; i < d.length; i++) { p._labels.push(d[i][labelIdx]); } } d = null; } } else if (p.labels.length) { p._labels = p.labels; } }; $.jqplot.PointLabels.prototype.xOffset = function (elem, location, padding) { location = location || this.location; padding = padding || this.xpadding; var offset; switch (location) { case 'nw': offset = -elem.outerWidth(true) - this.xpadding; break; case 'n': offset = -elem.outerWidth(true) / 2; break; case 'ne': offset = this.xpadding; break; case 'e': offset = this.xpadding; break; case 'se': offset = this.xpadding; break; case 's': offset = -elem.outerWidth(true) / 2; break; case 'sw': offset = -elem.outerWidth(true) - this.xpadding; break; case 'w': offset = -elem.outerWidth(true) - this.xpadding; break; default: // same as 'nw' offset = -elem.outerWidth(true) - this.xpadding; break; } return offset; }; $.jqplot.PointLabels.prototype.yOffset = function (elem, location, padding) { location = location || this.location; padding = padding || this.xpadding; var offset; switch (location) { case 'nw': offset = -elem.outerHeight(true) - this.ypadding; break; case 'n': offset = -elem.outerHeight(true) - this.ypadding; break; case 'ne': offset = -elem.outerHeight(true) - this.ypadding; break; case 'e': offset = -elem.outerHeight(true) / 2; break; case 'se': offset = this.ypadding; break; case 's': offset = this.ypadding; break; case 'sw': offset = this.ypadding; break; case 'w': offset = -elem.outerHeight(true) / 2; break; default: // same as 'nw' offset = -elem.outerHeight(true) - this.ypadding; break; } return offset; }; // called with scope of series $.jqplot.PointLabels.draw = function (sctx, options, plot) { var p = this.plugins.pointLabels; // set labels again in case they have changed. p.setLabels.call(this); // remove any previous labels for (var i = 0; i < p._elems.length; i++) { // Memory Leaks patch // p._elems[i].remove(); p._elems[i].emptyForce(); } p._elems.splice(0, p._elems.length); if (p.show) { var ax = '_' + this._stackAxis + 'axis'; if (!p.formatString) { p.formatString = this[ax]._ticks[0].formatString; p.formatter = this[ax]._ticks[0].formatter; } var pd = this._plotData; var xax = this._xaxis; var yax = this._yaxis; var elem, helem; for (var i = 0, l = p._labels.length; i < l; i++) { var label = p._labels[i]; if (p.hideZeros && parseInt(p._labels[i], 10) == 0) { label = ''; } if (label != null) { label = p.formatter(p.formatString, label); } helem = document.createElement('div'); p._elems[i] = $(helem); elem = p._elems[i]; elem.addClass('jqplot-point-label jqplot-series-' + this.index + ' jqplot-point-' + i); elem.css('position', 'absolute'); elem.insertAfter(sctx.canvas); if (p.escapeHTML) { elem.text(label); } else { elem.html(label); } var location = p.location; if ((this.fillToZero && pd[i][1] < 0) || (this.fillToZero && this._type === 'bar' && this.barDirection === 'horizontal' && pd[i][0] < 0) || (this.waterfall && parseInt(label, 10)) < 0) { location = oppositeLocations[locationIndicies[location]]; } var ell = xax.u2p(pd[i][0]) + p.xOffset(elem, location); var elt = yax.u2p(pd[i][1]) + p.yOffset(elem, location); if (this.renderer.constructor == $.jqplot.BarRenderer) { if (this.barDirection == "vertical") { ell += this._barNudge; } else { elt -= this._barNudge; } } elem.css('left', ell); elem.css('top', elt); var elr = ell + elem.width(); var elb = elt + elem.height(); var et = p.edgeTolerance; var scl = $(sctx.canvas).position().left; var sct = $(sctx.canvas).position().top; var scr = sctx.canvas.width + scl; var scb = sctx.canvas.height + sct; // if label is outside of allowed area, remove it if (ell - et < scl || elt - et < sct || elr + et > scr || elb + et > scb) { elem.remove(); } elem = null; helem = null; } // finally, animate them if the series is animated // if (this.renderer.animation && this.renderer.animation._supported && this.renderer.animation.show && plot._drawCount < 2) { // var sel = '.jqplot-point-label.jqplot-series-'+this.index; // $(sel).hide(); // $(sel).fadeIn(1000); // } } }; $.jqplot.postSeriesInitHooks.push($.jqplot.PointLabels.init); $.jqplot.postDrawSeriesHooks.push($.jqplot.PointLabels.draw); })(jQuery);
/* * Copyright (C) 2012 Google Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** * @constructor * @implements {WebInspector.SourceMapping} * @param {WebInspector.CSSStyleModel} cssModel * @param {WebInspector.Workspace} workspace * @param {WebInspector.SimpleWorkspaceProvider} networkWorkspaceProvider */ WebInspector.SASSSourceMapping = function(cssModel, workspace, networkWorkspaceProvider) { this._cssModel = cssModel; this._workspace = workspace; this._networkWorkspaceProvider = networkWorkspaceProvider; this._sourceMapByURL = {}; this._sourceMapByStyleSheetURL = {}; this._cssURLsForSASSURL = {}; this._timeoutForURL = {}; WebInspector.resourceTreeModel.addEventListener(WebInspector.ResourceTreeModel.EventTypes.ResourceAdded, this._resourceAdded, this); WebInspector.fileManager.addEventListener(WebInspector.FileManager.EventTypes.SavedURL, this._fileSaveFinished, this); this._cssModel.addEventListener(WebInspector.CSSStyleModel.Events.StyleSheetChanged, this._styleSheetChanged, this); this._workspace.addEventListener(WebInspector.Workspace.Events.UISourceCodeContentCommitted, this._uiSourceCodeContentCommitted, this); this._workspace.addEventListener(WebInspector.Workspace.Events.ProjectWillReset, this._reset, this); } WebInspector.SASSSourceMapping.prototype = { _populate: function() { function populateFrame(frame) { for (var i = 0; i < frame.childFrames.length; ++i) populateFrame.call(this, frame.childFrames[i]); var resources = frame.resources(); for (var i = 0; i < resources.length; ++i) this._resourceAdded({data:resources[i]}); } populateFrame.call(this, WebInspector.resourceTreeModel.mainFrame); }, /** * @param {WebInspector.Event} event */ _styleSheetChanged: function(event) { var isAddingRevision = this._isAddingRevision; delete this._isAddingRevision; if (isAddingRevision) return; var url = this._cssModel.resourceBinding().resourceURLForStyleSheetId(event.data.styleSheetId); if (!url) return; this._cssModel.setSourceMapping(url, null); }, /** * @param {WebInspector.Event} event */ _fileSaveFinished: function(event) { var sassURL = /** @type {string} */ (event.data); this._sassFileSaved(sassURL); }, /** * @param {string} sassURL */ _sassFileSaved: function(sassURL) { function callback() { delete this._timeoutForURL[sassURL]; var cssURLs = this._cssURLsForSASSURL[sassURL]; if (!cssURLs) return; for (var i = 0; i < cssURLs.length; ++i) this._reloadCSS(cssURLs[i]); } var timer = this._timeoutForURL[sassURL]; if (timer) { clearTimeout(timer); delete this._timeoutForURL[sassURL]; } if (!WebInspector.settings.cssReloadEnabled.get() || !this._cssURLsForSASSURL[sassURL]) return; var timeout = WebInspector.settings.cssReloadTimeout.get(); if (timeout && isFinite(timeout)) this._timeoutForURL[sassURL] = setTimeout(callback.bind(this), Number(timeout)); }, _reloadCSS: function(url) { var uiSourceCode = this._workspace.uiSourceCodeForURL(url); if (!uiSourceCode) return; var newContent = InspectorFrontendHost.loadResourceSynchronously(url); this._isAddingRevision = true; uiSourceCode.addRevision(newContent); // this._isAddingRevision will be deleted in this._styleSheetChanged(). this._loadAndProcessSourceMap(newContent, url, true); }, /** * @param {WebInspector.Event} event */ _resourceAdded: function(event) { var resource = /** @type {WebInspector.Resource} */ (event.data); if (resource.type !== WebInspector.resourceTypes.Stylesheet) return; /** * @param {?string} content * @param {boolean} contentEncoded * @param {string} mimeType */ function didRequestContent(content, contentEncoded, mimeType) { this._loadAndProcessSourceMap(content, resource.url); } resource.requestContent(didRequestContent.bind(this)); }, /** * @param {?string} content * @param {string} cssURL * @param {boolean=} forceRebind */ _loadAndProcessSourceMap: function(content, cssURL, forceRebind) { if (!content) return; var lines = content.split(/\r?\n/); if (!lines.length) return; const sourceMapRegex = /^\/\*@ sourceMappingURL=([^\s]+)\s*\*\/$/; var lastLine = lines[lines.length - 1]; var match = lastLine.match(sourceMapRegex); if (!match) return; if (!forceRebind && this._sourceMapByStyleSheetURL[cssURL]) return; var sourceMap = this.loadSourceMapForStyleSheet(match[1], cssURL, forceRebind); if (!sourceMap) return; this._sourceMapByStyleSheetURL[cssURL] = sourceMap; this._bindUISourceCode(cssURL, sourceMap); }, /** * @param {string} cssURL * @param {string} sassURL */ _addCSSURLforSASSURL: function(cssURL, sassURL) { var cssURLs; if (this._cssURLsForSASSURL.hasOwnProperty(sassURL)) cssURLs = this._cssURLsForSASSURL[sassURL]; else { cssURLs = []; this._cssURLsForSASSURL[sassURL] = cssURLs; } if (cssURLs.indexOf(cssURL) === -1) cssURLs.push(cssURL); }, /** * @param {string} sourceMapURL * @param {string} styleSheetURL * @param {boolean=} forceReload * @return {WebInspector.SourceMap} */ loadSourceMapForStyleSheet: function(sourceMapURL, styleSheetURL, forceReload) { var completeStyleSheetURL = WebInspector.ParsedURL.completeURL(WebInspector.inspectedPageURL, styleSheetURL); if (!completeStyleSheetURL) return null; var completeSourceMapURL = WebInspector.ParsedURL.completeURL(completeStyleSheetURL, sourceMapURL); if (!completeSourceMapURL) return null; var sourceMap = this._sourceMapByURL[completeSourceMapURL]; if (sourceMap && !forceReload) return sourceMap; sourceMap = WebInspector.SourceMap.load(completeSourceMapURL, completeStyleSheetURL); if (!sourceMap) { delete this._sourceMapByURL[completeSourceMapURL]; return null; } this._sourceMapByURL[completeSourceMapURL] = sourceMap; return sourceMap; }, /** * @param {string} rawURL * @param {WebInspector.SourceMap} sourceMap */ _bindUISourceCode: function(rawURL, sourceMap) { this._cssModel.setSourceMapping(rawURL, this); var sources = sourceMap.sources(); for (var i = 0; i < sources.length; ++i) { var url = sources[i]; if (!this._workspace.hasMappingForURL(url)) { if (!this._workspace.uiSourceCodeForURL(url)) { var content = InspectorFrontendHost.loadResourceSynchronously(url); var contentProvider = new WebInspector.StaticContentProvider(WebInspector.resourceTypes.Stylesheet, content, "text/x-scss"); var uiSourceCode = this._networkWorkspaceProvider.addFileForURL(url, contentProvider, true); uiSourceCode.setSourceMapping(this); this._addCSSURLforSASSURL(rawURL, url); } } else this._addCSSURLforSASSURL(rawURL, url); } }, /** * @param {WebInspector.RawLocation} rawLocation * @return {WebInspector.UILocation} */ rawLocationToUILocation: function(rawLocation) { var location = /** @type WebInspector.CSSLocation */ (rawLocation); var entry; var sourceMap = this._sourceMapByStyleSheetURL[location.url]; if (!sourceMap) return null; entry = sourceMap.findEntry(location.lineNumber, location.columnNumber); if (!entry || entry.length === 2) return null; var uiSourceCode = this._workspace.uiSourceCodeForURL(entry[2]); if (!uiSourceCode) return null; return new WebInspector.UILocation(uiSourceCode, entry[3], entry[4]); }, /** * @param {WebInspector.UISourceCode} uiSourceCode * @param {number} lineNumber * @param {number} columnNumber * @return {WebInspector.RawLocation} */ uiLocationToRawLocation: function(uiSourceCode, lineNumber, columnNumber) { // FIXME: Implement this when ui -> raw mapping has clients. return new WebInspector.CSSLocation(uiSourceCode.url || "", lineNumber, columnNumber); }, /** * @return {boolean} */ isIdentity: function() { return false; }, /** * @param {WebInspector.Event} event */ _uiSourceCodeContentCommitted: function(event) { var uiSourceCode = /** @type {WebInspector.UISourceCode} */ (event.data.uiSourceCode); this._sassFileSaved(uiSourceCode.url); }, _reset: function() { this._sourceMapByURL = {}; this._sourceMapByStyleSheetURL = {}; this._populate(); } }
import React, { Component } from 'react' class Home extends Component { render() { return ( <h2> It's Works </h2> ) } } export default Home
//>>built define(["dojo/_base/kernel","./entities","dojo/_base/array","dojo/_base/window","dojo/_base/sniff"],function(h,y,D,E,z){var p=h.getObject("dojox.html.format",!0);p.prettyPrint=function(p,l,n,A,F){var e=[],k=0,v=[],m="\t",f="",B=[],w,G=/[=]([^"']+?)(\s|>)/g,H=/style=("[^"]*"|'[^']*'|\S*)/gi,I=/[\w-]+=("[^"]*"|'[^']*'|\S*)/gi;if(l&&0<l&&10>l)for(m="",w=0;w<l;w++)m+=" ";l=E.doc.createElement("div");l.innerHTML=p;var J=y.encode,K=y.decode,x=l.ownerDocument.createElement("div"),L=function(a){a=a.cloneNode(!1); x.appendChild(a);a=x.innerHTML;x.innerHTML="";return a},q=function(){var a;for(a=0;a<k;a++)e.push(m)},r=function(){e.push("\n")},t=function(a){var b,d;a=a.split("\n");for(b=0;b<a.length;b++)a[b]=h.trim(a[b]);a=a.join(" ");a=h.trim(a);if(""!==a){var c=[];if(n&&0<n){var g="";for(b=0;b<k;b++)g+=m;b=g.length;g=n;for(n>b&&(g-=b);a;)if(a.length>n){for(b=g;0<b&&" "!==a.charAt(b);b--);if(!b)for(b=g;b<a.length&&" "!==a.charAt(b);b++);var e=a.substring(0,b),e=h.trim(e);a=h.trim(a.substring(b==a.length?a.length: b+1,a.length));if(e){d="";for(b=0;b<k;b++)d+=m;e=d+e+"\n"}c.push(e)}else{d="";for(b=0;b<k;b++)d+=m;a=d+a+"\n";c.push(a);a=null}return c.join("")}d="";for(b=0;b<k;b++)d+=m;return d+a+"\n"}return""},M=function(a){if(a){var b=a;b&&(b=b.replace(/&quot;/gi,'"'),b=b.replace(/&gt;/gi,"\x3e"),b=b.replace(/&lt;/gi,"\x3c"),b=b.replace(/&amp;/gi,"\x26"));var d,c;a=0;for(var g=b.split("\n"),e=[],b=0;b<g.length;b++){var f=g[b],u=-1<f.indexOf("\n");if(f=h.trim(f)){u=a;for(d=0;d<f.length;d++)c=f.charAt(d),"{"=== c?a++:"}"===c&&(a--,u=a);c="";for(d=0;d<k+u;d++)c+=m;e.push(c+f+"\n")}else u&&0===b&&e.push("\n")}a=e.join("")}return a},N=function(a){var b=a.nodeName.toLowerCase(),d=h.trim(L(a));a=d.substring(0,d.indexOf("\x3e")+1);a=a.replace(G,'\x3d"$1"$2');a=a.replace(H,function(a){var b=a.substring(0,6);a=a.substring(6,a.length);var c=a.charAt(0);a=h.trim(a.substring(1,a.length-1));a=a.split(";");var d=[];D.forEach(a,function(a){if(a=h.trim(a))a=a.substring(0,a.indexOf(":")).toLowerCase()+a.substring(a.indexOf(":"), a.length),d.push(a)});d=d.sort();a=d.join("; ");var e=h.trim(a);return e&&";"!==e?b+c+(a+";")+c:""});var c=[];a=a.replace(I,function(a){c.push(h.trim(a));return""});c=c.sort();a="\x3c"+b;c.length&&(a+=" "+c.join(" "));-1!=d.indexOf("\x3c/")?(v.push(b),a+="\x3e"):(a=F?a+" /\x3e":a+"\x3e",v.push(!1));a:switch(b){case "a":case "b":case "strong":case "s":case "strike":case "i":case "u":case "em":case "sup":case "sub":case "span":case "font":case "big":case "cite":case "q":case "small":b=!0;break a;default:b= !1}B.push(b);f&&!b&&(e.push(t(f)),f="");b?f+=a:(q(),e.push(a),r(),k++)},C=function(a){var b=a.childNodes;if(b){var d;for(d=0;d<b.length;d++){var c=b[d];if(1===c.nodeType){var g=h.trim(c.tagName.toLowerCase());z("ie")&&c.parentNode!=a||g&&"/"===g.charAt(0)||(N(c),"script"===g?e.push(M(c.innerHTML)):"pre"===g?(c=c.innerHTML,z("mozilla")&&(c=c.replace("\x3cbr\x3e","\n"),c=c.replace("\x3cpre\x3e",""),c=c.replace("\x3c/pre\x3e","")),"\n"!==c.charAt(c.length-1)&&(c+="\n"),e.push(c)):C(c),c=B.pop(),f&&!c&& (e.push(t(f)),f=""),(g=v.pop())?(g="\x3c/"+g+"\x3e",c?f+=g:(k--,q(),e.push(g),r())):k--)}else 3===c.nodeType||4===c.nodeType?f+=J(c.nodeValue,A):8===c.nodeType&&(c=K(c.nodeValue,A),q(),e.push("\x3c!--"),r(),k++,e.push(t(c)),k--,q(),e.push("--\x3e"),r())}}};C(l);f&&(e.push(t(f)),f="");return e.join("")};return p});
/** * @class Autolinker * @extends Object * * Utility class used to process a given string of text, and wrap the matches in * the appropriate anchor (&lt;a&gt;) tags to turn them into links. * * Any of the configuration options may be provided in an Object (map) provided * to the Autolinker constructor, which will configure how the {@link #link link()} * method will process the links. * * For example: * * var autolinker = new Autolinker( { * newWindow : false, * truncate : 30 * } ); * * var html = autolinker.link( "Joe went to www.yahoo.com" ); * // produces: 'Joe went to <a href="http://www.yahoo.com">yahoo.com</a>' * * * The {@link #static-link static link()} method may also be used to inline options into a single call, which may * be more convenient for one-off uses. For example: * * var html = Autolinker.link( "Joe went to www.yahoo.com", { * newWindow : false, * truncate : 30 * } ); * // produces: 'Joe went to <a href="http://www.yahoo.com">yahoo.com</a>' * * * ## Custom Replacements of Links * * If the configuration options do not provide enough flexibility, a {@link #replaceFn} * may be provided to fully customize the output of Autolinker. This function is * called once for each URL/Email/Phone#/Twitter Handle/Hashtag match that is * encountered. * * For example: * * var input = "..."; // string with URLs, Email Addresses, Phone #s, Twitter Handles, and Hashtags * * var linkedText = Autolinker.link( input, { * replaceFn : function( autolinker, match ) { * console.log( "href = ", match.getAnchorHref() ); * console.log( "text = ", match.getAnchorText() ); * * switch( match.getType() ) { * case 'url' : * console.log( "url: ", match.getUrl() ); * * if( match.getUrl().indexOf( 'mysite.com' ) === -1 ) { * var tag = autolinker.getTagBuilder().build( match ); // returns an `Autolinker.HtmlTag` instance, which provides mutator methods for easy changes * tag.setAttr( 'rel', 'nofollow' ); * tag.addClass( 'external-link' ); * * return tag; * * } else { * return true; // let Autolinker perform its normal anchor tag replacement * } * * case 'email' : * var email = match.getEmail(); * console.log( "email: ", email ); * * if( email === "my@own.address" ) { * return false; // don't auto-link this particular email address; leave as-is * } else { * return; // no return value will have Autolinker perform its normal anchor tag replacement (same as returning `true`) * } * * case 'phone' : * var phoneNumber = match.getPhoneNumber(); * console.log( phoneNumber ); * * return '<a href="http://newplace.to.link.phone.numbers.to/">' + phoneNumber + '</a>'; * * case 'twitter' : * var twitterHandle = match.getTwitterHandle(); * console.log( twitterHandle ); * * return '<a href="http://newplace.to.link.twitter.handles.to/">' + twitterHandle + '</a>'; * * case 'hashtag' : * var hashtag = match.getHashtag(); * console.log( hashtag ); * * return '<a href="http://newplace.to.link.hashtag.handles.to/">' + hashtag + '</a>'; * } * } * } ); * * * The function may return the following values: * * - `true` (Boolean): Allow Autolinker to replace the match as it normally would. * - `false` (Boolean): Do not replace the current match at all - leave as-is. * - Any String: If a string is returned from the function, the string will be used directly as the replacement HTML for * the match. * - An {@link Autolinker.HtmlTag} instance, which can be used to build/modify an HTML tag before writing out its HTML text. * * @constructor * @param {Object} [config] The configuration options for the Autolinker instance, specified in an Object (map). */ var Autolinker = function( cfg ) { Autolinker.Util.assign( this, cfg ); // assign the properties of `cfg` onto the Autolinker instance. Prototype properties will be used for missing configs. // Validate the value of the `hashtag` cfg. var hashtag = this.hashtag; if( hashtag !== false && hashtag !== 'twitter' && hashtag !== 'facebook' && hashtag !== 'instagram' ) { throw new Error( "invalid `hashtag` cfg - see docs" ); } }; Autolinker.prototype = { constructor : Autolinker, // fix constructor property /** * @cfg {Boolean} urls * * `true` if miscellaneous URLs should be automatically linked, `false` if they should not be. */ urls : true, /** * @cfg {Boolean} email * * `true` if email addresses should be automatically linked, `false` if they should not be. */ email : true, /** * @cfg {Boolean} twitter * * `true` if Twitter handles ("@example") should be automatically linked, `false` if they should not be. */ twitter : true, /** * @cfg {Boolean} phone * * `true` if Phone numbers ("(555)555-5555") should be automatically linked, `false` if they should not be. */ phone: true, /** * @cfg {Boolean/String} hashtag * * A string for the service name to have hashtags (ex: "#myHashtag") * auto-linked to. The currently-supported values are: * * - 'twitter' * - 'facebook' * - 'instagram' * * Pass `false` to skip auto-linking of hashtags. */ hashtag : false, /** * @cfg {Boolean} newWindow * * `true` if the links should open in a new window, `false` otherwise. */ newWindow : true, /** * @cfg {Boolean} stripPrefix * * `true` if 'http://' or 'https://' and/or the 'www.' should be stripped * from the beginning of URL links' text, `false` otherwise. */ stripPrefix : true, /** * @cfg {Number} truncate * * A number for how many characters long matched text should be truncated to inside the text of * a link. If the matched text is over this number of characters, it will be truncated to this length by * adding a two period ellipsis ('..') to the end of the string. * * For example: A url like 'http://www.yahoo.com/some/long/path/to/a/file' truncated to 25 characters might look * something like this: 'yahoo.com/some/long/pat..' */ truncate : undefined, /** * @cfg {String} className * * A CSS class name to add to the generated links. This class will be added to all links, as well as this class * plus match suffixes for styling url/email/phone/twitter/hashtag links differently. * * For example, if this config is provided as "myLink", then: * * - URL links will have the CSS classes: "myLink myLink-url" * - Email links will have the CSS classes: "myLink myLink-email", and * - Twitter links will have the CSS classes: "myLink myLink-twitter" * - Phone links will have the CSS classes: "myLink myLink-phone" * - Hashtag links will have the CSS classes: "myLink myLink-hashtag" */ className : "", /** * @cfg {Function} replaceFn * * A function to individually process each match found in the input string. * * See the class's description for usage. * * This function is called with the following parameters: * * @cfg {Autolinker} replaceFn.autolinker The Autolinker instance, which may be used to retrieve child objects from (such * as the instance's {@link #getTagBuilder tag builder}). * @cfg {Autolinker.match.Match} replaceFn.match The Match instance which can be used to retrieve information about the * match that the `replaceFn` is currently processing. See {@link Autolinker.match.Match} subclasses for details. */ /** * @private * @property {Autolinker.htmlParser.HtmlParser} htmlParser * * The HtmlParser instance used to skip over HTML tags, while finding text nodes to process. This is lazily instantiated * in the {@link #getHtmlParser} method. */ htmlParser : undefined, /** * @private * @property {Autolinker.matchParser.MatchParser} matchParser * * The MatchParser instance used to find matches in the text nodes of an input string passed to * {@link #link}. This is lazily instantiated in the {@link #getMatchParser} method. */ matchParser : undefined, /** * @private * @property {Autolinker.AnchorTagBuilder} tagBuilder * * The AnchorTagBuilder instance used to build match replacement anchor tags. Note: this is lazily instantiated * in the {@link #getTagBuilder} method. */ tagBuilder : undefined, /** * Automatically links URLs, Email addresses, Phone numbers, Twitter * handles, and Hashtags found in the given chunk of HTML. Does not link * URLs found within HTML tags. * * For instance, if given the text: `You should go to http://www.yahoo.com`, * then the result will be `You should go to * &lt;a href="http://www.yahoo.com"&gt;http://www.yahoo.com&lt;/a&gt;` * * This method finds the text around any HTML elements in the input * `textOrHtml`, which will be the text that is processed. Any original HTML * elements will be left as-is, as well as the text that is already wrapped * in anchor (&lt;a&gt;) tags. * * @param {String} textOrHtml The HTML or text to autolink matches within * (depending on if the {@link #urls}, {@link #email}, {@link #phone}, * {@link #twitter}, and {@link #hashtag} options are enabled). * @return {String} The HTML, with matches automatically linked. */ link : function( textOrHtml ) { if( !textOrHtml ) { return ""; } // handle `null` and `undefined` var htmlParser = this.getHtmlParser(), htmlNodes = htmlParser.parse( textOrHtml ), anchorTagStackCount = 0, // used to only process text around anchor tags, and any inner text/html they may have resultHtml = []; for( var i = 0, len = htmlNodes.length; i < len; i++ ) { var node = htmlNodes[ i ], nodeType = node.getType(), nodeText = node.getText(); if( nodeType === 'element' ) { // Process HTML nodes in the input `textOrHtml` if( node.getTagName() === 'a' ) { if( !node.isClosing() ) { // it's the start <a> tag anchorTagStackCount++; } else { // it's the end </a> tag anchorTagStackCount = Math.max( anchorTagStackCount - 1, 0 ); // attempt to handle extraneous </a> tags by making sure the stack count never goes below 0 } } resultHtml.push( nodeText ); // now add the text of the tag itself verbatim } else if( nodeType === 'entity' || nodeType === 'comment' ) { resultHtml.push( nodeText ); // append HTML entity nodes (such as '&nbsp;') or HTML comments (such as '<!-- Comment -->') verbatim } else { // Process text nodes in the input `textOrHtml` if( anchorTagStackCount === 0 ) { // If we're not within an <a> tag, process the text node to linkify var linkifiedStr = this.linkifyStr( nodeText ); resultHtml.push( linkifiedStr ); } else { // `text` is within an <a> tag, simply append the text - we do not want to autolink anything // already within an <a>...</a> tag resultHtml.push( nodeText ); } } } return resultHtml.join( "" ); }, /** * Process the text that lies in between HTML tags, performing the anchor * tag replacements for the matches, and returns the string with the * replacements made. * * This method does the actual wrapping of matches with anchor tags. * * @private * @param {String} str The string of text to auto-link. * @return {String} The text with anchor tags auto-filled. */ linkifyStr : function( str ) { return this.getMatchParser().replace( str, this.createMatchReturnVal, this ); }, /** * Creates the return string value for a given match in the input string, * for the {@link #linkifyStr} method. * * This method handles the {@link #replaceFn}, if one was provided. * * @private * @param {Autolinker.match.Match} match The Match object that represents the match. * @return {String} The string that the `match` should be replaced with. This is usually the anchor tag string, but * may be the `matchStr` itself if the match is not to be replaced. */ createMatchReturnVal : function( match ) { // Handle a custom `replaceFn` being provided var replaceFnResult; if( this.replaceFn ) { replaceFnResult = this.replaceFn.call( this, this, match ); // Autolinker instance is the context, and the first arg } if( typeof replaceFnResult === 'string' ) { return replaceFnResult; // `replaceFn` returned a string, use that } else if( replaceFnResult === false ) { return match.getMatchedText(); // no replacement for the match } else if( replaceFnResult instanceof Autolinker.HtmlTag ) { return replaceFnResult.toAnchorString(); } else { // replaceFnResult === true, or no/unknown return value from function // Perform Autolinker's default anchor tag generation var tagBuilder = this.getTagBuilder(), anchorTag = tagBuilder.build( match ); // returns an Autolinker.HtmlTag instance return anchorTag.toAnchorString(); } }, /** * Lazily instantiates and returns the {@link #htmlParser} instance for this Autolinker instance. * * @protected * @return {Autolinker.htmlParser.HtmlParser} */ getHtmlParser : function() { var htmlParser = this.htmlParser; if( !htmlParser ) { htmlParser = this.htmlParser = new Autolinker.htmlParser.HtmlParser(); } return htmlParser; }, /** * Lazily instantiates and returns the {@link #matchParser} instance for this Autolinker instance. * * @protected * @return {Autolinker.matchParser.MatchParser} */ getMatchParser : function() { var matchParser = this.matchParser; if( !matchParser ) { matchParser = this.matchParser = new Autolinker.matchParser.MatchParser( { urls : this.urls, email : this.email, twitter : this.twitter, phone : this.phone, hashtag : this.hashtag, stripPrefix : this.stripPrefix } ); } return matchParser; }, /** * Returns the {@link #tagBuilder} instance for this Autolinker instance, lazily instantiating it * if it does not yet exist. * * This method may be used in a {@link #replaceFn} to generate the {@link Autolinker.HtmlTag HtmlTag} instance that * Autolinker would normally generate, and then allow for modifications before returning it. For example: * * var html = Autolinker.link( "Test google.com", { * replaceFn : function( autolinker, match ) { * var tag = autolinker.getTagBuilder().build( match ); // returns an {@link Autolinker.HtmlTag} instance * tag.setAttr( 'rel', 'nofollow' ); * * return tag; * } * } ); * * // generated html: * // Test <a href="http://google.com" target="_blank" rel="nofollow">google.com</a> * * @return {Autolinker.AnchorTagBuilder} */ getTagBuilder : function() { var tagBuilder = this.tagBuilder; if( !tagBuilder ) { tagBuilder = this.tagBuilder = new Autolinker.AnchorTagBuilder( { newWindow : this.newWindow, truncate : this.truncate, className : this.className } ); } return tagBuilder; } }; /** * Automatically links URLs, Email addresses, Phone Numbers, Twitter handles, * and Hashtags found in the given chunk of HTML. Does not link URLs found * within HTML tags. * * For instance, if given the text: `You should go to http://www.yahoo.com`, * then the result will be `You should go to &lt;a href="http://www.yahoo.com"&gt;http://www.yahoo.com&lt;/a&gt;` * * Example: * * var linkedText = Autolinker.link( "Go to google.com", { newWindow: false } ); * // Produces: "Go to <a href="http://google.com">google.com</a>" * * @static * @param {String} textOrHtml The HTML or text to find matches within (depending * on if the {@link #urls}, {@link #email}, {@link #phone}, {@link #twitter}, * and {@link #hashtag} options are enabled). * @param {Object} [options] Any of the configuration options for the Autolinker * class, specified in an Object (map). See the class description for an * example call. * @return {String} The HTML text, with matches automatically linked. */ Autolinker.link = function( textOrHtml, options ) { var autolinker = new Autolinker( options ); return autolinker.link( textOrHtml ); }; // Autolinker Namespaces Autolinker.match = {}; Autolinker.htmlParser = {}; Autolinker.matchParser = {};
var expect = require("chai").expect; var hooks = require("./hooks"); module.exports = function (helpers) { var component = helpers.mount(require.resolve("./index"), { name: "Frank" }); expect(component.el.querySelector(".foo .name").innerHTML).to.equal("Frank"); expect(hooks.getHookNames("foo")).to.deep.equal([ "create", "render", "mount" ]); expect(hooks.getHookNames("root")).to.deep.equal([ "create", "render", "mount" ]); hooks.reset(); component.input = { name: "John" }; component.update(); expect(component.el.querySelector(".foo .name").innerHTML).to.equal("John"); expect(hooks.getHookNames("foo")).to.deep.equal(["render", "update"]); expect(hooks.getHookNames("root")).to.deep.equal(["render", "update"]); };
$(document).ready(function() { function draw_sub_nav(formScope) { // Draws the proper sub navigation // Special cases for different nav drawing if (formScope == "orders") { draw_orders_nav(formScope); return; } else if (formScope == "users") { draw_users_nav(formScope); return; } // Controller that handles returning nav list in json jsonUrl = '/admins/control_get/' + formScope; // Everytime we draw a sub navigation clear the #form_holder and #messages $('#form_holder').html(''); $('#messages').html(''); // Make the ajax call and draw the list items $.get(jsonUrl, function(list) { var buf = "<ul>"; buf += "<li data-id='add' data-scope='" + formScope + "'><b>Add New</b></li>"; for(var i=0; i<list.length; i++) { buf += "<li data-id='" + list[i].id + "' data-scope='" + formScope + "'>" + list[i].name + "</li>"; } buf += "</ul>"; $('#sub_nav').html(buf); }, 'json'); } function draw_orders_nav(formScope) { // Draws the proper sub navigation jsonUrl = '/admins/control_get/orders/'; // Everytime we draw a sub navigation clear the #form_holder and #messages $('#form_holder').html(''); $('#messages').html(''); $.get(jsonUrl, function(list) { var buf = "<ul>"; // Sort by items that need to be shipped list.sort(function compare(a,b) { if (a.shipped < b.shipped) return -1; if (a.shipped > b.shipped) return 1; return 0; }); for(var i=0; i<list.length; i++) { buf += "<li data-id='" + list[i].id + "' data-scope='" + formScope + "'>"; if (list[i].shipped == 0) { buf += "<strong>"; } buf += "Order #: " + list[i].id; if (list[i].shipped == 0) { buf += "</strong>"; } buf += "</li>"; } buf += "</ul>"; $('#sub_nav').html(buf); }, 'json'); } function draw_users_nav(formScope) { // Draws the proper sub navigation jsonUrl = '/admins/control_get/' + formScope; // Everytime we draw a sub navigation clear the #form_holder and #messages $('#form_holder').html(''); $('#messages').html(''); $.get(jsonUrl, function(list) { var buf = "<ul>"; for(var i=0; i<list.length; i++) { buf += "<li data-id='" + list[i].id + "' data-scope='" + formScope + "'>" + "(" + list[i].id + ") " + list[i].email + "</li>"; } buf += "</ul>"; $('#sub_nav').html(buf); }, 'json'); } $(document).on('click', '#products, #gems, #galleries, #orders, #users', function(e){ url = '/admins/control_get/' + e.target.id; scope = e.target.id; draw_sub_nav(scope); }); // Creating the add/edit forms $(document).on('click', "li[data-scope]", function(e) { var id = $(this).data('id'); var scope = $(this).data('scope'); $('#messages').html(''); $.get('/admins/make_form/' + scope + '/' + id, function(res) { $('#form_holder').html(res); }, 'html'); }); $(document).on('submit',"#edit_form", function(e) { var scope = $(this).data('scope'); var url = '/admins/control_edit/' + scope; $.post(url, $(this).serialize(), function(res) { if (res.success) { // Redraw the subnav for inserted items draw_sub_nav(scope); } $('#messages').html(res.message); }, 'json'); return false; }); $(document).on('click','.del-item', function(e) { if (confirm('Are you sure you want to delete this?')) { var this_id = $(this).data('id'); var scope = $(this).data('scope'); $.get('/admins/control_delete/' + scope + '/' + this_id, function(res) { if (res.success) { // Redraw the subnav for inserted items draw_sub_nav(scope); } $('#messages').html(res.message); }, 'json'); } }); });
'use strict'; module.exports = { up: function (queryInterface, Sequelize) { return queryInterface.bulkInsert('Skus', [ { "name": "FOCUS B JR", "code": "FGJ01FOCUB", "categoryId": 1, "colorId": 4, "genderId": 3, "createdAt": new Date(), "updatedAt": new Date() },{ "name": "LATIO B", "code": "FGJ01LATIO", "categoryId": 2, "colorId": 4, "genderId": 3, "createdAt": new Date(), "updatedAt": new Date() },{ "name": "LIBERTY B JR", "code": "FGJ01LIBEB", "categoryId": 1, "colorId": 2, "genderId": 3, "createdAt": new Date(), "updatedAt": new Date() },{ "name": "ARUMBA B", "code": "FGJ04ARUMB", "categoryId": 1, "colorId": 4, "genderId": 1, "createdAt": new Date(), "updatedAt": new Date() },{ "name": "VALLEN BM", "code": "FGW07VALLENBM", "categoryId": 1, "colorId": 4, "genderId": 2, "createdAt": new Date(), "updatedAt": new Date() }], {}); }, down: function (queryInterface, Sequelize) { return queryInterface.bulkDelete('Skus', null, {}); } };
const DrawCard = require('../../drawcard.js'); class RecruiterForTheWatch extends DrawCard { setupCardAbilities(ability) { this.persistentEffect({ match: this, effect: ability.effects.optionalStandDuringStanding() }); this.action({ title: 'Take control of character', phase: 'marshal', cost: ability.costs.kneelSelf(), target: { activePromptTitle: 'Select character with printed cost 2 or less', cardCondition: card => card.getType() === 'character' && card.controller !== this.controller && card.getCost(true) <= 2 }, handler: context => { this.game.addMessage('{0} kneels {1} to take control of {2}', this.controller, this, context.target); this.lastingEffect(ability => ({ until: { onCardStood: event => event.card === this, onCardLeftPlay: event => event.card === this }, match: context.target, effect: ability.effects.takeControl(this.controller) })); } }); } } RecruiterForTheWatch.code = '06045'; module.exports = RecruiterForTheWatch;
import React from 'react' import { Dimmer, Image, Segment } from 'semantic-ui-react' const DimmerExampleActive = () => ( <Segment> <Dimmer active /> <p> <Image src='/assets/images/wireframe/short-paragraph.png' /> </p> <p> <Image src='/assets/images/wireframe/short-paragraph.png' /> </p> </Segment> ) export default DimmerExampleActive
// Copyright 2009 the Sputnik authors. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /** * @name: S9.3.1_A5_T2; * @section: 9.3.1, 15.7.1; * @assertion: The MV of StrDecimalLiteral::: - StrUnsignedDecimalLiteral is the negative * of the MV of StrUnsignedDecimalLiteral. (the negative of this 0 is also 0); * @description: Compare Number('-[or +]any_number') with -[or without -]any_number); */ // CHECK#1 if (Number("1") !== 1) { $ERROR('#1: Number("1") === 1'); } // CHECK#2 if (Number("+1") !== 1) { $ERROR('#3: Number("+1") === 1'); } // CHECK#3 if (Number("-1") !== -1) { $ERROR('#3: Number("-1") === -1'); } // CHECK#4 if (Number("2") !== 2) { $ERROR('#4: Number("2") === 2'); } // CHECK#5 if (Number("+2") !== 2) { $ERROR('#5: Number("+2") === 2'); } // CHECK#6 if (Number("-2") !== -2) { $ERROR('#6: Number("-2") === -2'); } // CHECK#7 if (Number("3") !== 3) { $ERROR('#7: Number("3") === 3'); } // CHECK#8 if (Number("+3") !== 3) { $ERROR('#8: Number("+3") === 3'); } // CHECK#9 if (Number("-3") !== -3) { $ERROR('#9: Number("-3") === -3'); } // CHECK#10 if (Number("4") !== 4) { $ERROR('#10: Number("4") === 4'); } // CHECK#11 if (Number("+4") !== 4) { $ERROR('#11: Number("+4") === 4'); } // CHECK#12 if (Number("-4") !== -4) { $ERROR('#12: Number("-4") === -4'); } // CHECK#13 if (Number("5") !== 5) { $ERROR('#13: Number("5") === 5'); } // CHECK#14 if (Number("+5") !== 5) { $ERROR('#14: Number("+5") === 5'); } // CHECK#15 if (Number("-5") !== -5) { $ERROR('#15: Number("-5") === -5'); } // CHECK#16 if (Number("6") !== 6) { $ERROR('#16: Number("6") === 6'); } // CHECK#17 if (Number("+6") !== 6) { $ERROR('#17: Number("+6") === 6'); } // CHECK#18 if (Number("-6") !== -6) { $ERROR('#18: Number("-6") === -6'); } // CHECK#19 if (Number("7") !== 7) { $ERROR('#19: Number("7") === 7'); } // CHECK#20 if (Number("+7") !== 7) { $ERROR('#20: Number("+7") === 7'); } // CHECK#21 if (Number("-7") !== -7) { $ERROR('#21: Number("-7") === -7'); } // CHECK#22 if (Number("8") !== 8) { $ERROR('#22: Number("8") === 8'); } // CHECK#23 if (Number("+8") !== 8) { $ERROR('#23: Number("+8") === 8'); } // CHECK#24 if (Number("-8") !== -8) { $ERROR('#24: Number("-8") === -8'); } // CHECK#25 if (Number("9") !== 9) { $ERROR('#25: Number("9") === 9'); } // CHECK#26 if (Number("+9") !== 9) { $ERROR('#26: Number("+9") === 9'); } // CHECK#27 if (Number("-9") !== -9) { $ERROR('#27: Number("-9") === -9'); }
/////////////////////////////////////////////////////////////////////////// // Copyright © Esri. All Rights Reserved. // // 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. /////////////////////////////////////////////////////////////////////////// define([ "dojo/_base/lang", 'jimu/utils', "dojo/date", "dojo/_base/array", 'dojo/dom-construct', 'dijit/form/DateTextBox', 'dijit/form/NumberSpinner', 'dijit/form/NumberTextBox', 'dijit/form/FilteringSelect', 'dijit/form/TextBox', 'dijit/form/ValidationTextBox', 'dijit/form/TimeTextBox', "dijit/Editor", "dijit/form/SimpleTextarea", 'dojo/store/Memory' ], function ( lang, jimuUtils, date, array, domConstruct, DateTextBox, NumberSpinner, NumberTextBox, FilteringSelect, TextBox, ValidationTextBox, TimeTextBox, Editor, SimpleTextarea, Memory ) { var mo = {}; mo.integerFields = [ "esriFieldTypeSmallInteger", "esriFieldTypeInteger", "esriFieldTypeSingle", "esriFieldTypeDouble"]; mo.getFieldInfoByFieldName = function (fieldInfos, fieldName) { var fieldInfo = {}; array.some(fieldInfos, function (field) { if (field.name === fieldName) { lang.mixin(fieldInfo, field); return true; } }); return fieldInfo; }; mo.getDateFromRelativeInfo = function (relativeDateInfos, localize) { var currentDate = new Date(); if (relativeDateInfos.dateType === "fixed") { if (relativeDateInfos.dateTime) { currentDate = new Date(relativeDateInfos.dateTime); } else { currentDate = ""; } } else if (relativeDateInfos.dateType === "future") { currentDate = date.add(currentDate, "year", relativeDateInfos.year); currentDate = date.add(currentDate, "month", relativeDateInfos.month); currentDate = date.add(currentDate, "day", relativeDateInfos.day); currentDate = date.add(currentDate, "hour", relativeDateInfos.hour); currentDate = date.add(currentDate, "minute", relativeDateInfos.minute); currentDate = date.add(currentDate, "second", relativeDateInfos.second); } else if (relativeDateInfos.dateType === "past") { if (relativeDateInfos.year) { currentDate = date.add(currentDate, "year", -1 * relativeDateInfos.year); } if (relativeDateInfos.month) { currentDate = date.add(currentDate, "month", -1 * relativeDateInfos.month); } if (relativeDateInfos.day) { currentDate = date.add(currentDate, "day", -1 * relativeDateInfos.day); } if (relativeDateInfos.hour) { currentDate = date.add(currentDate, "hour", -1 * relativeDateInfos.hour); } if (relativeDateInfos.minute) { currentDate = date.add(currentDate, "minute", -1 * relativeDateInfos.minute); } if (relativeDateInfos.second) { currentDate = date.add(currentDate, "second", -1 * relativeDateInfos.second); } } if (localize && currentDate !== "") { return jimuUtils.localizeDate(currentDate); } return currentDate; }; mo.getDateFieldValue = function (field, dijit) { var newFieldVal; // Convert to epoch time if fieldType is date/time if (field.type === "esriFieldTypeDate") { if (dijit instanceof Array) { var dateObj, timeObj; // Get individual date & time values for sync if (dijit.length > 0 && dijit[0]) { dateObj = dijit[0].getValue(); } if (dijit.length > 1 && dijit[1]) { timeObj = dijit[1].getValue(); } if (dateObj && timeObj) { newFieldVal = new Date( dateObj.getFullYear(), dateObj.getMonth(), dateObj.getDate(), timeObj.getHours(), timeObj.getMinutes(), timeObj.getSeconds(), timeObj.getMilliseconds() ); } else { newFieldVal = dateObj || timeObj || null; } } else { newFieldVal = dijit.getValue(); if (field.domain) { newFieldVal = Number(newFieldVal); } } newFieldVal = (newFieldVal && newFieldVal.getTime) ? newFieldVal.getTime() : (newFieldVal && newFieldVal.toGregorian ? newFieldVal.toGregorian().getTime() : newFieldVal); } return newFieldVal; }; mo.isGuid = function (value) { if (value[0] === "{") { value = value.substring(1, value.length - 1); } var regexGuid = /^(\{){0,1}[0-9a-fA-F]{8}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{12}(\}){0,1}$/gi; return regexGuid.test(value); }; mo.validateGUID = function (value, constraints) { constraints = constraints; return this.isGuid(value); }; mo.isValidPresetValue = function (nodes) { var isValid = true; array.some(nodes, function (node) { if (node.isValid && !node.isValid()) { isValid = false; return true; } }); return isValid; }; mo.createPresetFieldContentNode = function (fieldInfo) { var nodes = []; var node; if (fieldInfo.domain) { // domain.type = codedValue if (fieldInfo.domain.type === "codedValue") { var domainValues = fieldInfo.domain.codedValues; var options = []; array.forEach(domainValues, function (dv) { options.push({ name: dv.name, id: dv.code }); }); node = new FilteringSelect({ "class": "ee-inputField", name: fieldInfo.fieldName, store: new Memory({ data: options }), searchAttr: "name", required:false }, domConstruct.create("div")); } else { //domain.type = range var cons = null; switch (fieldInfo.type) { case "esriFieldTypeSmallInteger": case "esriFieldTypeInteger": cons = { min: fieldInfo.domain.minValue, max: fieldInfo.domain.maxValue, places: 0 }; break; case "esriFieldTypeSingle": case "esriFieldTypeDouble": cons = { min: fieldInfo.domain.minValue, max: fieldInfo.domain.maxValue }; break; } node = new NumberSpinner({ "class": "ee-inputField", name: fieldInfo.fieldName, smallDelta: 1, constraints: cons }, domConstruct.create("div")); } nodes.push(node); } else { switch (fieldInfo.type) { case "esriFieldTypeGUID": node = new ValidationTextBox({ "class": "ee-inputField", name: fieldInfo.fieldName }, domConstruct.create("div")); node.validator = lang.hitch(this, this.validateGUID); nodes.push(node); break; case "esriFieldTypeDate": node = new DateTextBox({ "class": "ee-inputField", name: fieldInfo.fieldName }, domConstruct.create("div")); //value: new Date(), nodes.push(node); if (fieldInfo.format) { if (fieldInfo.format.time && fieldInfo.format.time === true) { var timeNode = new TimeTextBox({ "class": "ee-inputField", "style": "margin-top:2px;" }, domConstruct.create("div")); nodes.push(timeNode); //value: new Date() } } break; case "esriFieldTypeString": var maxlength = null; if (fieldInfo.length && Number(fieldInfo.length) && Number(fieldInfo.length) > 0) { maxlength = fieldInfo.length; } if (fieldInfo.hasOwnProperty("stringFieldOption")) { if (fieldInfo.stringFieldOption === "richtext") { var params = { 'class': 'ee-inputField ee-inputFieldRichText', trim: true, maxLength: maxlength }; params['class'] += ' atiRichTextField'; params.height = '100%'; params.width = '100%'; params.name = fieldInfo.fieldName; params.plugins = ['bold', 'italic', 'underline', 'foreColor', 'hiliteColor', '|', 'justifyLeft', 'justifyCenter', 'justifyRight', 'justifyFull', '|', 'insertOrderedList', 'insertUnorderedList', 'indent', 'outdent', '|', 'createLink']; node = new Editor(params, domConstruct.create("div")); node.startup(); } else if (fieldInfo.stringFieldOption === "textarea") { node = new SimpleTextarea({ "class": "ee-inputField ee-inputFieldTextArea", name: fieldInfo.fieldName, maxlength: maxlength }, domConstruct.create("div")); } else { node = new TextBox({ "class": "ee-inputField", name: fieldInfo.fieldName, maxlength: maxlength }, domConstruct.create("div")); } } else { node = new TextBox({ "class": "ee-inputField", name: fieldInfo.fieldName, maxlength: maxlength }, domConstruct.create("div")); } nodes.push(node); break; // todo: check for more types case "esriFieldTypeSmallInteger": case "esriFieldTypeInteger": node = new NumberTextBox({ "class": "ee-inputField", name: fieldInfo.fieldName, constraints: { places: 0 } }, domConstruct.create("div")); nodes.push(node); break; case "esriFieldTypeSingle": case "esriFieldTypeDouble": node = new NumberTextBox({ "class": "ee-inputField", name: fieldInfo.fieldName }, domConstruct.create("div")); nodes.push(node); break; default: node = new TextBox({ "class": "ee-unsupportField", name: fieldInfo.fieldName, value: "N/A", readOnly: true }, domConstruct.create("div")); nodes.push(node); break; } } return nodes; }; mo.changeFieldToMostRestrictive = function (existingField, newField) { if (!existingField.hasOwnProperty('type') && newField.hasOwnProperty('type')) { return newField; } if (newField.length && Number(newField.length) && Number(newField.length) > 0) { if (existingField.length && Number(existingField.length)) { if (newField.length < existingField.length) { existingField.length = newField.length; } } else { existingField.length = newField.length; } } if (existingField.type === newField.type) { switch (newField.type) { case "esriFieldTypeString": if (existingField.hasOwnProperty("stringFieldOption") && newField.hasOwnProperty("stringFieldOption")) { if (existingField.stringFieldOption === "richtext" && newField.stringFieldOption !== "richtext") { existingField.stringFieldOption = newField.stringFieldOption; } else if (existingField.stringFieldOption === "textarea" && newField.stringFieldOption === "textbox") { existingField.stringFieldOption = newField.stringFieldOption; } } break; } } return existingField; }; return mo; });
/*! * Ext JS Library 3.1.1 * Copyright(c) 2006-2010 Ext JS, LLC * licensing@extjs.com * http://www.extjs.com/license */ Ext.app.App = function(cfg){ Ext.apply(this, cfg); this.addEvents({ 'ready' : true, 'beforeunload' : true }); Ext.onReady(this.initApp, this); }; Ext.extend(Ext.app.App, Ext.util.Observable, { isReady: false, startMenu: null, modules: null, getStartConfig : function(){ }, initApp : function(){ this.startConfig = this.startConfig || this.getStartConfig(); this.desktop = new Ext.Desktop(this); this.launcher = this.desktop.taskbar.startMenu; this.modules = this.getModules(); if(this.modules){ this.initModules(this.modules); } this.init(); Ext.EventManager.on(window, 'beforeunload', this.onUnload, this); this.fireEvent('ready', this); this.isReady = true; }, getModules : Ext.emptyFn, init : Ext.emptyFn, initModules : function(ms){ for(var i = 0, len = ms.length; i < len; i++){ var m = ms[i]; this.launcher.add(m.launcher); m.app = this; } }, getModule : function(name){ var ms = this.modules; for(var i = 0, len = ms.length; i < len; i++){ if(ms[i].id == name || ms[i].appType == name){ return ms[i]; } } return ''; }, onReady : function(fn, scope){ if(!this.isReady){ this.on('ready', fn, scope); }else{ fn.call(scope, this); } }, getDesktop : function(){ return this.desktop; }, onUnload : function(e){ if(this.fireEvent('beforeunload', this) === false){ e.stopEvent(); } } });
'use strict'; var gulp = require('gulp'); var merge = require('merge-stream'); var uglify = require('gulp-uglify'); var uglifycss = require('gulp-uglifycss'); var bower = require('gulp-bower'); var concat = require('gulp-concat'); var mainBowerFiles = require('main-bower-files'); var sass = require('gulp-sass'); var less = require('gulp-less'); var flatten = require('gulp-flatten'); var eslint = require('gulp-eslint'); //Output destination var base = ''; var dest = 'public/dist/'; var vendorDest = 'public/dist/vendor/'; const mainPaths = { js: [ 'public/js/module.js', 'public/js/directives/**/*.js', 'public/js/controllers/**/*.js' ], css: [ 'public/css/app.css' ] }; //Run bower gulp.task('bower', function () { return bower(); }); //Concatenate and minify iotdash JS gulp.task('js', function () { gulp.src(mainPaths.js) .pipe(concat('main.js')) .pipe(uglify({ mangle: false })) .pipe(gulp.dest(dest + 'js')); }); //Concatenate and minify vendor CSS gulp.task('css', function () { gulp.src(mainPaths.css, { base: base }) .pipe(concat('app.css')) .pipe(uglifycss()) .pipe(gulp.dest(dest + 'css')); }); //Concatenate and minify vendor JS gulp.task('vendorJs', function () { gulp.src(mainBowerFiles('**/*.js')) .pipe(concat('vendor.js')) .pipe(uglify()) .pipe(gulp.dest(vendorDest + 'js')); }); //Concatenate and minify vendor CSS gulp.task('vendorCss', function () { var lessStream = gulp.src(mainBowerFiles('**/*.less')) .pipe(less()) .pipe(concat('less-files.less')); var scssStream = gulp.src(mainBowerFiles('**/*.scss')) .pipe(sass()) .pipe(concat('scss-files.scss')); var cssStream = gulp.src(mainBowerFiles('**/*.css')) .pipe(concat('css-files.css')); var mergedStream = merge(scssStream, lessStream, cssStream) .pipe(concat('style.css')) .pipe(uglifycss()) .pipe(gulp.dest(vendorDest + 'css')); return mergedStream; }); gulp.task('vendorFonts', function () { return gulp.src('./bower_components/**/*.{eot,svg,ttf,woff,woff2}', { base: base }) .pipe(flatten()) .pipe(gulp.dest(vendorDest + 'fonts')); }); //Lint everything using elsint gulp.task('lint', function () { return gulp.src(['**/**.js', '!gulpfile.js', '!public/dist/**', '!node_modules/**', '!bower_components/**']) .pipe(eslint()) .pipe(eslint.format()) .pipe(eslint.failAfterError()); }); gulp.task('default', ['bower', 'lint', 'js', 'css', 'vendorFonts', 'vendorJs', 'vendorCss']);
/*! jQuery UI - v1.10.3 - 2013-09-04 * http://jqueryui.com * Copyright 2013 jQuery Foundation and other contributors; Licensed MIT */ jQuery(function(e){e.datepicker.regional["pt-BR"]={closeText:"Fechar",prevText:"&#x3C;Anterior",nextText:"Próximo&#x3E;",currentText:"Hoje",monthNames:["Janeiro","Fevereiro","Março","Abril","Maio","Junho","Julho","Agosto","Setembro","Outubro","Novembro","Dezembro"],monthNamesShort:["Jan","Fev","Mar","Abr","Mai","Jun","Jul","Ago","Set","Out","Nov","Dez"],dayNames:["Domingo","Segunda-feira","Terça-feira","Quarta-feira","Quinta-feira","Sexta-feira","Sábado"],dayNamesShort:["Dom","Seg","Ter","Qua","Qui","Sex","Sáb"],dayNamesMin:["Dom","Seg","Ter","Qua","Qui","Sex","Sáb"],weekHeader:"Sm",dateFormat:"dd/mm/yy",firstDay:0,isRTL:!1,showMonthAfterYear:!1,yearSuffix:""},e.datepicker.setDefaults(e.datepicker.regional["pt-BR"])});
(function ($) { var link = '<a href="http://airstream.com/$1">$1</a>', list = [/\B(@[\w]*)/g, /\B(#[\w]*)/g]; $.fn.autolink = function () { return this.each(function () { var elm = $(this); $.each(list, function (i, regex) { elm.html(elm.html().replace(regex, link)); }); }); }; })(jQuery);
// @flow const foo = require('./a'); module.exports = () => foo();
// Generated by LiveScript 1.5.0 /** * @package Static pages * @category modules * @author Nazar Mokrynskyi <nazar@mokrynskyi.com> * @license 0BSD */ (function(){ Polymer({ is: 'cs-static-pages-admin-pages-list', behaviors: [cs.Polymer.behaviors.Language('static_pages_')], properties: { category: Number, pages: Array }, observers: ['_reload_pages(category)'], _reload_pages: function(){ var this$ = this; cs.api("get api/Static_pages/admin/categories/" + this.category + "/pages").then(function(pages){ this$.set('pages', pages); }); }, _add: function(){ cs.ui.simple_modal("<h3>" + this.L.adding_of_page + "</h3>\n<cs-static-pages-admin-pages-add-edit-form category=\"" + this.category + "\"/>").addEventListener('close', bind$(this, '_reload_pages')); }, _edit: function(e){ var title; title = this.L.editing_of_page(e.model.item.title); cs.ui.simple_modal("<h2>" + title + "</h2>\n<cs-static-pages-admin-pages-add-edit-form id=\"" + e.model.item.id + "\"/>").addEventListener('close', bind$(this, '_reload_pages')); }, _delete: function(e){ var this$ = this; cs.ui.confirm(this.L.sure_to_delete_page(e.model.item.title)).then(function(){ return cs.api('delete api/Static_pages/admin/pages/' + e.model.item.id); }).then(function(){ cs.ui.notify(this$.L.changes_saved, 'success', 5); this$._reload_pages(); }); } }); function bind$(obj, key, target){ return function(){ return (target || obj)[key].apply(obj, arguments) }; } }).call(this);
/*! * jQuery FormHelp Plugin Sample * https://github.com/invetek/jquery-formhelp * * Copyright 2013 Loran Kloeze - Invetek * Released under the MIT license */ $(document).ready(function() { //Normal operation $.formHelp({pushpinEnabled: true}); //Operation with a class prefix $.formHelp( {classPrefix: 'myprefix', pushpinEnabled: false} ); });
'use strict'; const _ = require('lodash'), urlParse = require('url'), { replaceVersion } = require('clayutils'); let propagatingVersions = ['published', 'latest']; /** * @param {[string]} value */ function setPropagatingVersions(value) { propagatingVersions = value; } /** * @returns {[string]} */ function getPropagatingVersions() { return propagatingVersions; } /** * @param {object} obj * @param {Function} [filter=_.identity] Optional filter * @returns {array} */ function listDeepObjects(obj, filter) { let cursor, items, list = [], queue = [obj]; while (queue.length) { cursor = queue.pop(); items = _.filter(cursor, _.isObject); list = list.concat(_.filter(items, filter || _.identity)); queue = queue.concat(items); } return list; } /** * @param {string} version * @returns {function} */ function replaceAllVersions(version) { return function (data) { _.each(listDeepObjects(data, '_ref'), function (obj) { obj._ref = replaceVersion(obj._ref, version); }); return data; }; } /** * Some versions should propagate throughout the rest of the data. * @param {string} uri * @returns {boolean} */ function isPropagatingVersion(uri) { const version = uri.split('@')[1]; return !!version && _.includes(propagatingVersions, version); } /** * @param {string} url * @returns {boolean} */ function isUrl(url) { const parts = _.isString(url) && urlParse.parse(url); return !!parts && !!parts.protocol && !!parts.hostname && !!parts.path; } /** * @param {string} uri * @returns {boolean} */ function isUri(uri) { return _.isString(uri) && uri.indexOf(':') === -1; } /** * Take the protocol and port from a sourceUrl and apply them to some uri * @param {string} uri * @param {string} [protocol] * @param {string} [port] * @returns {string} */ function uriToUrl(uri, protocol, port) { // just pretend to start with http; it's overwritten two lines down const parts = urlParse.parse('http://' + uri); parts.protocol = protocol || 'http'; parts.port = port || process.env.PORT; delete parts.host; if (parts.port && (parts.protocol === 'http' && parts.port.toString() === '80') || parts.protocol === 'https' && parts.port.toString() === '443' ) { delete parts.port; } return parts.format(); } /** * Remove protocol and port * @param {string} url * @returns {string} */ function urlToUri(url) { let parts; if (!isUrl(url)) { throw new Error('Invalid url ' + url); } parts = urlParse.parse(url); return `${parts.hostname}${decodeURIComponent(parts.path)}`; } /** * Remove the configuration properties of a page, leaving only page-level references * @param {object} pageData * @returns {object} */ function omitPageConfiguration(pageData) { return _.omit(pageData, ['_dynamic', 'layout', 'url', 'urlHistory', 'customUrl', 'lastModified', 'priority', 'changeFrequency']); } /** * Returns the list of all page-level references in page data, removing layout, url, etc. * * @param {object} pageData * @returns {[string]} */ function getPageReferences(pageData) { return _.flatten(_.values(omitPageConfiguration(pageData))); } module.exports.replaceVersion = replaceVersion; module.exports.replaceAllVersions = replaceAllVersions; module.exports.setPropagatingVersions = setPropagatingVersions; module.exports.getPropagatingVersions = getPropagatingVersions; module.exports.isPropagatingVersion = isPropagatingVersion; module.exports.isUrl = isUrl; module.exports.isUri = isUri; module.exports.uriToUrl = uriToUrl; module.exports.urlToUri = urlToUri; module.exports.omitPageConfiguration = omitPageConfiguration; module.exports.getPageReferences = getPageReferences; module.exports.listDeepObjects = listDeepObjects;
console.log([1,2,3,4].slice(1)); console.log([].slice.call([1,2,3,4],1)); console.log([].slice.call({length: 3, 0: 1, 1: 2, 2: 3 }, 1));