code
stringlengths
2
1.05M
repo_name
stringlengths
5
114
path
stringlengths
4
991
language
stringclasses
1 value
license
stringclasses
15 values
size
int32
2
1.05M
/** * File: app/pancity/ui/PanCityLog.js * Author: liusha */ Ext.define('zhwh.pancity.ui.PanCityLog', { extend: 'Ext.panel.Panel', id: 'PanCityLog', layout: { type: 'border' }, closable: true, iconCls: 'service_tabs', title: '平安城市维护日志', initComponent: function() { var me = this; me.items = [ { xtype: 'form', height: 80, defaults: { labelWidth: 60 }, layout: { type: 'column' }, bodyPadding: 10, bodyStyle: 'background-color:#d8e6f4', collapsed: true, collapsible: true, //floatable: false, titleCollapse: true, title: '查询日志', region: 'north', items: [ { xtype: 'combobox', labelWidth: 40, width: 256, margin: '2 20 10 0', name: 'V_CAM_NO', fieldLabel: '编号', queryParam: 'V_CAM_NAME', queryMode: 'remote', minChars: 1, queryDelay: 200, store: me.panCityInfoStore, displayField: 'V_CAM_NAME_VIEW', valueField: 'V_CAM_NO_VIEW' }, { xtype: 'datefield', margin: '2 20 10 0', name: 'D_LOG_TIME_START', fieldLabel: '日志时间', vtype: 'dateRange', dateRange: {begin: 'D_LOG_TIME_START', end: 'D_LOG_TIME_END', parent: me}, format: 'Y年m月d日', submitFormat: 'Y-m-d', editable: false }, { xtype: 'datefield', margin: '2 20 10 0', name: 'D_LOG_TIME_END', fieldLabel: '到', vtype: 'dateRange', dateRange: {begin: 'D_LOG_TIME_START', end: 'D_LOG_TIME_END', parent: me}, labelWidth: 20, format: 'Y年m月d日', submitFormat: 'Y-m-d', editable: false }, { xtype: 'button', margin: '2 10 10 0', iconCls: 'search_btn', text: '查找' }, { xtype: 'button', margin: '2 20 10 0', iconCls: 'reset_btn', text: '重置' } ] }, { xtype: 'gridpanel', region: 'center', store: me.panCityLogStore, columns: [ { xtype: 'gridcolumn', hidden: true, dataIndex: 'ID_VIEW', hideable: false, text: 'ID' }, { xtype: 'gridcolumn', width: 100, dataIndex: 'V_CAM_NO_VIEW', text: '监控点编号' }, { xtype: 'gridcolumn', width: 200, dataIndex: 'V_CAM_NAME_VIEW', text: '监控点名称' }, { xtype: 'gridcolumn', width: 120, dataIndex: 'V_STREET_VIEW', text: '所属街道' }, { xtype: 'gridcolumn', width: 300, dataIndex: 'V_CONTENT_VIEW', text: '维护内容及存在问题' }, { xtype: 'templatecolumn', dataIndex: 'N_STATUS_VIEW', text: '是否恢复', tpl: '<tpl if="N_STATUS_VIEW == 1"><p style="color:green">已恢复</p></tpl><tpl if="N_STATUS_VIEW == 0"><p style="color:red">未恢复</p></tpl>' }, { xtype: 'gridcolumn', width: 100, dataIndex: 'V_RESULT_VIEW', text: '处理结果' }, { xtype: 'datecolumn', width: 150, dataIndex: 'D_LOG_TIME_VIEW', text: '日志时间', format: 'Y-m-d H:i:s' }, { xtype: 'gridcolumn', dataIndex: 'V_USER_NAME_VIEW', text: '登记人' }, { xtype: 'gridcolumn', width: 300, dataIndex: 'V_REMARK_VIEW', text: '备注' } ], viewConfig: { }, dockedItems: [ { xtype: 'toolbar', dock: 'top', items: [ { xtype: 'button', iconCls: 'add_btn', text: '增加日志' }, { xtype: 'tbseparator' }, { xtype: 'button', iconCls: 'modify_btn', text: '修改日志' }, { xtype: 'tbseparator' }, { xtype: 'button', iconCls: 'remove_btn', text: '删除日志' }, { xtype: 'tbseparator' }, { xtype: 'button', iconCls: 'ext_xls', text: '导出' } ] }, { xtype: 'pagingtoolbar', displayInfo: true, store: me.panCityLogStore, dock: 'bottom' } ] } ]; me.callParent(arguments); } });
flowsha/zhwh
web_root/app/static/app/pancity/ui/PanCityLog.js
JavaScript
apache-2.0
7,235
import { shallow } from 'enzyme'; import React from 'react'; import { ApiError, InternalError, RequestError } from 'redux-api-middleware'; import Error from '../../src/components/Error.jsx'; function setup(error) { return shallow(<Error error={error} />) } describe('Error', () => { it('should render generic error', () => { const enzymeWrapper = setup(new Error()) expect(enzymeWrapper.find('div').hasClass('error')).toBe(true) expect(enzymeWrapper.find('div').text()).toEqual('An unknown error occurred. Please contact your friendly QuotaService owners for help.') }) it('should render InternalError', () => { const enzymeWrapper = setup(new InternalError()) expect(enzymeWrapper.find('div').hasClass('error')).toBe(true) expect(enzymeWrapper.find('div').text()).toEqual('An unknown error occurred. Please contact your friendly QuotaService owners for help.') }) it('should render ApiError', () => { let enzymeWrapper = setup(new ApiError(400, 'bad request')) expect(enzymeWrapper.find('div').hasClass('error')).toBe(true) expect(enzymeWrapper.find('div').text()).toEqual('An error occurred: "bad request"') enzymeWrapper = setup(new ApiError(400, 'bad request', { description: 'This is the description.' })) expect(enzymeWrapper.find('div').hasClass('error')).toBe(true) expect(enzymeWrapper.find('div').text()).toEqual('This is the description.') }) it('should render RequestError', () => { let enzymeWrapper = setup(new RequestError('network timeout')) expect(enzymeWrapper.find('div').hasClass('error')).toBe(true) expect(enzymeWrapper.find('div').text()).toEqual('A network error occurred: "network timeout"') }) })
maniksurtani/qs
admin/public/__tests__/components/Error-test.js
JavaScript
apache-2.0
1,708
// Licensed to Cloudera, Inc. under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. Cloudera, Inc. licenses this file // to you 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. var SentryViewModel = (function () { var Authorizable = function (vm, privilege, authorizable) { var self = this; self.type = ko.observable(typeof authorizable.type != "undefined" && authorizable.type != null ? authorizable.type : ""); self.type.subscribe(function () { if (privilege.status() == '') { privilege.status('modified'); } }); self.name_ = ko.observable(typeof authorizable.name != "undefined" && authorizable.name != null ? authorizable.name : ""); self.name_.subscribe(function () { if (privilege.status() == '') { privilege.status('modified'); } }); } var Privilege = function (vm, privilege) { var self = this; self.id = ko.observable(typeof privilege.id != "undefined" && privilege.id != null ? privilege.id : ""); self.roleName = ko.observable(typeof privilege.roleName != "undefined" && privilege.roleName != null ? privilege.roleName : ""); self.status = ko.observable(typeof privilege.status != "undefined" && privilege.status != null ? privilege.status : ""); self.editing = ko.observable(typeof privilege.editing != "undefined" && privilege.editing != null ? privilege.editing : false); self.serverName = ko.observable(typeof privilege.serverName != "undefined" && privilege.serverName != null ? privilege.serverName : ""); self.serverName.subscribe(function () { if (self.status() == '') { self.status('modified'); } }); self.component = ko.observable(typeof privilege.component != "undefined" && privilege.component != null ? privilege.component : vm.component()); self.authorizables = ko.observableArray(); if (typeof privilege.authorizables != "undefined" && privilege.authorizables != null) { self.authorizables( $.map(privilege.authorizables, function(authorizable) { return new Authorizable(vm, privilege, authorizable); }) ) }; self.authorizables.subscribe(function () { if (self.status() == '') { self.status('modified'); } }); self.action = ko.observable(typeof privilege.action != "undefined" && privilege.action != null ? privilege.action : 'SELECT'); self.action.subscribe(function () { if (self.status() == '') { self.status('modified'); } }); self.timestamp = ko.observable(typeof privilege.timestamp != "undefined" && privilege.timestamp != null ? privilege.timestamp : 0); self.grantorPrincipal = ko.observable(typeof privilege.grantorPrincipal != "undefined" && privilege.grantorPrincipal != null ? privilege.grantorPrincipal : vm.user()); self.grantOption = ko.observable(typeof privilege.grantOption != "undefined" && privilege.grantOption != null ? privilege.grantOption : false); self.grantOption.subscribe(function () { if (self.status() == '') { self.status('modified'); } }); // UI self.privilegeType = ko.computed(function() { var last = self.authorizables().slice(-1)[0]; return last ? last.type().toUpperCase() : 'SERVER'; }); self.showAdvanced = ko.observable(false); self.path = ko.computed({ read: function () { if (vm.component() == 'solr') { return $.map(self.authorizables(), function (authorizable) { if (authorizable.name_() !== '') { if (authorizable.type() === 'COLLECTION') { return 'collections.' + authorizable.name_(); } else { return 'configs.' + authorizable.name_(); } } }).join(""); } else { return $.map(self.authorizables(), function (authorizable) { if (authorizable.name_() !== '') { return authorizable.name_(); } }).join("."); } }, write: function (value) { var _parts = value.split("."); self.authorizables.removeAll(); if (vm.component() == 'solr') { if (_parts[0] == 'collections') { self.authorizables.push(new Authorizable(vm, self, {type: 'COLLECTION', name: _parts[1]})) } else if (_parts[0] == 'configs') { self.authorizables.push(new Authorizable(vm, self, {type: 'CONFIG', name: _parts[1]})) } else if (_parts[0] == 'admin') { self.authorizables.push(new Authorizable(vm, self, {type: 'ADMIN', name: _parts[1]})) } } else { self.authorizables.push(new Authorizable(vm, self, {type: 'DATABASE', name: _parts[0]})) if (_parts.length > 1) { self.authorizables.push(new Authorizable(vm, self, {type: 'TABLE', name: _parts[1]})) } if (_parts.length > 2) { self.authorizables.push(new Authorizable(vm, self, {type: 'COLUMN', name: _parts[2]})) } } }, owner: self }); self.indexerPath = ko.computed(function () { if (self.authorizables().length > 0 && self.authorizables()[0].type() == 'COLLECTION') { return '/indexer/#edit/' + self.authorizables()[0].name_(); } else { return '/indexer/#manage'; } }); self.metastorePath = ko.computed(function() { var path = ''; if (self.authorizables()[0] && self.authorizables()[0]['type'] == 'DATABASE') { path = '/metastore/tables/' + self.authorizables()[0]; } if (self.authorizables()[1] && self.authorizables()[1]['type'] == 'TABLE') { path += "/" + self.authorizables()[1]; } if (self.authorizables()[2] && self.authorizables()[2]['type'] == 'COLUMN') { path += "#col=" + self.authorizables()[2]; } return path; }); self.remove = function (privilege) { if (privilege.status() == 'new') { privilege.status('alreadydeleted'); } else { privilege.status('deleted'); } } } var Role = function (vm, role) { var self = this; self.name = ko.observable(typeof role.name != "undefined" && role.name != null ? role.name : ""); self.name.subscribe(function (value){ var _found = false; vm.role().isEditing(false); ko.utils.arrayForEach(vm.roles(), function (role) { if (role.name() == value){ vm.role(role); _found = true; } }); if (_found) { vm.role().isEditing(true); vm.list_sentry_privileges_by_role(vm.role()); $(document).trigger("destroyTypeahead"); } }); self.selected = ko.observable(false); self.handleSelect = function (row, e) { self.selected(!self.selected()); } self.groups = ko.observableArray(); self.originalGroups = ko.observableArray(); self.groups.extend({ rateLimit: 300 }); self.originalGroups.extend({ rateLimit: 300 }); $.each(typeof role.groups != "undefined" && role.groups != null ? role.groups : [], function (index, group) { self.groups.push(group); self.originalGroups.push(group); }); self.privileges = ko.observableArray(); // Not included in the API self.privilegesForViewTo = ko.observable(49); self.originalPrivileges = ko.observableArray(); self.showPrivileges = ko.observable(false); self.showPrivileges.subscribe(function (value) { var _expanded = vm.expandedRoles(); if (value) { if (_expanded.indexOf(self.name()) == -1) { _expanded.push(self.name()); } } else { if (_expanded.indexOf(self.name()) > -1) { _expanded.splice(_expanded.indexOf(self.name()), 1); } } vm.expandedRoles(_expanded); }); self.showEditGroups = ko.observable(false); self.isEditing = ko.observable(false); self.isValid = ko.computed(function () { return self.name().length > 0 && $.grep(self.privileges(), function (privilege) { return privilege.path() === ''; }).length === 0; }); self.privilegesChanged = ko.computed(function () { return $.grep(self.privileges(), function (privilege) { return ['new', 'deleted', 'modified'].indexOf(privilege.status()) != -1; }); }); self.groupsChanged = ko.computed(function () { return !($(self.groups()).not(self.originalGroups()).length == 0 && $(self.originalGroups()).not(self.groups()).length == 0); }); self.groupsChanged.extend({ rateLimit: 300 }); self.privilegesForView = ko.computed(function() { var _filter = vm.privilegeFilter().toLowerCase(); if (_filter == "") { return self.privileges().slice(0, self.privilegesForViewTo()); } else { var _filtered = ko.utils.arrayFilter(self.privileges(), function (priv) { return $.grep(priv.authorizables(), function(auth) { return auth.name_().toLowerCase().indexOf(_filter) > -1; }).length > 0 || priv.action().toLowerCase().indexOf(_filter) > -1; }); return _filtered.slice(0, self.privilegesForViewTo()); } }); self.reset = function () { self.name(''); self.groups.removeAll(); self.privileges.removeAll(); self.originalPrivileges.removeAll(); self.isEditing(false); } self.addGroup = function () { self.groups.push(''); } self.addPrivilege = function () { var privilege = new Privilege(vm, {'serverName': vm.assist.server(), 'status': 'new', 'editing': true}); if (vm.assist.path() && vm.getSectionHash() == 'edit') { privilege.path(vm.assist.path()); } self.privileges.push(privilege); } self.resetGroups = function () { self.groups.removeAll(); $.each(self.originalGroups(), function (index, group) { self.groups.push(group); }); } self.saveGroups = function () { $(".jHueNotify").remove(); $.post("/security/api/sentry/update_role_groups", { role: ko.mapping.toJSON(self), component: vm.component() }, function (data) { if (data.status == 0) { self.showEditGroups(false); self.originalGroups.removeAll(); $.each(self.groups(), function (index, group) { self.originalGroups.push(group); }); } else { $(document).trigger("error", data.message); } }).fail(function (xhr, textStatus, errorThrown) { $(document).trigger("error", xhr.responseText); }); } self.create = function () { $(".jHueNotify").remove(); if (self.isValid()) { $.post("/security/api/sentry/create_role", { role: ko.mapping.toJSON(self), component: vm.component() }, function (data) { if (data.status == 0) { $(document).trigger("info", data.message); vm.showCreateRole(false); self.reset(); var role = new Role(vm, data.role); role.showPrivileges(true); vm.originalRoles.unshift(role); vm.list_sentry_privileges_by_authorizable(); $(document).trigger("createdRole"); } else { $(document).trigger("error", data.message); } }).fail(function (xhr, textStatus, errorThrown) { $(document).trigger("error", xhr.responseText); }); } } self.update = function () { $(".jHueNotify").remove(); if (self.isValid()) { $.post("/security/api/sentry/save_privileges", { role: ko.mapping.toJSON(self), component: vm.component() }, function (data) { if (data.status == 0) { $(document).trigger("info", data.message); vm.showCreateRole(false); vm.list_sentry_privileges_by_authorizable(); $(document).trigger("createdRole"); } else { $(document).trigger("error", data.message); } }).fail(function (xhr, textStatus, errorThrown) { $(document).trigger("error", xhr.responseText); }); } } self.remove = function (role) { $(".jHueNotify").remove(); $.post("/security/api/sentry/drop_sentry_role", { roleName: role.name, component: vm.component() }, function (data) { if (data.status == 0) { vm.removeRole(role.name()); vm.list_sentry_privileges_by_authorizable(); $(document).trigger("removedRole"); } else { $(document).trigger("error", data.message); } }).fail(function (xhr, textStatus, errorThrown) { $(document).trigger("error", xhr.responseText); }); } self.savePrivileges = function (role) { $(".jHueNotify").remove(); $.post("/security/api/sentry/save_privileges", { role: ko.mapping.toJSON(role), component: vm.component() }, function (data) { if (data.status == 0) { vm.list_sentry_privileges_by_authorizable(); $(document).trigger("createdRole"); } else { $(document).trigger("error", data.message); } }).fail(function (xhr, textStatus, errorThrown) { $(document).trigger("error", xhr.responseText); }); } } var Assist = function (vm, initial) { var self = this; self.compareNames = function (a, b) { if (a.name.toLowerCase() < b.name.toLowerCase()) return -1; if (a.name.toLowerCase() > b.name.toLowerCase()) return 1; return 0; } self.path = ko.observable(""); self.path.subscribe(function (path) { vm.updatePathHash(path); }); self.server = ko.observable(initial.sentry_provider); self.db = ko.computed(function () { var db = self.path().split(/[.]/)[0]; return db ? db : null; }); self.table = ko.computed(function () { var table = self.path().split(/[.]/)[1]; return table ? table : null; }); self.column = ko.computed(function () { var column = self.path().split(/[.]/)[2]; return column ? column : null; }); self.indexerPath = ko.computed(function () { if (self.table()) { return '/indexer/#edit/' + self.table(); } else { return '/indexer/#manage'; } }); self.metastorePath = ko.computed(function(){ if (self.column()) { return '/metastore/table/' + self.db() + "/" + self.table() + "#col=" + self.column(); } else if (self.table()) { return '/metastore/table/' + self.db() + "/" + self.table(); } else if (self.db()) { return '/metastore/tables/' + self.db(); } else { return '/metastore/databases'; } }); self.privileges = ko.observableArray(); self.roles = ko.observableArray(); self.isDiffMode = ko.observable(false); self.isDiffMode = ko.observable(false); self.isDiffMode.subscribe(function () { self.refreshTree(); }); self.isLoadingTree = ko.observable(false); self.treeAdditionalData = {}; self.treeData = ko.observable({nodes: []}); self.loadData = function (data) { self.treeData(new TreeNodeModel(data)); }; self.initialGrowingTree = { path: "__HUEROOT__", name: "__HUEROOT__", selected: false, nodes: [{ path: "", name: self.server(), withPrivileges: false, isServer: true, isDb: false, isTable: false, isColumn: false, isExpanded: true, isLoaded: true, isChecked: false, nodes: [] }] }; self.growingTree = ko.observable(jQuery.extend(true, {}, self.initialGrowingTree)); self.checkedItems = ko.observableArray([]); self.addDatabases = function (path, databases, skipLoading) { var _tree = self.growingTree().nodes[0]; databases.forEach(function (db) { var _mainFound = false; _tree.nodes.forEach(function (node) { if (node.path == db) { _mainFound = true; } }); if (!_mainFound) { var _item = { path: db, name: db, withPrivileges: false, isServer: false, isDb: true, isTable: false, isColumn: false, isExpanded: false, isLoaded: false, isChecked: false, nodes: [] }; _tree.nodes.push(_item); } }); if (typeof skipLoading == "undefined" || !skipLoading) { self.loadData(self.growingTree()); } } self.addTables = function (path, tablesMeta, skipLoading) { var _branch = self.growingTree().nodes[0]; _branch.nodes.forEach(function (node) { if (node.path == path) { _branch = node; } }); tablesMeta.forEach(function (tableMeta) { var _mainFound = false; var _path = path + "." + tableMeta.name; _branch.nodes.forEach(function (node) { if (node.path == _path) { _mainFound = true; } }); if (!_mainFound) { var _item = { path: _path, name: tableMeta.name, withPrivileges: false, isServer: false, isDb: false, isTable: true, isColumn: false, isExpanded: false, isLoaded: false, isChecked: false, nodes: [] }; _branch.nodes.push(_item); } }); if (typeof skipLoading == "undefined" || !skipLoading) { self.loadData(self.growingTree()); } } self.addColumns = function (path, columns, skipLoading) { var _branch = self.growingTree().nodes[0]; _branch.nodes.forEach(function (node) { if (node.path == path.split(".")[0]) { node.nodes.forEach(function (inode) { if (inode.path == path) { _branch = inode; } }); } }); columns.forEach(function (column) { var _mainFound = false; var _path = path + "." + column; _branch.nodes.forEach(function (node) { if (node.path == _path) { _mainFound = true; } }); if (!_mainFound) { var _item = { path: _path, name: column, withPrivileges: false, isServer: false, isDb: false, isTable: false, isColumn: true, isExpanded: false, isLoaded: false, isChecked: false, nodes: [] }; _branch.nodes.push(_item); } }); if (typeof skipLoading == "undefined" || !skipLoading) { self.loadData(self.growingTree()); } } self.collapseTree = function () { self.updateTreeProperty(self.growingTree(), "isExpanded", false); self.updatePathProperty(self.growingTree(), "__HUEROOT__", "isExpanded", true); self.updatePathProperty(self.growingTree(), "", "isExpanded", true); self.loadData(self.growingTree()); } self.collapseOthers = function () { self.updateTreeProperty(self.growingTree(), "isExpanded", false); self.updatePathProperty(self.growingTree(), "__HUEROOT__", "isExpanded", true); self.updatePathProperty(self.growingTree(), "", "isExpanded", true); var _path = self.path(); var _crumb = ""; for (var i = 0; i < _path.length; i++) { if ((_path[i] === "." && _crumb != "")) { self.updatePathProperty(self.growingTree(), _crumb, "isExpanded", true); } _crumb += _path[i]; } self.updatePathProperty(self.growingTree(), _path, "isExpanded", true); self.loadData(self.growingTree()); } self.expandTree = function () { self.updateTreeProperty(self.growingTree(), "isExpanded", true); self.loadData(self.growingTree()); } self.refreshTree = function (force) { self.growingTree(jQuery.extend(true, {}, self.initialGrowingTree)); // load root first self.fetchAuthorizablesPath("", function () { Object.keys(self.treeAdditionalData).forEach(function (path) { if (path.indexOf(".") == -1 && path != "") { if (typeof force == "boolean" && force) { self.fetchAuthorizablesPath(path); } else { if (self.treeAdditionalData[path].loaded) { self.fetchAuthorizablesPath(path, function () { self.updatePathProperty(self.growingTree(), path, "isExpanded", self.treeAdditionalData[path].expanded); var _withTable = false; Object.keys(self.treeAdditionalData).forEach(function (ipath) { if (ipath.split(".").length == 2 && ipath.split(".")[0] == path) { self.fetchAuthorizablesPath(ipath, function () { _withTable = true; self.updatePathProperty(self.growingTree(), ipath, "isExpanded", self.treeAdditionalData[ipath].expanded); self.loadData(self.growingTree()); }); } }); if (! _withTable){ self.loadData(self.growingTree()); } }); } } } }); }); vm.list_sentry_privileges_by_authorizable(); } self.setPath = function (obj, toggle, skipListAuthorizable) { if (self.getTreeAdditionalDataForPath(obj.path()).loaded || (!obj.isExpanded() && !self.getTreeAdditionalDataForPath(obj.path()).loaded)) { if (typeof toggle == "boolean" && toggle) { obj.isExpanded(!obj.isExpanded()); self.getTreeAdditionalDataForPath(obj.path()).expanded = obj.isExpanded(); } self.updatePathProperty(self.growingTree(), obj.path(), "isExpanded", obj.isExpanded()); } else { if (typeof toggle == "boolean" && toggle) { obj.isExpanded(!obj.isExpanded()); } else { obj.isExpanded(false); } self.getTreeAdditionalDataForPath(obj.path()).expanded = obj.isExpanded(); self.updatePathProperty(self.growingTree(), obj.path(), "isExpanded", obj.isExpanded()); } if (vm.component() === 'solr' && obj.path() !== '' && obj.path().indexOf('.') == -1) { self.path(obj.path() + '.*'); } else { self.path(obj.path()); } $(document).trigger("changedPath"); if (self.getTreeAdditionalDataForPath(obj.path()).loaded){ if (typeof skipListAuthorizable == "undefined" || !skipListAuthorizable) { vm.list_sentry_privileges_by_authorizable(); } } else { self.fetchAuthorizablesPath(); } } self.togglePath = function (obj) { self.setPath(obj, true); } self.showAuthorizable = function (obj, e) { e.preventDefault(); e.stopPropagation(); e.stopImmediatePropagation(); self.fetchAuthorizablesPath(obj.path(), function (data) { if (vm.component() === 'solr') { location.href = data.authorizable_link; } else { location.href = "/security/hdfs#" + data.hdfs_link.substring("/filebrowser/view=".length); } }); } self.getCheckedItems = function (leaf, checked) { if (leaf == null){ leaf = self.growingTree(); } if (checked == null){ checked = [] } if (leaf.isChecked){ checked.push(leaf); } if (leaf.nodes.length > 0) { leaf.nodes.forEach(function (node) { self.getCheckedItems(node, checked); }); } return checked; } self.checkPath = function (obj) { obj.isChecked(!obj.isChecked()); self.updatePathProperty(self.growingTree(), obj.path(), "isChecked", obj.isChecked()); self.checkedItems(self.getCheckedItems()); } self.getTreeAdditionalDataForPath = function (path) { if (typeof self.treeAdditionalData[path] == "undefined") { var _add = { loaded: false, expanded: true } self.treeAdditionalData[path] = _add; } return self.treeAdditionalData[path]; } self.updatePathProperty = function (leaf, path, property, value) { if (leaf.path == path) { leaf[property] = value; } if (leaf.nodes.length > 0) { leaf.nodes.forEach(function (node) { self.updatePathProperty(node, path, property, value); }); } return leaf; } self.updateTreeProperty = function (leaf, property, value) { leaf[property] = value; if (leaf.nodes.length > 0) { leaf.nodes.forEach(function (node) { self.updateTreeProperty(node, property, value); }); } return leaf; } self.loadParents = function (callback) { self.fetchAuthorizablesPath("", function () { self.updatePathProperty(self.growingTree(), "", "isExpanded", true); var _crumbs = self.path().split("."); self.fetchAuthorizablesPath(_crumbs[0], function () { self.updatePathProperty(self.growingTree(), _crumbs[0], "isExpanded", true); if (_crumbs.length > 1) { self.fetchAuthorizablesPath(_crumbs[0] + "." + _crumbs[1], function () { self.updatePathProperty(self.growingTree(), _crumbs[0] + "." + _crumbs[1], "isExpanded", true); self.loadData(self.growingTree()); if (typeof callback != "undefined") { callback(); } else { self.collapseOthers(); vm.list_sentry_privileges_by_authorizable(); } }); } else { self.loadData(self.growingTree()); if (typeof callback != "undefined") { callback(); } else { self.collapseOthers(); vm.list_sentry_privileges_by_authorizable(); } } }); }); } self.fetchAuthorizablesPath = function (optionalPath, loadCallback) { var _originalPath = typeof optionalPath != "undefined" ? optionalPath : self.path(); if (vm.component() === 'solr' && _originalPath.indexOf('.*') > -1) { _originalPath = _originalPath.split('.')[0]; } if (_originalPath.split(".").length < 4) { self.isLoadingTree(true); var _path = _originalPath.replace('.', '/'); var request = { url: '/security/api/sentry/fetch_authorizables', data: { 'path': _path, 'component': vm.component(), 'doas': vm.doAs(), 'isDiffMode': self.isDiffMode() }, dataType: 'json', type: 'GET', success: function (data) { var _hasCallback = typeof loadCallback != "undefined"; self.getTreeAdditionalDataForPath(_originalPath).loaded = true; self.updatePathProperty(self.growingTree(), _originalPath, "isLoaded", true); if (data.databases) { self.addDatabases(_originalPath, data.databases, _hasCallback); if (vm.getPathHash() == ""){ self.setPath(self.treeData().nodes()[0], false, true); } } else if (data.tables_meta && data.tables_meta.length > 0) { self.addTables(_originalPath, data.tables_meta, _hasCallback); } else if (data.columns && data.columns.length > 0) { self.addColumns(_originalPath, data.columns, _hasCallback); } self.isLoadingTree(false); if (_hasCallback) { loadCallback(data); } else { vm.list_sentry_privileges_by_authorizable(); } }, cache: false }; $.ajax(request).fail(function (xhr, textStatus, errorThrown) { $(document).trigger("error", xhr.responseText); }); } else { vm.list_sentry_privileges_by_authorizable(); } }; self.afterRender = function () { $(document).trigger("renderedTree"); } } var SentryViewModel = function (initial) { var self = this; self.isLoadingRoles = ko.observable(false); self.isLoadingPrivileges = ko.observable(true); self.isApplyingBulk = ko.observable(false); self.availablePrivileges = ko.observableArray(); self.availableSolrConfigActions = ko.observableArray(); if (initial.component == 'solr') { self.availableActions = function () { return ko.observableArray(['QUERY', 'UPDATE', 'ALL']); } self.availableSolrConfigActions(['ALL']); } else { self.availableActions = function (authorizables) { var actions = ['SELECT', 'INSERT', 'ALL']; var databaseActions = ['CREATE']; var tableActions = ['REFRESH']; // 'ALTER', 'DROP' if (authorizables.length < 2) { // server and database actions = actions.concat(databaseActions).concat(tableActions); } else { actions = actions.concat(tableActions); } return ko.observableArray(actions.sort()); } } self.privilegeFilter = ko.observable(""); // Models self.component = ko.observable(initial.component); self.user = ko.observable(initial.user); self.server = ko.observable(initial.sentry_provider); self.roles = ko.observableArray(); self.tempRoles = ko.observableArray(); self.originalRoles = ko.observableArray(); self.roleFilter = ko.observable(""); self.filteredRoles = ko.computed(function () { var _filter = self.roleFilter().toLowerCase(); if (!_filter) { return self.roles(); } else { return ko.utils.arrayFilter(self.roles(), function (role) { var _inGroups = false; role.groups().forEach(function (group) { if (group.toLowerCase().indexOf(_filter) > -1) { _inGroups = true; } }); var _inPrivileges = false; role.privileges().forEach(function (priv) { var matches = $.grep(priv.authorizables(), function(auth) { return auth.name_().toLowerCase().indexOf(_filter) > -1; }); if (matches.length > 0 || priv.action().toLowerCase().indexOf(_filter) > -1) { _inPrivileges = true; } }); return role.name().toLowerCase().indexOf(_filter) > -1 || _inGroups || _inPrivileges; }); } }, self); self.selectableRoles = ko.computed(function () { var _roles = ko.utils.arrayMap(self.roles(), function (role) { return role.name(); }); return _roles.sort(); }, self); self.is_sentry_admin = initial.is_sentry_admin; self.availableHadoopGroups = ko.observableArray(); self.assist = new Assist(self, initial); // Editing self.showCreateRole = ko.observable(false); self.role = ko.observable(new Role(self, {})); self.roleToUpdate = ko.observable(); self.grantToPrivilege = ko.observable(); self.grantToPrivilegeRole = ko.observable(); self.resetCreateRole = function() { self.roles(self.originalRoles()); self.role(new Role(self, {})); $(document).trigger("createTypeahead"); }; self.deletePrivilegeModal = function (role) { var cascadeDeletes = $.grep(role.privilegesChanged(), function (privilege) { return privilege.status() == 'deleted' && (privilege.privilegeType() == 'SERVER' || privilege.privilegeType() == 'DATABASE'); }); if (cascadeDeletes.length > 0) { self.roleToUpdate(role); huePubSub.publish('show.delete.privilege.modal'); } else { self.role().savePrivileges(role); } }; self.privilege = new Privilege(self, {}); self.doAs = ko.observable(initial.user); self.doAs.subscribe(function () { self.assist.refreshTree(); }); self.availableHadoopUsers = ko.observableArray(); self.selectableHadoopUsers = ko.computed(function () { var _users = ko.utils.arrayMap(self.availableHadoopUsers(), function (user) { return user.username; }); return _users.sort(); }, self); self.selectableHadoopGroups = ko.computed(function () { var _groups = ko.utils.arrayMap(self.availableHadoopGroups(), function (group) { return group.name; }); _groups.push(""); return _groups.sort(); }, self); self.selectAllRoles = function () { self.allRolesSelected(!self.allRolesSelected()); ko.utils.arrayForEach(self.roles(), function (role) { role.selected(false); }); ko.utils.arrayForEach(self.filteredRoles(), function (role) { role.selected(self.allRolesSelected()); }); return true; }; self.allRolesSelected = ko.observable(false); self.selectedRoles = ko.computed(function () { return ko.utils.arrayFilter(self.roles(), function (role) { return role.selected(); }); }, self); self.selectedRole = ko.computed(function () { return self.selectedRoles()[0]; }, self); self.deleteSelectedRoles = function () { ko.utils.arrayForEach(self.selectedRoles(), function (role) { role.remove(role); }); $(document).trigger("deletedRole"); }; self.expandSelectedRoles = function () { ko.utils.arrayForEach(self.selectedRoles(), function (role) { if (! role.showPrivileges()) { self.list_sentry_privileges_by_role(role); } }); }; self.expandedRoles = ko.observableArray([]); self.init = function (path) { self.assist.isLoadingTree(true); self.isLoadingRoles(true); self.assist.path(path); window.setTimeout(function(){ self.fetchUsers(); self.list_sentry_roles_by_group(); if (path != "") { self.assist.loadParents(); } else { self.assist.fetchAuthorizablesPath(); } }, 100); }; self.removeRole = function (roleName) { $.each(self.roles(), function (index, role) { if (role.name() == roleName) { self.roles.remove(role); return false; } }); $.each(self.originalRoles(), function (index, role) { if (role.name() == roleName) { self.originalRoles.remove(role); return false; } }); }; self.list_sentry_roles_by_group = function () { self.isLoadingRoles(true); $.ajax({ type: "POST", url: "/security/api/sentry/list_sentry_roles_by_group", data: { 'groupName': $('#selectedGroup').val(), 'component': self.component() }, success: function (data) { if (typeof data.status !== "undefined" && data.status == -1) { $(document).trigger("error", data.message); } else { self.roles.removeAll(); self.originalRoles.removeAll(); var _roles = []; var _originalRoles = []; $.each(data.roles, function (index, item) { _roles.push(new Role(self, item)); _originalRoles.push(new Role(self, item)); }); self.roles(_roles); self.originalRoles(_originalRoles); } } }).fail(function (xhr, textStatus, errorThrown) { $(document).trigger("error", xhr.responseText); }).always(function() { self.isLoadingRoles(false); }); }; self.refreshExpandedRoles = function () { ko.utils.arrayForEach(self.filteredRoles(), function (r) { if (self.expandedRoles().indexOf(r.name()) > -1){ self.list_sentry_privileges_by_role(r); } }); } self.showRole = function (role) { $(document).trigger("showRole", role); ko.utils.arrayForEach(self.filteredRoles(), function (r) { if (r.name() == role.name()){ self.list_sentry_privileges_by_role(r); } }); } self.list_sentry_privileges_by_role = function (role) { $.ajax({ type: "POST", url: "/security/api/sentry/list_sentry_privileges_by_role", data: { 'server': self.server(), 'component': self.component(), 'roleName': role.name }, success: function (data) { if (typeof data.status !== "undefined" && data.status == -1) { $(document).trigger("error", data.message); } else { role.privileges.removeAll(); role.originalPrivileges.removeAll(); $.each(data.sentry_privileges, function (index, item) { var privilege = _create_ko_privilege(item); var privilegeCopy = _create_ko_privilege(item); privilegeCopy.id(privilege.id()); role.privileges.push(privilege); role.originalPrivileges.push(privilegeCopy); }); role.showPrivileges(true); } } }).fail(function (xhr, textStatus, errorThrown) { $(document).trigger("error", xhr.responseText); }); }; function _create_ko_privilege(privilege) { var _privilege = new Privilege(self, { 'component': privilege.component, 'serverName': privilege.serviceName, 'authorizables': privilege.authorizables, 'action': privilege.action, 'timestamp': privilege.timestamp, 'grantorPrincipal': privilege.grantorPrincipal, 'grantOption': privilege.grantOption, 'id': hueUtils.UUID() }); return _privilege; } function _create_authorizable_from_ko(optionalPath) { var authorizables = []; var paths = optionalPath.split(/[.]/); if (self.component() == 'solr') { if (paths.length > 1) { if (paths[0] == 'admin') { authorizables.push({'type': 'ADMIN', 'name': paths[1]}); } else if (paths[0] == 'configs') { authorizables.push({'type': 'CONFIG', 'name': paths[1]}); } else { authorizables.push({'type': 'COLLECTION', 'name': paths[1]}); } } } else { // TODO Hive if (optionalPath != null) { if (paths[0]) { authorizables.push({'type': 'DATABASE', 'name': paths[0]}); } if (paths[1]) { authorizables.push({'type': 'TABLE', 'name': paths[1]}); } if (paths[2]) { authorizables.push({'type': 'COLUMN', 'name': paths[2]}); } } else { authorizables.push({'type': 'COLUMN', 'name': self.assist.db()}); authorizables.push({'type': 'TABLE', 'name': self.assist.table()}); authorizables.push({'type': 'COLUMN', 'name': self.assist.column()}); } } return { 'server': self.assist.server(), 'authorizables': authorizables }; } self.grant_privilege = function () { $(".jHueNotify").remove(); $.ajax({ type: "POST", url: "/security/api/sentry/grant_privilege", data: { 'privilege': ko.mapping.toJSON(self.grantToPrivilege()), 'roleName': ko.mapping.toJSON(self.grantToPrivilegeRole()), 'component': self.component() }, success: function (data) { if (data.status == 0) { $(document).trigger("info", data.message); self.assist.refreshTree(); self.clearTempRoles(); $(document).trigger("createdRole"); } else { $(document).trigger("error", data.message); } } }).fail(function (xhr, textStatus, errorThrown) { $(document).trigger("error", xhr.responseText); }); } self.clearTempRoles = function () { var _roles = []; self.roles().forEach(function(role){ var _found = false; self.tempRoles().forEach(function(tempRole){ if (role.name() == tempRole.name()){ _found = true; } }); if (! _found){ _roles.push(role); } }); self.roles(_roles); self.tempRoles([]); } self.list_sentry_privileges_by_authorizable = function (optionalPath, skipList) { var _path = self.assist.path(); if (optionalPath != null){ _path = optionalPath; } self.isLoadingPrivileges(true); self.assist.roles.removeAll(); self.assist.privileges.removeAll(); $.ajax({ type: "POST", url: "/security/api/sentry/list_sentry_privileges_by_authorizable", data: { server: self.server(), groupName: $('#selectedGroup').val(), roleSet: ko.mapping.toJSON({all: true, roles: []}), authorizableHierarchy: ko.mapping.toJSON(_create_authorizable_from_ko(_path)), component: self.component() }, success: function (data) { if (data.status == 0) { var _privileges = []; $.each(data.privileges, function (index, item) { if (typeof skipList == "undefined" || (skipList != null && typeof skipList == "Boolean" && !skipList)){ var _role = null; self.assist.roles().forEach(function (role) { if (role.name() == item.roleName) { _role = role; } }); if (_role == null) { var _idx = self.assist.roles.push(new Role(self, { name: item.roleName })); _role = self.assist.roles()[_idx - 1]; } var privilege = _create_ko_privilege(item); var privilegeCopy = _create_ko_privilege(item); privilegeCopy.id(privilege.id()); _role.privileges.push(privilege); _role.originalPrivileges.push(privilegeCopy); _privileges.push(privilege); } }); if (typeof skipList == "undefined" || (skipList != null && typeof skipList == "Boolean" && !skipList)) { self.assist.privileges(_privileges); } self.assist.loadData(self.assist.growingTree()); } else { $(document).trigger("error", data.message); } } }).fail(function (xhr, textStatus, errorThrown) { $(document).trigger("error", xhr.responseText); }).always(function() { self.isLoadingPrivileges(false); }); }; self.bulkAction = ko.observable(""); self.bulkPerfomAction = function () { switch (self.bulkAction()) { case "add": self.bulk_add_privileges(); break; case "sync": self.bulk_delete_privileges({norefresh: true}); self.bulk_add_privileges(); break; case "delete": self.bulk_delete_privileges(); break; } self.bulkAction(""); } self.bulk_delete_privileges = function (norefresh) { $(".jHueNotify").remove(); var checkedPaths = self.assist.checkedItems(); $.post("/security/api/sentry/bulk_delete_privileges", { 'authorizableHierarchy': ko.mapping.toJSON(_create_authorizable_from_ko()), 'checkedPaths': ko.mapping.toJSON(checkedPaths), 'recursive': false, 'component': self.component() }, function (data) { if (data.status == 0) { if (norefresh == undefined) { self.list_sentry_privileges_by_authorizable(); // Refresh $(document).trigger("deletedBulkPrivileges"); } } else { $(document).trigger("error", data.message); } }).fail(function (xhr, textStatus, errorThrown) { $(document).trigger("error", xhr.responseText); }); } self.bulk_add_privileges = function (role) { $(".jHueNotify").remove(); var checkedPaths = self.assist.checkedItems(); $.post("/security/api/sentry/bulk_add_privileges", { 'privileges': ko.mapping.toJSON(self.assist.privileges), 'authorizableHierarchy': ko.mapping.toJSON(_create_authorizable_from_ko()), 'checkedPaths': ko.mapping.toJSON(checkedPaths), 'recursive': false, 'component': self.component() }, function (data) { if (data.status == 0) { self.list_sentry_privileges_by_authorizable(); // Refresh $(document).trigger("addedBulkPrivileges"); } else { $(document).trigger("error", data.message); } }).fail(function (xhr, textStatus, errorThrown) { $(document).trigger("error", xhr.responseText); }); } self.bulk_refresh_privileges= function () { ko.utils.arrayForEach(self.assist.checkedItems(), function (item) { self.list_sentry_privileges_by_authorizable(item.path, true); }); }; self.fetchUsers = function () { var data = { 'count': 2000, 'include_myself': true, 'extend_user': true }; if (! self.is_sentry_admin) { data['only_mygroups'] = true; } $.getJSON('/desktop/api/users/autocomplete', data, function (data) { self.availableHadoopUsers(data.users); self.availableHadoopGroups(data.groups); $(document).trigger("loadedUsers"); }); } self.lastHash = ''; self.updatePathHash = function (path) { var _hash = window.location.hash.replace(/(<([^>]+)>)/ig, ""); if (_hash.indexOf("@") == -1) { window.location.hash = path; } else { window.location.hash = path + "@" + _hash.split("@")[1]; } self.lastHash = window.location.hash; } self.updateSectionHash = function (section) { var _hash = window.location.hash.replace(/(<([^>]+)>)/ig, ""); if (_hash == "") { window.location.hash = "@" + section; } if (_hash.indexOf("@") == -1) { window.location.hash = _hash + "@" + section; } else { window.location.hash = _hash.split("@")[0] + "@" + section; } self.lastHash = window.location.hash; } self.getPathHash = function () { if (window.location.hash != "") { var _hash = window.location.hash.substr(1).replace(/(<([^>]+)>)/ig, ""); if (_hash.indexOf("@") > -1) { return _hash.split("@")[0]; } else { return _hash; } } return ""; } self.getSectionHash = function () { if (window.location.hash != "") { var _hash = window.location.hash.substr(1).replace(/(<([^>]+)>)/ig, ""); if (_hash.indexOf("@") > -1) { return _hash.split("@")[1]; } } return "edit"; } self.linkToBrowse = function (path) { self.assist.path(path); $(document).trigger("changedPath"); self.assist.loadParents(); self.updateSectionHash("edit"); $(document).trigger("showMainSection"); } }; return SentryViewModel; })();
cloudera/hue
apps/security/src/security/static/security/js/sentry.ko.js
JavaScript
apache-2.0
48,227
/** * Created by Armin on 25.05.2017. */ 'use strict'; module.exports = function(grunt) { // Project configuration. grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), uglify: { options: { banner: '/*! <%= pkg.name %> <%= grunt.template.today("yyyy-mm-dd") %> */\n' }, build: { src: 'public/javascripts/bundle.js', dest: 'public/javascripts/bundle.min.js' } }, nodeunit: { files: ['openwhisk/**/*test.js'] }, jshint: { files: ['**/*.js', // lint all javascript files except the follow '!Gruntfile.js', '!node_modules/**', '!tts-token.js', '!stt-token.js', '!public/javascripts/jquery.leanModal.min.js', '!public/javascripts/bundle.js', '!public/javascripts/bundle.min.js'], options: { jshintrc: '.jshintrc', reporterOutput: "" // This is to ommit bug! } }, browserify: { build: { src: 'public/javascripts/main.js', dest: 'public/javascripts/bundle.js' } }, // run once --> grunt watch // After that every change on a file matching the patterns used bellow // will execute the corresponding task watch: { /* unittest: { files: '<%= nodeunit.files %>', tasks: ['nodeunit'] },*/ linting: { files: '<%= jshint.files %>', tasks: ['jshint'] } /*, uglify: { files: '<%= uglify.build.src %>', tasks: ['uglify'] }*/ } }); // These plugins provide necessary tasks. grunt.loadNpmTasks('grunt-contrib-jshint'); // Linter grunt.loadNpmTasks('grunt-contrib-nodeunit'); // Test-Framework grunt.loadNpmTasks('grunt-contrib-uglify'); // Minifier grunt.loadNpmTasks('grunt-contrib-watch'); // Watcher (if files changed, then run condigured tasks) grunt.loadNpmTasks('grunt-browserify'); // Convert the nodejs app to javascript which works in browsers // (another way is to use require.js) // Default task. grunt.registerTask('default', ['jshint']); grunt.registerTask('localBuild', ['jshint', 'uglify', 'browserify']); };
moru1012/IWIBot
Gruntfile.js
JavaScript
apache-2.0
2,605
// Makes a menu out of the element on which it's called. // Options can be passed to this function aswell. // Animate (default - true): A boolean that indicates wether the menu should be displayed using an animation; // AnimateDirection (default - up): When animate is enabled, this is the direction in which the menu should be animated. // AnimateDirectionSubMenu (default - left): When animate is enabled, this is the difrection in which the submenu should be animated. // DelayTime (default - 500): When there's a submenu item, this is the delay that it would take before the submenu opens. // TransitionTime (default - 100): The time it takes before the animation of the menu is completed. $.fn.Menu = function(options) { // Specify the default options for the menu plugin. var options = $.extend({ Animate: true, AnimateDirection: "up", AnimateDirectionSubMenu: "left", DelayTime: 500, TransitionTime: 100 }, options ); // Get the object on which this is called. var object = $(this); Initialize(); // Section: Functions. // Initialize the menu. This is done by placing classes on the various elements that together form the menu. // This is done to keep the HTML less cluthered. function Initialize() { $(".menucontents UL").addClass("OfficeUI_nowrap OfficeUI_nopadding OfficeUI_nomargin"); $(".menu").addClass("OfficeUI_absolute"); } // End of section: Functions. // Section: Event Handlers var waitHandle; // An object that is used to specify a delay. // Executed when you click on a menu entry. $("LI.menuEntry:not(.OfficeUI_disabled)").on("click", function(e) { e.stopPropagation(); // Make sure to clear the timeout on the waithandle, otherwise, the menuitem might be showed twice. clearTimeout(waitHandle); // Check if the menuitem holds a submenu. if ($(".subMenuHolder", this).length > 0) { var element = $(this); transitionDirection = options.AnimateDirectionSubMenu; // Hide all the other open submenus. $(".menu", $(element).parent()).each(function() { $(this).hide().parent().Deactivate(); }); // When the menu should be animated (specified in the options, animate it, otherwise just show it.) if (options.Animate) { $(".menu", element).first().show("slide", { direction: transitionDirection }, options.TransitionTime).Activate(); } else { $(".menu", element).first().show(); } } }); // Shows the submenu of a menuitem that's not disabled when hovering over it. $("LI.menuEntry:not(.OfficeUI_disabled)").on("mouseenter", function(e) { // Prevents the page from further execution. e.stopPropagation(); // Sets the current transition direction. This variable is needed because it changes depending if it's a submenu or not. var transitionDirection = options.AnimateDirection; // Check if the menuitem holds a submenu. if ($(".subMenuHolder", this).length > 0) { var element = $(this); // Sets the direction of the transition. transitionDirection = options.AnimateDirectionSubMenu; // Specifies the function that should occur after the delay time has been passed. waitHandle = setTimeout(function() { // Hide all the other open submenus. $(".menu", $(element).parent()).each(function() { $(this).hide().parent().Deactivate(); }); // When the menu should be animated (specified in the options, animate it, otherwise just show it.) if (options.Animate) { $(".menu", element).first().show("slide", { direction: transitionDirection }, options.TransitionTime).Activate(); } else { $(".menu", element).first().show(); } }, options.DelayTime); } else { // The menuitem does not hold a submenu, which means that we can close all the other submenu items. $(".menu", $(this).parent()).each(function() { $(this).hide().parent().Deactivate(); }); } }); // When the cursor moves away from the menuitem, make sure to clear the timeout, otherwise, the menu on which your cursor was placed will still open. $("LI.menuEntry").on("mouseout", function(e) { clearTimeout(waitHandle); }); // When you click anywhere on the document, make sure that all the menu's are hidden. $(document).on("click", function (e) { $(".menu").each(function() { $(this).hide().parent().Deactivate(); $(this).data("state", 0); }); }); // End of section: Event Handlers. // Section: API Creation. // Create an API and return that one. return CreateMenuAPI(); // Creates the ribbon API. function CreateMenuAPI() { return { Show: Show, Hide: Hide, OpenContextMenu : OpenContextMenu } } // Shows the menu entry on which it it called. function Show() { if (options.Animate) { object.show("slide", { direction: options.AnimateDirection }, options.TransitionTime).Activate(); } // Always shows the menu. Never hide it on a hover. else { object.show(); } } // Hides the menu on which it is called. function Hide() { object.hide(); } // Open a context menu. // Parameters: // e: The page event. function OpenContextMenu(e) { // Prevent the page from further execution. e.preventDefault(); //getting height and width of the message box var height = $(".contextMenuInArea").height(); var width = $(".contextMenuInArea").width(); //calculating offset for displaying popup message leftVal = e.pageX - (width / 2) + "px"; topVal = e.pageY - (height / 2) + "px"; //show the popup message and hide with fading effect if (options.Animate) { object.css({left:leftVal,top:topVal}).show("slide", { direction: options.AnimateDirection }, options.TransitionTime).Activate(); } // Always shows the menu. Never hide it on a hover. else { object.css({left:leftVal,top:topVal}).show(); } return false; } // End of section: API Creation. }
AppManics/OfficeUI.OLD
Resources/Scripts/Plugins/Menu/OfficeUI.Menu.js
JavaScript
apache-2.0
7,019
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ goog.provide('goog.gxp.js.JavascriptClosure'); /** * Closure for content-type: text/javascript * * @constructor * @param {Function} writeJavascript function that will write closure * contents to a given output. */ goog.gxp.js.JavascriptClosure = function(writeJavascript) { this.writeJavascript = writeJavascript; this.gxp$writeJavascript = writeJavascript; };
Primosbookkeeping/gxp
javascript/src/gxp/js/javascript-closure.js
JavaScript
apache-2.0
986
'use strict'; angular.module("ngLocale", [], ["$provide", function($provide) { var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"}; function getDecimals(n) { n = n + ''; var i = n.indexOf('.'); return (i == -1) ? 0 : n.length - i - 1; } function getVF(n, opt_precision) { var v = opt_precision; if (undefined === v) { v = Math.min(getDecimals(n), 3); } var base = Math.pow(10, v); var f = ((n * base) | 0) % base; return {v: v, f: f}; } $provide.value("$locale", { "DATETIME_FORMATS": { "AMPMS": [ "AM", "PM" ], "DAY": [ "Jumapili", "Jumatatu", "Jumanne", "Jumatano", "Alhamisi", "Ijumaa", "Jumamosi" ], "ERANAMES": [ "Kabla ya Kristo", "Baada ya Kristo" ], "ERAS": [ "BC", "AD" ], "FIRSTDAYOFWEEK": 0, "MONTH": [ "Januari", "Februari", "Machi", "Aprili", "Mei", "Juni", "Julai", "Agosti", "Septemba", "Oktoba", "Novemba", "Desemba" ], "SHORTDAY": [ "Jumapili", "Jumatatu", "Jumanne", "Jumatano", "Alhamisi", "Ijumaa", "Jumamosi" ], "SHORTMONTH": [ "Jan", "Feb", "Mac", "Apr", "Mei", "Jun", "Jul", "Ago", "Sep", "Okt", "Nov", "Des" ], "STANDALONEMONTH": [ "Januari", "Februari", "Machi", "Aprili", "Mei", "Juni", "Julai", "Agosti", "Septemba", "Oktoba", "Novemba", "Desemba" ], "WEEKENDRANGE": [ 5, 6 ], "fullDate": "EEEE, d MMMM y", "longDate": "d MMMM y", "medium": "d MMM y HH:mm:ss", "mediumDate": "d MMM y", "mediumTime": "HH:mm:ss", "short": "dd/MM/y HH:mm", "shortDate": "dd/MM/y", "shortTime": "HH:mm" }, "NUMBER_FORMATS": { "CURRENCY_SYM": "TSh", "DECIMAL_SEP": ".", "GROUP_SEP": ",", "PATTERNS": [ { "gSize": 3, "lgSize": 3, "maxFrac": 3, "minFrac": 0, "minInt": 1, "negPre": "-", "negSuf": "", "posPre": "", "posSuf": "" }, { "gSize": 3, "lgSize": 3, "maxFrac": 2, "minFrac": 2, "minInt": 1, "negPre": "-\u00a4", "negSuf": "", "posPre": "\u00a4", "posSuf": "" } ] }, "id": "sw-tz", "localeID": "sw_TZ", "pluralCat": function(n, opt_precision) { var i = n | 0; var vf = getVF(n, opt_precision); if (i == 1 && vf.v == 0) { return PLURAL_CATEGORY.ONE; } return PLURAL_CATEGORY.OTHER;} }); }]);
yoyocms/YoYoCms.AbpProjectTemplate
src/YoYoCms.AbpProjectTemplate.Web/Scripts/i18n/angular-locale_sw-tz.js
JavaScript
apache-2.0
2,748
'use strict'; angular.module("ngLocale", [], ["$provide", function($provide) { var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"}; function getDecimals(n) { n = n + ''; var i = n.indexOf('.'); return (i == -1) ? 0 : n.length - i - 1; } function getVF(n, opt_precision) { var v = opt_precision; if (undefined === v) { v = Math.min(getDecimals(n), 3); } var base = Math.pow(10, v); var f = ((n * base) | 0) % base; return {v: v, f: f}; } $provide.value("$locale", { "DATETIME_FORMATS": { "AMPMS": [ "AM", "PM" ], "DAY": [ "Sunntag", "M\u00e4ntag", "Zi\u0161tag", "Mittwu\u010d", "Fr\u00f3ntag", "Fritag", "Sam\u0161tag" ], "ERANAMES": [ "v. Chr.", "n. Chr" ], "ERAS": [ "v. Chr.", "n. Chr" ], "FIRSTDAYOFWEEK": 0, "MONTH": [ "Jenner", "Hornig", "M\u00e4rze", "Abrille", "Meije", "Br\u00e1\u010det", "Heiwet", "\u00d6ig\u0161te", "Herb\u0161tm\u00e1net", "W\u00edm\u00e1net", "Winterm\u00e1net", "Chri\u0161tm\u00e1net" ], "SHORTDAY": [ "Sun", "M\u00e4n", "Zi\u0161", "Mit", "Fr\u00f3", "Fri", "Sam" ], "SHORTMONTH": [ "Jen", "Hor", "M\u00e4r", "Abr", "Mei", "Br\u00e1", "Hei", "\u00d6ig", "Her", "W\u00edm", "Win", "Chr" ], "STANDALONEMONTH": [ "Jenner", "Hornig", "M\u00e4rze", "Abrille", "Meije", "Br\u00e1\u010det", "Heiwet", "\u00d6ig\u0161te", "Herb\u0161tm\u00e1net", "W\u00edm\u00e1net", "Winterm\u00e1net", "Chri\u0161tm\u00e1net" ], "WEEKENDRANGE": [ 5, 6 ], "fullDate": "EEEE, d. MMMM y", "longDate": "d. MMMM y", "medium": "d. MMM y HH:mm:ss", "mediumDate": "d. MMM y", "mediumTime": "HH:mm:ss", "short": "y-MM-dd HH:mm", "shortDate": "y-MM-dd", "shortTime": "HH:mm" }, "NUMBER_FORMATS": { "CURRENCY_SYM": "CHF", "DECIMAL_SEP": ",", "GROUP_SEP": "\u2019", "PATTERNS": [ { "gSize": 3, "lgSize": 3, "maxFrac": 3, "minFrac": 0, "minInt": 1, "negPre": "-", "negSuf": "", "posPre": "", "posSuf": "" }, { "gSize": 3, "lgSize": 3, "maxFrac": 2, "minFrac": 2, "minInt": 1, "negPre": "-\u00a4\u00a0", "negSuf": "", "posPre": "\u00a4\u00a0", "posSuf": "" } ] }, "id": "wae", "localeID": "wae", "pluralCat": function(n, opt_precision) { var i = n | 0; var vf = getVF(n, opt_precision); if (i == 1 && vf.v == 0) { return PLURAL_CATEGORY.ONE; } return PLURAL_CATEGORY.OTHER;} }); }]);
yoyocms/YoYoCms.AbpProjectTemplate
src/YoYoCms.AbpProjectTemplate.Web/Scripts/i18n/angular-locale_wae.js
JavaScript
apache-2.0
2,928
/** * @license * Copyright 2020 Google LLC * SPDX-License-Identifier: Apache-2.0 */ /** * @fileoverview The interface for an AST node location. */ 'use strict'; /** * The interface for an AST node location. * @namespace Blockly.IASTNodeLocation */ goog.module('Blockly.IASTNodeLocation'); /** * An AST node location interface. * @interface * @alias Blockly.IASTNodeLocation */ const IASTNodeLocation = function() {}; exports.IASTNodeLocation = IASTNodeLocation;
rachel-fenichel/blockly
core/interfaces/i_ast_node_location.js
JavaScript
apache-2.0
480
function RegisterServiceTO() { this.id; this.cehrtLabel; this.organizationName; this.directEmailAddress; this.pointOfContact; this.pocFirstName; this.pocLastName; this.timezone; this.directTrustMembership; this.availFromDate; this.availToDate; this.userEmailAddress; this.notes; }
monikadrajer/direct-vendor-tools
site-login/src/main/webapp/js/to/RegisterServiceTO.js
JavaScript
bsd-2-clause
293
// Copyright 2009 the Sputnik authors. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /*--- esid: sec-boolean.prototype.tostring info: | The toString function is not generic, it cannot be transferred to other kinds of objects for use as a method and there is should be a TypeError exception if its this value is not a Boolean object es5id: 15.6.4.2_A2_T4 description: transferring to the Object objects ---*/ //CHECK#1 try { var s1 = new Object(); s1.toString = Boolean.prototype.toString; var v1 = s1.toString(); $ERROR('#1: Boolean.prototype.toString on not a Boolean object should throw TypeError'); } catch (e) { if (!(e instanceof TypeError)) { $ERROR('#1: Boolean.prototype.toString on not a Boolean object should throw TypeError, not ' + e); } } //CHECK#1 try { var s2 = new Object(); s2.myToString = Boolean.prototype.toString; var v2 = s2.myToString(); $ERROR('#2: Boolean.prototype.toString on not a Boolean object should throw TypeError'); } catch (e) { if (!(e instanceof TypeError)) { $ERROR('#2: Boolean.prototype.toString on not a Boolean object should throw TypeError, not ' + e); } }
sebastienros/jint
Jint.Tests.Test262/test/built-ins/Boolean/prototype/toString/S15.6.4.2_A2_T4.js
JavaScript
bsd-2-clause
1,194
"use strict"; var coefficient_table = [ { "p" : 0.10, "co_eff" : 1.22 }, { "p" : 0.05, "co_eff" : 1.36 }, { "p" : 0.025, "co_eff" : 1.48 }, { "p" : 0.01, "co_eff" : 1.63 }, { "p" : 0.005, "co_eff" : 1.73 }, { "p" : 0.001, "co_eff" : 1.95 } ]; // CDFs, not CSFs function ks_test(perc_one, perc_two, len_one, len_two) { var dn = (len_one * len_two) / (len_one + len_two); var max_delta = 0; var at; for (var i = 0; i < perc_one.length; i+=10) { var d_one = perc_one[i]; var d_two = perc_two[i]; var delta = Math.abs(d_one[1] - d_two[1]); var max_delta = Math.max(delta, max_delta); if (max_delta === delta) { at = i; } } if (!at) { return; } var one_val = (perc_one[at] && perc_one[at][1]) || 0; var two_val = (perc_two[at] && perc_two[at][1]) || 0; var high_val = Math.max(one_val, two_val); var low_val = Math.min(one_val, two_val); var low_series = low_val === one_val ? perc_one : perc_two; var high_series = high_val === one_val ? perc_one : perc_two; var it = high_series[at]; var new_at = at; var delta = 0; var low_delta = 0, high_delta = 0; while (it[1] >= low_val + 1) { new_at -= 1; if (!high_series[new_at]) { new_at += 1; break; } it = high_series[new_at]; } low_delta = Math.abs(new_at - at); new_at = at; var it = low_series[at]; while (it[1] <= high_val - 1) { new_at += 1; if (!low_series[new_at]) { new_at -= 1; break; } it = low_series[new_at]; } var high_delta = Math.abs(new_at - at); var max_perc_delta = Math.max(low_delta, high_delta); if (max_perc_delta === high_delta) { at = high_series[at][1]; } else { at = low_series[at][1]; } var ks_val = Math.sqrt(dn) * max_perc_delta / 1000; var p; _.each(coefficient_table, function(row) { if (row.co_eff > ks_val) { p = row.p; } }); if (max_perc_delta <= 1) { max_perc_delta = 0; at = 0; } var results = { max: max_perc_delta / 1000, at: at, len_one: len_one, len_two: len_two, ks: ks_val, p: p }; return results; } module.exports = ks_test;
logV/snorkel
snorkel/app/client/ks_test.js
JavaScript
bsd-2-clause
2,166
/*! jQuery UI - v1.10.4 - 2016-01-24 * http://jqueryui.com * Copyright jQuery Foundation and other contributors; Licensed MIT */ jQuery(function(e){e.datepicker.regional.ta={closeText:"மூடு",prevText:"முன்னையது",nextText:"அடுத்தது",currentText:"இன்று",monthNames:["தை","மாசி","பங்குனி","சித்திரை","வைகாசி","ஆனி","ஆடி","ஆவணி","புரட்டாசி","ஐப்பசி","கார்த்திகை","மார்கழி"],monthNamesShort:["தை","மாசி","பங்","சித்","வைகா","ஆனி","ஆடி","ஆவ","புர","ஐப்","கார்","மார்"],dayNames:["ஞாயிற்றுக்கிழமை","திங்கட்கிழமை","செவ்வாய்க்கிழமை","புதன்கிழமை","வியாழக்கிழமை","வெள்ளிக்கிழமை","சனிக்கிழமை"],dayNamesShort:["ஞாயிறு","திங்கள்","செவ்வாய்","புதன்","வியாழன்","வெள்ளி","சனி"],dayNamesMin:["ஞா","தி","செ","பு","வி","வெ","ச"],weekHeader:"Не",dateFormat:"dd/mm/yy",firstDay:1,isRTL:!1,showMonthAfterYear:!1,yearSuffix:""},e.datepicker.setDefaults(e.datepicker.regional.ta)});
glebstar/guides
web/jquery-ui/development-bundle/ui/minified/i18n/jquery.ui.datepicker-ta.min.js
JavaScript
bsd-3-clause
1,412
/* * Copyright 2014 TWO SIGMA OPEN SOURCE, LLC * * 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. */ (function() { 'use strict'; var retfunc = function(bkUtils) { return { dataTypeMap : { "Line" : "line", "Stems" : "stem", "Bars" : "bar", "Area" : "area", "Text" : "text", "Points" : "point", "" : "" }, lineStyleMap : { "DEFAULT": "solid", "SOLID" : "solid", "DASH" : "dash", "DOT" : "dot", "DASHDOT" : "dashdot", "LONGDASH" : "longdash", "" : "solid" }, pointShapeMap : { "DEFAULT" : "rect", "CIRCLE" : "circle", "DIAMOND" : "diamond", "" : "rect" }, interpolationMap : { 0 : "none", 1 : "linear", 2 : "linear", // should be "curve" but right now it is not implemented yet "" : "linear" }, convertGroovyData : function(newmodel, model) { var yIncludeZero = false; var logx = false, logy = false, logxb, logyb; if (model.rangeAxes != null) { var axis = model.rangeAxes[0]; if (axis.auto_range_includes_zero === true) { yIncludeZero = true; } if (axis.use_log === true) { logy = true; logyb = axis.log_base == null ? 10 : axis.log_base; } } if (model.log_x === true) { logx = true; logxb = model.x_log_base == null ? 10 : model.x_log_base; } // set margin newmodel.margin = {}; // set axis bound as focus if (model.x_auto_range === false) { if (model.x_lower_bound != null) { newmodel.userFocus.xl = model.x_lower_bound; } if (model.x_upper_bound != null) { newmodel.userFocus.xr = model.x_upper_bound; } } else { if (model.x_lower_margin != null) { newmodel.margin.left = model.x_lower_margin; } if (model.x_upper_margin != null) { newmodel.margin.right = model.x_upper_margin; } } if (model.rangeAxes != null) { var axis = model.rangeAxes[0]; if (axis.auto_range === false) { if (axis.lower_bound != null) { newmodel.userFocus.yl = axis.lower_bound; } if (axis.upper_bound != null) { newmodel.userFocus.yr = axis.upper_bound; } } else { if (axis.lower_margin != null) { newmodel.margin.bottom = axis.lower_margin; } if (axis.upper_margin != null) { newmodel.margin.top = axis.upper_margin; } } } if (model.crosshair != null) { var color = model.crosshair.color; newmodel.xCursor = {}; var cursor = newmodel.xCursor; cursor.color_opacity = parseInt(color.substr(1,2), 16) / 255; cursor.color = "#" + color.substr(3); var style = model.crosshair.style; if (style == null) style = ""; cursor.style = this.lineStyleMap[style]; cursor.width = model.crosshair.width != null ? model.crosshair.width : 2; newmodel.yCursor = {}; _.extend(newmodel.yCursor, cursor); } // log scaling if (logx) { newmodel.xAxis.type = "log"; newmodel.xAxis.base = logxb; } else if (model.type === "TimePlot") { newmodel.xAxis.type = "time"; } else if (model.type === "NanoPlot"){ // TODO } else { newmodel.xAxis.type = "linear"; } if (logy) { newmodel.yAxis.type = "log"; newmodel.yAxis.base = logyb; } else { newmodel.yAxis.type = "linear"; } var list = model.graphics_list; var numLines = list.length; for (var i = 0; i < numLines; i++) { var item = list[i]; item.legend = item.display_name; delete item.display_name; if (item.use_tool_tip != null) { item.useToolTip = item.use_tool_tip; delete item.use_tool_tip; } if (item.color != null) { item.color_opacity = parseInt(item.color.substr(1,2), 16) / 255; item.color = "#" + item.color.substr(3); } if (item.fill != null && item.fill === false) { item.color = "none"; } if (item.outline_color != null) { item.stroke_opacity = parseInt(item.outline_color.substr(1,2), 16) / 255; item.stroke = "#" + item.outline_color.substr(3); delete item.outline_color; } if (item.type == null) { item.type = ""; } if (item.style == null) { item.style = ""; } if (item.stroke_dasharray == null) { item.stroke_dasharray = ""; } if (item.interpolation == null) { item.interpolation = ""; } item.type = this.dataTypeMap[item.type]; if(item.type === "bar" || item.type === "area") { //newmodel.yPreventNegative = true; // auto range to y = 0 } if(item.type === "line" || item.type === "stem") { item.style = this.lineStyleMap[item.style]; } if(item.type === "line" || item.type === "area") { item.interpolation = this.interpolationMap[item.interpolation]; } if(item.type === "bar") { if (item.width == null) { item.width = 1; } } if (item.type === "point") { if (item.shape == null) { item.shape = "DEFAULT"; } item.shape = this.pointShapeMap[item.shape]; } if (item.base != null && logy) { if (item.base === 0) { item.base = 1; } } var elements = []; for (var j = 0; j < item.x.length; j++) { var ele = {}; ele.x = item.x[j]; ele.y = item.y[j]; if (item.colors != null) { ele.color_opacity = parseInt(item.colors[j].substr(1,2), 16) / 255; ele.color = "#" + item.colors[j].substr(3); } if (item.fills != null && item.fills[j] === false) { ele.color = "none"; } if (item.outline_colors != null) { ele.stroke_opacity = parseInt(item.outline_colors[j].substr(1,2), 16) / 255; ele.stroke = "#" + item.outline_colors[j].substr(3); } if (item.type === "line" || item.type === "stem") { if (item.styles != null) { var style = item.styles[j]; if (style == null) { style = ""; } item.style = this.lineStyleMap[style]; } } if ((item.type === "stem" || item.type === "bar" || item.type === "area") && ele.y2 == null) { if (item.bases != null) { ele.y2 = item.bases[j]; } } if (item.type === "point") { if (item.sizes != null) { ele.size = item.sizes[j]; } } if (item.type === "bar" && item.widths != null) { ele.x -= item.widths[j] / 2; ele.x2 = ele.x + item.widths[j]; } elements.push(ele); } item.elements = elements; newmodel.data.push(item); } if(model.constant_lines != null) { for(var i = 0; i < model.constant_lines.length; i++) { var line = model.constant_lines[i]; var item = { "type": "constline", "width": line.width != null ? line.width : 1, "color": "black", "elements": [] }; if (line.color != null) { item.color_opacity = parseInt(line.color.substr(1,2), 16) / 255; item.color = "#" + line.color.substr(3); } var style = line.style; if (style == null) { style = ""; } item.style = this.lineStyleMap[style]; if (line.x != null) { var ele = {"type": "x", "x": line.x}; } else if(line.y != null) { var y = line.y; var ele = {"type": "y", "y": y}; } item.elements.push(ele); newmodel.data.push(item); } } if (model.constant_bands != null) { for (var i = 0; i < model.constant_bands.length; i++) { var band = model.constant_bands[i]; var item = { "type" : "constband", "elements" : [] }; if (band.color != null) { item.color_opacity = parseInt(band.color.substr(1, 2), 16) / 255; item.color = "#" + band.color.substr(3); } if (band.x != null) { var ele = { "type" : "x", "x" : band.x[0], "x2" : band.x[1] }; } else if (band.y != null) { var ele = { "type" : "y" }; var y1 = band.y[0], y2 = band.y[1]; ele.y = y1; ele.y2 = y2; } item.elements.push(ele); newmodel.data.push(item); } } if (model.texts != null) { for (var i = 0; i < model.texts.length; i++) { var mtext = model.texts[i]; var item = { "type" : "text", "color" : mtext.color != null ? mtext.color : "black", "elements" : [] }; var ele = { "x" : mtext.x, "y" : mtext.y, "text" : mtext.text }; item.elements.push(ele); newmodel.data.push(item); } } newmodel.yIncludeZero = yIncludeZero; }, cleanupModel : function(model) { for (var i = 0; i < model.data.length; i++) { var item = model.data[i]; if (item.x != null) { delete item.x; } if (item.y != null) { delete item.y; } if (item.colors) { delete item.colors; } if (item.sizes) { delete item.sizes; } if (item.bases) { delete item.bases; } if (item.outline_colors) { delete item.outline_colors; } } } }; }; beaker.bkoFactory('plotConverter', ["bkUtils", retfunc]); })();
twosigma/beaker-sharing-server
nbviewer/static/v2/src/outputdisplay/bko-plot/plotconverter.js
JavaScript
bsd-3-clause
11,237
'use strict'; var _interopRequireDefault = require('babel-runtime/helpers/interop-require-default')['default']; exports.__esModule = true; var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _reactLibWarning = require('react/lib/warning'); var _reactLibWarning2 = _interopRequireDefault(_reactLibWarning); var _Jumbotron = require('../Jumbotron'); var _Jumbotron2 = _interopRequireDefault(_Jumbotron); _reactLibWarning2['default'](false, 'Support for factories will be removed in v0.25, for details see https://github.com/react-bootstrap/react-bootstrap/issues/825'); exports['default'] = _react2['default'].createFactory(_Jumbotron2['default']); module.exports = exports['default'];
principle-systems/react-shopping-cart-starter-kit
node_modules/react-bootstrap/lib/factories/Jumbotron.js
JavaScript
bsd-3-clause
722
/* Yes */ import UnityScript.Tests.CSharp; var foo = FooBarEnum.None; foo |= FooBarEnum.Foo; if ((foo & FooBarEnum.Foo) != 0) print ("Yes");
bamboo/unityscript
tests/integration/enum-2.js
JavaScript
bsd-3-clause
143
/* eslint-disable sort-keys */ const http = require('http'); const path = require('path'); const fs = require('fs'); const connect = require('connect'); const optimist = require('optimist'); const reactMiddleware = require('react-page-middleware'); const convert = require('./convert.js'); const translationPre = require('./translationPre.js'); const translation = require('./translation.js'); console.log('server.js triggered...'); const argv = optimist.argv; const PROJECT_ROOT = path.resolve(__dirname, '..'); const FILE_SERVE_ROOT = path.join(PROJECT_ROOT, 'src'); let port = argv.port; if (argv.$0.indexOf('node ./server/generate.js') !== -1) { // Using a different port so that you can publish the website // and keeping the server up at the same time. port = 8079; } const buildOptions = { projectRoot: PROJECT_ROOT, pageRouteRoot: FILE_SERVE_ROOT, useBrowserBuiltins: false, logTiming: true, useSourceMaps: true, ignorePaths(p) { return p.indexOf('__tests__') !== -1; }, serverRender: true, dev: argv.dev !== 'false', static: true, }; // clean up localization files, it can take a while to remove files so let's // have our next steps run in a callback translationPre(); const app = connect() .use((req, res, next) => { // Convert localized .json files into .js translation(); // convert all the md files on every request. This is not optimal // but fast enough that we don't really need to care right now. convert(); next(); }) .use('/jest/blog/feed.xml', (req, res) => { res.end( fs.readFileSync(path.join(FILE_SERVE_ROOT, 'jest/blog/feed.xml')) + '' ); }) .use('/jest/blog/atom.xml', (req, res) => { res.end( fs.readFileSync(path.join(FILE_SERVE_ROOT, 'jest/blog/atom.xml')) + '' ); }) .use(reactMiddleware.provide(buildOptions)) .use(connect['static'](FILE_SERVE_ROOT)) // .use(connect.favicon(path.join(FILE_SERVE_ROOT, 'elements', 'favicon', 'favicon.ico'))) .use(connect.logger()) .use(connect.compress()) .use(connect.errorHandler()); const portToUse = port || 8080; const server = http.createServer(app); server.listen(portToUse); console.log('Open http://localhost:' + portToUse + '/jest/index.html'); module.exports = server;
mpontus/jest
website/server/server.js
JavaScript
bsd-3-clause
2,260
var colog = require('colog'); module.exports = (function () { 'use strict'; colog.success('\t[\u2714] Auction'); /** * Imports for the Auction model. */ var AuctionSchema = require('./auction-schema'); require('./auction-life-cycle'); require('./auction-model'); return AuctionSchema; })();
Mickael-van-der-Beek/wow-ah
src/database/models/auction/auction.js
JavaScript
bsd-3-clause
308
//= require 'upload_selection' describe("tab selection", function(){ fixture.set("<ul class='nav nav-tabs' role='tablist'>" + "<li role='presentation' class='active'>" + "<a href='#local-file' aria-controls='local-file' role='tab' data-toggle='tab'>Local file</a>" + "</li>" + "<li role='presentation'>" + "<a href='#remote-url' aria-controls='remote-url' role='tab' data-toggle='tab'>Remote URL</a>" + "</li>" + "</ul>" ); it("should select local file tab by default", function() { var active_tab_text = jQuery('li.active a')[0].text; expect(active_tab_text).to.equal('Local file'); }); it("should select remote url tab when it is clicked", function() { var remote_url_tab = jQuery('ul.nav-tabs li')[1]; expect(remote_url_tab.class).not.to.equal('active'); remote_url_tab.children[0].click(); var active_tab_text = jQuery('li.active a')[0].text; expect(active_tab_text).to.equal('Remote URL'); }); });
SynthSys/seek
spec/javascripts/upload_selection_spec.js
JavaScript
bsd-3-clause
1,041
// setup Elm.Native = Elm.Native || {}; Elm.Native.Graphics = Elm.Native.Graphics || {}; Elm.Native.Graphics.Element = Elm.Native.Graphics.Element || {}; // definition Elm.Native.Graphics.Element.make = function(localRuntime) { 'use strict'; // attempt to short-circuit if ('values' in Elm.Native.Graphics.Element) { return Elm.Native.Graphics.Element.values; } var Color = Elm.Native.Color.make(localRuntime); var List = Elm.Native.List.make(localRuntime); var Utils = Elm.Native.Utils.make(localRuntime); function createNode(elementType) { var node = document.createElement(elementType); node.style.padding = "0"; node.style.margin = "0"; return node; } function setProps(elem, node) { var props = elem.props; var element = elem.element; var width = props.width - (element.adjustWidth || 0); var height = props.height - (element.adjustHeight || 0); node.style.width = (width |0) + 'px'; node.style.height = (height|0) + 'px'; if (props.opacity !== 1) { node.style.opacity = props.opacity; } if (props.color.ctor === 'Just') { node.style.backgroundColor = Color.toCss(props.color._0); } if (props.tag !== '') { node.id = props.tag; } if (props.hover.ctor !== '_Tuple0') { addHover(node, props.hover); } if (props.click.ctor !== '_Tuple0') { addClick(node, props.click); } if (props.href !== '') { var anchor = createNode('a'); anchor.href = props.href; anchor.style.display = 'block'; anchor.style.pointerEvents = 'auto'; anchor.appendChild(node); node = anchor; } return node; } function addClick(e, handler) { e.style.pointerEvents = 'auto'; e.elm_click_handler = handler; function trigger(ev) { e.elm_click_handler(Utils.Tuple0); ev.stopPropagation(); } e.elm_click_trigger = trigger; e.addEventListener('click', trigger); } function removeClick(e, handler) { if (e.elm_click_trigger) { e.removeEventListener('click', e.elm_click_trigger); e.elm_click_trigger = null; e.elm_click_handler = null; } } function addHover(e, handler) { e.style.pointerEvents = 'auto'; e.elm_hover_handler = handler; e.elm_hover_count = 0; function over(evt) { if (e.elm_hover_count++ > 0) return; e.elm_hover_handler(true); evt.stopPropagation(); } function out(evt) { if (e.contains(evt.toElement || evt.relatedTarget)) return; e.elm_hover_count = 0; e.elm_hover_handler(false); evt.stopPropagation(); } e.elm_hover_over = over; e.elm_hover_out = out; e.addEventListener('mouseover', over); e.addEventListener('mouseout', out); } function removeHover(e) { e.elm_hover_handler = null; if (e.elm_hover_over) { e.removeEventListener('mouseover', e.elm_hover_over); e.elm_hover_over = null; } if (e.elm_hover_out) { e.removeEventListener('mouseout', e.elm_hover_out); e.elm_hover_out = null; } } function image(props, img) { switch (img._0.ctor) { case 'Plain': return plainImage(img._3); case 'Fitted': return fittedImage(props.width, props.height, img._3); case 'Cropped': return croppedImage(img,props.width,props.height,img._3); case 'Tiled': return tiledImage(img._3); } } function plainImage(src) { var img = createNode('img'); img.src = src; img.name = src; img.style.display = "block"; return img; } function tiledImage(src) { var div = createNode('div'); div.style.backgroundImage = 'url(' + src + ')'; return div; } function fittedImage(w, h, src) { var div = createNode('div'); div.style.background = 'url(' + src + ') no-repeat center'; div.style.webkitBackgroundSize = 'cover'; div.style.MozBackgroundSize = 'cover'; div.style.OBackgroundSize = 'cover'; div.style.backgroundSize = 'cover'; return div; } function croppedImage(elem, w, h, src) { var pos = elem._0._0; var e = createNode('div'); e.style.overflow = "hidden"; var img = createNode('img'); img.onload = function() { var sw = w / elem._1, sh = h / elem._2; img.style.width = ((this.width * sw)|0) + 'px'; img.style.height = ((this.height * sh)|0) + 'px'; img.style.marginLeft = ((- pos._0 * sw)|0) + 'px'; img.style.marginTop = ((- pos._1 * sh)|0) + 'px'; }; img.src = src; img.name = src; e.appendChild(img); return e; } function goOut(node) { node.style.position = 'absolute'; return node; } function goDown(node) { return node; } function goRight(node) { node.style.styleFloat = 'left'; node.style.cssFloat = 'left'; return node; } var directionTable = { DUp : goDown, DDown : goDown, DLeft : goRight, DRight : goRight, DIn : goOut, DOut : goOut }; function needsReversal(dir) { return dir == 'DUp' || dir == 'DLeft' || dir == 'DIn'; } function flow(dir,elist) { var array = List.toArray(elist); var container = createNode('div'); var goDir = directionTable[dir]; if (goDir == goOut) { container.style.pointerEvents = 'none'; } if (needsReversal(dir)) { array.reverse(); } var len = array.length; for (var i = 0; i < len; ++i) { container.appendChild(goDir(render(array[i]))); } return container; } function toPos(pos) { switch(pos.ctor) { case "Absolute": return pos._0 + "px"; case "Relative": return (pos._0 * 100) + "%"; } } // must clear right, left, top, bottom, and transform // before calling this function function setPos(pos,elem,e) { var element = elem.element; var props = elem.props; var w = props.width + (element.adjustWidth ? element.adjustWidth : 0); var h = props.height + (element.adjustHeight ? element.adjustHeight : 0); e.style.position = 'absolute'; e.style.margin = 'auto'; var transform = ''; switch(pos.horizontal.ctor) { case 'P': e.style.right = toPos(pos.x); e.style.removeProperty('left'); break; case 'Z': transform = 'translateX(' + ((-w/2)|0) + 'px) '; case 'N': e.style.left = toPos(pos.x); e.style.removeProperty('right'); break; } switch(pos.vertical.ctor) { case 'N': e.style.bottom = toPos(pos.y); e.style.removeProperty('top'); break; case 'Z': transform += 'translateY(' + ((-h/2)|0) + 'px)'; case 'P': e.style.top = toPos(pos.y); e.style.removeProperty('bottom'); break; } if (transform !== '') { addTransform(e.style, transform); } return e; } function addTransform(style, transform) { style.transform = transform; style.msTransform = transform; style.MozTransform = transform; style.webkitTransform = transform; style.OTransform = transform; } function container(pos,elem) { var e = render(elem); setPos(pos, elem, e); var div = createNode('div'); div.style.position = 'relative'; div.style.overflow = 'hidden'; div.appendChild(e); return div; } function rawHtml(elem) { var html = elem.html; var guid = elem.guid; var align = elem.align; var div = createNode('div'); div.innerHTML = html; div.style.visibility = "hidden"; if (align) { div.style.textAlign = align; } div.style.visibility = 'visible'; div.style.pointerEvents = 'auto'; return div; } function render(elem) { return setProps(elem, makeElement(elem)); } function makeElement(e) { var elem = e.element; switch(elem.ctor) { case 'Image': return image(e.props, elem); case 'Flow': return flow(elem._0.ctor, elem._1); case 'Container': return container(elem._0, elem._1); case 'Spacer': return createNode('div'); case 'RawHtml': return rawHtml(elem); case 'Custom': return elem.render(elem.model); } } function updateAndReplace(node, curr, next) { var newNode = update(node, curr, next); if (newNode !== node) { node.parentNode.replaceChild(newNode, node); } return newNode; } function update(node, curr, next) { var rootNode = node; if (node.tagName === 'A') { node = node.firstChild; } if (curr.props.id === next.props.id) { updateProps(node, curr, next); return rootNode; } if (curr.element.ctor !== next.element.ctor) { return render(next); } var nextE = next.element; var currE = curr.element; switch(nextE.ctor) { case "Spacer": updateProps(node, curr, next); return rootNode; case "RawHtml": // only markdown blocks have guids, so this must be a text block if (nextE.guid === null) { if(currE.html.valueOf() !== nextE.html.valueOf()) { node.innerHTML = nextE.html; } updateProps(node, curr, next); return rootNode; } if (nextE.guid !== currE.guid) { return render(next); } updateProps(node, curr, next); return rootNode; case "Image": if (nextE._0.ctor === 'Plain') { if (nextE._3 !== currE._3) { node.src = nextE._3; } } else if (!Utils.eq(nextE,currE) || next.props.width !== curr.props.width || next.props.height !== curr.props.height) { return render(next); } updateProps(node, curr, next); return rootNode; case "Flow": var arr = List.toArray(nextE._1); for (var i = arr.length; i--; ) { arr[i] = arr[i].element.ctor; } if (nextE._0.ctor !== currE._0.ctor) { return render(next); } var nexts = List.toArray(nextE._1); var kids = node.childNodes; if (nexts.length !== kids.length) { return render(next); } var currs = List.toArray(currE._1); var dir = nextE._0.ctor; var goDir = directionTable[dir]; var toReverse = needsReversal(dir); var len = kids.length; for (var i = len; i-- ;) { var subNode = kids[toReverse ? len - i - 1 : i]; goDir(updateAndReplace(subNode, currs[i], nexts[i])); } updateProps(node, curr, next); return rootNode; case "Container": var subNode = node.firstChild; var newSubNode = updateAndReplace(subNode, currE._1, nextE._1); setPos(nextE._0, nextE._1, newSubNode); updateProps(node, curr, next); return rootNode; case "Custom": if (currE.type === nextE.type) { var updatedNode = nextE.update(node, currE.model, nextE.model); updateProps(updatedNode, curr, next); return updatedNode; } else { return render(next); } } } function updateProps(node, curr, next) { var nextProps = next.props; var currProps = curr.props; var element = next.element; var width = nextProps.width - (element.adjustWidth || 0); var height = nextProps.height - (element.adjustHeight || 0); if (width !== currProps.width) { node.style.width = (width|0) + 'px'; } if (height !== currProps.height) { node.style.height = (height|0) + 'px'; } if (nextProps.opacity !== currProps.opacity) { node.style.opacity = nextProps.opacity; } var nextColor = nextProps.color.ctor === 'Just' ? Color.toCss(nextProps.color._0) : ''; if (node.style.backgroundColor !== nextColor) { node.style.backgroundColor = nextColor; } if (nextProps.tag !== currProps.tag) { node.id = nextProps.tag; } if (nextProps.href !== currProps.href) { if (currProps.href === '') { // add a surrounding href var anchor = createNode('a'); anchor.href = nextProps.href; anchor.style.display = 'block'; anchor.style.pointerEvents = 'auto'; node.parentNode.replaceChild(anchor, node); anchor.appendChild(node); } else if (nextProps.href === '') { // remove the surrounding href var anchor = node.parentNode; anchor.parentNode.replaceChild(node, anchor); } else { // just update the link node.parentNode.href = nextProps.href; } } // update click and hover handlers var removed = false; // update hover handlers if (currProps.hover.ctor === '_Tuple0') { if (nextProps.hover.ctor !== '_Tuple0') { addHover(node, nextProps.hover); } } else { if (nextProps.hover.ctor === '_Tuple0') { removed = true; removeHover(node); } else { node.elm_hover_handler = nextProps.hover; } } // update click handlers if (currProps.click.ctor === '_Tuple0') { if (nextProps.click.ctor !== '_Tuple0') { addClick(node, nextProps.click); } } else { if (nextProps.click.ctor === '_Tuple0') { removed = true; removeClick(node); } else { node.elm_click_handler = nextProps.click; } } // stop capturing clicks if if (removed && nextProps.hover.ctor === '_Tuple0' && nextProps.click.ctor === '_Tuple0') { node.style.pointerEvents = 'none'; } } function htmlHeight(width, rawHtml) { // create dummy node var temp = document.createElement('div'); temp.innerHTML = rawHtml.html; if (width > 0) { temp.style.width = width + "px"; } temp.style.visibility = "hidden"; temp.style.styleFloat = "left"; temp.style.cssFloat = "left"; document.body.appendChild(temp); // get dimensions var style = window.getComputedStyle(temp, null); var w = Math.ceil(style.getPropertyValue("width").slice(0,-2) - 0); var h = Math.ceil(style.getPropertyValue("height").slice(0,-2) - 0); document.body.removeChild(temp); return Utils.Tuple2(w,h); } return Elm.Native.Graphics.Element.values = { render: render, update: update, updateAndReplace: updateAndReplace, createNode: createNode, addTransform: addTransform, htmlHeight: F2(htmlHeight), guid: Utils.guid }; };
slava-sh/core
src/Native/Graphics/Element.js
JavaScript
bsd-3-clause
16,290
// Copyright (c) 2014 Readium Foundation and/or its licensees. All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // 1. Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // 2. 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. // 3. Neither the name of the organization nor the names of its contributors may be // used to endorse or promote products derived from this software without specific // prior written permission. define(['workers/Messages'], function(Messages){ var FileUtils = (function(){ var toArray = function(list) { return Array.prototype.slice.call(list || [], 0); } var makeFile = function(root, filename, contents, callback, error){ root.getFile(filename, {create:true}, function(fileEntry){ fileEntry.createWriter(function(writer){ writer.onwriteend = function(){ // strange piece of the FileWriter api. Writing to an // existing file just overwrites content in place. Still need to truncate // which triggers onwritend event...again. o_O if (!writer.error && writer.position < writer.length){ writer.truncate(writer.position); } else if (callback) { callback(fileEntry); } } writer.onerror = function(e){ console.error('failed: ' + filename); error(writer.error); } if (contents instanceof ArrayBuffer){ contents = new Uint8Array(contents); } var blob = contents instanceof Blob ? contents : new Blob([contents]); writer.write(blob); }, error); }, error); } var makeDir = function(root, dirname, callback, error){ root.getDirectory(dirname, {create:true},callback, error); } return { mkdirs : function(root, dirname, callback, error){ var pathParts; if (dirname instanceof Array){ pathParts = dirname; } else{ pathParts = dirname.split('/'); } var makeDirCallback = function(dir){ if (pathParts.length){ makeDir(dir, pathParts.shift(), makeDirCallback, error); } else{ if (callback) callback(dir); } } makeDirCallback(root); }, rmDir : function (root, dirname, callback, error){ root.getDirectory(dirname, {create:true}, function(dirEntry){ dirEntry.removeRecursively(callback, error); }); }, rmFile : function(root, filename, callback, error){ root.getFile(filename, {create:true}, function(fileEntry){ fileEntry.remove(callback, error); }); }, mkfile : function(root, filename, contents, callback, error){ if (filename.charAt(0) == '/'){ filename = filename.substring(1); } var pathParts = filename.split('/'); if (pathParts.length > 1){ FileUtils.mkdirs(root, pathParts.slice(0, pathParts.length - 1), function(dir){ makeFile(dir, pathParts[pathParts.length - 1], contents, callback, error); }, error); } else{ makeFile(root, filename, contents, callback, error); } }, ls: function(dir, callback, error){ var reader = dir.createReader(); var entries = []; var readEntries = function() { reader.readEntries (function(results) { if (!results.length) { callback(entries); } else { entries = entries.concat(toArray(results)); readEntries(); } }, error); } readEntries(); }, readBlob: function(blob, dataType, callback){ var reader = new FileReader(); reader.onloadend = function(e){ callback(reader.result); } reader["readAs" + dataType](blob); }, readFileEntry : function(fileEntry, dataType, callback){ fileEntry.file(function(file){ FileUtils.readBlob(file, dataType, callback); }); }, readFile : function(root, file, dataType, callback, error) { root.getFile(file, {create:false}, function(fileEntry){ FileUtils.readFileEntry(fileEntry, dataType, callback, error); }, error); } }; } )(); var rootDir; var wrapErrorHandler = function(op, path, handler){ return function(err){ var data = {original: err, path: path, error: err.name, op: op}; handler(Messages.ERROR_STORAGE, data); console.error(data); } }; var copyDir = function(from, to, success, error){ FileUtils.ls(from, function(entries){ var counter = 0; var checkFinished = function(){ if (++counter == entries.length){ success(); } } entries.forEach(function(entry){ if (entry.isFile){ entry.file(function(file){ FileUtils.mkfile(to, entry.name, file, checkFinished); }); } else{ FileUtils.mkdirs(to, entry.name, function(dir){ copyDir(entry, dir, checkFinished); }, error); } }); }, error); } var migrateBook = function(tempRoot, ebookData, success, error){ var rootDirName = ebookData.key; tempRoot.getDirectory(rootDirName, {create: false}, function(oldBookRoot){ var nextStep = function(){ rootDir.getDirectory(rootDirName, {create: true}, function(newBookRoot){ copyDir(oldBookRoot, newBookRoot, success, error); }, error); } rootDir.getDirectory(rootDirName, {create: false}, function(newBookRoot){ newBookRoot.removeRecursively(nextStep, error); }, nextStep); }, error); } var migrateBookFiles = function(existingBooks, db, results, success, error, progress){ var extensionId = self.location.hostname; requestFileSystem(self.TEMPORARY, 5*1024*1024*1024, function(fs){ var tempRoot = fs.root; var ebooks = []; for (var i = 0; i < results.rows.length; i++){ var ebookData = JSON.parse(results.rows.item(i).value); // not all records contain books if (ebookData.id){ ebooks.push(ebookData); } } var count = 0; var checkFinished = function(ebook){ if (++count == ebooks.length){ success(); } else{ progress(Math.round(count/ebooks.length * 100), ebook.title); } } ebooks.forEach(function(ebook){ migrateBook(tempRoot, ebook, function(){ var oldRootUrl = "filesystem:chrome-extension://" + extensionId + '/temporary/', coverPath = ebook.cover_href ? ebook.cover_href.substring(oldRootUrl.length) : null; var newObj = { id: ebook.id, rootDir: ebook.key, rootUrl : StaticStorageManager.getPathUrl(ebook.key), packagePath: ebook.package_doc_path.substring(ebook.key.length + 1), title: ebook.title, author: ebook.author, coverHref: (coverPath ? StaticStorageManager.getPathUrl(coverPath) : null) } existingBooks.push(newObj); var blob = new Blob([JSON.stringify(existingBooks)]); StaticStorageManager.saveFile('/epub_library.json', blob, function(){ db.transaction(function(t){ t.executeSql('delete from records where id=? or id=?', [ebook.key, ebook.key + '_epubViewProperties'], checkFinished.bind(null, ebook), error); }); }, error); }); }); }, error); } var migrateBooks = function(success, error, progress){ var db = openDatabase('records', '1.0.0', 'records', 65536); if (db){ db.transaction(function(t){ t.executeSql("select id, value from records", [], function(xxx, results){ if (results.rows.length) { var nextStep = function(data){ var library = []; if (typeof data == 'string' || data instanceof String){ library = JSON.parse(data); } migrateBookFiles(library, db, results, success, error, progress); } FileUtils.readFile(rootDir, '/epub_library.json', 'Text', nextStep, nextStep) } else{ success(); } }, error); }); } } self.requestFileSystem = self.requestFileSystem || self.webkitRequestFileSystem; var StaticStorageManager = { saveFile : function(path, blob, success, error){ FileUtils.mkfile(rootDir, path, blob, success, wrapErrorHandler('save', path, error)); }, deleteFile : function(path, success, error){ var errorHandler = wrapErrorHandler('delete', path, error); if (path == '/'){ FileUtils.ls(rootDir, function(entries){ var count = entries.length; var checkDone = function(){ if (--count == 0){ success(); } } entries.forEach(function(entry){ if (entry.isDirectory){ entry.removeRecursively(checkDone, errorHandler) } else{ entry.remove(checkDone, errorHandler); } }); }, error); } else{ FileUtils.rmDir(rootDir, path, success, errorHandler); } }, getPathUrl : function(path){ if (path.charAt(0) == '/') path = path.substring(1); return rootDir.toURL() + path }, initStorage : function(success, error){ if (rootDir){ success(); return; } requestFileSystem(self.PERSISTENT, 5*1024*1024*1024, function(fs){ rootDir = fs.root; success(); }, wrapErrorHandler('init', '/', error)); }, migrateLegacyBooks : function(success, error, progress){ var errorWrap = function(){ var data = JSON.stringify(arguments); var errorMsg = 'Unexpected error while migrating. ' + data; console.error(errorMsg) error(errorMsg); } migrateBooks(success, errorWrap, progress); } } //$(window).bind('libraryUIReady', function(){ return StaticStorageManager; });
cene-co-za/readium-js-viewer
chrome-app/storage/FileSystemStorage.js
JavaScript
bsd-3-clause
10,052
import {NavigationView, Page, contentView} from 'tabris'; new NavigationView({layoutData: 'stretch'}) .append(new Page({title: 'Albums'})) .appendTo(contentView);
eclipsesource/tabris-js
doc/api/Page.js
JavaScript
bsd-3-clause
168
define(['test/mocks/lazo'], function (lazo) { function createView(ctl, id, LazoView, _) { var el; var template = _.template('I am a template!'); el = LAZO.app.isClient ? $('<div class="view-"' + id + '>') : null; return new LazoView({ el: el, templateEngine: 'micro', template: template, ctl: ctl }); } // these paths do not exist until after the intern configuration has // been set. requirejs will be defined at this point. return { setUpApp: function (callback) { requirejs(['underscore'], function (_) { var template = _.template('I am a template!'); LAZO.app.getDefaultTemplateEngineName = function () {}; LAZO.app.getTemplateEngine = function () { return { compile: function (template) { return _.template(template); }, execute: function (compiledTemplate, data) { return compiledTemplate(data); }, engine: _.template }; }; callback(); }); }, createCtlTree: function (callback) { requirejs(['lazoView', 'underscore'], function (LazoView, _) { var childCtl; var ctl = { currentView: null, children: { foo: [] } }; for (var i = 0; i < 3; i++) { if (!i) { ctl.currentView = createView(ctl, i, LazoView, _); ctl.currentView.template = _.template('<div lazo-cmp-container="foo"></div>'); ctl.cid = i; ctl.name = 'name' + i; ctl.ctx = {}; } else { childCtl = { currentView: null, cid: i, name: 'name' + i, ctx: {} }; childCtl.currentView = createView(childCtl, i, LazoView, _); ctl.children.foo.push(childCtl); } } callback(ctl); }); } }; });
rodfernandez/lazojs
test/unit/utils.js
JavaScript
mit
2,508
/** * Copyright (c) 2008-2010 The Open Source Geospatial Foundation * * Published under the BSD license. * See http://svn.geoext.org/core/trunk/geoext/license.txt for the full text * of the license. */ /** * @requires GeoExt/widgets/tips/SliderTip.js */ /** api: (extends) * GeoExt/widgets/tips/SliderTip.js */ /** api: (define) * module = GeoExt * class = LayerOpacitySliderTip * base_link = `Ext.Tip <http://dev.sencha.com/deploy/dev/docs/?class=Ext.Tip>`_ */ Ext.namespace("GeoExt"); /** api: example * Sample code to create a slider tip to display scale and resolution: * * .. code-block:: javascript * * var slider = new GeoExt.LayerOpacitySlider({ * renderTo: document.body, * width: 200, * layer: layer, * plugins: new GeoExt.LayerOpacitySliderTip({ * template: "Opacity: {opacity}%" * }) * }); */ /** api: constructor * .. class:: LayerOpacitySliderTip(config) * * Create a slider tip displaying :class:`GeoExt.LayerOpacitySlider` values. */ GeoExt.LayerOpacitySliderTip = Ext.extend(GeoExt.SliderTip, { /** api: config[template] * ``String`` * Template for the tip. Can be customized using the following keywords in * curly braces: * * * ``opacity`` - the opacity value in percent. */ template: '<div>{opacity}%</div>', /** private: property[compiledTemplate] * ``Ext.Template`` * The template compiled from the ``template`` string on init. */ compiledTemplate: null, /** private: method[init] * Called to initialize the plugin. */ init: function(slider) { this.compiledTemplate = new Ext.Template(this.template); GeoExt.LayerOpacitySliderTip.superclass.init.call(this, slider); }, /** private: method[getText] * :param slider: ``Ext.Slider`` The slider this tip is attached to. */ getText: function(thumb) { var data = { opacity: thumb.value }; return this.compiledTemplate.apply(data); } });
ksetyadi/Sahana-Eden
static/scripts/gis/GeoExt/lib/GeoExt/widgets/tips/LayerOpacitySliderTip.js
JavaScript
mit
2,088
/* eslint-env mocha */ /* eslint max-nested-callbacks: ["error", 5] */ 'use strict' const chai = require('chai') const dirtyChai = require('dirty-chai') const expect = chai.expect chai.use(require('chai-checkmark')) chai.use(dirtyChai) const sinon = require('sinon') const PeerBook = require('peer-book') const parallel = require('async/parallel') const series = require('async/series') const WS = require('libp2p-websockets') const TCP = require('libp2p-tcp') const secio = require('libp2p-secio') const multiplex = require('pull-mplex') const pull = require('pull-stream') const identify = require('libp2p-identify') const utils = require('./utils') const createInfos = utils.createInfos const Switch = require('../src') describe('dialFSM', () => { let switchA let switchB let switchC let switchDialOnly let peerAId let peerBId let protocol before((done) => createInfos(4, (err, infos) => { expect(err).to.not.exist() const peerA = infos[0] const peerB = infos[1] const peerC = infos[2] const peerDialOnly = infos[3] peerAId = peerA.id.toB58String() peerBId = peerB.id.toB58String() peerA.multiaddrs.add('/ip4/0.0.0.0/tcp/0') peerB.multiaddrs.add('/ip4/0.0.0.0/tcp/0') peerC.multiaddrs.add('/ip4/0.0.0.0/tcp/0/ws') // Give peer C a tcp address we wont actually support peerC.multiaddrs.add('/ip4/0.0.0.0/tcp/0') switchA = new Switch(peerA, new PeerBook()) switchB = new Switch(peerB, new PeerBook()) switchC = new Switch(peerC, new PeerBook()) switchDialOnly = new Switch(peerDialOnly, new PeerBook()) switchA.transport.add('tcp', new TCP()) switchB.transport.add('tcp', new TCP()) switchC.transport.add('ws', new WS()) switchDialOnly.transport.add('ws', new WS()) switchA.connection.crypto(secio.tag, secio.encrypt) switchB.connection.crypto(secio.tag, secio.encrypt) switchC.connection.crypto(secio.tag, secio.encrypt) switchDialOnly.connection.crypto(secio.tag, secio.encrypt) switchA.connection.addStreamMuxer(multiplex) switchB.connection.addStreamMuxer(multiplex) switchC.connection.addStreamMuxer(multiplex) switchDialOnly.connection.addStreamMuxer(multiplex) switchA.connection.reuse() switchB.connection.reuse() switchC.connection.reuse() switchDialOnly.connection.reuse() parallel([ (cb) => switchA.start(cb), (cb) => switchB.start(cb), (cb) => switchC.start(cb) ], done) })) after((done) => { parallel([ (cb) => switchA.stop(cb), (cb) => switchB.stop(cb), (cb) => switchC.stop(cb) ], done) }) afterEach(() => { switchA.unhandle(protocol) switchB.unhandle(protocol) switchC.unhandle(protocol) protocol = null }) it('should emit `error:connection_attempt_failed` when a transport fails to dial', (done) => { protocol = '/warn/1.0.0' switchC.handle(protocol, () => { }) switchA.dialFSM(switchC._peerInfo, protocol, (err, connFSM) => { expect(err).to.not.exist() connFSM.once('error:connection_attempt_failed', (errors) => { expect(errors).to.be.an('array') expect(errors).to.have.length(1) done() }) }) }) it('should emit an `error` event when a it cannot dial a peer', (done) => { protocol = '/error/1.0.0' switchC.handle(protocol, () => { }) switchA.dialer.clearDenylist(switchC._peerInfo) switchA.dialFSM(switchC._peerInfo, protocol, (err, connFSM) => { expect(err).to.not.exist() connFSM.once('error', (err) => { expect(err).to.be.exist() expect(err).to.have.property('code', 'CONNECTION_FAILED') done() }) }) }) it('should error when the peer is denylisted', (done) => { protocol = '/error/1.0.0' switchC.handle(protocol, () => { }) switchA.dialer.clearDenylist(switchC._peerInfo) switchA.dialFSM(switchC._peerInfo, protocol, (err, connFSM) => { expect(err).to.not.exist() connFSM.once('error', () => { // dial with the denylist switchA.dialFSM(switchC._peerInfo, protocol, (err) => { expect(err).to.exist() expect(err.code).to.eql('ERR_DENIED') done() }) }) }) }) it('should not denylist a peer that was successfully connected', (done) => { protocol = '/nodenylist/1.0.0' switchB.handle(protocol, () => { }) switchA.dialer.clearDenylist(switchB._peerInfo) switchA.dialFSM(switchB._peerInfo, protocol, (err, connFSM) => { expect(err).to.not.exist() connFSM.once('connection', () => { connFSM.once('close', () => { // peer should not be denylisted switchA.dialFSM(switchB._peerInfo, protocol, (err, conn) => { expect(err).to.not.exist() conn.once('close', done) conn.close() }) }) connFSM.close(new Error('bad things')) }) }) }) it('should clear the denylist for a peer that connected to us', (done) => { series([ // Attempt to dial the peer that's not listening (cb) => switchC.dial(switchDialOnly._peerInfo, (err) => { expect(err).to.exist() cb() }), // Dial from the dial only peer (cb) => switchDialOnly.dial(switchC._peerInfo, (err) => { expect(err).to.not.exist() // allow time for muxing to occur setTimeout(cb, 100) }), // "Dial" to the dial only peer, this should reuse the existing connection (cb) => switchC.dial(switchDialOnly._peerInfo, (err) => { expect(err).to.not.exist() cb() }) ], (err) => { expect(err).to.not.exist() done() }) }) it('should emit a `closed` event when closed', (done) => { protocol = '/closed/1.0.0' switchB.handle(protocol, () => { }) switchA.dialFSM(switchB._peerInfo, protocol, (err, connFSM) => { expect(err).to.not.exist() connFSM.once('close', () => { expect(switchA.connection.getAllById(peerBId)).to.have.length(0) done() }) connFSM.once('muxed', () => { expect(switchA.connection.getAllById(peerBId)).to.have.length(1) connFSM.close() }) }) }) it('should have the peers protocols once connected', (done) => { protocol = '/lscheck/1.0.0' switchB.handle(protocol, () => { }) expect(4).checks(done) switchB.once('peer-mux-established', (peerInfo) => { const peerB = switchA._peerBook.get(switchB._peerInfo.id.toB58String()) const peerA = switchB._peerBook.get(switchA._peerInfo.id.toB58String()) // Verify the dialer knows the receiver's protocols expect(Array.from(peerB.protocols)).to.eql([ multiplex.multicodec, identify.multicodec, protocol ]).mark() // Verify the receiver knows the dialer's protocols expect(Array.from(peerA.protocols)).to.eql([ multiplex.multicodec, identify.multicodec ]).mark() switchA.hangUp(switchB._peerInfo) }) switchA.dialFSM(switchB._peerInfo, protocol, (err, connFSM) => { expect(err).to.not.exist().mark() connFSM.once('close', () => { // Just mark that close was called expect(true).to.eql(true).mark() }) }) }) it('should close when the receiver closes', (done) => { protocol = '/closed/1.0.0' switchB.handle(protocol, () => { }) // wait for the expects to happen expect(2).checks(() => { done() }) switchB.on('peer-mux-established', (peerInfo) => { if (peerInfo.id.toB58String() === peerAId) { switchB.removeAllListeners('peer-mux-established') expect(switchB.connection.getAllById(peerAId)).to.have.length(1).mark() switchB.connection.getOne(peerAId).close() } }) switchA.dialFSM(switchB._peerInfo, protocol, (err, connFSM) => { expect(err).to.not.exist() connFSM.once('close', () => { expect(switchA.connection.getAllById(peerBId)).to.have.length(0).mark() }) }) }) it('parallel dials to the same peer should not create new connections', (done) => { switchB.handle('/parallel/2.0.0', (_, conn) => { pull(conn, conn) }) parallel([ (cb) => switchA.dialFSM(switchB._peerInfo, '/parallel/2.0.0', cb), (cb) => switchA.dialFSM(switchB._peerInfo, '/parallel/2.0.0', cb) ], (err, results) => { expect(err).to.not.exist() expect(results).to.have.length(2) expect(switchA.connection.getAllById(peerBId)).to.have.length(1) switchA.hangUp(switchB._peerInfo, () => { expect(switchA.connection.getAllById(peerBId)).to.have.length(0) done() }) }) }) it('parallel dials to one another should disconnect on hangup', function (done) { this.timeout(10e3) protocol = '/parallel/1.0.0' switchA.handle(protocol, (_, conn) => { pull(conn, conn) }) switchB.handle(protocol, (_, conn) => { pull(conn, conn) }) expect(switchA.connection.getAllById(peerBId)).to.have.length(0) // Expect 4 `peer-mux-established` events expect(4).checks(() => { // Expect 2 `peer-mux-closed`, plus 1 hangup expect(3).checks(() => { switchA.removeAllListeners('peer-mux-closed') switchB.removeAllListeners('peer-mux-closed') switchA.removeAllListeners('peer-mux-established') switchB.removeAllListeners('peer-mux-established') done() }) switchA.hangUp(switchB._peerInfo, (err) => { expect(err).to.not.exist().mark() }) }) switchA.on('peer-mux-established', (peerInfo) => { expect(peerInfo.id.toB58String()).to.eql(peerBId).mark() }) switchB.on('peer-mux-established', (peerInfo) => { expect(peerInfo.id.toB58String()).to.eql(peerAId).mark() }) switchA.on('peer-mux-closed', (peerInfo) => { expect(peerInfo.id.toB58String()).to.eql(peerBId).mark() }) switchB.on('peer-mux-closed', (peerInfo) => { expect(peerInfo.id.toB58String()).to.eql(peerAId).mark() }) switchA.dialFSM(switchB._peerInfo, protocol, (err, connFSM) => { expect(err).to.not.exist() // Hold the dial from A, until switch B is done dialing to ensure // we have both incoming and outgoing connections connFSM._state.on('DIALING:leave', (cb) => { switchB.dialFSM(switchA._peerInfo, protocol, (err, connB) => { expect(err).to.not.exist() connB.on('muxed', cb) }) }) }) }) it('parallel dials to one another should disconnect on stop', (done) => { protocol = '/parallel/1.0.0' switchA.handle(protocol, (_, conn) => { pull(conn, conn) }) switchB.handle(protocol, (_, conn) => { pull(conn, conn) }) // 2 close checks and 1 hangup check expect(2).checks(() => { switchA.removeAllListeners('peer-mux-closed') switchB.removeAllListeners('peer-mux-closed') // restart the node for subsequent tests switchA.start(done) }) switchA.on('peer-mux-closed', (peerInfo) => { expect(peerInfo.id.toB58String()).to.eql(peerBId).mark() }) switchB.on('peer-mux-closed', (peerInfo) => { expect(peerInfo.id.toB58String()).to.eql(peerAId).mark() }) switchA.dialFSM(switchB._peerInfo, '/parallel/1.0.0', (err, connFSM) => { expect(err).to.not.exist() // Hold the dial from A, until switch B is done dialing to ensure // we have both incoming and outgoing connections connFSM._state.on('DIALING:leave', (cb) => { switchB.dialFSM(switchA._peerInfo, '/parallel/1.0.0', (err, connB) => { expect(err).to.not.exist() connB.on('muxed', cb) }) }) connFSM.on('connection', () => { // Hangup and verify the connections are closed switchA.stop((err) => { expect(err).to.not.exist().mark() }) }) }) }) it('queued dials should be aborted on node stop', (done) => { switchB.handle('/abort-queue/1.0.0', (_, conn) => { pull(conn, conn) }) switchA.dialFSM(switchB._peerInfo, '/abort-queue/1.0.0', (err, connFSM) => { expect(err).to.not.exist() // 2 conn aborts, 1 close, and 1 stop expect(4).checks(done) connFSM.once('close', (err) => { expect(err).to.not.exist().mark() }) sinon.stub(connFSM, '_onUpgrading').callsFake(() => { switchA.dialFSM(switchB._peerInfo, '/abort-queue/1.0.0', (err) => { expect(err.code).to.eql('DIAL_ABORTED').mark() }) switchA.dialFSM(switchB._peerInfo, '/abort-queue/1.0.0', (err) => { expect(err.code).to.eql('DIAL_ABORTED').mark() }) switchA.stop((err) => { expect(err).to.not.exist().mark() }) }) }) }) })
diasdavid/node-libp2p-swarm
test/dial-fsm.node.js
JavaScript
mit
12,799
'use strict'; var gulp = require('gulp'); var bump = require('gulp-bump'); var concat = require('gulp-concat'); var filter = require('gulp-filter'); var inject = require('gulp-inject'); var minifyCSS = require('gulp-minify-css'); var minifyHTML = require('gulp-minify-html'); var plumber = require('gulp-plumber'); var sourcemaps = require('gulp-sourcemaps'); var template = require('gulp-template'); var tsc = require('gulp-typescript'); var uglify = require('gulp-uglify'); var watch = require('gulp-watch'); var Builder = require('systemjs-builder'); var del = require('del'); var fs = require('fs'); var path = require('path'); var join = path.join; var runSequence = require('run-sequence'); var semver = require('semver'); var series = require('stream-series'); var express = require('express'); var serveStatic = require('serve-static'); var openResource = require('open'); var tinylr = require('tiny-lr')(); var connectLivereload = require('connect-livereload'); // -------------- // Configuration. var APP_BASE = '/'; var PATH = { dest: { all: 'dist', dev: { all: 'dist/dev', lib: 'dist/dev/lib', ng2: 'dist/dev/lib/angular2.js', router: 'dist/dev/lib/router.js' }, prod: { all: 'dist/prod', lib: 'dist/prod/lib' } }, src: { // Order is quite important here for the HTML tag injection. lib: [ './node_modules/angular2/node_modules/traceur/bin/traceur-runtime.js', './node_modules/es6-module-loader/dist/es6-module-loader-sans-promises.js', './node_modules/es6-module-loader/dist/es6-module-loader-sans-promises.js.map', './node_modules/reflect-metadata/Reflect.js', './node_modules/reflect-metadata/Reflect.js.map', './node_modules/systemjs/dist/system.src.js', './node_modules/angular2/node_modules/zone.js/dist/zone.js' ] } }; var PORT = 5555; var LIVE_RELOAD_PORT = 4002; var ng2Builder = new Builder({ paths: { 'angular2/*': 'node_modules/angular2/es6/dev/*.js', rx: 'node_modules/angular2/node_modules/rx/dist/rx.js' }, meta: { rx: { format: 'cjs' } } }); var appProdBuilder = new Builder({ baseURL: 'file:./tmp', meta: { 'angular2/angular2': { build: false }, 'angular2/router': { build: false } } }); var HTMLMinifierOpts = { conditionals: true }; var tsProject = tsc.createProject('tsconfig.json', { typescript: require('typescript') }); var semverReleases = ['major', 'premajor', 'minor', 'preminor', 'patch', 'prepatch', 'prerelease']; // -------------- // Clean. gulp.task('clean', function (done) { del(PATH.dest.all, done); }); gulp.task('clean.dev', function (done) { del(PATH.dest.dev.all, done); }); gulp.task('clean.app.dev', function (done) { // TODO: rework this part. del([join(PATH.dest.dev.all, '**/*'), '!' + PATH.dest.dev.lib, '!' + join(PATH.dest.dev.lib, '*')], done); }); gulp.task('clean.prod', function (done) { del(PATH.dest.prod.all, done); }); gulp.task('clean.app.prod', function (done) { // TODO: rework this part. del([join(PATH.dest.prod.all, '**/*'), '!' + PATH.dest.prod.lib, '!' + join(PATH.dest.prod.lib, '*')], done); }); gulp.task('clean.tmp', function(done) { del('tmp', done); }); // -------------- // Build dev. gulp.task('build.ng2.dev', function () { ng2Builder.build('angular2/router', PATH.dest.dev.router, {}); return ng2Builder.build('angular2/angular2', PATH.dest.dev.ng2, {}); }); gulp.task('build.lib.dev', ['build.ng2.dev'], function () { return gulp.src(PATH.src.lib) .pipe(gulp.dest(PATH.dest.dev.lib)); }); gulp.task('build.js.dev', function () { var result = gulp.src('./app/**/*ts') .pipe(plumber()) .pipe(sourcemaps.init()) .pipe(tsc(tsProject)); return result.js .pipe(sourcemaps.write()) .pipe(template(templateLocals())) .pipe(gulp.dest(PATH.dest.dev.all)); }); gulp.task('build.assets.dev', ['build.js.dev'], function () { return gulp.src(['./app/**/*.html', './app/**/*.css']) .pipe(gulp.dest(PATH.dest.dev.all)); }); gulp.task('build.index.dev', function() { var target = gulp.src(injectableDevAssetsRef(), { read: false }); return gulp.src('./app/index.html') .pipe(inject(target, { transform: transformPath('dev') })) .pipe(template(templateLocals())) .pipe(gulp.dest(PATH.dest.dev.all)); }); gulp.task('build.app.dev', function (done) { runSequence('clean.app.dev', 'build.assets.dev', 'build.index.dev', done); }); gulp.task('build.dev', function (done) { runSequence('clean.dev', 'build.lib.dev', 'build.app.dev', done); }); // -------------- // Build prod. gulp.task('build.ng2.prod', function () { ng2Builder.build('angular2/router', join('tmp', 'router.js'), {}); return ng2Builder.build('angular2/angular2', join('tmp', 'angular2.js'), {}); }); gulp.task('build.lib.prod', ['build.ng2.prod'], function () { var jsOnly = filter('**/*.js'); var lib = gulp.src(PATH.src.lib); var ng2 = gulp.src('tmp/angular2.js'); var router = gulp.src('tmp/router.js'); return series(lib, ng2, router) .pipe(jsOnly) .pipe(concat('lib.js')) .pipe(uglify()) .pipe(gulp.dest(PATH.dest.prod.lib)); }); gulp.task('build.js.tmp', function () { var result = gulp.src(['./app/**/*ts', '!./app/init.ts']) .pipe(plumber()) .pipe(tsc(tsProject)); return result.js .pipe(template({ VERSION: getVersion() })) .pipe(gulp.dest('tmp')); }); // TODO: add inline source maps (System only generate separate source maps file). gulp.task('build.js.prod', ['build.js.tmp'], function() { return appProdBuilder.build('app', join(PATH.dest.prod.all, 'app.js'), { minify: true }).catch(function (e) { console.log(e); }); }); gulp.task('build.init.prod', function() { var result = gulp.src('./app/init.ts') .pipe(plumber()) .pipe(sourcemaps.init()) .pipe(tsc(tsProject)); return result.js .pipe(uglify()) .pipe(template(templateLocals())) .pipe(sourcemaps.write()) .pipe(gulp.dest(PATH.dest.prod.all)); }); gulp.task('build.assets.prod', ['build.js.prod'], function () { var filterHTML = filter('**/*.html'); var filterCSS = filter('**/*.css'); return gulp.src(['./app/**/*.html', './app/**/*.css']) .pipe(filterHTML) .pipe(minifyHTML(HTMLMinifierOpts)) .pipe(filterHTML.restore()) .pipe(filterCSS) .pipe(minifyCSS()) .pipe(filterCSS.restore()) .pipe(gulp.dest(PATH.dest.prod.all)); }); gulp.task('build.index.prod', function() { var target = gulp.src([join(PATH.dest.prod.lib, 'lib.js'), join(PATH.dest.prod.all, '**/*.css')], { read: false }); return gulp.src('./app/index.html') .pipe(inject(target, { transform: transformPath('prod') })) .pipe(template(templateLocals())) .pipe(gulp.dest(PATH.dest.prod.all)); }); gulp.task('build.app.prod', function (done) { // build.init.prod does not work as sub tasks dependencies so placed it here. runSequence('clean.app.prod', 'build.init.prod', 'build.assets.prod', 'build.index.prod', 'clean.tmp', done); }); gulp.task('build.prod', function (done) { runSequence('clean.prod', 'build.lib.prod', 'clean.tmp', 'build.app.prod', done); }); // -------------- // Version. registerBumpTasks(); gulp.task('bump.reset', function() { return gulp.src('package.json') .pipe(bump({ version: '0.0.0' })) .pipe(gulp.dest('./')); }); // -------------- // Test. // To be implemented. // -------------- // Serve dev. gulp.task('serve.dev', ['build.dev', 'livereload'], function () { watch('./app/**', function (e) { runSequence('build.app.dev', function () { notifyLiveReload(e); }); }); serveSPA('dev'); }); // -------------- // Serve prod. gulp.task('serve.prod', ['build.prod', 'livereload'], function () { watch('./app/**', function (e) { runSequence('build.app.prod', function () { notifyLiveReload(e); }); }); serveSPA('prod'); }); // -------------- // Livereload. gulp.task('livereload', function() { tinylr.listen(LIVE_RELOAD_PORT); }); // -------------- // Utils. function notifyLiveReload(e) { var fileName = e.path; tinylr.changed({ body: { files: [fileName] } }); } function transformPath(env) { var v = '?v=' + getVersion(); return function (filepath) { var filename = filepath.replace('/' + PATH.dest[env].all, '') + v; arguments[0] = join(APP_BASE, filename); return inject.transform.apply(inject.transform, arguments); }; } function injectableDevAssetsRef() { var src = PATH.src.lib.map(function(path) { return join(PATH.dest.dev.lib, path.split('/').pop()); }); src.push(PATH.dest.dev.ng2, PATH.dest.dev.router, join(PATH.dest.dev.all, '**/*.css')); return src; } function getVersion(){ var pkg = JSON.parse(fs.readFileSync('package.json')); return pkg.version; } function templateLocals() { return { VERSION: getVersion(), APP_BASE: APP_BASE }; } function registerBumpTasks() { semverReleases.forEach(function (release) { var semverTaskName = 'semver.' + release; var bumpTaskName = 'bump.' + release; gulp.task(semverTaskName, function() { var version = semver.inc(getVersion(), release); return gulp.src('package.json') .pipe(bump({ version: version })) .pipe(gulp.dest('./')); }); gulp.task(bumpTaskName, function(done) { runSequence(semverTaskName, 'build.app.prod', done); }); }); } function serveSPA(env) { var app; app = express().use(APP_BASE, connectLivereload({ port: LIVE_RELOAD_PORT }), serveStatic(join(__dirname, PATH.dest[env].all))); app.all(APP_BASE + '*', function (req, res, next) { res.sendFile(join(__dirname, PATH.dest[env].all, 'index.html')); }); app.listen(PORT, function () { openResource('http://localhost:' + PORT + APP_BASE); }); }
uxnivek/angular2-seed
gulpfile.js
JavaScript
mit
9,897
goog.provide('interactionbtngroup'); goog.require('ngeo.DecorateInteraction'); goog.require('ngeo.btngroupDirective'); goog.require('ngeo.mapDirective'); goog.require('ol.FeatureOverlay'); goog.require('ol.Map'); goog.require('ol.View'); goog.require('ol.interaction.Draw'); goog.require('ol.layer.Tile'); goog.require('ol.source.MapQuest'); /** @const **/ var app = {}; /** @type {!angular.Module} **/ app.module = angular.module('app', ['ngeo']); /** * @param {ngeo.DecorateInteraction} ngeoDecorateInteraction Decorate * interaction service. * @constructor * @ngInject */ app.MainController = function(ngeoDecorateInteraction) { var source = new ol.source.Vector(); var vector = new ol.layer.Vector({ source: source, style: new ol.style.Style({ fill: new ol.style.Fill({ color: 'rgba(255, 255, 255, 0.2)' }), stroke: new ol.style.Stroke({ color: '#ffcc33', width: 2 }), image: new ol.style.Circle({ radius: 7, fill: new ol.style.Fill({ color: '#ffcc33' }) }) }) }); /** @type {ol.Map} */ var map = new ol.Map({ layers: [ new ol.layer.Tile({ source: new ol.source.MapQuest({layer: 'sat'}) }), vector ], view: new ol.View({ center: [-10997148, 4569099], zoom: 4 }) }); this['map'] = map; /** @type {ol.interaction.Draw} */ var drawPolygon = new ol.interaction.Draw( /** @type {olx.interaction.DrawOptions} */ ({ type: 'Polygon', source: source })); drawPolygon.setActive(false); ngeoDecorateInteraction(drawPolygon); map.addInteraction(drawPolygon); this['drawPolygon'] = drawPolygon; /** @type {ol.interaction.Draw} */ var drawPoint = new ol.interaction.Draw( /** @type {olx.interaction.DrawOptions} */ ({ type: 'Point', source: source })); drawPoint.setActive(false); ngeoDecorateInteraction(drawPoint); map.addInteraction(drawPoint); this['drawPoint'] = drawPoint; /** @type {ol.interaction.Draw} */ var drawLine = new ol.interaction.Draw( /** @type {olx.interaction.DrawOptions} */ ({ type: 'LineString', source: source })); drawLine.setActive(false); ngeoDecorateInteraction(drawLine); map.addInteraction(drawLine); this['drawLine'] = drawLine; }; app.module.controller('MainController', app.MainController);
gberaudo/ngeo
examples/interactionbtngroup.js
JavaScript
mit
2,434
/* CryptoJS v3.1.2 code.google.com/p/crypto-js (c) 2009-2013 by Jeff Mott. All rights reserved. code.google.com/p/crypto-js/wiki/License */ /** * CryptoJS core components. */ var CryptoJS = CryptoJS || (function (Math, undefined) { /** * CryptoJS namespace. */ var C = {}; /** * Library namespace. */ var C_lib = C.lib = {}; /** * Base object for prototypal inheritance. */ var Base = C_lib.Base = (function () { function F() {} return { /** * Creates a new object that inherits from this object. * * @param {Object} overrides Properties to copy into the new object. * * @return {Object} The new object. * * @static * * @example * * var MyType = CryptoJS.lib.Base.extend({ * field: 'value', * * method: function () { * } * }); */ extend: function (overrides) { // Spawn F.prototype = this; var subtype = new F(); // Augment if (overrides) { subtype.mixIn(overrides); } // Create default initializer if (!subtype.hasOwnProperty('init')) { subtype.init = function () { subtype.$super.init.apply(this, arguments); }; } // Initializer's prototype is the subtype object subtype.init.prototype = subtype; // Reference supertype subtype.$super = this; return subtype; }, /** * Extends this object and runs the init method. * Arguments to create() will be passed to init(). * * @return {Object} The new object. * * @static * * @example * * var instance = MyType.create(); */ create: function () { var instance = this.extend(); instance.init.apply(instance, arguments); return instance; }, /** * Initializes a newly created object. * Override this method to add some logic when your objects are created. * * @example * * var MyType = CryptoJS.lib.Base.extend({ * init: function () { * // ... * } * }); */ init: function () { }, /** * Copies properties into this object. * * @param {Object} properties The properties to mix in. * * @example * * MyType.mixIn({ * field: 'value' * }); */ mixIn: function (properties) { for (var propertyName in properties) { if (properties.hasOwnProperty(propertyName)) { this[propertyName] = properties[propertyName]; } } // IE won't copy toString using the loop above if (properties.hasOwnProperty('toString')) { this.toString = properties.toString; } }, /** * Creates a copy of this object. * * @return {Object} The clone. * * @example * * var clone = instance.clone(); */ clone: function () { return this.init.prototype.extend(this); } }; }()); /** * An array of 32-bit words. * * @property {Array} words The array of 32-bit words. * @property {number} sigBytes The number of significant bytes in this word array. */ var WordArray = C_lib.WordArray = Base.extend({ /** * Initializes a newly created word array. * * @param {Array} words (Optional) An array of 32-bit words. * @param {number} sigBytes (Optional) The number of significant bytes in the words. * * @example * * var wordArray = CryptoJS.lib.WordArray.create(); * var wordArray = CryptoJS.lib.WordArray.create([0x00010203, 0x04050607]); * var wordArray = CryptoJS.lib.WordArray.create([0x00010203, 0x04050607], 6); */ init: function (words, sigBytes) { words = this.words = words || []; if (sigBytes != undefined) { this.sigBytes = sigBytes; } else { this.sigBytes = words.length * 4; } }, /** * Converts this word array to a string. * * @param {Encoder} encoder (Optional) The encoding strategy to use. Default: CryptoJS.enc.Hex * * @return {string} The stringified word array. * * @example * * var string = wordArray + ''; * var string = wordArray.toString(); * var string = wordArray.toString(CryptoJS.enc.Utf8); */ toString: function (encoder) { return (encoder || Hex).stringify(this); }, /** * Concatenates a word array to this word array. * * @param {WordArray} wordArray The word array to append. * * @return {WordArray} This word array. * * @example * * wordArray1.concat(wordArray2); */ concat: function (wordArray) { // Shortcuts var thisWords = this.words; var thatWords = wordArray.words; var thisSigBytes = this.sigBytes; var thatSigBytes = wordArray.sigBytes; // Clamp excess bits this.clamp(); // Concat if (thisSigBytes % 4) { // Copy one byte at a time for (var i = 0; i < thatSigBytes; i++) { var thatByte = (thatWords[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff; thisWords[(thisSigBytes + i) >>> 2] |= thatByte << (24 - ((thisSigBytes + i) % 4) * 8); } } else if (thatWords.length > 0xffff) { // Copy one word at a time for (var i = 0; i < thatSigBytes; i += 4) { thisWords[(thisSigBytes + i) >>> 2] = thatWords[i >>> 2]; } } else { // Copy all words at once thisWords.push.apply(thisWords, thatWords); } this.sigBytes += thatSigBytes; // Chainable return this; }, /** * Removes insignificant bits. * * @example * * wordArray.clamp(); */ clamp: function () { // Shortcuts var words = this.words; var sigBytes = this.sigBytes; // Clamp words[sigBytes >>> 2] &= 0xffffffff << (32 - (sigBytes % 4) * 8); words.length = Math.ceil(sigBytes / 4); }, /** * Creates a copy of this word array. * * @return {WordArray} The clone. * * @example * * var clone = wordArray.clone(); */ clone: function () { var clone = Base.clone.call(this); clone.words = this.words.slice(0); return clone; }, /** * Creates a word array filled with random bytes. * * @param {number} nBytes The number of random bytes to generate. * * @return {WordArray} The random word array. * * @static * * @example * * var wordArray = CryptoJS.lib.WordArray.random(16); */ random: function (nBytes) { var words = []; for (var i = 0; i < nBytes; i += 4) { words.push((Math.random() * 0x100000000) | 0); } return new WordArray.init(words, nBytes); } }); /** * Encoder namespace. */ var C_enc = C.enc = {}; /** * Hex encoding strategy. */ var Hex = C_enc.Hex = { /** * Converts a word array to a hex string. * * @param {WordArray} wordArray The word array. * * @return {string} The hex string. * * @static * * @example * * var hexString = CryptoJS.enc.Hex.stringify(wordArray); */ stringify: function (wordArray) { // Shortcuts var words = wordArray.words; var sigBytes = wordArray.sigBytes; // Convert var hexChars = []; for (var i = 0; i < sigBytes; i++) { var bite = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff; hexChars.push((bite >>> 4).toString(16)); hexChars.push((bite & 0x0f).toString(16)); } return hexChars.join(''); }, /** * Converts a hex string to a word array. * * @param {string} hexStr The hex string. * * @return {WordArray} The word array. * * @static * * @example * * var wordArray = CryptoJS.enc.Hex.parse(hexString); */ parse: function (hexStr) { // Shortcut var hexStrLength = hexStr.length; // Convert var words = []; for (var i = 0; i < hexStrLength; i += 2) { words[i >>> 3] |= parseInt(hexStr.substr(i, 2), 16) << (24 - (i % 8) * 4); } return new WordArray.init(words, hexStrLength / 2); } }; /** * Latin1 encoding strategy. */ var Latin1 = C_enc.Latin1 = { /** * Converts a word array to a Latin1 string. * * @param {WordArray} wordArray The word array. * * @return {string} The Latin1 string. * * @static * * @example * * var latin1String = CryptoJS.enc.Latin1.stringify(wordArray); */ stringify: function (wordArray) { // Shortcuts var words = wordArray.words; var sigBytes = wordArray.sigBytes; // Convert var latin1Chars = []; for (var i = 0; i < sigBytes; i++) { var bite = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff; latin1Chars.push(String.fromCharCode(bite)); } return latin1Chars.join(''); }, /** * Converts a Latin1 string to a word array. * * @param {string} latin1Str The Latin1 string. * * @return {WordArray} The word array. * * @static * * @example * * var wordArray = CryptoJS.enc.Latin1.parse(latin1String); */ parse: function (latin1Str) { // Shortcut var latin1StrLength = latin1Str.length; // Convert var words = []; for (var i = 0; i < latin1StrLength; i++) { words[i >>> 2] |= (latin1Str.charCodeAt(i) & 0xff) << (24 - (i % 4) * 8); } return new WordArray.init(words, latin1StrLength); } }; /** * UTF-8 encoding strategy. */ var Utf8 = C_enc.Utf8 = { /** * Converts a word array to a UTF-8 string. * * @param {WordArray} wordArray The word array. * * @return {string} The UTF-8 string. * * @static * * @example * * var utf8String = CryptoJS.enc.Utf8.stringify(wordArray); */ stringify: function (wordArray) { try { return decodeURIComponent(escape(Latin1.stringify(wordArray))); } catch (e) { throw new Error('Malformed UTF-8 data'); } }, /** * Converts a UTF-8 string to a word array. * * @param {string} utf8Str The UTF-8 string. * * @return {WordArray} The word array. * * @static * * @example * * var wordArray = CryptoJS.enc.Utf8.parse(utf8String); */ parse: function (utf8Str) { return Latin1.parse(unescape(encodeURIComponent(utf8Str))); } }; /** * Abstract buffered block algorithm template. * * The property blockSize must be implemented in a concrete subtype. * * @property {number} _minBufferSize The number of blocks that should be kept unprocessed in the buffer. Default: 0 */ var BufferedBlockAlgorithm = C_lib.BufferedBlockAlgorithm = Base.extend({ /** * Resets this block algorithm's data buffer to its initial state. * * @example * * bufferedBlockAlgorithm.reset(); */ reset: function () { // Initial values this._data = new WordArray.init(); this._nDataBytes = 0; }, /** * Adds new data to this block algorithm's buffer. * * @param {WordArray|string} data The data to append. Strings are converted to a WordArray using UTF-8. * * @example * * bufferedBlockAlgorithm._append('data'); * bufferedBlockAlgorithm._append(wordArray); */ _append: function (data) { // Convert string to WordArray, else assume WordArray already if (typeof data == 'string') { data = Utf8.parse(data); } // Append this._data.concat(data); this._nDataBytes += data.sigBytes; }, /** * Processes available data blocks. * * This method invokes _doProcessBlock(offset), which must be implemented by a concrete subtype. * * @param {boolean} doFlush Whether all blocks and partial blocks should be processed. * * @return {WordArray} The processed data. * * @example * * var processedData = bufferedBlockAlgorithm._process(); * var processedData = bufferedBlockAlgorithm._process(!!'flush'); */ _process: function (doFlush) { // Shortcuts var data = this._data; var dataWords = data.words; var dataSigBytes = data.sigBytes; var blockSize = this.blockSize; var blockSizeBytes = blockSize * 4; // Count blocks ready var nBlocksReady = dataSigBytes / blockSizeBytes; if (doFlush) { // Round up to include partial blocks nBlocksReady = Math.ceil(nBlocksReady); } else { // Round down to include only full blocks, // less the number of blocks that must remain in the buffer nBlocksReady = Math.max((nBlocksReady | 0) - this._minBufferSize, 0); } // Count words ready var nWordsReady = nBlocksReady * blockSize; // Count bytes ready var nBytesReady = Math.min(nWordsReady * 4, dataSigBytes); // Process blocks if (nWordsReady) { for (var offset = 0; offset < nWordsReady; offset += blockSize) { // Perform concrete-algorithm logic this._doProcessBlock(dataWords, offset); } // Remove processed words var processedWords = dataWords.splice(0, nWordsReady); data.sigBytes -= nBytesReady; } // Return processed words return new WordArray.init(processedWords, nBytesReady); }, /** * Creates a copy of this object. * * @return {Object} The clone. * * @example * * var clone = bufferedBlockAlgorithm.clone(); */ clone: function () { var clone = Base.clone.call(this); clone._data = this._data.clone(); return clone; }, _minBufferSize: 0 }); /** * Abstract hasher template. * * @property {number} blockSize The number of 32-bit words this hasher operates on. Default: 16 (512 bits) */ var Hasher = C_lib.Hasher = BufferedBlockAlgorithm.extend({ /** * Configuration options. */ cfg: Base.extend(), /** * Initializes a newly created hasher. * * @param {Object} cfg (Optional) The configuration options to use for this hash computation. * * @example * * var hasher = CryptoJS.algo.SHA256.create(); */ init: function (cfg) { // Apply config defaults this.cfg = this.cfg.extend(cfg); // Set initial values this.reset(); }, /** * Resets this hasher to its initial state. * * @example * * hasher.reset(); */ reset: function () { // Reset data buffer BufferedBlockAlgorithm.reset.call(this); // Perform concrete-hasher logic this._doReset(); }, /** * Updates this hasher with a message. * * @param {WordArray|string} messageUpdate The message to append. * * @return {Hasher} This hasher. * * @example * * hasher.update('message'); * hasher.update(wordArray); */ update: function (messageUpdate) { // Append this._append(messageUpdate); // Update the hash this._process(); // Chainable return this; }, /** * Finalizes the hash computation. * Note that the finalize operation is effectively a destructive, read-once operation. * * @param {WordArray|string} messageUpdate (Optional) A final message update. * * @return {WordArray} The hash. * * @example * * var hash = hasher.finalize(); * var hash = hasher.finalize('message'); * var hash = hasher.finalize(wordArray); */ finalize: function (messageUpdate) { // Final message update if (messageUpdate) { this._append(messageUpdate); } // Perform concrete-hasher logic var hash = this._doFinalize(); return hash; }, blockSize: 512/32, /** * Creates a shortcut function to a hasher's object interface. * * @param {Hasher} hasher The hasher to create a helper for. * * @return {Function} The shortcut function. * * @static * * @example * * var SHA256 = CryptoJS.lib.Hasher._createHelper(CryptoJS.algo.SHA256); */ _createHelper: function (hasher) { return function (message, cfg) { return new hasher.init(cfg).finalize(message); }; }, /** * Creates a shortcut function to the HMAC's object interface. * * @param {Hasher} hasher The hasher to use in this HMAC helper. * * @return {Function} The shortcut function. * * @static * * @example * * var HmacSHA256 = CryptoJS.lib.Hasher._createHmacHelper(CryptoJS.algo.SHA256); */ _createHmacHelper: function (hasher) { return function (message, key) { return new C_algo.HMAC.init(hasher, key).finalize(message); }; } }); /** * Algorithm namespace. */ var C_algo = C.algo = {}; return C; }(Math)); /** * CryptoJS ENC-Base64 component. */ (function () { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var WordArray = C_lib.WordArray; var C_enc = C.enc; /** * Base64 encoding strategy. */ var Base64 = C_enc.Base64 = { /** * Converts a word array to a Base64 string. * * @param {WordArray} wordArray The word array. * * @return {string} The Base64 string. * * @static * * @example * * var base64String = CryptoJS.enc.Base64.stringify(wordArray); */ stringify: function (wordArray) { // Shortcuts var words = wordArray.words; var sigBytes = wordArray.sigBytes; var map = this._map; // Clamp excess bits wordArray.clamp(); // Convert var base64Chars = []; for (var i = 0; i < sigBytes; i += 3) { var byte1 = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff; var byte2 = (words[(i + 1) >>> 2] >>> (24 - ((i + 1) % 4) * 8)) & 0xff; var byte3 = (words[(i + 2) >>> 2] >>> (24 - ((i + 2) % 4) * 8)) & 0xff; var triplet = (byte1 << 16) | (byte2 << 8) | byte3; for (var j = 0; (j < 4) && (i + j * 0.75 < sigBytes); j++) { base64Chars.push(map.charAt((triplet >>> (6 * (3 - j))) & 0x3f)); } } // Add padding var paddingChar = map.charAt(64); if (paddingChar) { while (base64Chars.length % 4) { base64Chars.push(paddingChar); } } return base64Chars.join(''); }, /** * Converts a Base64 string to a word array. * * @param {string} base64Str The Base64 string. * * @return {WordArray} The word array. * * @static * * @example * * var wordArray = CryptoJS.enc.Base64.parse(base64String); */ parse: function (base64Str) { // Shortcuts var base64StrLength = base64Str.length; var map = this._map; // Ignore padding var paddingChar = map.charAt(64); if (paddingChar) { var paddingIndex = base64Str.indexOf(paddingChar); if (paddingIndex != -1) { base64StrLength = paddingIndex; } } // Convert var words = []; var nBytes = 0; for (var i = 0; i < base64StrLength; i++) { if (i % 4) { var bits1 = map.indexOf(base64Str.charAt(i - 1)) << ((i % 4) * 2); var bits2 = map.indexOf(base64Str.charAt(i)) >>> (6 - (i % 4) * 2); words[nBytes >>> 2] |= (bits1 | bits2) << (24 - (nBytes % 4) * 8); nBytes++; } } return WordArray.create(words, nBytes); }, _map: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=' }; }()); /** * CryptoJS MD5 component. */ (function (Math) { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var WordArray = C_lib.WordArray; var Hasher = C_lib.Hasher; var C_algo = C.algo; // Constants table var T = []; // Compute constants (function () { for (var i = 0; i < 64; i++) { T[i] = (Math.abs(Math.sin(i + 1)) * 0x100000000) | 0; } }()); /** * MD5 hash algorithm. */ var MD5 = C_algo.MD5 = Hasher.extend({ _doReset: function () { this._hash = new WordArray.init([ 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476 ]); }, _doProcessBlock: function (M, offset) { // Swap endian for (var i = 0; i < 16; i++) { // Shortcuts var offset_i = offset + i; var M_offset_i = M[offset_i]; M[offset_i] = ( (((M_offset_i << 8) | (M_offset_i >>> 24)) & 0x00ff00ff) | (((M_offset_i << 24) | (M_offset_i >>> 8)) & 0xff00ff00) ); } // Shortcuts var H = this._hash.words; var M_offset_0 = M[offset + 0]; var M_offset_1 = M[offset + 1]; var M_offset_2 = M[offset + 2]; var M_offset_3 = M[offset + 3]; var M_offset_4 = M[offset + 4]; var M_offset_5 = M[offset + 5]; var M_offset_6 = M[offset + 6]; var M_offset_7 = M[offset + 7]; var M_offset_8 = M[offset + 8]; var M_offset_9 = M[offset + 9]; var M_offset_10 = M[offset + 10]; var M_offset_11 = M[offset + 11]; var M_offset_12 = M[offset + 12]; var M_offset_13 = M[offset + 13]; var M_offset_14 = M[offset + 14]; var M_offset_15 = M[offset + 15]; // Working varialbes var a = H[0]; var b = H[1]; var c = H[2]; var d = H[3]; // Computation a = FF(a, b, c, d, M_offset_0, 7, T[0]); d = FF(d, a, b, c, M_offset_1, 12, T[1]); c = FF(c, d, a, b, M_offset_2, 17, T[2]); b = FF(b, c, d, a, M_offset_3, 22, T[3]); a = FF(a, b, c, d, M_offset_4, 7, T[4]); d = FF(d, a, b, c, M_offset_5, 12, T[5]); c = FF(c, d, a, b, M_offset_6, 17, T[6]); b = FF(b, c, d, a, M_offset_7, 22, T[7]); a = FF(a, b, c, d, M_offset_8, 7, T[8]); d = FF(d, a, b, c, M_offset_9, 12, T[9]); c = FF(c, d, a, b, M_offset_10, 17, T[10]); b = FF(b, c, d, a, M_offset_11, 22, T[11]); a = FF(a, b, c, d, M_offset_12, 7, T[12]); d = FF(d, a, b, c, M_offset_13, 12, T[13]); c = FF(c, d, a, b, M_offset_14, 17, T[14]); b = FF(b, c, d, a, M_offset_15, 22, T[15]); a = GG(a, b, c, d, M_offset_1, 5, T[16]); d = GG(d, a, b, c, M_offset_6, 9, T[17]); c = GG(c, d, a, b, M_offset_11, 14, T[18]); b = GG(b, c, d, a, M_offset_0, 20, T[19]); a = GG(a, b, c, d, M_offset_5, 5, T[20]); d = GG(d, a, b, c, M_offset_10, 9, T[21]); c = GG(c, d, a, b, M_offset_15, 14, T[22]); b = GG(b, c, d, a, M_offset_4, 20, T[23]); a = GG(a, b, c, d, M_offset_9, 5, T[24]); d = GG(d, a, b, c, M_offset_14, 9, T[25]); c = GG(c, d, a, b, M_offset_3, 14, T[26]); b = GG(b, c, d, a, M_offset_8, 20, T[27]); a = GG(a, b, c, d, M_offset_13, 5, T[28]); d = GG(d, a, b, c, M_offset_2, 9, T[29]); c = GG(c, d, a, b, M_offset_7, 14, T[30]); b = GG(b, c, d, a, M_offset_12, 20, T[31]); a = HH(a, b, c, d, M_offset_5, 4, T[32]); d = HH(d, a, b, c, M_offset_8, 11, T[33]); c = HH(c, d, a, b, M_offset_11, 16, T[34]); b = HH(b, c, d, a, M_offset_14, 23, T[35]); a = HH(a, b, c, d, M_offset_1, 4, T[36]); d = HH(d, a, b, c, M_offset_4, 11, T[37]); c = HH(c, d, a, b, M_offset_7, 16, T[38]); b = HH(b, c, d, a, M_offset_10, 23, T[39]); a = HH(a, b, c, d, M_offset_13, 4, T[40]); d = HH(d, a, b, c, M_offset_0, 11, T[41]); c = HH(c, d, a, b, M_offset_3, 16, T[42]); b = HH(b, c, d, a, M_offset_6, 23, T[43]); a = HH(a, b, c, d, M_offset_9, 4, T[44]); d = HH(d, a, b, c, M_offset_12, 11, T[45]); c = HH(c, d, a, b, M_offset_15, 16, T[46]); b = HH(b, c, d, a, M_offset_2, 23, T[47]); a = II(a, b, c, d, M_offset_0, 6, T[48]); d = II(d, a, b, c, M_offset_7, 10, T[49]); c = II(c, d, a, b, M_offset_14, 15, T[50]); b = II(b, c, d, a, M_offset_5, 21, T[51]); a = II(a, b, c, d, M_offset_12, 6, T[52]); d = II(d, a, b, c, M_offset_3, 10, T[53]); c = II(c, d, a, b, M_offset_10, 15, T[54]); b = II(b, c, d, a, M_offset_1, 21, T[55]); a = II(a, b, c, d, M_offset_8, 6, T[56]); d = II(d, a, b, c, M_offset_15, 10, T[57]); c = II(c, d, a, b, M_offset_6, 15, T[58]); b = II(b, c, d, a, M_offset_13, 21, T[59]); a = II(a, b, c, d, M_offset_4, 6, T[60]); d = II(d, a, b, c, M_offset_11, 10, T[61]); c = II(c, d, a, b, M_offset_2, 15, T[62]); b = II(b, c, d, a, M_offset_9, 21, T[63]); // Intermediate hash value H[0] = (H[0] + a) | 0; H[1] = (H[1] + b) | 0; H[2] = (H[2] + c) | 0; H[3] = (H[3] + d) | 0; }, _doFinalize: function () { // Shortcuts var data = this._data; var dataWords = data.words; var nBitsTotal = this._nDataBytes * 8; var nBitsLeft = data.sigBytes * 8; // Add padding dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32); var nBitsTotalH = Math.floor(nBitsTotal / 0x100000000); var nBitsTotalL = nBitsTotal; dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 15] = ( (((nBitsTotalH << 8) | (nBitsTotalH >>> 24)) & 0x00ff00ff) | (((nBitsTotalH << 24) | (nBitsTotalH >>> 8)) & 0xff00ff00) ); dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = ( (((nBitsTotalL << 8) | (nBitsTotalL >>> 24)) & 0x00ff00ff) | (((nBitsTotalL << 24) | (nBitsTotalL >>> 8)) & 0xff00ff00) ); data.sigBytes = (dataWords.length + 1) * 4; // Hash final blocks this._process(); // Shortcuts var hash = this._hash; var H = hash.words; // Swap endian for (var i = 0; i < 4; i++) { // Shortcut var H_i = H[i]; H[i] = (((H_i << 8) | (H_i >>> 24)) & 0x00ff00ff) | (((H_i << 24) | (H_i >>> 8)) & 0xff00ff00); } // Return final computed hash return hash; }, clone: function () { var clone = Hasher.clone.call(this); clone._hash = this._hash.clone(); return clone; } }); function FF(a, b, c, d, x, s, t) { var n = a + ((b & c) | (~b & d)) + x + t; return ((n << s) | (n >>> (32 - s))) + b; } function GG(a, b, c, d, x, s, t) { var n = a + ((b & d) | (c & ~d)) + x + t; return ((n << s) | (n >>> (32 - s))) + b; } function HH(a, b, c, d, x, s, t) { var n = a + (b ^ c ^ d) + x + t; return ((n << s) | (n >>> (32 - s))) + b; } function II(a, b, c, d, x, s, t) { var n = a + (c ^ (b | ~d)) + x + t; return ((n << s) | (n >>> (32 - s))) + b; } /** * Shortcut function to the hasher's object interface. * * @param {WordArray|string} message The message to hash. * * @return {WordArray} The hash. * * @static * * @example * * var hash = CryptoJS.MD5('message'); * var hash = CryptoJS.MD5(wordArray); */ C.MD5 = Hasher._createHelper(MD5); /** * Shortcut function to the HMAC's object interface. * * @param {WordArray|string} message The message to hash. * @param {WordArray|string} key The secret key. * * @return {WordArray} The HMAC. * * @static * * @example * * var hmac = CryptoJS.HmacMD5(message, key); */ C.HmacMD5 = Hasher._createHmacHelper(MD5); }(Math)); /** * CryptoJS EVPKF component. */ (function () { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var Base = C_lib.Base; var WordArray = C_lib.WordArray; var C_algo = C.algo; var MD5 = C_algo.MD5; /** * This key derivation function is meant to conform with EVP_BytesToKey. * www.openssl.org/docs/crypto/EVP_BytesToKey.html */ var EvpKDF = C_algo.EvpKDF = Base.extend({ /** * Configuration options. * * @property {number} keySize The key size in words to generate. Default: 4 (128 bits) * @property {Hasher} hasher The hash algorithm to use. Default: MD5 * @property {number} iterations The number of iterations to perform. Default: 1 */ cfg: Base.extend({ keySize: 128/32, hasher: MD5, iterations: 1 }), /** * Initializes a newly created key derivation function. * * @param {Object} cfg (Optional) The configuration options to use for the derivation. * * @example * * var kdf = CryptoJS.algo.EvpKDF.create(); * var kdf = CryptoJS.algo.EvpKDF.create({ keySize: 8 }); * var kdf = CryptoJS.algo.EvpKDF.create({ keySize: 8, iterations: 1000 }); */ init: function (cfg) { this.cfg = this.cfg.extend(cfg); }, /** * Derives a key from a password. * * @param {WordArray|string} password The password. * @param {WordArray|string} salt A salt. * * @return {WordArray} The derived key. * * @example * * var key = kdf.compute(password, salt); */ compute: function (password, salt) { // Shortcut var cfg = this.cfg; // Init hasher var hasher = cfg.hasher.create(); // Initial values var derivedKey = WordArray.create(); // Shortcuts var derivedKeyWords = derivedKey.words; var keySize = cfg.keySize; var iterations = cfg.iterations; // Generate key while (derivedKeyWords.length < keySize) { if (block) { hasher.update(block); } var block = hasher.update(password).finalize(salt); hasher.reset(); // Iterations for (var i = 1; i < iterations; i++) { block = hasher.finalize(block); hasher.reset(); } derivedKey.concat(block); } derivedKey.sigBytes = keySize * 4; return derivedKey; } }); /** * Derives a key from a password. * * @param {WordArray|string} password The password. * @param {WordArray|string} salt A salt. * @param {Object} cfg (Optional) The configuration options to use for this computation. * * @return {WordArray} The derived key. * * @static * * @example * * var key = CryptoJS.EvpKDF(password, salt); * var key = CryptoJS.EvpKDF(password, salt, { keySize: 8 }); * var key = CryptoJS.EvpKDF(password, salt, { keySize: 8, iterations: 1000 }); */ C.EvpKDF = function (password, salt, cfg) { return EvpKDF.create(cfg).compute(password, salt); }; }()); /** * Cipher core components. */ CryptoJS.lib.Cipher || (function (undefined) { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var Base = C_lib.Base; var WordArray = C_lib.WordArray; var BufferedBlockAlgorithm = C_lib.BufferedBlockAlgorithm; var C_enc = C.enc; var Utf8 = C_enc.Utf8; var Base64 = C_enc.Base64; var C_algo = C.algo; var EvpKDF = C_algo.EvpKDF; /** * Abstract base cipher template. * * @property {number} keySize This cipher's key size. Default: 4 (128 bits) * @property {number} ivSize This cipher's IV size. Default: 4 (128 bits) * @property {number} _ENC_XFORM_MODE A constant representing encryption mode. * @property {number} _DEC_XFORM_MODE A constant representing decryption mode. */ var Cipher = C_lib.Cipher = BufferedBlockAlgorithm.extend({ /** * Configuration options. * * @property {WordArray} iv The IV to use for this operation. */ cfg: Base.extend(), /** * Creates this cipher in encryption mode. * * @param {WordArray} key The key. * @param {Object} cfg (Optional) The configuration options to use for this operation. * * @return {Cipher} A cipher instance. * * @static * * @example * * var cipher = CryptoJS.algo.AES.createEncryptor(keyWordArray, { iv: ivWordArray }); */ createEncryptor: function (key, cfg) { return this.create(this._ENC_XFORM_MODE, key, cfg); }, /** * Creates this cipher in decryption mode. * * @param {WordArray} key The key. * @param {Object} cfg (Optional) The configuration options to use for this operation. * * @return {Cipher} A cipher instance. * * @static * * @example * * var cipher = CryptoJS.algo.AES.createDecryptor(keyWordArray, { iv: ivWordArray }); */ createDecryptor: function (key, cfg) { return this.create(this._DEC_XFORM_MODE, key, cfg); }, /** * Initializes a newly created cipher. * * @param {number} xformMode Either the encryption or decryption transormation mode constant. * @param {WordArray} key The key. * @param {Object} cfg (Optional) The configuration options to use for this operation. * * @example * * var cipher = CryptoJS.algo.AES.create(CryptoJS.algo.AES._ENC_XFORM_MODE, keyWordArray, { iv: ivWordArray }); */ init: function (xformMode, key, cfg) { // Apply config defaults this.cfg = this.cfg.extend(cfg); // Store transform mode and key this._xformMode = xformMode; this._key = key; // Set initial values this.reset(); }, /** * Resets this cipher to its initial state. * * @example * * cipher.reset(); */ reset: function () { // Reset data buffer BufferedBlockAlgorithm.reset.call(this); // Perform concrete-cipher logic this._doReset(); }, /** * Adds data to be encrypted or decrypted. * * @param {WordArray|string} dataUpdate The data to encrypt or decrypt. * * @return {WordArray} The data after processing. * * @example * * var encrypted = cipher.process('data'); * var encrypted = cipher.process(wordArray); */ process: function (dataUpdate) { // Append this._append(dataUpdate); // Process available blocks return this._process(); }, /** * Finalizes the encryption or decryption process. * Note that the finalize operation is effectively a destructive, read-once operation. * * @param {WordArray|string} dataUpdate The final data to encrypt or decrypt. * * @return {WordArray} The data after final processing. * * @example * * var encrypted = cipher.finalize(); * var encrypted = cipher.finalize('data'); * var encrypted = cipher.finalize(wordArray); */ finalize: function (dataUpdate) { // Final data update if (dataUpdate) { this._append(dataUpdate); } // Perform concrete-cipher logic var finalProcessedData = this._doFinalize(); return finalProcessedData; }, keySize: 128/32, ivSize: 128/32, _ENC_XFORM_MODE: 1, _DEC_XFORM_MODE: 2, /** * Creates shortcut functions to a cipher's object interface. * * @param {Cipher} cipher The cipher to create a helper for. * * @return {Object} An object with encrypt and decrypt shortcut functions. * * @static * * @example * * var AES = CryptoJS.lib.Cipher._createHelper(CryptoJS.algo.AES); */ _createHelper: (function () { function selectCipherStrategy(key) { if (typeof key == 'string') { return PasswordBasedCipher; } else { return SerializableCipher; } } return function (cipher) { return { encrypt: function (message, key, cfg) { return selectCipherStrategy(key).encrypt(cipher, message, key, cfg); }, decrypt: function (ciphertext, key, cfg) { return selectCipherStrategy(key).decrypt(cipher, ciphertext, key, cfg); } }; }; }()) }); /** * Abstract base stream cipher template. * * @property {number} blockSize The number of 32-bit words this cipher operates on. Default: 1 (32 bits) */ var StreamCipher = C_lib.StreamCipher = Cipher.extend({ _doFinalize: function () { // Process partial blocks var finalProcessedBlocks = this._process(!!'flush'); return finalProcessedBlocks; }, blockSize: 1 }); /** * Mode namespace. */ var C_mode = C.mode = {}; /** * Abstract base block cipher mode template. */ var BlockCipherMode = C_lib.BlockCipherMode = Base.extend({ /** * Creates this mode for encryption. * * @param {Cipher} cipher A block cipher instance. * @param {Array} iv The IV words. * * @static * * @example * * var mode = CryptoJS.mode.CBC.createEncryptor(cipher, iv.words); */ createEncryptor: function (cipher, iv) { return this.Encryptor.create(cipher, iv); }, /** * Creates this mode for decryption. * * @param {Cipher} cipher A block cipher instance. * @param {Array} iv The IV words. * * @static * * @example * * var mode = CryptoJS.mode.CBC.createDecryptor(cipher, iv.words); */ createDecryptor: function (cipher, iv) { return this.Decryptor.create(cipher, iv); }, /** * Initializes a newly created mode. * * @param {Cipher} cipher A block cipher instance. * @param {Array} iv The IV words. * * @example * * var mode = CryptoJS.mode.CBC.Encryptor.create(cipher, iv.words); */ init: function (cipher, iv) { this._cipher = cipher; this._iv = iv; } }); /** * Cipher Block Chaining mode. */ var CBC = C_mode.CBC = (function () { /** * Abstract base CBC mode. */ var CBC = BlockCipherMode.extend(); /** * CBC encryptor. */ CBC.Encryptor = CBC.extend({ /** * Processes the data block at offset. * * @param {Array} words The data words to operate on. * @param {number} offset The offset where the block starts. * * @example * * mode.processBlock(data.words, offset); */ processBlock: function (words, offset) { // Shortcuts var cipher = this._cipher; var blockSize = cipher.blockSize; // XOR and encrypt xorBlock.call(this, words, offset, blockSize); cipher.encryptBlock(words, offset); // Remember this block to use with next block this._prevBlock = words.slice(offset, offset + blockSize); } }); /** * CBC decryptor. */ CBC.Decryptor = CBC.extend({ /** * Processes the data block at offset. * * @param {Array} words The data words to operate on. * @param {number} offset The offset where the block starts. * * @example * * mode.processBlock(data.words, offset); */ processBlock: function (words, offset) { // Shortcuts var cipher = this._cipher; var blockSize = cipher.blockSize; // Remember this block to use with next block var thisBlock = words.slice(offset, offset + blockSize); // Decrypt and XOR cipher.decryptBlock(words, offset); xorBlock.call(this, words, offset, blockSize); // This block becomes the previous block this._prevBlock = thisBlock; } }); function xorBlock(words, offset, blockSize) { // Shortcut var iv = this._iv; // Choose mixing block if (iv) { var block = iv; // Remove IV for subsequent blocks this._iv = undefined; } else { var block = this._prevBlock; } // XOR blocks for (var i = 0; i < blockSize; i++) { words[offset + i] ^= block[i]; } } return CBC; }()); /** * Padding namespace. */ var C_pad = C.pad = {}; /** * PKCS #5/7 padding strategy. */ var Pkcs7 = C_pad.Pkcs7 = { /** * Pads data using the algorithm defined in PKCS #5/7. * * @param {WordArray} data The data to pad. * @param {number} blockSize The multiple that the data should be padded to. * * @static * * @example * * CryptoJS.pad.Pkcs7.pad(wordArray, 4); */ pad: function (data, blockSize) { // Shortcut var blockSizeBytes = blockSize * 4; // Count padding bytes var nPaddingBytes = blockSizeBytes - data.sigBytes % blockSizeBytes; // Create padding word var paddingWord = (nPaddingBytes << 24) | (nPaddingBytes << 16) | (nPaddingBytes << 8) | nPaddingBytes; // Create padding var paddingWords = []; for (var i = 0; i < nPaddingBytes; i += 4) { paddingWords.push(paddingWord); } var padding = WordArray.create(paddingWords, nPaddingBytes); // Add padding data.concat(padding); }, /** * Unpads data that had been padded using the algorithm defined in PKCS #5/7. * * @param {WordArray} data The data to unpad. * * @static * * @example * * CryptoJS.pad.Pkcs7.unpad(wordArray); */ unpad: function (data) { // Get number of padding bytes from last byte var nPaddingBytes = data.words[(data.sigBytes - 1) >>> 2] & 0xff; // Remove padding data.sigBytes -= nPaddingBytes; } }; /** * Abstract base block cipher template. * * @property {number} blockSize The number of 32-bit words this cipher operates on. Default: 4 (128 bits) */ var BlockCipher = C_lib.BlockCipher = Cipher.extend({ /** * Configuration options. * * @property {Mode} mode The block mode to use. Default: CBC * @property {Padding} padding The padding strategy to use. Default: Pkcs7 */ cfg: Cipher.cfg.extend({ mode: CBC, padding: Pkcs7 }), reset: function () { // Reset cipher Cipher.reset.call(this); // Shortcuts var cfg = this.cfg; var iv = cfg.iv; var mode = cfg.mode; // Reset block mode if (this._xformMode == this._ENC_XFORM_MODE) { var modeCreator = mode.createEncryptor; } else /* if (this._xformMode == this._DEC_XFORM_MODE) */ { var modeCreator = mode.createDecryptor; // Keep at least one block in the buffer for unpadding this._minBufferSize = 1; } this._mode = modeCreator.call(mode, this, iv && iv.words); }, _doProcessBlock: function (words, offset) { this._mode.processBlock(words, offset); }, _doFinalize: function () { // Shortcut var padding = this.cfg.padding; // Finalize if (this._xformMode == this._ENC_XFORM_MODE) { // Pad data padding.pad(this._data, this.blockSize); // Process final blocks var finalProcessedBlocks = this._process(!!'flush'); } else /* if (this._xformMode == this._DEC_XFORM_MODE) */ { // Process final blocks var finalProcessedBlocks = this._process(!!'flush'); // Unpad data padding.unpad(finalProcessedBlocks); } return finalProcessedBlocks; }, blockSize: 128/32 }); /** * A collection of cipher parameters. * * @property {WordArray} ciphertext The raw ciphertext. * @property {WordArray} key The key to this ciphertext. * @property {WordArray} iv The IV used in the ciphering operation. * @property {WordArray} salt The salt used with a key derivation function. * @property {Cipher} algorithm The cipher algorithm. * @property {Mode} mode The block mode used in the ciphering operation. * @property {Padding} padding The padding scheme used in the ciphering operation. * @property {number} blockSize The block size of the cipher. * @property {Format} formatter The default formatting strategy to convert this cipher params object to a string. */ var CipherParams = C_lib.CipherParams = Base.extend({ /** * Initializes a newly created cipher params object. * * @param {Object} cipherParams An object with any of the possible cipher parameters. * * @example * * var cipherParams = CryptoJS.lib.CipherParams.create({ * ciphertext: ciphertextWordArray, * key: keyWordArray, * iv: ivWordArray, * salt: saltWordArray, * algorithm: CryptoJS.algo.AES, * mode: CryptoJS.mode.CBC, * padding: CryptoJS.pad.PKCS7, * blockSize: 4, * formatter: CryptoJS.format.OpenSSL * }); */ init: function (cipherParams) { this.mixIn(cipherParams); }, /** * Converts this cipher params object to a string. * * @param {Format} formatter (Optional) The formatting strategy to use. * * @return {string} The stringified cipher params. * * @throws Error If neither the formatter nor the default formatter is set. * * @example * * var string = cipherParams + ''; * var string = cipherParams.toString(); * var string = cipherParams.toString(CryptoJS.format.OpenSSL); */ toString: function (formatter) { return (formatter || this.formatter).stringify(this); } }); /** * Format namespace. */ var C_format = C.format = {}; /** * OpenSSL formatting strategy. */ var OpenSSLFormatter = C_format.OpenSSL = { /** * Converts a cipher params object to an OpenSSL-compatible string. * * @param {CipherParams} cipherParams The cipher params object. * * @return {string} The OpenSSL-compatible string. * * @static * * @example * * var openSSLString = CryptoJS.format.OpenSSL.stringify(cipherParams); */ stringify: function (cipherParams) { // Shortcuts var ciphertext = cipherParams.ciphertext; var salt = cipherParams.salt; // Format if (salt) { var wordArray = WordArray.create([0x53616c74, 0x65645f5f]).concat(salt).concat(ciphertext); } else { var wordArray = ciphertext; } return wordArray.toString(Base64); }, /** * Converts an OpenSSL-compatible string to a cipher params object. * * @param {string} openSSLStr The OpenSSL-compatible string. * * @return {CipherParams} The cipher params object. * * @static * * @example * * var cipherParams = CryptoJS.format.OpenSSL.parse(openSSLString); */ parse: function (openSSLStr) { // Parse base64 var ciphertext = Base64.parse(openSSLStr); // Shortcut var ciphertextWords = ciphertext.words; // Test for salt if (ciphertextWords[0] == 0x53616c74 && ciphertextWords[1] == 0x65645f5f) { // Extract salt var salt = WordArray.create(ciphertextWords.slice(2, 4)); // Remove salt from ciphertext ciphertextWords.splice(0, 4); ciphertext.sigBytes -= 16; } return CipherParams.create({ ciphertext: ciphertext, salt: salt }); } }; /** * A cipher wrapper that returns ciphertext as a serializable cipher params object. */ var SerializableCipher = C_lib.SerializableCipher = Base.extend({ /** * Configuration options. * * @property {Formatter} format The formatting strategy to convert cipher param objects to and from a string. Default: OpenSSL */ cfg: Base.extend({ format: OpenSSLFormatter }), /** * Encrypts a message. * * @param {Cipher} cipher The cipher algorithm to use. * @param {WordArray|string} message The message to encrypt. * @param {WordArray} key The key. * @param {Object} cfg (Optional) The configuration options to use for this operation. * * @return {CipherParams} A cipher params object. * * @static * * @example * * var ciphertextParams = CryptoJS.lib.SerializableCipher.encrypt(CryptoJS.algo.AES, message, key); * var ciphertextParams = CryptoJS.lib.SerializableCipher.encrypt(CryptoJS.algo.AES, message, key, { iv: iv }); * var ciphertextParams = CryptoJS.lib.SerializableCipher.encrypt(CryptoJS.algo.AES, message, key, { iv: iv, format: CryptoJS.format.OpenSSL }); */ encrypt: function (cipher, message, key, cfg) { // Apply config defaults cfg = this.cfg.extend(cfg); // Encrypt var encryptor = cipher.createEncryptor(key, cfg); var ciphertext = encryptor.finalize(message); // Shortcut var cipherCfg = encryptor.cfg; // Create and return serializable cipher params return CipherParams.create({ ciphertext: ciphertext, key: key, iv: cipherCfg.iv, algorithm: cipher, mode: cipherCfg.mode, padding: cipherCfg.padding, blockSize: cipher.blockSize, formatter: cfg.format }); }, /** * Decrypts serialized ciphertext. * * @param {Cipher} cipher The cipher algorithm to use. * @param {CipherParams|string} ciphertext The ciphertext to decrypt. * @param {WordArray} key The key. * @param {Object} cfg (Optional) The configuration options to use for this operation. * * @return {WordArray} The plaintext. * * @static * * @example * * var plaintext = CryptoJS.lib.SerializableCipher.decrypt(CryptoJS.algo.AES, formattedCiphertext, key, { iv: iv, format: CryptoJS.format.OpenSSL }); * var plaintext = CryptoJS.lib.SerializableCipher.decrypt(CryptoJS.algo.AES, ciphertextParams, key, { iv: iv, format: CryptoJS.format.OpenSSL }); */ decrypt: function (cipher, ciphertext, key, cfg) { // Apply config defaults cfg = this.cfg.extend(cfg); // Convert string to CipherParams ciphertext = this._parse(ciphertext, cfg.format); // Decrypt var plaintext = cipher.createDecryptor(key, cfg).finalize(ciphertext.ciphertext); return plaintext; }, /** * Converts serialized ciphertext to CipherParams, * else assumed CipherParams already and returns ciphertext unchanged. * * @param {CipherParams|string} ciphertext The ciphertext. * @param {Formatter} format The formatting strategy to use to parse serialized ciphertext. * * @return {CipherParams} The unserialized ciphertext. * * @static * * @example * * var ciphertextParams = CryptoJS.lib.SerializableCipher._parse(ciphertextStringOrParams, format); */ _parse: function (ciphertext, format) { if (typeof ciphertext == 'string') { return format.parse(ciphertext, this); } else { return ciphertext; } } }); /** * Key derivation function namespace. */ var C_kdf = C.kdf = {}; /** * OpenSSL key derivation function. */ var OpenSSLKdf = C_kdf.OpenSSL = { /** * Derives a key and IV from a password. * * @param {string} password The password to derive from. * @param {number} keySize The size in words of the key to generate. * @param {number} ivSize The size in words of the IV to generate. * @param {WordArray|string} salt (Optional) A 64-bit salt to use. If omitted, a salt will be generated randomly. * * @return {CipherParams} A cipher params object with the key, IV, and salt. * * @static * * @example * * var derivedParams = CryptoJS.kdf.OpenSSL.execute('Password', 256/32, 128/32); * var derivedParams = CryptoJS.kdf.OpenSSL.execute('Password', 256/32, 128/32, 'saltsalt'); */ execute: function (password, keySize, ivSize, salt) { // Generate random salt if (!salt) { salt = WordArray.random(64/8); } // Derive key and IV var key = EvpKDF.create({ keySize: keySize + ivSize }).compute(password, salt); // Separate key and IV var iv = WordArray.create(key.words.slice(keySize), ivSize * 4); key.sigBytes = keySize * 4; // Return params return CipherParams.create({ key: key, iv: iv, salt: salt }); } }; /** * A serializable cipher wrapper that derives the key from a password, * and returns ciphertext as a serializable cipher params object. */ var PasswordBasedCipher = C_lib.PasswordBasedCipher = SerializableCipher.extend({ /** * Configuration options. * * @property {KDF} kdf The key derivation function to use to generate a key and IV from a password. Default: OpenSSL */ cfg: SerializableCipher.cfg.extend({ kdf: OpenSSLKdf }), /** * Encrypts a message using a password. * * @param {Cipher} cipher The cipher algorithm to use. * @param {WordArray|string} message The message to encrypt. * @param {string} password The password. * @param {Object} cfg (Optional) The configuration options to use for this operation. * * @return {CipherParams} A cipher params object. * * @static * * @example * * var ciphertextParams = CryptoJS.lib.PasswordBasedCipher.encrypt(CryptoJS.algo.AES, message, 'password'); * var ciphertextParams = CryptoJS.lib.PasswordBasedCipher.encrypt(CryptoJS.algo.AES, message, 'password', { format: CryptoJS.format.OpenSSL }); */ encrypt: function (cipher, message, password, cfg) { // Apply config defaults cfg = this.cfg.extend(cfg); // Derive key and other params var derivedParams = cfg.kdf.execute(password, cipher.keySize, cipher.ivSize); // Add IV to config cfg.iv = derivedParams.iv; // Encrypt var ciphertext = SerializableCipher.encrypt.call(this, cipher, message, derivedParams.key, cfg); // Mix in derived params ciphertext.mixIn(derivedParams); return ciphertext; }, /** * Decrypts serialized ciphertext using a password. * * @param {Cipher} cipher The cipher algorithm to use. * @param {CipherParams|string} ciphertext The ciphertext to decrypt. * @param {string} password The password. * @param {Object} cfg (Optional) The configuration options to use for this operation. * * @return {WordArray} The plaintext. * * @static * * @example * * var plaintext = CryptoJS.lib.PasswordBasedCipher.decrypt(CryptoJS.algo.AES, formattedCiphertext, 'password', { format: CryptoJS.format.OpenSSL }); * var plaintext = CryptoJS.lib.PasswordBasedCipher.decrypt(CryptoJS.algo.AES, ciphertextParams, 'password', { format: CryptoJS.format.OpenSSL }); */ decrypt: function (cipher, ciphertext, password, cfg) { // Apply config defaults cfg = this.cfg.extend(cfg); // Convert string to CipherParams ciphertext = this._parse(ciphertext, cfg.format); // Derive key and other params var derivedParams = cfg.kdf.execute(password, cipher.keySize, cipher.ivSize, ciphertext.salt); // Add IV to config cfg.iv = derivedParams.iv; // Decrypt var plaintext = SerializableCipher.decrypt.call(this, cipher, ciphertext, derivedParams.key, cfg); return plaintext; } }); }()); /** * CryptoJS AES component. */ (function () { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var BlockCipher = C_lib.BlockCipher; var C_algo = C.algo; // Lookup tables var SBOX = []; var INV_SBOX = []; var SUB_MIX_0 = []; var SUB_MIX_1 = []; var SUB_MIX_2 = []; var SUB_MIX_3 = []; var INV_SUB_MIX_0 = []; var INV_SUB_MIX_1 = []; var INV_SUB_MIX_2 = []; var INV_SUB_MIX_3 = []; // Compute lookup tables (function () { // Compute double table var d = []; for (var i = 0; i < 256; i++) { if (i < 128) { d[i] = i << 1; } else { d[i] = (i << 1) ^ 0x11b; } } // Walk GF(2^8) var x = 0; var xi = 0; for (var i = 0; i < 256; i++) { // Compute sbox var sx = xi ^ (xi << 1) ^ (xi << 2) ^ (xi << 3) ^ (xi << 4); sx = (sx >>> 8) ^ (sx & 0xff) ^ 0x63; SBOX[x] = sx; INV_SBOX[sx] = x; // Compute multiplication var x2 = d[x]; var x4 = d[x2]; var x8 = d[x4]; // Compute sub bytes, mix columns tables var t = (d[sx] * 0x101) ^ (sx * 0x1010100); SUB_MIX_0[x] = (t << 24) | (t >>> 8); SUB_MIX_1[x] = (t << 16) | (t >>> 16); SUB_MIX_2[x] = (t << 8) | (t >>> 24); SUB_MIX_3[x] = t; // Compute inv sub bytes, inv mix columns tables var t = (x8 * 0x1010101) ^ (x4 * 0x10001) ^ (x2 * 0x101) ^ (x * 0x1010100); INV_SUB_MIX_0[sx] = (t << 24) | (t >>> 8); INV_SUB_MIX_1[sx] = (t << 16) | (t >>> 16); INV_SUB_MIX_2[sx] = (t << 8) | (t >>> 24); INV_SUB_MIX_3[sx] = t; // Compute next counter if (!x) { x = xi = 1; } else { x = x2 ^ d[d[d[x8 ^ x2]]]; xi ^= d[d[xi]]; } } }()); // Precomputed Rcon lookup var RCON = [0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36]; /** * AES block cipher algorithm. */ var AES = C_algo.AES = BlockCipher.extend({ _doReset: function () { // Shortcuts var key = this._key; var keyWords = key.words; var keySize = key.sigBytes / 4; // Compute number of rounds var nRounds = this._nRounds = keySize + 6 // Compute number of key schedule rows var ksRows = (nRounds + 1) * 4; // Compute key schedule var keySchedule = this._keySchedule = []; for (var ksRow = 0; ksRow < ksRows; ksRow++) { if (ksRow < keySize) { keySchedule[ksRow] = keyWords[ksRow]; } else { var t = keySchedule[ksRow - 1]; if (!(ksRow % keySize)) { // Rot word t = (t << 8) | (t >>> 24); // Sub word t = (SBOX[t >>> 24] << 24) | (SBOX[(t >>> 16) & 0xff] << 16) | (SBOX[(t >>> 8) & 0xff] << 8) | SBOX[t & 0xff]; // Mix Rcon t ^= RCON[(ksRow / keySize) | 0] << 24; } else if (keySize > 6 && ksRow % keySize == 4) { // Sub word t = (SBOX[t >>> 24] << 24) | (SBOX[(t >>> 16) & 0xff] << 16) | (SBOX[(t >>> 8) & 0xff] << 8) | SBOX[t & 0xff]; } keySchedule[ksRow] = keySchedule[ksRow - keySize] ^ t; } } // Compute inv key schedule var invKeySchedule = this._invKeySchedule = []; for (var invKsRow = 0; invKsRow < ksRows; invKsRow++) { var ksRow = ksRows - invKsRow; if (invKsRow % 4) { var t = keySchedule[ksRow]; } else { var t = keySchedule[ksRow - 4]; } if (invKsRow < 4 || ksRow <= 4) { invKeySchedule[invKsRow] = t; } else { invKeySchedule[invKsRow] = INV_SUB_MIX_0[SBOX[t >>> 24]] ^ INV_SUB_MIX_1[SBOX[(t >>> 16) & 0xff]] ^ INV_SUB_MIX_2[SBOX[(t >>> 8) & 0xff]] ^ INV_SUB_MIX_3[SBOX[t & 0xff]]; } } }, encryptBlock: function (M, offset) { this._doCryptBlock(M, offset, this._keySchedule, SUB_MIX_0, SUB_MIX_1, SUB_MIX_2, SUB_MIX_3, SBOX); }, decryptBlock: function (M, offset) { // Swap 2nd and 4th rows var t = M[offset + 1]; M[offset + 1] = M[offset + 3]; M[offset + 3] = t; this._doCryptBlock(M, offset, this._invKeySchedule, INV_SUB_MIX_0, INV_SUB_MIX_1, INV_SUB_MIX_2, INV_SUB_MIX_3, INV_SBOX); // Inv swap 2nd and 4th rows var t = M[offset + 1]; M[offset + 1] = M[offset + 3]; M[offset + 3] = t; }, _doCryptBlock: function (M, offset, keySchedule, SUB_MIX_0, SUB_MIX_1, SUB_MIX_2, SUB_MIX_3, SBOX) { // Shortcut var nRounds = this._nRounds; // Get input, add round key var s0 = M[offset] ^ keySchedule[0]; var s1 = M[offset + 1] ^ keySchedule[1]; var s2 = M[offset + 2] ^ keySchedule[2]; var s3 = M[offset + 3] ^ keySchedule[3]; // Key schedule row counter var ksRow = 4; // Rounds for (var round = 1; round < nRounds; round++) { // Shift rows, sub bytes, mix columns, add round key var t0 = SUB_MIX_0[s0 >>> 24] ^ SUB_MIX_1[(s1 >>> 16) & 0xff] ^ SUB_MIX_2[(s2 >>> 8) & 0xff] ^ SUB_MIX_3[s3 & 0xff] ^ keySchedule[ksRow++]; var t1 = SUB_MIX_0[s1 >>> 24] ^ SUB_MIX_1[(s2 >>> 16) & 0xff] ^ SUB_MIX_2[(s3 >>> 8) & 0xff] ^ SUB_MIX_3[s0 & 0xff] ^ keySchedule[ksRow++]; var t2 = SUB_MIX_0[s2 >>> 24] ^ SUB_MIX_1[(s3 >>> 16) & 0xff] ^ SUB_MIX_2[(s0 >>> 8) & 0xff] ^ SUB_MIX_3[s1 & 0xff] ^ keySchedule[ksRow++]; var t3 = SUB_MIX_0[s3 >>> 24] ^ SUB_MIX_1[(s0 >>> 16) & 0xff] ^ SUB_MIX_2[(s1 >>> 8) & 0xff] ^ SUB_MIX_3[s2 & 0xff] ^ keySchedule[ksRow++]; // Update state s0 = t0; s1 = t1; s2 = t2; s3 = t3; } // Shift rows, sub bytes, add round key var t0 = ((SBOX[s0 >>> 24] << 24) | (SBOX[(s1 >>> 16) & 0xff] << 16) | (SBOX[(s2 >>> 8) & 0xff] << 8) | SBOX[s3 & 0xff]) ^ keySchedule[ksRow++]; var t1 = ((SBOX[s1 >>> 24] << 24) | (SBOX[(s2 >>> 16) & 0xff] << 16) | (SBOX[(s3 >>> 8) & 0xff] << 8) | SBOX[s0 & 0xff]) ^ keySchedule[ksRow++]; var t2 = ((SBOX[s2 >>> 24] << 24) | (SBOX[(s3 >>> 16) & 0xff] << 16) | (SBOX[(s0 >>> 8) & 0xff] << 8) | SBOX[s1 & 0xff]) ^ keySchedule[ksRow++]; var t3 = ((SBOX[s3 >>> 24] << 24) | (SBOX[(s0 >>> 16) & 0xff] << 16) | (SBOX[(s1 >>> 8) & 0xff] << 8) | SBOX[s2 & 0xff]) ^ keySchedule[ksRow++]; // Set output M[offset] = t0; M[offset + 1] = t1; M[offset + 2] = t2; M[offset + 3] = t3; }, keySize: 256/32 }); /** * Shortcut functions to the cipher's object interface. * * @example * * var ciphertext = CryptoJS.AES.encrypt(message, key, cfg); * var plaintext = CryptoJS.AES.decrypt(ciphertext, key, cfg); */ C.AES = BlockCipher._createHelper(AES); }()); exports.CryptoJS = CryptoJS;
GrdMe/GrdMe
Firefox/src/lib/aes.js
JavaScript
mit
74,606
var assert = require('assert'), error = require('../../../lib/error/index'), math = require('../../../index'), string = math.string; describe('string', function() { it('should be \'\' if called with no argument', function() { assert.equal(string(), ''); }); it('should convert a boolean to a string', function() { assert.equal(string(true), 'true'); assert.equal(string(false), 'false'); }); it('should convert null to a string', function() { assert.equal(string(null), 'null'); }); it('should be the identity if called with a string', function() { assert.equal(string('hello'), 'hello'); assert.equal(string(''), ''); assert.equal(string(' '), ' '); }); it('should convert the elements of an array to strings', function() { assert.deepEqual(string([[2,true],['hi',null]]), [['2', 'true'],['hi', 'null']]); }); it('should convert the elements of a matrix to strings', function() { assert.deepEqual(string(math.matrix([[2,true],['hi',null]])), math.matrix([['2', 'true'],['hi', 'null']])); }); it('should convert a number to string', function() { assert.equal(string(1/8), '0.125'); assert.equal(string(2.1e-3), '0.0021'); assert.equal(string(123456789), '1.23456789e+8'); assert.equal(string(2000000), '2e+6'); }); it('should convert a bignumber to string', function() { assert.equal(string(math.bignumber('2.3e+500')), '2.3e+500'); }); it('should convert a complex number to string', function() { assert.equal(string(math.complex(2,3)), '2 + 3i'); }); it('should convert a unit to string', function() { assert.equal(string(math.unit('5cm')), '50 mm'); }); it('should throw an error if called with wrong number of arguments', function() { assert.throws(function () {string(1,2)}, error.ArgumentsError); assert.throws(function () {string(1,2,3)}, error.ArgumentsError); }); });
jeslopcru/code-refactoring-course
class6/ejercicio/mathjs-solucion/test/function/construction/string.test.js
JavaScript
mit
1,925
/* Our App is an Angular Module */ var gnaWithService = angular.module('gnaWithService', []); /* Creating a new directive for aur app */ gnaWithService.directive('gna', function($interval, gnaService) { return { restrict: 'A', template: ' <div id="gna-container"> ' + ' <div class="btn title" ng-click="generateRandomNumber()">Generar Numero Aleatorio</div> ' + ' <h3 class="number"> {{randomNumber}} </h3> ' + ' </div> ', link: function (scope, element, attrs) { var numberId, button, intervalPromise; init(); function init() { // DOM button = element.find('.btn'); scope.mod = attrs.mod; scope.interval = attrs.interval; scope.randomNumber = '-'; scope.$on('$destroy', function () { $interval.cancel(intervalPromise); }); } scope.generateRandomNumber = function() { function generateRandomNumber (){ return Math.floor((Math.random() * attrs.mod) + 1) } if (intervalPromise == undefined){ // We trigger the interval intervalPromise = $interval(function() { scope.randomNumber = gnaService.getRandomNumber(attrs.mod); }, scope.interval); // And turn the button into the stop button button.text('STOP'); } else { // We stop the interval $interval.cancel(intervalPromise); intervalPromise = undefined; // And set the original text of the button button.text('Generar Numero Aleatorio'); } }; } }; }); /* Creating a new service for aur app */ /* Añade el servicio factory a tu modulo gnaWithService */
redradix/Redradix-course-angular-november2015
TEMA4/EJERCICIOS/SERVICIO PROPIO/Solucion Mia/gna.js
JavaScript
mit
1,745
//= require jquery //= require jquery_ujs //= require bootstrap-sprockets $(document).ready(function(){ $('.dropdown-toggle').dropdown(); });
BrilliantChemistry/NotifyOn
spec/dummy/app/assets/javascripts/application.js
JavaScript
mit
145
"use strict"; const releases = new Map(); // keep test data isolated afterEach(() => { releases.clear(); }); const client = { repos: { createRelease: jest.fn((opts) => { releases.set(opts.name, opts); return Promise.resolve(); }), }, }; module.exports.createGitLabClient = jest.fn(() => client); module.exports.createGitLabClient.releases = releases;
kittens/lerna
commands/__mocks__/@lerna/gitlab-client.js
JavaScript
mit
381
import React from 'react'; import { IntlProvider } from 'react-intl'; import { Provider } from 'react-redux'; import { browserHistory } from 'react-router-dom'; import { render } from 'react-testing-library'; import ReposList from '../index'; import configureStore from '../../../configureStore'; describe('<ReposList />', () => { it('should render the loading indicator when its loading', () => { const { container } = render(<ReposList loading />); expect(container.firstChild).toMatchSnapshot(); }); it('should render an error if loading failed', () => { const { queryByText } = render( <IntlProvider locale="en"> <ReposList loading={false} error={{ message: 'Loading failed!' }} /> </IntlProvider>, ); expect(queryByText(/Something went wrong/)).not.toBeNull(); }); it('should render the repositories if loading was successful', () => { const store = configureStore( { global: { currentUser: 'mxstbr' } }, browserHistory, ); const repos = [ { owner: { login: 'mxstbr', }, html_url: 'https://github.com/react-boilerplate/react-boilerplate', name: 'react-boilerplate', open_issues_count: 20, full_name: 'react-boilerplate/react-boilerplate', }, ]; const { container } = render( <Provider store={store}> <IntlProvider locale="en"> <ReposList repos={repos} error={false} /> </IntlProvider> </Provider>, ); expect(container.firstChild).toMatchSnapshot(); }); it('should not render anything if nothing interesting is provided', () => { const { container } = render( <ReposList repos={false} error={false} loading={false} />, ); expect(container.firstChild).toBeNull(); }); });
rlagman/raphthelagman
app/components/ReposList/tests/index.test.js
JavaScript
mit
1,804
'use strict'; angular.module('ngDependencyGraph.models', []);
rajexcited/AngularJS-Birbal
vendor/ng-dependency-graph/scripts/models/models.module.js
JavaScript
mit
63
/* globals LivechatVideoCall, Livechat */ // Functions to call on messages of type 'command' this.Commands = { survey: function() { if (!($('body #survey').length)) { Blaze.render(Template.survey, $('body').get(0)); } }, endCall: function() { LivechatVideoCall.finish(); }, promptTranscript: function() { if (Livechat.transcript) { const user = Meteor.user(); let email = user.visitorEmails && user.visitorEmails.length > 0 ? user.visitorEmails[0].address : ''; swal({ title: t('Chat_ended'), text: Livechat.transcriptMessage, type: 'input', inputValue: email, showCancelButton: true, cancelButtonText: t('no'), confirmButtonText: t('yes'), closeOnCancel: true, closeOnConfirm: false }, (response) => { if ((typeof response === 'boolean') && !response) { return true; } else { if (!response) { swal.showInputError(t('please enter your email')); return false; } if (response.trim() === '') { swal.showInputError(t('please enter your email')); return false; } else { Meteor.call('livechat:sendTranscript', visitor.getRoom(), response, (err) => { if (err) { console.error(err); } swal({ title: t('transcript_sent'), type: 'success', timer: 1000, showConfirmButton: false }); }); } } }); } else { swal({ title: t('Chat_ended'), type: 'success', timer: 1000, showConfirmButton: false }); } }, connected: function() { Livechat.connecting = false; } };
fazilou/chat
packages/rocketchat-livechat/app/client/lib/commands.js
JavaScript
mit
1,594
AlmReport.Item = DS.Model.extend({ doi: DS.attr('string'), title: DS.attr('string'), journal: DS.attr('string'), publisher_id: DS.attr('number'), issued: DS.attr(), published: function () { var parts = this.get('issued')['date-parts'][0] if(parts[1]) { parts[1] = parts[1] - 1; } return new Date( parts[0], parts[1], parts[2] ) }.property('issued'), canonical_url: DS.attr('string'), pmid: DS.attr('string'), pmcid: DS.attr('string'), mendeley_uuid: DS.attr('string'), wos: DS.attr('string'), scp: DS.attr('string'), update_date: DS.attr('date'), viewed: DS.attr('number'), saved: DS.attr('number'), discussed: DS.attr('number'), cited: DS.attr('number'), subjects: DS.attr(), sources: DS.attr(), affiliations: DS.attr(), events: DS.attr() });
mfenner/alm-report
app/assets/javascripts/models/item.js
JavaScript
mit
832
'use strict'; angular.module('core').controller('HomeController', ['$scope', 'Authentication', function($scope, Authentication) { //Watch user login $scope.user = User.get(); $scope.isAuthenticated = Authentication.isAuthenticated(); $rootScope.$on('Auth',function(){ $scope.user = User.get(); $scope.isAuthenticated = Authentication.isAuthenticated(); }); // This provides Authentication context. $scope.authentication = Authentication; } ]);
buildproto/sean-fixups
public/modules/core/controllers/home.client.controller.js
JavaScript
mit
519
module.exports = { plugins: [ require('postcss-import'), require('autoprefixer'), require('postcss-css-variables'), require('postcss-color-mod-function'), require('cssnano'), require('postcss-custom-properties') ] };
EdwardStudy/myghostblog
versions/2.16.4/core/server/lib/members/static/auth/postcss.config.js
JavaScript
mit
273
const precedence = { ':link': 4, ':visited': 3, ':hover': 2, ':focus': 1.5, ':active': 1 } export default function sortPseudoClasses(left, right) { const precedenceLeft = precedence[left]; // eslint-disable-line const precedenceRight = precedence[right] // Only sort if both properties are listed // This prevents other pseudos from reordering if (precedenceLeft && precedenceRight) { return precedenceLeft < precedenceRight ? 1 : -1 } return 0 }
rofrischmann/react-look
packages/react-look/modules/utils/sortPseudoClasses.js
JavaScript
mit
476
/* * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is * regenerated. */ 'use strict'; const models = require('./index'); /** * A copy activity Oracle source. * * @extends models['CopySource'] */ class OracleSource extends models['CopySource'] { /** * Create a OracleSource. * @member {object} [oracleReaderQuery] Oracle reader query. Type: string (or * Expression with resultType string). * @member {object} [queryTimeout] Query timeout. Type: string (or Expression * with resultType string), pattern: * ((\d+)\.)?(\d\d):(60|([0-5][0-9])):(60|([0-5][0-9])). */ constructor() { super(); } /** * Defines the metadata of OracleSource * * @returns {object} metadata of OracleSource * */ mapper() { return { required: false, serializedName: 'OracleSource', type: { name: 'Composite', className: 'OracleSource', modelProperties: { sourceRetryCount: { required: false, serializedName: 'sourceRetryCount', type: { name: 'Object' } }, sourceRetryWait: { required: false, serializedName: 'sourceRetryWait', type: { name: 'Object' } }, type: { required: true, serializedName: 'type', type: { name: 'String' } }, oracleReaderQuery: { required: false, serializedName: 'oracleReaderQuery', type: { name: 'Object' } }, queryTimeout: { required: false, serializedName: 'queryTimeout', type: { name: 'Object' } } } } }; } } module.exports = OracleSource;
lmazuel/azure-sdk-for-node
lib/services/datafactoryManagement/lib/models/oracleSource.js
JavaScript
mit
2,119
module.exports = /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) /******/ return installedModules[moduleId].exports; /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ exports: {}, /******/ id: moduleId, /******/ loaded: false /******/ }; /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ // Flag the module as loaded /******/ module.loaded = true; /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ // __webpack_public_path__ /******/ __webpack_require__.p = "/dist/"; /******/ // Load entry module and return exports /******/ return __webpack_require__(0); /******/ }) /************************************************************************/ /******/ ({ /***/ 0: /***/ function(module, exports, __webpack_require__) { module.exports = __webpack_require__(289); /***/ }, /***/ 3: /***/ function(module, exports) { /* globals __VUE_SSR_CONTEXT__ */ // this module is a runtime utility for cleaner component module output and will // be included in the final webpack user bundle module.exports = function normalizeComponent ( rawScriptExports, compiledTemplate, injectStyles, scopeId, moduleIdentifier /* server only */ ) { var esModule var scriptExports = rawScriptExports = rawScriptExports || {} // ES6 modules interop var type = typeof rawScriptExports.default if (type === 'object' || type === 'function') { esModule = rawScriptExports scriptExports = rawScriptExports.default } // Vue.extend constructor export interop var options = typeof scriptExports === 'function' ? scriptExports.options : scriptExports // render functions if (compiledTemplate) { options.render = compiledTemplate.render options.staticRenderFns = compiledTemplate.staticRenderFns } // scopedId if (scopeId) { options._scopeId = scopeId } var hook if (moduleIdentifier) { // server build hook = function (context) { // 2.3 injection context = context || (this.$vnode && this.$vnode.ssrContext) // 2.2 with runInNewContext: true if (!context && typeof __VUE_SSR_CONTEXT__ !== 'undefined') { context = __VUE_SSR_CONTEXT__ } // inject component styles if (injectStyles) { injectStyles.call(this, context) } // register component module identifier for async chunk inferrence if (context && context._registeredComponents) { context._registeredComponents.add(moduleIdentifier) } } // used by ssr in case component is cached and beforeCreate // never gets called options._ssrRegister = hook } else if (injectStyles) { hook = injectStyles } if (hook) { // inject component registration as beforeCreate hook var existing = options.beforeCreate options.beforeCreate = existing ? [].concat(existing, hook) : [hook] } return { esModule: esModule, exports: scriptExports, options: options } } /***/ }, /***/ 289: /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _steps = __webpack_require__(290); var _steps2 = _interopRequireDefault(_steps); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /* istanbul ignore next */ _steps2.default.install = function (Vue) { Vue.component(_steps2.default.name, _steps2.default); }; exports.default = _steps2.default; /***/ }, /***/ 290: /***/ function(module, exports, __webpack_require__) { var Component = __webpack_require__(3)( /* script */ __webpack_require__(291), /* template */ __webpack_require__(292), /* styles */ null, /* scopeId */ null, /* moduleIdentifier (server only) */ null ) module.exports = Component.exports /***/ }, /***/ 291: /***/ function(module, exports) { 'use strict'; exports.__esModule = true; // // // // // // // // exports.default = { name: 'ElSteps', props: { space: [Number, String], active: Number, direction: { type: String, default: 'horizontal' }, alignCenter: Boolean, center: Boolean, finishStatus: { type: String, default: 'finish' }, processStatus: { type: String, default: 'process' } }, data: function data() { return { steps: [], stepOffset: 0 }; }, watch: { active: function active(newVal, oldVal) { this.$emit('change', newVal, oldVal); }, steps: function steps(_steps) { var _this = this; _steps.forEach(function (child, index) { child.index = index; }); if (this.center) { (function () { var len = _steps.length; _this.$nextTick(function () { _this.stepOffset = _steps[len - 1].$el.getBoundingClientRect().width / (len - 1); }); })(); } } } }; /***/ }, /***/ 292: /***/ function(module, exports) { module.exports={render:function (){var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h; return _c('div', { staticClass: "el-steps", class: ['is-' + _vm.direction, _vm.center ? 'is-center' : ''] }, [_vm._t("default")], 2) },staticRenderFns: []} /***/ } /******/ });
shikun2014010800/manga
web/console/node_modules/element-ui/lib/steps.js
JavaScript
mit
6,005
/** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule CSSCore * @typechecks */ "use strict"; var invariant = require("./invariant"); /** * The CSSCore module specifies the API (and implements most of the methods) * that should be used when dealing with the display of elements (via their * CSS classes and visibility on screen. It is an API focused on mutating the * display and not reading it as no logical state should be encoded in the * display of elements. */ var CSSCore = { /** * Adds the class passed in to the element if it doesn't already have it. * * @param {DOMElement} element the element to set the class on * @param {string} className the CSS className * @return {DOMElement} the element passed in */ addClass: function addClass(element, className) { "production" !== process.env.NODE_ENV ? invariant(!/\s/.test(className), "CSSCore.addClass takes only a single class name. \"%s\" contains " + "multiple classes.", className) : invariant(!/\s/.test(className)); if (className) { if (element.classList) { element.classList.add(className); } else if (!CSSCore.hasClass(element, className)) { element.className = element.className + " " + className; } } return element; }, /** * Removes the class passed in from the element * * @param {DOMElement} element the element to set the class on * @param {string} className the CSS className * @return {DOMElement} the element passed in */ removeClass: function removeClass(element, className) { "production" !== process.env.NODE_ENV ? invariant(!/\s/.test(className), "CSSCore.removeClass takes only a single class name. \"%s\" contains " + "multiple classes.", className) : invariant(!/\s/.test(className)); if (className) { if (element.classList) { element.classList.remove(className); } else if (CSSCore.hasClass(element, className)) { element.className = element.className.replace(new RegExp("(^|\\s)" + className + "(?:\\s|$)", "g"), "$1").replace(/\s+/g, " ") // multiple spaces to one .replace(/^\s*|\s*$/g, ""); // trim the ends } } return element; }, /** * Helper to add or remove a class from an element based on a condition. * * @param {DOMElement} element the element to set the class on * @param {string} className the CSS className * @param {*} bool condition to whether to add or remove the class * @return {DOMElement} the element passed in */ conditionClass: function conditionClass(element, className, bool) { return (bool ? CSSCore.addClass : CSSCore.removeClass)(element, className); }, /** * Tests whether the element has the class specified. * * @param {DOMNode|DOMWindow} element the element to set the class on * @param {string} className the CSS className * @return {boolean} true if the element has the class, false if not */ hasClass: function hasClass(element, className) { "production" !== process.env.NODE_ENV ? invariant(!/\s/.test(className), "CSS.hasClass takes only a single class name.") : invariant(!/\s/.test(className)); if (element.classList) { return !!className && element.classList.contains(className); } return (" " + element.className + " ").indexOf(" " + className + " ") > -1; } }; module.exports = CSSCore;
danielbrenners/react-synthesizer
node_modules/belle/lib/vendor/react/lib/CSSCore.js
JavaScript
mit
3,627
import React from 'react' import StudentData from './StudentData' class Students extends React.Component { constructor(props){ super(props); this.state = { displayListener: this.props.displayListener, className : this.props.className, }; } render(){ if(this.props.display[0] === 'class') { return ( <div> {} <StudentData display={this.props.display} displayListener={this.state.displayListener.bind(this)} className={this.props.className}/> </div> ) } else { return ( <div> </div> ) } } } module.exports = Students;
absurdSquid/thumbroll
client/desktop/app/components/teacher/classes/students/Students.js
JavaScript
mit
654
version https://git-lfs.github.com/spec/v1 oid sha256:71107fdbe7d8247624add6c7dad911fba362e157c32ad1bd98372c5c86dbd98e size 4009
yogeshsaroya/new-cdnjs
ajax/libs/yui/3.4.1/event-simulate/event-simulate-min.js
JavaScript
mit
129
Package.describe({ summary: "Collection of small helpers: _.map, _.each, ...", version: '1.0.9' }); Package.onUse(function (api) { // Like all packages, we have an implicit depedency on the 'meteor' // package, which provides such things as the *.js file handler. Use // an undocumented API to allow 'meteor' to alter us even though we // depend on it. This is necessary since 'meteor' depends on us. One // day we will avoid this problem by refactor, but for now this is a // practical and expedient solution. // // XXX Now the *.js handler is intrinsic rather than coming from the // 'meteor' package and we could remove this (if we provided a way // to let the package opt to not depend on 'meteor'.) We could even // remove unordered dependency support, though I think it's worth keeping // around for now to keep the possibility of dependency // configuration alive in the codebase. api.use('meteor', {unordered: true}); api.export('_'); // NOTE: we patch _.each and various other functions that polymorphically take // objects, arrays, and array-like objects (such as the querySelectorAll // return value, document.images, and 'arguments') such that objects with a // numeric length field whose constructor === Object are still treated as // objects, not as arrays. Search for looksLikeArray. api.addFiles(['pre.js', 'underscore.js', 'post.js']); }); Package.onTest(function (api) { // Also turn off the strong 'meteor' dependency in the test slice api.use('meteor', {unordered: true}); });
jdivy/meteor
packages/underscore/package.js
JavaScript
mit
1,553
function Tile(position, value) { this.x = position.x; this.y = position.y; this.value = value; this.previousPosition = null; } Tile.prototype.toString = function(){ return "["+this.x+","+this.y+","+this.value+"]"; } Tile.prototype.savePosition = function () { this.previousPosition = { x: this.x, y: this.y }; }; Tile.prototype.updatePosition = function (position) { this.x = position.x; this.y = position.y; }; Tile.prototype.serialize = function () { return { position: { x: this.x, y: this.y }, value: this.value }; };
hscaizh/html5chess
js/tile.js
JavaScript
mit
612
// MySQL Schema Compiler // ------- import inherits from 'inherits'; import SchemaCompiler from '../../../schema/compiler'; import { assign } from 'lodash' function SchemaCompiler_MySQL(client, builder) { SchemaCompiler.call(this, client, builder) } inherits(SchemaCompiler_MySQL, SchemaCompiler) assign(SchemaCompiler_MySQL.prototype, { // Rename a table on the schema. renameTable(tableName, to) { this.pushQuery(`rename table ${this.formatter.wrap(tableName)} to ${this.formatter.wrap(to)}`); }, // Check whether a table exists on the query. hasTable(tableName) { let sql = 'select * from information_schema.tables where table_name = ?'; const bindings = [ tableName ]; if (this.schema) { sql += ' and table_schema = ?'; bindings.push(this.schema); } else { sql += ' and table_schema = database()'; } this.pushQuery({ sql, bindings, output: function output(resp) { return resp.length > 0; } }); }, // Check whether a column exists on the schema. hasColumn(tableName, column) { this.pushQuery({ sql: `show columns from ${this.formatter.wrap(tableName)}` + ' like ' + this.formatter.parameter(column), output(resp) { return resp.length > 0; } }); } }) export default SchemaCompiler_MySQL;
EdwardStudy/myghostblog
versions/1.25.7/node_modules/knex/src/dialects/mysql/schema/compiler.js
JavaScript
mit
1,345
'use strict'; const assert = require('./../../assert'); const common = require('./../../common'); let battle; describe('Primordial Sea', function () { afterEach(function () { battle.destroy(); }); it('should activate the Primordial Sea weather upon switch-in', function () { battle = common.createBattle(); battle.setPlayer('p1', {team: [{species: "Kyogre", ability: 'primordialsea', moves: ['helpinghand']}]}); battle.setPlayer('p2', {team: [{species: "Abra", ability: 'magicguard', moves: ['teleport']}]}); assert(battle.field.isWeather('primordialsea')); }); it('should increase the damage (not the basePower) of Water-type attacks', function () { battle = common.createBattle(); battle.randomizer = dmg => dmg; // max damage battle.setPlayer('p1', {team: [{species: 'Kyogre', ability: 'primordialsea', moves: ['waterpledge']}]}); battle.setPlayer('p2', {team: [{species: 'Blastoise', ability: 'torrent', moves: ['splash']}]}); const attacker = battle.p1.active[0]; const defender = battle.p2.active[0]; assert.hurtsBy(defender, 104, () => battle.makeChoices('move waterpledge', 'move splash')); const move = Dex.moves.get('waterpledge'); const basePower = battle.runEvent('BasePower', attacker, defender, move, move.basePower, true); assert.equal(basePower, move.basePower); }); it('should cause Fire-type attacks to fail', function () { battle = common.createBattle(); battle.setPlayer('p1', {team: [{species: "Kyogre", ability: 'primordialsea', moves: ['helpinghand']}]}); battle.setPlayer('p2', {team: [{species: "Charizard", ability: 'blaze', moves: ['flamethrower']}]}); battle.makeChoices('move helpinghand', 'move flamethrower'); assert.fullHP(battle.p1.active[0]); }); it('should not cause Fire-type Status moves to fail', function () { battle = common.createBattle(); battle.setPlayer('p1', {team: [{species: "Kyogre", ability: 'primordialsea', moves: ['helpinghand']}]}); battle.setPlayer('p2', {team: [{species: "Charizard", ability: 'noguard', moves: ['willowisp']}]}); assert.sets(() => battle.p1.active[0].status, 'brn', () => battle.makeChoices('move helpinghand', 'move willowisp')); }); it('should prevent moves and abilities from setting the weather to Sunny Day, Rain Dance, Sandstorm, or Hail', function () { battle = common.createBattle(); battle.setPlayer('p1', {team: [{species: "Kyogre", ability: 'primordialsea', moves: ['helpinghand']}]}); battle.setPlayer('p2', {team: [ {species: "Abra", ability: 'magicguard', moves: ['teleport']}, {species: "Kyogre", ability: 'drizzle', moves: ['raindance']}, {species: "Groudon", ability: 'drought', moves: ['sunnyday']}, {species: "Tyranitar", ability: 'sandstream', moves: ['sandstorm']}, {species: "Abomasnow", ability: 'snowwarning', moves: ['hail']}, ]}); for (let i = 2; i <= 5; i++) { battle.makeChoices('move helpinghand', 'switch ' + i); assert(battle.field.isWeather('primordialsea')); battle.makeChoices('auto', 'auto'); assert(battle.field.isWeather('primordialsea')); } }); it('should be treated as Rain Dance for any forme, move or ability that requires it', function () { battle = common.createBattle(); battle.setPlayer('p1', {team: [{species: "Kyogre", ability: 'primordialsea', moves: ['sonicboom']}]}); battle.setPlayer('p2', {team: [ {species: "Castform", ability: 'forecast', moves: ['weatherball']}, {species: "Kingdra", ability: 'swiftswim', moves: ['focusenergy']}, {species: "Ludicolo", ability: 'raindish', moves: ['watersport']}, {species: "Toxicroak", ability: 'dryskin', moves: ['bulkup']}, {species: "Manaphy", ability: 'hydration', item: 'laggingtail', moves: ['rest']}, ]}); battle.onEvent('Hit', battle.format, (target, pokemon, move) => { if (move.id === 'weatherball') { assert.equal(move.type, 'Water'); } }); const myActive = battle.p2.active; battle.makeChoices('move sonicboom', 'move weatherball'); assert.species(myActive[0], 'Castform-Rainy'); battle.makeChoices('move sonicboom', 'switch 2'); assert.equal(myActive[0].getStat('spe'), 2 * myActive[0].storedStats['spe'], "Kingdra's Speed should be doubled by Swift Swim"); battle.makeChoices('move sonicboom', 'switch 3'); assert.notEqual(myActive[0].maxhp - myActive[0].hp, 20); battle.makeChoices('move sonicboom', 'switch 4'); assert.notEqual(myActive[0].maxhp - myActive[0].hp, 20); battle.makeChoices('move sonicboom', 'switch 5'); battle.makeChoices('move sonicboom', 'move rest'); assert.equal(myActive[0].status, ''); }); it('should cause the Primordial Sea weather to fade if it switches out and no other Primordial Sea Pokemon are active', function () { battle = common.createBattle(); battle.setPlayer('p1', {team: [ {species: "Kyogre", ability: 'primordialsea', moves: ['helpinghand']}, {species: "Ho-Oh", ability: 'pressure', moves: ['roost']}, ]}); battle.setPlayer('p2', {team: [{species: "Lugia", ability: 'pressure', moves: ['roost']}]}); assert.sets(() => battle.field.isWeather('primordialsea'), false, () => battle.makeChoices('switch 2', 'move roost')); }); it('should not cause the Primordial Sea weather to fade if it switches out and another Primordial Sea Pokemon is active', function () { battle = common.createBattle(); battle.setPlayer('p1', {team: [ {species: "Kyogre", ability: 'primordialsea', moves: ['helpinghand']}, {species: "Ho-Oh", ability: 'pressure', moves: ['roost']}, ]}); battle.setPlayer('p2', {team: [{species: "Kyogre", ability: 'primordialsea', moves: ['bulkup']}]}); assert.constant(() => battle.field.isWeather('primordialsea'), () => battle.makeChoices('switch 2', 'move bulkup')); }); it('should cause the Primordial Sea weather to fade if its ability is suppressed and no other Primordial Sea Pokemon are active', function () { battle = common.createBattle(); battle.setPlayer('p1', {team: [{species: "Kyogre", ability: 'primordialsea', moves: ['helpinghand']}]}); battle.setPlayer('p2', {team: [{species: "Lugia", ability: 'pressure', moves: ['gastroacid']}]}); assert.sets(() => battle.field.isWeather('primordialsea'), false, () => battle.makeChoices('move helpinghand', 'move gastroacid')); }); it('should not cause the Primordial Sea weather to fade if its ability is suppressed and another Primordial Sea Pokemon is active', function () { battle = common.createBattle(); battle.setPlayer('p1', {team: [{species: "Kyogre", ability: 'primordialsea', moves: ['helpinghand']}]}); battle.setPlayer('p2', {team: [{species: "Kyogre", ability: 'primordialsea', moves: ['gastroacid']}]}); assert.constant(() => battle.field.isWeather('primordialsea'), () => battle.makeChoices('move helpinghand', 'move gastroacid')); }); it('should cause the Primordial Sea weather to fade if its ability is changed and no other Primordial Sea Pokemon are active', function () { battle = common.createBattle(); battle.setPlayer('p1', {team: [{species: "Kyogre", ability: 'primordialsea', moves: ['helpinghand']}]}); battle.setPlayer('p2', {team: [{species: "Lugia", ability: 'pressure', moves: ['entrainment']}]}); assert.sets(() => battle.field.isWeather('primordialsea'), false, () => battle.makeChoices('move helpinghand', 'move entrainment')); }); });
Zarel/Pokemon-Showdown
test/sim/abilities/primordialsea.js
JavaScript
mit
7,291
'use strict'; // Template for context menu commands var template = [ { label: 'Edit', submenu: [ { label: 'Undo', accelerator: 'CmdOrCtrl+Z', role: 'undo' }, { label: 'Redo', accelerator: 'Shift+CmdOrCtrl+Z', role: 'redo' }, { type: 'separator' }, { label: 'Cut', accelerator: 'CmdOrCtrl+X', role: 'cut' }, { label: 'Copy', accelerator: 'CmdOrCtrl+C', role: 'copy' }, { label: 'Paste', accelerator: 'CmdOrCtrl+V', role: 'paste' }, { label: 'Select All', accelerator: 'CmdOrCtrl+A', role: 'selectall' }, ] }, { label: 'View', submenu: [ { label: 'Reload', accelerator: 'CmdOrCtrl+R', click: function(item, focusedWindow) { if (focusedWindow) { focusedWindow.reload(); } } }, { label: 'Toggle Full Screen', accelerator: (function() { if (process.platform ==='darwin') { return 'Ctrl+Command+F'; } else { return 'F11'; } })(), click: function(item, focusedWindow) { if (focusedWindow) { focusedWindow.setFullScreen(!focusedWindow.isFullScreen()); } } }, { label: 'Toggle Developer Tools', accelerator: (function() { if (process.platform ==='darwin') { return 'Alt+Command+I'; } else { return 'Ctrl+Shift+I'; } })(), click: function(item, focusedWindow) { if (focusedWindow) { focusedWindow.webContents.toggleDevTools(); } } }, { label: 'Toggle Plugin Developer Tools', accelerator: (function() { if (process.platform ==='darwin') { return 'Alt+Command+P'; } else { return 'Ctrl+Shift+P'; } })(), click: function(item, focusedWindow) { if (focusedWindow) { focusedWindow.webContents.executeJavaScript('Plugins.Current.toggleDevTools();'); } } }, ] }, { label: 'Window', role: 'window', submenu: [ { label: 'Minimize', accelerator: 'CmdOrCtrl+M', role: 'minimize' }, { label: 'Close', accelerator: 'CmdOrCtrl+W', role: 'close' }, ] }, { label: 'Help', role: 'help', submenu: [ { label: 'Learn More', click: function() { require('electron').shell.openExternal('http://sia.tech/'); } }, ] }, ]; if (process.platform ==='darwin') { var appName = 'Sia-UI'; template.unshift({ label: appName, submenu: [ { label: 'About ' + appName, role: 'about' }, { type: 'separator' }, { label: 'Services', role: 'services', submenu: [] }, { type: 'separator' }, { label: 'Hide ' + appName, accelerator: 'Command+H', role: 'hide' }, { label: 'Hide Others', accelerator: 'Command+Shift+H', role: 'hideothers' }, { label: 'Show All', role: 'unhide' }, { type: 'separator' }, { label: 'Quit', accelerator: 'Command+Q', click: function() { require('electron').app.quit(); } }, ] }); // Window menu. template[3].submenu.push( { type: 'separator' }, { label: 'Bring All to Front', role: 'front' } ); } // Exports the created menu module.exports = template;
Mingling94/Sia-UI
js/mainjs/contextMenu.js
JavaScript
mit
2,978
Package.describe({ name: 'rocketchat:livechat', version: '0.0.1', summary: 'Livechat plugin for Rocket.Chat' }); Package.registerBuildPlugin({ name: 'Livechat', use: [], sources: [ 'plugin/build-livechat.js' ], npmDependencies: { 'shelljs': '0.5.1', 'uglify-js': '2.7.5' } }); Npm.depends({ 'ua-parser-js': '0.7.10', 'uglify-js': '2.7.5' }); Package.onUse(function(api) { api.use(['webapp', 'autoupdate'], 'server'); api.use('ecmascript'); api.use('underscorestring:underscore.string'); api.use('rocketchat:lib'); api.use('rocketchat:authorization'); api.use('rocketchat:logger'); api.use('rocketchat:api'); api.use('rocketchat:theme'); api.use('rocketchat:streamer'); api.use('konecty:user-presence'); api.use('rocketchat:ui'); api.use('kadira:flow-router', 'client'); api.use('templating', 'client'); api.use('http'); api.use('check'); api.use('mongo'); api.use('ddp-rate-limiter'); api.use('rocketchat:sms'); api.use('tracker'); api.use('less'); api.addFiles('livechat.js', 'server'); api.addFiles('server/startup.js', 'server'); api.addFiles('permissions.js', 'server'); api.addFiles('messageTypes.js'); api.addFiles('roomType.js'); api.addFiles('config.js', 'server'); api.addFiles('client/ui.js', 'client'); api.addFiles('client/route.js', 'client'); api.addFiles('client/stylesheets/livechat.less', 'client'); // collections api.addFiles('client/collections/AgentUsers.js', 'client'); api.addFiles('client/collections/LivechatCustomField.js', 'client'); api.addFiles('client/collections/LivechatDepartment.js', 'client'); api.addFiles('client/collections/LivechatDepartmentAgents.js', 'client'); api.addFiles('client/collections/LivechatIntegration.js', 'client'); api.addFiles('client/collections/LivechatPageVisited.js', 'client'); api.addFiles('client/collections/LivechatQueueUser.js', 'client'); api.addFiles('client/collections/LivechatTrigger.js', 'client'); api.addFiles('client/collections/LivechatInquiry.js', 'client'); api.addFiles('client/collections/livechatOfficeHour.js', 'client'); api.addFiles('client/methods/changeLivechatStatus.js', 'client'); // client views api.addFiles('client/views/app/livechatAppearance.html', 'client'); api.addFiles('client/views/app/livechatAppearance.js', 'client'); api.addFiles('client/views/app/livechatCurrentChats.html', 'client'); api.addFiles('client/views/app/livechatCurrentChats.js', 'client'); api.addFiles('client/views/app/livechatCustomFields.html', 'client'); api.addFiles('client/views/app/livechatCustomFields.js', 'client'); api.addFiles('client/views/app/livechatCustomFieldForm.html', 'client'); api.addFiles('client/views/app/livechatCustomFieldForm.js', 'client'); api.addFiles('client/views/app/livechatDashboard.html', 'client'); api.addFiles('client/views/app/livechatDepartmentForm.html', 'client'); api.addFiles('client/views/app/livechatDepartmentForm.js', 'client'); api.addFiles('client/views/app/livechatDepartments.html', 'client'); api.addFiles('client/views/app/livechatDepartments.js', 'client'); api.addFiles('client/views/app/livechatInstallation.html', 'client'); api.addFiles('client/views/app/livechatInstallation.js', 'client'); api.addFiles('client/views/app/livechatIntegrations.html', 'client'); api.addFiles('client/views/app/livechatIntegrations.js', 'client'); api.addFiles('client/views/app/livechatNotSubscribed.html', 'client'); api.addFiles('client/views/app/livechatQueue.html', 'client'); api.addFiles('client/views/app/livechatQueue.js', 'client'); api.addFiles('client/views/app/livechatTriggers.html', 'client'); api.addFiles('client/views/app/livechatTriggers.js', 'client'); api.addFiles('client/views/app/livechatTriggersForm.html', 'client'); api.addFiles('client/views/app/livechatTriggersForm.js', 'client'); api.addFiles('client/views/app/livechatUsers.html', 'client'); api.addFiles('client/views/app/livechatUsers.js', 'client'); api.addFiles('client/views/app/livechatOfficeHours.html', 'client'); api.addFiles('client/views/app/livechatOfficeHours.js', 'client'); api.addFiles('client/views/app/tabbar/externalSearch.html', 'client'); api.addFiles('client/views/app/tabbar/externalSearch.js', 'client'); api.addFiles('client/views/app/tabbar/visitorHistory.html', 'client'); api.addFiles('client/views/app/tabbar/visitorHistory.js', 'client'); api.addFiles('client/views/app/tabbar/visitorNavigation.html', 'client'); api.addFiles('client/views/app/tabbar/visitorNavigation.js', 'client'); api.addFiles('client/views/app/tabbar/visitorEdit.html', 'client'); api.addFiles('client/views/app/tabbar/visitorEdit.js', 'client'); api.addFiles('client/views/app/tabbar/visitorForward.html', 'client'); api.addFiles('client/views/app/tabbar/visitorForward.js', 'client'); api.addFiles('client/views/app/tabbar/visitorInfo.html', 'client'); api.addFiles('client/views/app/tabbar/visitorInfo.js', 'client'); api.addFiles('client/views/sideNav/livechat.html', 'client'); api.addFiles('client/views/sideNav/livechat.js', 'client'); api.addFiles('client/views/sideNav/livechatFlex.html', 'client'); api.addFiles('client/views/sideNav/livechatFlex.js', 'client'); api.addFiles('client/views/app/triggers/livechatTriggerAction.html', 'client'); api.addFiles('client/views/app/triggers/livechatTriggerAction.js', 'client'); api.addFiles('client/views/app/triggers/livechatTriggerCondition.html', 'client'); api.addFiles('client/views/app/triggers/livechatTriggerCondition.js', 'client'); // hooks api.addFiles('server/hooks/externalMessage.js', 'server'); api.addFiles('server/hooks/markRoomResponded.js', 'server'); api.addFiles('server/hooks/offlineMessage.js', 'server'); api.addFiles('server/hooks/sendToCRM.js', 'server'); // methods api.addFiles('server/methods/addAgent.js', 'server'); api.addFiles('server/methods/addManager.js', 'server'); api.addFiles('server/methods/changeLivechatStatus.js', 'server'); api.addFiles('server/methods/closeByVisitor.js', 'server'); api.addFiles('server/methods/closeRoom.js', 'server'); api.addFiles('server/methods/getCustomFields.js', 'server'); api.addFiles('server/methods/getAgentData.js', 'server'); api.addFiles('server/methods/getInitialData.js', 'server'); api.addFiles('server/methods/loginByToken.js', 'server'); api.addFiles('server/methods/pageVisited.js', 'server'); api.addFiles('server/methods/registerGuest.js', 'server'); api.addFiles('server/methods/removeAgent.js', 'server'); api.addFiles('server/methods/removeCustomField.js', 'server'); api.addFiles('server/methods/removeDepartment.js', 'server'); api.addFiles('server/methods/removeManager.js', 'server'); api.addFiles('server/methods/removeTrigger.js', 'server'); api.addFiles('server/methods/saveAppearance.js', 'server'); api.addFiles('server/methods/saveCustomField.js', 'server'); api.addFiles('server/methods/saveDepartment.js', 'server'); api.addFiles('server/methods/saveInfo.js', 'server'); api.addFiles('server/methods/saveIntegration.js', 'server'); api.addFiles('server/methods/saveSurveyFeedback.js', 'server'); api.addFiles('server/methods/saveTrigger.js', 'server'); api.addFiles('server/methods/searchAgent.js', 'server'); api.addFiles('server/methods/sendMessageLivechat.js', 'server'); api.addFiles('server/methods/sendOfflineMessage.js', 'server'); api.addFiles('server/methods/setCustomField.js', 'server'); api.addFiles('server/methods/startVideoCall.js', 'server'); api.addFiles('server/methods/transfer.js', 'server'); api.addFiles('server/methods/webhookTest.js', 'server'); api.addFiles('server/methods/takeInquiry.js', 'server'); api.addFiles('server/methods/returnAsInquiry.js', 'server'); api.addFiles('server/methods/saveOfficeHours.js', 'server'); api.addFiles('server/methods/sendTranscript.js', 'server'); // models api.addFiles('server/models/Users.js', 'server'); api.addFiles('server/models/Rooms.js', 'server'); api.addFiles('server/models/LivechatExternalMessage.js', ['client', 'server']); api.addFiles('server/models/LivechatCustomField.js', 'server'); api.addFiles('server/models/LivechatDepartment.js', 'server'); api.addFiles('server/models/LivechatDepartmentAgents.js', 'server'); api.addFiles('server/models/LivechatPageVisited.js', 'server'); api.addFiles('server/models/LivechatTrigger.js', 'server'); api.addFiles('server/models/indexes.js', 'server'); api.addFiles('server/models/LivechatInquiry.js', 'server'); api.addFiles('server/models/LivechatOfficeHour.js', 'server'); // server lib api.addFiles('server/lib/Livechat.js', 'server'); api.addFiles('server/lib/QueueMethods.js', 'server'); api.addFiles('server/lib/OfficeClock.js', 'server'); api.addFiles('server/sendMessageBySMS.js', 'server'); api.addFiles('server/unclosedLivechats.js', 'server'); // publications api.addFiles('server/publications/customFields.js', 'server'); api.addFiles('server/publications/departmentAgents.js', 'server'); api.addFiles('server/publications/externalMessages.js', 'server'); api.addFiles('server/publications/livechatAgents.js', 'server'); api.addFiles('server/publications/livechatAppearance.js', 'server'); api.addFiles('server/publications/livechatDepartments.js', 'server'); api.addFiles('server/publications/livechatIntegration.js', 'server'); api.addFiles('server/publications/livechatManagers.js', 'server'); api.addFiles('server/publications/livechatRooms.js', 'server'); api.addFiles('server/publications/livechatQueue.js', 'server'); api.addFiles('server/publications/livechatTriggers.js', 'server'); api.addFiles('server/publications/visitorHistory.js', 'server'); api.addFiles('server/publications/visitorInfo.js', 'server'); api.addFiles('server/publications/visitorPageVisited.js', 'server'); api.addFiles('server/publications/livechatInquiries.js', 'server'); api.addFiles('server/publications/livechatOfficeHours.js', 'server'); // REST endpoints api.addFiles('server/api.js', 'server'); // livechat app api.addAssets('assets/demo.html', 'client'); // DEPRECATED api.addAssets('assets/rocket-livechat.js', 'client'); // this file is still added to not break currently installed livechat widgets api.addAssets('assets/rocketchat-livechat.min.js', 'client'); api.addAssets('public/head.html', 'server'); });
ealbers/Rocket.Chat
packages/rocketchat-livechat/package.js
JavaScript
mit
10,300
import Component from '@ember/component'; import { computed } from '@ember/object'; import { empty } from '@ember/object/computed'; export default Component.extend({ emptySnippet: empty('snippet'), exampleFrameClass: 'col s12 position-relative', partialName: computed('snippet', { get() { return `snippets/${this.get('snippet') || 'none'}`; } }), snippetName: computed('snippet', { get() { return `${this.get('snippet') || 'none'}.hbs`; } }), send() { let target = this.get('targetObject'); target.send(...arguments); } });
sgasser/ember-cli-materialize
tests/dummy/app/components/example-snippet.js
JavaScript
mit
577
/*! Select2 4.0.0 | https://github.com/select2/select2/blob/master/LICENSE.md */ (function(){if(jQuery&&jQuery.fn&&jQuery.fn.select2&&jQuery.fn.select2.amd)var e=jQuery.fn.select2.amd;return e.define("select2/i18n/nl",[],function(){return{errorLoading:function(){return"De resultaten konden niet worden geladen."},inputTooLong:function(e){var t=e.input.length-e.maximum,n="Gelieve "+t+" karakters te verwijderen";return n},inputTooShort:function(e){var t=e.minimum-e.input.length,n="Gelieve "+t+" of meer karakters in te voeren";return n},loadingMore:function(){return"Meer resultaten laden..."},maximumSelected:function(e){var t="Er kunnen maar "+e.maximum+" item";return e.maximum!=1&&(t+="s"),t+=" worden geselecteerd",t},noResults:function(){return"Geen resultaten gevonden..."},searching:function(){return"Zoeken..."}}}),{define:e.define,require:e.require}})();
jpaoletti/java-presentation-manager-2
modules/jpm2-web-bs5/src/main/webapp/static/js/locale/select2/nl.js
JavaScript
mit
867
import Mirage from 'ember-cli-mirage'; export default Mirage.Factory.extend({ id: (i) => (i+1), user: (i) => (i+1), username: (i) => (i+1), });
stopfstedt/frontend
app/mirage/factories/authentication.js
JavaScript
mit
151
/* Tailwind - The Utility-First CSS Framework A project by Adam Wathan (@adamwathan), Jonathan Reinink (@reinink), David Hemphill (@davidhemphill) and Steve Schoger (@steveschoger). Welcome to the Tailwind config file. This is where you can customize Tailwind specifically for your project. Don't be intimidated by the length of this file. It's really just a big JavaScript object and we've done our very best to explain each section. View the full documentation at https://tailwindcss.com. |------------------------------------------------------------------------------- | The default config |------------------------------------------------------------------------------- | | This variable contains the default Tailwind config. You don't have | to use it, but it can sometimes be helpful to have available. For | example, you may choose to merge your custom configuration | values with some of the Tailwind defaults. | */ let defaultConfig = require('tailwindcss/defaultConfig')() /* |------------------------------------------------------------------------------- | Colors https://tailwindcss.com/docs/colors |------------------------------------------------------------------------------- | | Here you can specify the colors used in your project. To get you started, | we've provided a generous palette of great looking colors that are perfect | for prototyping, but don't hesitate to change them for your project. You | own these colors, nothing will break if you change everything about them. | | We've used literal color names ("red", "blue", etc.) for the default | palette, but if you'd rather use functional names like "primary" and | "secondary", or even a numeric scale like "100" and "200", go for it. | */ let colors = { 'transparent': 'transparent', 'black': '#22292f', 'grey-darkest': '#3d4852', 'grey-darker': '#606f7b', 'grey-dark': '#8795a1', 'grey': '#b8c2cc', 'grey-light': '#dae1e7', 'grey-lighter': '#f1f5f8', 'grey-lightest': '#f8fafc', 'white': '#ffffff', 'red-darkest': '#3b0d0c', 'red-darker': '#621b18', 'red-dark': '#cc1f1a', 'red': '#e3342f', 'red-light': '#ef5753', 'red-lighter': '#f9acaa', 'red-lightest': '#fcebea', 'orange-darkest': '#462a16', 'orange-darker': '#613b1f', 'orange-dark': '#de751f', 'orange': '#f6993f', 'orange-light': '#faad63', 'orange-lighter': '#fcd9b6', 'orange-lightest': '#fff5eb', 'yellow-darkest': '#453411', 'yellow-darker': '#684f1d', 'yellow-dark': '#f2d024', 'yellow': '#ffed4a', 'yellow-light': '#fff382', 'yellow-lighter': '#fff9c2', 'yellow-lightest': '#fcfbeb', 'green-darkest': '#0f2f21', 'green-darker': '#1a4731', 'green-dark': '#1f9d55', 'green': '#38c172', 'green-light': '#51d88a', 'green-lighter': '#a2f5bf', 'green-lightest': '#e3fcec', 'teal-darkest': '#0d3331', 'teal-darker': '#20504f', 'teal-dark': '#38a89d', 'teal': '#4dc0b5', 'teal-light': '#64d5ca', 'teal-lighter': '#a0f0ed', 'teal-lightest': '#e8fffe', 'blue-darkest': '#12283a', 'blue-darker': '#1c3d5a', 'blue-dark': '#2779bd', 'blue': '#3490dc', 'blue-light': '#6cb2eb', 'blue-lighter': '#bcdefa', 'blue-lightest': '#eff8ff', 'indigo-darkest': '#191e38', 'indigo-darker': '#2f365f', 'indigo-dark': '#5661b3', 'indigo': '#6574cd', 'indigo-light': '#7886d7', 'indigo-lighter': '#b2b7ff', 'indigo-lightest': '#e6e8ff', 'purple-darkest': '#21183c', 'purple-darker': '#382b5f', 'purple-dark': '#794acf', 'purple': '#9561e2', 'purple-light': '#a779e9', 'purple-lighter': '#d6bbfc', 'purple-lightest': '#f3ebff', 'pink-darkest': '#451225', 'pink-darker': '#6f213f', 'pink-dark': '#eb5286', 'pink': '#f66d9b', 'pink-light': '#fa7ea8', 'pink-lighter': '#ffbbca', 'pink-lightest': '#ffebef', } module.exports = { /* |----------------------------------------------------------------------------- | Colors https://tailwindcss.com/docs/colors |----------------------------------------------------------------------------- | | The color palette defined above is also assigned to the "colors" key of | your Tailwind config. This makes it easy to access them in your CSS | using Tailwind's config helper. For example: | | .error { color: config('colors.red') } | */ colors: colors, /* |----------------------------------------------------------------------------- | Screens https://tailwindcss.com/docs/responsive-design |----------------------------------------------------------------------------- | | Screens in Tailwind are translated to CSS media queries. They define the | responsive breakpoints for your project. By default Tailwind takes a | "mobile first" approach, where each screen size represents a minimum | viewport width. Feel free to have as few or as many screens as you | want, naming them in whatever way you'd prefer for your project. | | Tailwind also allows for more complex screen definitions, which can be | useful in certain situations. Be sure to see the full responsive | documentation for a complete list of options. | | Class name: .{screen}:{utility} | */ screens: { 'sm': '576px', 'md': '768px', 'lg': '992px', 'xl': '1200px', }, /* |----------------------------------------------------------------------------- | Fonts https://tailwindcss.com/docs/fonts |----------------------------------------------------------------------------- | | Here is where you define your project's font stack, or font families. | Keep in mind that Tailwind doesn't actually load any fonts for you. | If you're using custom fonts you'll need to import them prior to | defining them here. | | By default we provide a native font stack that works remarkably well on | any device or OS you're using, since it just uses the default fonts | provided by the platform. | | Class name: .font-{name} | */ fonts: { 'sans': [ 'nunito', '-apple-system', 'BlinkMacSystemFont', 'Segoe UI', 'Roboto', 'Oxygen', 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', 'sans-serif', ], 'serif': [ 'Constantia', 'Lucida Bright', 'Lucidabright', 'Lucida Serif', 'Lucida', 'DejaVu Serif', 'Bitstream Vera Serif', 'Liberation Serif', 'Georgia', 'serif', ], 'mono': [ 'Menlo', 'Monaco', 'Consolas', 'Liberation Mono', 'Courier New', 'monospace', ] }, /* |----------------------------------------------------------------------------- | Text sizes https://tailwindcss.com/docs/text-sizing |----------------------------------------------------------------------------- | | Here is where you define your text sizes. Name these in whatever way | makes the most sense to you. We use size names by default, but | you're welcome to use a numeric scale or even something else | entirely. | | By default Tailwind uses the "rem" unit type for most measurements. | This allows you to set a root font size which all other sizes are | then based on. That said, you are free to use whatever units you | prefer, be it rems, ems, pixels or other. | | Class name: .text-{size} | */ textSizes: { 'xs': '.75rem', // 12px 'sm': '.875rem', // 14px 'base': '1rem', // 16px 'lg': '1.125rem', // 18px 'xl': '1.25rem', // 20px '2xl': '1.5rem', // 24px '3xl': '1.875rem', // 30px '4xl': '2.25rem', // 36px '5xl': '3rem', // 48px }, /* |----------------------------------------------------------------------------- | Font weights https://tailwindcss.com/docs/font-weight |----------------------------------------------------------------------------- | | Here is where you define your font weights. We've provided a list of | common font weight names with their respective numeric scale values | to get you started. It's unlikely that your project will require | all of these, so we recommend removing those you don't need. | | Class name: .font-{weight} | */ fontWeights: { 'hairline': 100, 'thin': 200, 'light': 300, 'normal': 400, 'medium': 500, 'semibold': 600, 'bold': 700, 'extrabold': 800, 'black': 900, }, /* |----------------------------------------------------------------------------- | Leading (line height) https://tailwindcss.com/docs/line-height |----------------------------------------------------------------------------- | | Here is where you define your line height values, or as we call | them in Tailwind, leadings. | | Class name: .leading-{size} | */ leading: { 'none': 1, 'tight': 1.25, 'normal': 1.5, 'loose': 2, }, /* |----------------------------------------------------------------------------- | Tracking (letter spacing) https://tailwindcss.com/docs/letter-spacing |----------------------------------------------------------------------------- | | Here is where you define your letter spacing values, or as we call | them in Tailwind, tracking. | | Class name: .tracking-{size} | */ tracking: { 'tight': '-0.05em', 'normal': '0', 'wide': '0.05em', }, /* |----------------------------------------------------------------------------- | Text colors https://tailwindcss.com/docs/text-color |----------------------------------------------------------------------------- | | Here is where you define your text colors. By default these use the | color palette we defined above, however you're welcome to set these | independently if that makes sense for your project. | | Class name: .text-{color} | */ textColors: colors, /* |----------------------------------------------------------------------------- | Background colors https://tailwindcss.com/docs/background-color |----------------------------------------------------------------------------- | | Here is where you define your background colors. By default these use | the color palette we defined above, however you're welcome to set | these independently if that makes sense for your project. | | Class name: .bg-{color} | */ backgroundColors: colors, /* |----------------------------------------------------------------------------- | Border widths https://tailwindcss.com/docs/border-width |----------------------------------------------------------------------------- | | Here is where you define your border widths. Take note that border | widths require a special "default" value set as well. This is the | width that will be used when you do not specify a border width. | | Class name: .border{-side?}{-width?} | */ borderWidths: { default: '1px', '0': '0', '2': '2px', '4': '4px', '8': '8px', }, /* |----------------------------------------------------------------------------- | Border colors https://tailwindcss.com/docs/border-color |----------------------------------------------------------------------------- | | Here is where you define your border colors. By default these use the | color palette we defined above, however you're welcome to set these | independently if that makes sense for your project. | | Take note that border colors require a special "default" value set | as well. This is the color that will be used when you do not | specify a border color. | | Class name: .border-{color} | */ borderColors: Object.assign({ default: colors['grey-light'] }, colors), /* |----------------------------------------------------------------------------- | Border radius https://tailwindcss.com/docs/border-radius |----------------------------------------------------------------------------- | | Here is where you define your border radius values. If a `default` radius | is provided, it will be made available as the non-suffixed `.rounded` | utility. | | If your scale includes a `0` value to reset already rounded corners, it's | a good idea to put it first so other values are able to override it. | | Class name: .rounded{-side?}{-size?} | */ borderRadius: { 'none': '0', 'sm': '.125rem', default: '.25rem', 'lg': '.5rem', 'full': '9999px', }, /* |----------------------------------------------------------------------------- | Width https://tailwindcss.com/docs/width |----------------------------------------------------------------------------- | | Here is where you define your width utility sizes. These can be | percentage based, pixels, rems, or any other units. By default | we provide a sensible rem based numeric scale, a percentage | based fraction scale, plus some other common use-cases. You | can, of course, modify these values as needed. | | | It's also worth mentioning that Tailwind automatically escapes | invalid CSS class name characters, which allows you to have | awesome classes like .w-2/3. | | Class name: .w-{size} | */ width: { 'auto': 'auto', 'px': '1px', '1': '0.25rem', '2': '0.5rem', '3': '0.75rem', '4': '1rem', '6': '1.5rem', '8': '2rem', '10': '2.5rem', '12': '3rem', '16': '4rem', '24': '6rem', '32': '8rem', '48': '12rem', '64': '16rem', '1/2': '50%', '1/3': '33.33333%', '2/3': '66.66667%', '1/4': '25%', '3/4': '75%', '1/5': '20%', '2/5': '40%', '3/5': '60%', '4/5': '80%', '1/6': '16.66667%', '5/6': '83.33333%', 'full': '100%', 'screen': '100vw' }, /* |----------------------------------------------------------------------------- | Height https://tailwindcss.com/docs/height |----------------------------------------------------------------------------- | | Here is where you define your height utility sizes. These can be | percentage based, pixels, rems, or any other units. By default | we provide a sensible rem based numeric scale plus some other | common use-cases. You can, of course, modify these values as | needed. | | Class name: .h-{size} | */ height: { 'auto': 'auto', 'px': '1px', '1': '0.25rem', '2': '0.5rem', '3': '0.75rem', '4': '1rem', '6': '1.5rem', '8': '2rem', '10': '2.5rem', '12': '3rem', '16': '4rem', '24': '6rem', '32': '8rem', '48': '12rem', '64': '16rem', 'full': '100%', 'screen': '100vh' }, /* |----------------------------------------------------------------------------- | Minimum width https://tailwindcss.com/docs/min-width |----------------------------------------------------------------------------- | | Here is where you define your minimum width utility sizes. These can | be percentage based, pixels, rems, or any other units. We provide a | couple common use-cases by default. You can, of course, modify | these values as needed. | | Class name: .min-w-{size} | */ minWidth: { '0': '0', 'full': '100%', }, /* |----------------------------------------------------------------------------- | Minimum height https://tailwindcss.com/docs/min-height |----------------------------------------------------------------------------- | | Here is where you define your minimum height utility sizes. These can | be percentage based, pixels, rems, or any other units. We provide a | few common use-cases by default. You can, of course, modify these | values as needed. | | Class name: .min-h-{size} | */ minHeight: { '0': '0', 'full': '100%', 'screen': '100vh' }, /* |----------------------------------------------------------------------------- | Maximum width https://tailwindcss.com/docs/max-width |----------------------------------------------------------------------------- | | Here is where you define your maximum width utility sizes. These can | be percentage based, pixels, rems, or any other units. By default | we provide a sensible rem based scale and a "full width" size, | which is basically a reset utility. You can, of course, | modify these values as needed. | | Class name: .max-w-{size} | */ maxWidth: { 'xs': '20rem', 'sm': '30rem', 'md': '40rem', 'lg': '50rem', 'xl': '60rem', '2xl': '70rem', '3xl': '80rem', '4xl': '90rem', '5xl': '100rem', 'full': '100%', }, /* |----------------------------------------------------------------------------- | Maximum height https://tailwindcss.com/docs/max-height |----------------------------------------------------------------------------- | | Here is where you define your maximum height utility sizes. These can | be percentage based, pixels, rems, or any other units. We provide a | couple common use-cases by default. You can, of course, modify | these values as needed. | | Class name: .max-h-{size} | */ maxHeight: { 'full': '100%', 'screen': '100vh', }, /* |----------------------------------------------------------------------------- | Padding https://tailwindcss.com/docs/padding |----------------------------------------------------------------------------- | | Here is where you define your padding utility sizes. These can be | percentage based, pixels, rems, or any other units. By default we | provide a sensible rem based numeric scale plus a couple other | common use-cases like "1px". You can, of course, modify these | values as needed. | | Class name: .p{side?}-{size} | */ padding: { 'px': '1px', '0': '0', '1': '0.25rem', '2': '0.5rem', '3': '0.75rem', '4': '1rem', '6': '1.5rem', '8': '2rem', }, /* |----------------------------------------------------------------------------- | Margin https://tailwindcss.com/docs/margin |----------------------------------------------------------------------------- | | Here is where you define your margin utility sizes. These can be | percentage based, pixels, rems, or any other units. By default we | provide a sensible rem based numeric scale plus a couple other | common use-cases like "1px". You can, of course, modify these | values as needed. | | Class name: .m{side?}-{size} | */ margin: { 'auto': 'auto', 'px': '1px', '0': '0', '1': '0.25rem', '2': '0.5rem', '3': '0.75rem', '4': '1rem', '6': '1.5rem', '8': '2rem', }, /* |----------------------------------------------------------------------------- | Negative margin https://tailwindcss.com/docs/negative-margin |----------------------------------------------------------------------------- | | Here is where you define your negative margin utility sizes. These can | be percentage based, pixels, rems, or any other units. By default we | provide matching values to the padding scale since these utilities | generally get used together. You can, of course, modify these | values as needed. | | Class name: .-m{side?}-{size} | */ negativeMargin: { 'px': '1px', '0': '0', '1': '0.25rem', '2': '0.5rem', '3': '0.75rem', '4': '1rem', '6': '1.5rem', '8': '2rem', }, /* |----------------------------------------------------------------------------- | Shadows https://tailwindcss.com/docs/shadows |----------------------------------------------------------------------------- | | Here is where you define your shadow utilities. As you can see from | the defaults we provide, it's possible to apply multiple shadows | per utility using comma separation. | | If a `default` shadow is provided, it will be made available as the non- | suffixed `.shadow` utility. | | Class name: .shadow-{size?} | */ shadows: { default: '0 2px 4px 0 rgba(0,0,0,0.10)', 'md': '0 4px 8px 0 rgba(0,0,0,0.12), 0 2px 4px 0 rgba(0,0,0,0.08)', 'lg': '0 15px 30px 0 rgba(0,0,0,0.11), 0 5px 15px 0 rgba(0,0,0,0.08)', 'inner': 'inset 0 2px 4px 0 rgba(0,0,0,0.06)', 'none': 'none', }, /* |----------------------------------------------------------------------------- | Z-index https://tailwindcss.com/docs/z-index |----------------------------------------------------------------------------- | | Here is where you define your z-index utility values. By default we | provide a sensible numeric scale. You can, of course, modify these | values as needed. | | Class name: .z-{index} | */ zIndex: { 'auto': 'auto', '0': 0, '10': 10, '20': 20, '30': 30, '40': 40, '50': 50, }, /* |----------------------------------------------------------------------------- | Opacity https://tailwindcss.com/docs/opacity |----------------------------------------------------------------------------- | | Here is where you define your opacity utility values. By default we | provide a sensible numeric scale. You can, of course, modify these | values as needed. | | Class name: .opacity-{name} | */ opacity: { '0': '0', '25': '.25', '50': '.5', '75': '.75', '100': '1', }, /* |----------------------------------------------------------------------------- | SVG fill https://tailwindcss.com/docs/svg |----------------------------------------------------------------------------- | | Here is where you define your SVG fill colors. By default we just provide | `fill-current` which sets the fill to the current text color. This lets you | specify a fill color using existing text color utilities and helps keep the | generated CSS file size down. | | Class name: .fill-{name} | */ svgFill: { 'current': 'currentColor', }, /* |----------------------------------------------------------------------------- | SVG stroke https://tailwindcss.com/docs/svg |----------------------------------------------------------------------------- | | Here is where you define your SVG stroke colors. By default we just provide | `stroke-current` which sets the stroke to the current text color. This lets | you specify a stroke color using existing text color utilities and helps | keep the generated CSS file size down. | | Class name: .stroke-{name} | */ svgStroke: { 'current': 'currentColor', }, /* |----------------------------------------------------------------------------- | Modules https://tailwindcss.com/docs/configuration#modules |----------------------------------------------------------------------------- | | Here is where you control which modules are generated and what variants are | generated for each of those modules. | | Currently supported variants: 'responsive', 'hover', 'focus' | | To disable a module completely, use `false` instead of an array. | */ modules: { appearance: ['responsive'], backgroundAttachment: ['responsive'], backgroundColors: ['responsive', 'hover'], backgroundPosition: ['responsive'], backgroundRepeat: ['responsive'], backgroundSize: ['responsive'], borderColors: ['responsive', 'hover'], borderRadius: ['responsive'], borderStyle: ['responsive'], borderWidths: ['responsive'], cursor: ['responsive'], display: ['responsive'], flexbox: ['responsive'], float: ['responsive'], fonts: ['responsive'], fontWeights: ['responsive', 'hover'], height: ['responsive'], leading: ['responsive'], lists: ['responsive'], margin: ['responsive'], maxHeight: ['responsive'], maxWidth: ['responsive'], minHeight: ['responsive'], minWidth: ['responsive'], negativeMargin: ['responsive'], opacity: ['responsive'], overflow: ['responsive'], padding: ['responsive'], pointerEvents: ['responsive'], position: ['responsive'], resize: ['responsive'], shadows: ['responsive'], svgFill: [], svgStroke: [], textAlign: ['responsive'], textColors: ['responsive', 'hover'], textSizes: ['responsive'], textStyle: ['responsive', 'hover'], tracking: ['responsive'], userSelect: ['responsive'], verticalAlign: ['responsive'], visibility: ['responsive'], whitespace: ['responsive'], width: ['responsive'], zIndex: ['responsive'], }, /* |----------------------------------------------------------------------------- | Advanced Options https://tailwindcss.com/docs/configuration#options |----------------------------------------------------------------------------- | | Here is where you can tweak advanced configuration options. We recommend | leaving these options alone unless you absolutely need to change them. | */ options: { prefix: '', important: false, separator: ':', }, }
merelinguist/ludolatin
tailwind.js
JavaScript
mit
25,586
/** View class responsible for rendering the `<tbody>` section of a table. Used as the default `bodyView` for `Y.DataTable.Base` and `Y.DataTable` classes. @module datatable @submodule datatable-body @since 3.5.0 **/ var Lang = Y.Lang, isArray = Lang.isArray, isNumber = Lang.isNumber, isString = Lang.isString, fromTemplate = Lang.sub, htmlEscape = Y.Escape.html, toArray = Y.Array, bind = Y.bind, YObject = Y.Object, valueRegExp = /\{value\}/g, EV_CONTENT_UPDATE = 'contentUpdate', shiftMap = { above: [-1, 0], below: [1, 0], next: [0, 1], prev: [0, -1], previous: [0, -1] }; /** View class responsible for rendering the `<tbody>` section of a table. Used as the default `bodyView` for `Y.DataTable.Base` and `Y.DataTable` classes. Translates the provided `modelList` into a rendered `<tbody>` based on the data in the constituent Models, altered or amended by any special column configurations. The `columns` configuration, passed to the constructor, determines which columns will be rendered. The rendering process involves constructing an HTML template for a complete row of data, built by concatenating a customized copy of the instance's `CELL_TEMPLATE` into the `ROW_TEMPLATE` once for each column. This template is then populated with values from each Model in the `modelList`, aggregating a complete HTML string of all row and column data. A `<tbody>` Node is then created from the markup and any column `nodeFormatter`s are applied. Supported properties of the column objects include: * `key` - Used to link a column to an attribute in a Model. * `name` - Used for columns that don't relate to an attribute in the Model (`formatter` or `nodeFormatter` only) if the implementer wants a predictable name to refer to in their CSS. * `cellTemplate` - Overrides the instance's `CELL_TEMPLATE` for cells in this column only. * `formatter` - Used to customize or override the content value from the Model. These do not have access to the cell or row Nodes and should return string (HTML) content. * `nodeFormatter` - Used to provide content for a cell as well as perform any custom modifications on the cell or row Node that could not be performed by `formatter`s. Should be used sparingly for better performance. * `emptyCellValue` - String (HTML) value to use if the Model data for a column, or the content generated by a `formatter`, is the empty string, `null`, or `undefined`. * `allowHTML` - Set to `true` if a column value, `formatter`, or `emptyCellValue` can contain HTML. This defaults to `false` to protect against XSS. * `className` - Space delimited CSS classes to add to all `<td>`s in a column. A column `formatter` can be: * a function, as described below. * a string which can be: * the name of a pre-defined formatter function which can be located in the `Y.DataTable.BodyView.Formatters` hash using the value of the `formatter` property as the index. * A template that can use the `{value}` placeholder to include the value for the current cell or the name of any field in the underlaying model also enclosed in curly braces. Any number and type of these placeholders can be used. Column `formatter`s are passed an object (`o`) with the following properties: * `value` - The current value of the column's associated attribute, if any. * `data` - An object map of Model keys to their current values. * `record` - The Model instance. * `column` - The column configuration object for the current column. * `className` - Initially empty string to allow `formatter`s to add CSS classes to the cell's `<td>`. * `rowIndex` - The zero-based row number. * `rowClass` - Initially empty string to allow `formatter`s to add CSS classes to the cell's containing row `<tr>`. They may return a value or update `o.value` to assign specific HTML content. A returned value has higher precedence. Column `nodeFormatter`s are passed an object (`o`) with the following properties: * `value` - The current value of the column's associated attribute, if any. * `td` - The `<td>` Node instance. * `cell` - The `<div>` liner Node instance if present, otherwise, the `<td>`. When adding content to the cell, prefer appending into this property. * `data` - An object map of Model keys to their current values. * `record` - The Model instance. * `column` - The column configuration object for the current column. * `rowIndex` - The zero-based row number. They are expected to inject content into the cell's Node directly, including any "empty" cell content. Each `nodeFormatter` will have access through the Node API to all cells and rows in the `<tbody>`, but not to the `<table>`, as it will not be attached yet. If a `nodeFormatter` returns `false`, the `o.td` and `o.cell` Nodes will be `destroy()`ed to remove them from the Node cache and free up memory. The DOM elements will remain as will any content added to them. _It is highly advisable to always return `false` from your `nodeFormatter`s_. @class BodyView @namespace DataTable @extends View @since 3.5.0 **/ Y.namespace('DataTable').BodyView = Y.Base.create('tableBody', Y.View, [], { // -- Instance properties ------------------------------------------------- /** HTML template used to create table cells. @property CELL_TEMPLATE @type {String} @default '<td {headers} class="{className}">{content}</td>' @since 3.5.0 **/ CELL_TEMPLATE: '<td {headers} class="{className}">{content}</td>', /** CSS class applied to even rows. This is assigned at instantiation. For DataTable, this will be `yui3-datatable-even`. @property CLASS_EVEN @type {String} @default 'yui3-table-even' @since 3.5.0 **/ //CLASS_EVEN: null /** CSS class applied to odd rows. This is assigned at instantiation. When used by DataTable instances, this will be `yui3-datatable-odd`. @property CLASS_ODD @type {String} @default 'yui3-table-odd' @since 3.5.0 **/ //CLASS_ODD: null /** HTML template used to create table rows. @property ROW_TEMPLATE @type {String} @default '<tr id="{rowId}" data-yui3-record="{clientId}" class="{rowClass}">{content}</tr>' @since 3.5.0 **/ ROW_TEMPLATE : '<tr id="{rowId}" data-yui3-record="{clientId}" class="{rowClass}">{content}</tr>', /** The object that serves as the source of truth for column and row data. This property is assigned at instantiation from the `host` property of the configuration object passed to the constructor. @property host @type {Object} @default (initially unset) @since 3.5.0 **/ //TODO: should this be protected? //host: null, /** HTML templates used to create the `<tbody>` containing the table rows. @property TBODY_TEMPLATE @type {String} @default '<tbody class="{className}">{content}</tbody>' @since 3.6.0 **/ TBODY_TEMPLATE: '<tbody class="{className}"></tbody>', // -- Public methods ------------------------------------------------------ /** Returns the `<td>` Node from the given row and column index. Alternately, the `seed` can be a Node. If so, the nearest ancestor cell is returned. If the `seed` is a cell, it is returned. If there is no cell at the given coordinates, `null` is returned. Optionally, include an offset array or string to return a cell near the cell identified by the `seed`. The offset can be an array containing the number of rows to shift followed by the number of columns to shift, or one of "above", "below", "next", or "previous". <pre><code>// Previous cell in the previous row var cell = table.getCell(e.target, [-1, -1]); // Next cell var cell = table.getCell(e.target, 'next'); var cell = table.getCell(e.target, [0, 1];</pre></code> @method getCell @param {Number[]|Node} seed Array of row and column indexes, or a Node that is either the cell itself or a descendant of one. @param {Number[]|String} [shift] Offset by which to identify the returned cell Node @return {Node} @since 3.5.0 **/ getCell: function (seed, shift) { var tbody = this.tbodyNode, row, cell, index, rowIndexOffset; if (seed && tbody) { if (isArray(seed)) { row = tbody.get('children').item(seed[0]); cell = row && row.get('children').item(seed[1]); } else if (seed._node) { cell = seed.ancestor('.' + this.getClassName('cell'), true); } if (cell && shift) { rowIndexOffset = tbody.get('firstChild.rowIndex'); if (isString(shift)) { if (!shiftMap[shift]) { Y.error('Unrecognized shift: ' + shift, null, 'datatable-body'); } shift = shiftMap[shift]; } if (isArray(shift)) { index = cell.get('parentNode.rowIndex') + shift[0] - rowIndexOffset; row = tbody.get('children').item(index); index = cell.get('cellIndex') + shift[1]; cell = row && row.get('children').item(index); } } } return cell || null; }, /** Returns the generated CSS classname based on the input. If the `host` attribute is configured, it will attempt to relay to its `getClassName` or use its static `NAME` property as a string base. If `host` is absent or has neither method nor `NAME`, a CSS classname will be generated using this class's `NAME`. @method getClassName @param {String} token* Any number of token strings to assemble the classname from. @return {String} @protected @since 3.5.0 **/ getClassName: function () { var host = this.host, args; if (host && host.getClassName) { return host.getClassName.apply(host, arguments); } else { args = toArray(arguments); args.unshift(this.constructor.NAME); return Y.ClassNameManager.getClassName .apply(Y.ClassNameManager, args); } }, /** Returns the Model associated to the row Node or id provided. Passing the Node or id for a descendant of the row also works. If no Model can be found, `null` is returned. @method getRecord @param {String|Node} seed Row Node or `id`, or one for a descendant of a row @return {Model} @since 3.5.0 **/ getRecord: function (seed) { var modelList = this.get('modelList'), tbody = this.tbodyNode, row = null, record; if (tbody) { if (isString(seed)) { seed = tbody.one('#' + seed); } if (seed && seed._node) { row = seed.ancestor(function (node) { return node.get('parentNode').compareTo(tbody); }, true); record = row && modelList.getByClientId(row.getData('yui3-record')); } } return record || null; }, /** Returns the `<tr>` Node from the given row index, Model, or Model's `clientId`. If the rows haven't been rendered yet, or if the row can't be found by the input, `null` is returned. @method getRow @param {Number|String|Model} id Row index, Model instance, or clientId @return {Node} @since 3.5.0 **/ getRow: function (id) { var tbody = this.tbodyNode, row = null; if (tbody) { if (id) { id = this._idMap[id.get ? id.get('clientId') : id] || id; } row = isNumber(id) ? tbody.get('children').item(id) : tbody.one('#' + id); } return row; }, /** Creates the table's `<tbody>` content by assembling markup generated by populating the `ROW\_TEMPLATE`, and `CELL\_TEMPLATE` templates with content from the `columns` and `modelList` attributes. The rendering process happens in three stages: 1. A row template is assembled from the `columns` attribute (see `_createRowTemplate`) 2. An HTML string is built up by concatenating the application of the data in each Model in the `modelList` to the row template. For cells with `formatter`s, the function is called to generate cell content. Cells with `nodeFormatter`s are ignored. For all other cells, the data value from the Model attribute for the given column key is used. The accumulated row markup is then inserted into the container. 3. If any column is configured with a `nodeFormatter`, the `modelList` is iterated again to apply the `nodeFormatter`s. Supported properties of the column objects include: * `key` - Used to link a column to an attribute in a Model. * `name` - Used for columns that don't relate to an attribute in the Model (`formatter` or `nodeFormatter` only) if the implementer wants a predictable name to refer to in their CSS. * `cellTemplate` - Overrides the instance's `CELL_TEMPLATE` for cells in this column only. * `formatter` - Used to customize or override the content value from the Model. These do not have access to the cell or row Nodes and should return string (HTML) content. * `nodeFormatter` - Used to provide content for a cell as well as perform any custom modifications on the cell or row Node that could not be performed by `formatter`s. Should be used sparingly for better performance. * `emptyCellValue` - String (HTML) value to use if the Model data for a column, or the content generated by a `formatter`, is the empty string, `null`, or `undefined`. * `allowHTML` - Set to `true` if a column value, `formatter`, or `emptyCellValue` can contain HTML. This defaults to `false` to protect against XSS. * `className` - Space delimited CSS classes to add to all `<td>`s in a column. Column `formatter`s are passed an object (`o`) with the following properties: * `value` - The current value of the column's associated attribute, if any. * `data` - An object map of Model keys to their current values. * `record` - The Model instance. * `column` - The column configuration object for the current column. * `className` - Initially empty string to allow `formatter`s to add CSS classes to the cell's `<td>`. * `rowIndex` - The zero-based row number. * `rowClass` - Initially empty string to allow `formatter`s to add CSS classes to the cell's containing row `<tr>`. They may return a value or update `o.value` to assign specific HTML content. A returned value has higher precedence. Column `nodeFormatter`s are passed an object (`o`) with the following properties: * `value` - The current value of the column's associated attribute, if any. * `td` - The `<td>` Node instance. * `cell` - The `<div>` liner Node instance if present, otherwise, the `<td>`. When adding content to the cell, prefer appending into this property. * `data` - An object map of Model keys to their current values. * `record` - The Model instance. * `column` - The column configuration object for the current column. * `rowIndex` - The zero-based row number. They are expected to inject content into the cell's Node directly, including any "empty" cell content. Each `nodeFormatter` will have access through the Node API to all cells and rows in the `<tbody>`, but not to the `<table>`, as it will not be attached yet. If a `nodeFormatter` returns `false`, the `o.td` and `o.cell` Nodes will be `destroy()`ed to remove them from the Node cache and free up memory. The DOM elements will remain as will any content added to them. _It is highly advisable to always return `false` from your `nodeFormatter`s_. @method render @chainable @since 3.5.0 **/ render: function () { var table = this.get('container'), data = this.get('modelList'), displayCols = this.get('columns'), tbody = this.tbodyNode || (this.tbodyNode = this._createTBodyNode()); // Needed for mutation this._createRowTemplate(displayCols); if (data) { tbody.setHTML(this._createDataHTML(displayCols)); this._applyNodeFormatters(tbody, displayCols); } if (tbody.get('parentNode') !== table) { table.appendChild(tbody); } this.bindUI(); return this; }, /** Refreshes the provided row against the provided model and the Array of columns to be updated. @method refreshRow @param {Node} row @param {Model} model Y.Model representation of the row @param {String[]} colKeys Array of column keys @chainable */ refreshRow: function (row, model, colKeys) { var col, cell, len = colKeys.length, i; for (i = 0; i < len; i++) { col = this.getColumn(colKeys[i]); if (col !== null) { cell = row.one('.' + this.getClassName('col', col._id || col.key)); this.refreshCell(cell, model); } } return this; }, /** Refreshes the given cell with the provided model data and the provided column configuration. Uses the provided column formatter if aviable. @method refreshCell @param {Node} cell Y.Node pointer to the cell element to be updated @param {Model} [model] Y.Model representation of the row @param {Object} [col] Column configuration object for the cell @chainable */ refreshCell: function (cell, model, col) { var content, formatterFn, formatterData, data = model.toJSON(); cell = this.getCell(cell); /* jshint -W030 */ model || (model = this.getRecord(cell)); col || (col = this.getColumn(cell)); /* jshint +W030 */ if (col.nodeFormatter) { formatterData = { cell: cell.one('.' + this.getClassName('liner')) || cell, column: col, data: data, record: model, rowIndex: this._getRowIndex(cell.ancestor('tr')), td: cell, value: data[col.key] }; keep = col.nodeFormatter.call(host,formatterData); if (keep === false) { // Remove from the Node cache to reduce // memory footprint. This also purges events, // which you shouldn't be scoping to a cell // anyway. You've been warned. Incidentally, // you should always return false. Just sayin. cell.destroy(true); } } else if (col.formatter) { if (!col._formatterFn) { col = this._setColumnsFormatterFn([col])[0]; } formatterFn = col._formatterFn || null; if (formatterFn) { formatterData = { value : data[col.key], data : data, column : col, record : model, className: '', rowClass : '', rowIndex : this._getRowIndex(cell.ancestor('tr')) }; // Formatters can either return a value ... content = formatterFn.call(this.get('host'), formatterData); // ... or update the value property of the data obj passed if (content === undefined) { content = formatterData.value; } } if (content === undefined || content === null || content === '') { content = col.emptyCellValue || ''; } } else { content = data[col.key] || col.emptyCellValue || ''; } cell.setHTML(col.allowHTML ? content : Y.Escape.html(content)); return this; }, /** Returns column data from this.get('columns'). If a Y.Node is provided as the key, will try to determine the key from the classname @method getColumn @param {String|Node} name @return {Object} Returns column configuration */ getColumn: function (name) { if (name && name._node) { // get column name from node name = name.get('className').match( new RegExp( this.getClassName('col') +'-([^ ]*)' ) )[1]; } if (this.host) { return this.host._columnMap[name] || null; } var displayCols = this.get('columns'), col = null; Y.Array.some(displayCols, function (_col) { if ((_col._id || _col.key) === name) { col = _col; return true; } }); return col; }, // -- Protected and private methods --------------------------------------- /** Handles changes in the source's columns attribute. Redraws the table data. @method _afterColumnsChange @param {EventFacade} e The `columnsChange` event object @protected @since 3.5.0 **/ // TODO: Preserve existing DOM // This will involve parsing and comparing the old and new column configs // and reacting to four types of changes: // 1. formatter, nodeFormatter, emptyCellValue changes // 2. column deletions // 3. column additions // 4. column moves (preserve cells) _afterColumnsChange: function () { this.render(); }, /** Handles modelList changes, including additions, deletions, and updates. Modifies the existing table DOM accordingly. @method _afterDataChange @param {EventFacade} e The `change` event from the ModelList @protected @since 3.5.0 **/ _afterDataChange: function (e) { var type = (e.type.match(/:(add|change|remove)$/) || [])[1], index = e.index, displayCols = this.get('columns'), col, changed = e.changed && Y.Object.keys(e.changed), key, row, i, len; for (i = 0, len = displayCols.length; i < len; i++ ) { col = displayCols[i]; // since nodeFormatters typcially make changes outside of it's // cell, we need to see if there are any columns that have a // nodeFormatter and if so, we need to do a full render() of the // tbody if (col.hasOwnProperty('nodeFormatter')) { this.render(); this.fire(EV_CONTENT_UPDATE); return; } } // TODO: if multiple rows are being added/remove/swapped, can we avoid the restriping? switch (type) { case 'change': for (i = 0, len = displayCols.length; i < len; i++) { col = displayCols[i]; key = col.key; if (col.formatter && !e.changed[key]) { changed.push(key); } } this.refreshRow(this.getRow(e.target), e.target, changed); break; case 'add': // we need to make sure we don't have an index larger than the data we have index = Math.min(index, this.get('modelList').size() - 1); // updates the columns with formatter functions this._setColumnsFormatterFn(displayCols); row = Y.Node.create(this._createRowHTML(e.model, index, displayCols)); this.tbodyNode.insert(row, index); this._restripe(index); break; case 'remove': this.getRow(index).remove(true); // we removed a row, so we need to back up our index to stripe this._restripe(index - 1); break; default: this.render(); } // Event fired to tell users when we are done updating after the data // was changed this.fire(EV_CONTENT_UPDATE); }, /** Toggles the odd/even classname of the row after the given index. This method is used to update rows after a row is inserted into or removed from the table. Note this event is delayed so the table is only restriped once when multiple rows are updated at one time. @protected @method _restripe @param {Number} [index] Index of row to start restriping after @since 3.11.0 */ _restripe: function (index) { var task = this._restripeTask, self; // index|0 to force int, avoid NaN. Math.max() to avoid neg indexes. index = Math.max((index|0), 0); if (!task) { self = this; this._restripeTask = { timer: setTimeout(function () { // Check for self existence before continuing if (!self || self.get('destroy') || !self.tbodyNode || !self.tbodyNode.inDoc()) { self._restripeTask = null; return; } var odd = [self.CLASS_ODD, self.CLASS_EVEN], even = [self.CLASS_EVEN, self.CLASS_ODD], index = self._restripeTask.index; self.tbodyNode.get('childNodes') .slice(index) .each(function (row, i) { // TODO: each vs batch row.replaceClass.apply(row, (index + i) % 2 ? even : odd); }); self._restripeTask = null; }, 0), index: index }; } else { task.index = Math.min(task.index, index); } }, /** Handles replacement of the modelList. Rerenders the `<tbody>` contents. @method _afterModelListChange @param {EventFacade} e The `modelListChange` event @protected @since 3.6.0 **/ _afterModelListChange: function () { var handles = this._eventHandles; if (handles.dataChange) { handles.dataChange.detach(); delete handles.dataChange; this.bindUI(); } if (this.tbodyNode) { this.render(); } }, /** Iterates the `modelList`, and calls any `nodeFormatter`s found in the `columns` param on the appropriate cell Nodes in the `tbody`. @method _applyNodeFormatters @param {Node} tbody The `<tbody>` Node whose columns to update @param {Object[]} displayCols The column configurations @protected @since 3.5.0 **/ _applyNodeFormatters: function (tbody, displayCols) { var host = this.host || this, data = this.get('modelList'), formatters = [], linerQuery = '.' + this.getClassName('liner'), rows, i, len; // Only iterate the ModelList again if there are nodeFormatters for (i = 0, len = displayCols.length; i < len; ++i) { if (displayCols[i].nodeFormatter) { formatters.push(i); } } if (data && formatters.length) { rows = tbody.get('childNodes'); data.each(function (record, index) { var formatterData = { data : record.toJSON(), record : record, rowIndex : index }, row = rows.item(index), i, len, col, key, cells, cell, keep; if (row) { cells = row.get('childNodes'); for (i = 0, len = formatters.length; i < len; ++i) { cell = cells.item(formatters[i]); if (cell) { col = formatterData.column = displayCols[formatters[i]]; key = col.key || col.id; formatterData.value = record.get(key); formatterData.td = cell; formatterData.cell = cell.one(linerQuery) || cell; keep = col.nodeFormatter.call(host,formatterData); if (keep === false) { // Remove from the Node cache to reduce // memory footprint. This also purges events, // which you shouldn't be scoping to a cell // anyway. You've been warned. Incidentally, // you should always return false. Just sayin. cell.destroy(true); } } } } }); } }, /** Binds event subscriptions from the UI and the host (if assigned). @method bindUI @protected @since 3.5.0 **/ bindUI: function () { var handles = this._eventHandles, modelList = this.get('modelList'), changeEvent = modelList.model.NAME + ':change'; if (!handles.columnsChange) { handles.columnsChange = this.after('columnsChange', bind('_afterColumnsChange', this)); } if (modelList && !handles.dataChange) { handles.dataChange = modelList.after( ['add', 'remove', 'reset', changeEvent], bind('_afterDataChange', this)); } }, /** Iterates the `modelList` and applies each Model to the `_rowTemplate`, allowing any column `formatter` or `emptyCellValue` to override cell content for the appropriate column. The aggregated HTML string is returned. @method _createDataHTML @param {Object[]} displayCols The column configurations to customize the generated cell content or class names @return {String} The markup for all Models in the `modelList`, each applied to the `_rowTemplate` @protected @since 3.5.0 **/ _createDataHTML: function (displayCols) { var data = this.get('modelList'), html = ''; if (data) { data.each(function (model, index) { html += this._createRowHTML(model, index, displayCols); }, this); } return html; }, /** Applies the data of a given Model, modified by any column formatters and supplemented by other template values to the instance's `_rowTemplate` (see `_createRowTemplate`). The generated string is then returned. The data from Model's attributes is fetched by `toJSON` and this data object is appended with other properties to supply values to {placeholders} in the template. For a template generated from a Model with 'foo' and 'bar' attributes, the data object would end up with the following properties before being used to populate the `_rowTemplate`: * `clientID` - From Model, used the assign the `<tr>`'s 'id' attribute. * `foo` - The value to populate the 'foo' column cell content. This value will be the value stored in the Model's `foo` attribute, or the result of the column's `formatter` if assigned. If the value is '', `null`, or `undefined`, and the column's `emptyCellValue` is assigned, that value will be used. * `bar` - Same for the 'bar' column cell content. * `foo-className` - String of CSS classes to apply to the `<td>`. * `bar-className` - Same. * `rowClass` - String of CSS classes to apply to the `<tr>`. This will be the odd/even class per the specified index plus any additional classes assigned by column formatters (via `o.rowClass`). Because this object is available to formatters, any additional properties can be added to fill in custom {placeholders} in the `_rowTemplate`. @method _createRowHTML @param {Model} model The Model instance to apply to the row template @param {Number} index The index the row will be appearing @param {Object[]} displayCols The column configurations @return {String} The markup for the provided Model, less any `nodeFormatter`s @protected @since 3.5.0 **/ _createRowHTML: function (model, index, displayCols) { var data = model.toJSON(), clientId = model.get('clientId'), values = { rowId : this._getRowId(clientId), clientId: clientId, rowClass: (index % 2) ? this.CLASS_ODD : this.CLASS_EVEN }, host = this.host || this, i, len, col, token, value, formatterData; for (i = 0, len = displayCols.length; i < len; ++i) { col = displayCols[i]; value = data[col.key]; token = col._id || col.key; values[token + '-className'] = ''; if (col._formatterFn) { formatterData = { value : value, data : data, column : col, record : model, className: '', rowClass : '', rowIndex : index }; // Formatters can either return a value value = col._formatterFn.call(host, formatterData); // or update the value property of the data obj passed if (value === undefined) { value = formatterData.value; } values[token + '-className'] = formatterData.className; values.rowClass += ' ' + formatterData.rowClass; } // if the token missing OR is the value a legit value if (!values.hasOwnProperty(token) || data.hasOwnProperty(col.key)) { if (value === undefined || value === null || value === '') { value = col.emptyCellValue || ''; } values[token] = col.allowHTML ? value : htmlEscape(value); } } // replace consecutive whitespace with a single space values.rowClass = values.rowClass.replace(/\s+/g, ' '); return fromTemplate(this._rowTemplate, values); }, /** Locates the row within the tbodyNode and returns the found index, or Null if it is not found in the tbodyNode @param {Node} row @return {Number} Index of row in tbodyNode */ _getRowIndex: function (row) { var tbody = this.tbodyNode, index = 1; if (tbody && row) { //if row is not in the tbody, return if (row.ancestor('tbody') !== tbody) { return null; } // increment until we no longer have a previous node /*jshint boss: true*/ while (row = row.previous()) { // NOTE: assignment /*jshint boss: false*/ index++; } } return index; }, /** Creates a custom HTML template string for use in generating the markup for individual table rows with {placeholder}s to capture data from the Models in the `modelList` attribute or from column `formatter`s. Assigns the `_rowTemplate` property. @method _createRowTemplate @param {Object[]} displayCols Array of column configuration objects @protected @since 3.5.0 **/ _createRowTemplate: function (displayCols) { var html = '', cellTemplate = this.CELL_TEMPLATE, i, len, col, key, token, headers, tokenValues, formatter; this._setColumnsFormatterFn(displayCols); for (i = 0, len = displayCols.length; i < len; ++i) { col = displayCols[i]; key = col.key; token = col._id || key; formatter = col._formatterFn; // Only include headers if there are more than one headers = (col._headers || []).length > 1 ? 'headers="' + col._headers.join(' ') + '"' : ''; tokenValues = { content : '{' + token + '}', headers : headers, className: this.getClassName('col', token) + ' ' + (col.className || '') + ' ' + this.getClassName('cell') + ' {' + token + '-className}' }; if (!formatter && col.formatter) { tokenValues.content = col.formatter.replace(valueRegExp, tokenValues.content); } if (col.nodeFormatter) { // Defer all node decoration to the formatter tokenValues.content = ''; } html += fromTemplate(col.cellTemplate || cellTemplate, tokenValues); } this._rowTemplate = fromTemplate(this.ROW_TEMPLATE, { content: html }); }, /** Parses the columns array and defines the column's _formatterFn if there is a formatter available on the column @protected @method _setColumnsFormatterFn @param {Object[]} displayCols Array of column configuration objects @return {Object[]} Returns modified displayCols configuration Array */ _setColumnsFormatterFn: function (displayCols) { var Formatters = Y.DataTable.BodyView.Formatters, formatter, col, i, len; for (i = 0, len = displayCols.length; i < len; i++) { col = displayCols[i]; formatter = col.formatter; if (!col._formatterFn && formatter) { if (Lang.isFunction(formatter)) { col._formatterFn = formatter; } else if (formatter in Formatters) { col._formatterFn = Formatters[formatter].call(this.host || this, col); } } } return displayCols; }, /** Creates the `<tbody>` node that will store the data rows. @method _createTBodyNode @return {Node} @protected @since 3.6.0 **/ _createTBodyNode: function () { return Y.Node.create(fromTemplate(this.TBODY_TEMPLATE, { className: this.getClassName('data') })); }, /** Destroys the instance. @method destructor @protected @since 3.5.0 **/ destructor: function () { (new Y.EventHandle(YObject.values(this._eventHandles))).detach(); }, /** Holds the event subscriptions needing to be detached when the instance is `destroy()`ed. @property _eventHandles @type {Object} @default undefined (initially unset) @protected @since 3.5.0 **/ //_eventHandles: null, /** Returns the row ID associated with a Model's clientId. @method _getRowId @param {String} clientId The Model clientId @return {String} @protected **/ _getRowId: function (clientId) { return this._idMap[clientId] || (this._idMap[clientId] = Y.guid()); }, /** Map of Model clientIds to row ids. @property _idMap @type {Object} @protected **/ //_idMap, /** Initializes the instance. Reads the following configuration properties in addition to the instance attributes: * `columns` - (REQUIRED) The initial column information * `host` - The object to serve as source of truth for column info and for generating class names @method initializer @param {Object} config Configuration data @protected @since 3.5.0 **/ initializer: function (config) { this.host = config.host; this._eventHandles = { modelListChange: this.after('modelListChange', bind('_afterModelListChange', this)) }; this._idMap = {}; this.CLASS_ODD = this.getClassName('odd'); this.CLASS_EVEN = this.getClassName('even'); } /** The HTML template used to create a full row of markup for a single Model in the `modelList` plus any customizations defined in the column configurations. @property _rowTemplate @type {String} @default (initially unset) @protected @since 3.5.0 **/ //_rowTemplate: null },{ /** Hash of formatting functions for cell contents. This property can be populated with a hash of formatting functions by the developer or a set of pre-defined functions can be loaded via the `datatable-formatters` module. See: [DataTable.BodyView.Formatters](./DataTable.BodyView.Formatters.html) @property Formatters @type Object @since 3.8.0 @static **/ Formatters: {} });
inikoo/fact
libs/yui/yui3/src/datatable/js/body.js
JavaScript
mit
41,858
import React from 'react'; import Textfield from 'components/form/Textfield'; import Textarea from 'components/form/Textarea'; import Select from 'components/form/Select'; import Cell from 'components/Cell'; import Cells from 'components/Cells'; import {matchLibraries} from 'utils/utils'; import {codeFromSchema} from 'utils/codegen'; import brace from 'brace'; import AceEditor from 'react-ace'; import 'brace/mode/javascript'; import 'brace/mode/json'; //import 'brace/theme/github'; import {configNode} from 'utils/ReactDecorators'; @configNode() export default class Node extends React.Component { constructor(props){ super(props); this.state={selected:null}; this._createInputCode = this._createInputCode.bind(this); this._createOutputCode = this._createOutputCode.bind(this); this._createInputType = this._createInputType.bind(this); this._createOutputType = this._createOutputType.bind(this); } renderInputCodeGenerators(){ const {node, inputs=[]} = this.props; return inputs.map((_node, i)=>{ const iconstyle = { alignSelf: 'center', height: 40, width: 40, color:'white', background: _node._def.color || '#ca2525', border: '2px solid white', textAlign: 'center', boxShadow: '0 3px 8px 0 rgba(0, 0, 0, 0.1), 0 6px 20px 0 rgba(0, 0, 0, 0.09)', marginTop: 5, paddingTop: 5, color: 'white', fontSize: 30, WebkitFlex: '0 0 auto', } return <div onClick={this._createInputCode.bind(null, _node)} key={i} style={iconstyle}> <i className={`fa ${_node._def.icon} fa-fw`}></i> </div> }); } renderOutputCodeGenerators(){ const {node, outputs=[]} = this.props; return outputs.map((_node, i)=>{ const iconstyle = { alignSelf: 'center', height: 40, width: 40, color:'white', background: _node._def.color || '#ca2525', border: '2px solid white', textAlign: 'center', boxShadow: '0 3px 8px 0 rgba(0, 0, 0, 0.1), 0 6px 20px 0 rgba(0, 0, 0, 0.09)', marginTop: 5, paddingTop: 5, color: 'white', fontSize: 30, WebkitFlex: '0 0 auto', } return <div onClick={this._createOutputCode.bind(null, _node)} key={i} style={iconstyle}> <i className={`fa ${_node._def.icon} fa-fw`}></i> </div> }); } renderInputTypeGenerators(){ const {node, inputs=[]} = this.props; return inputs.map((_node, i)=>{ const iconstyle = { alignSelf: 'center', height: 40, width: 40, color:'white', background: _node._def.color || '#ca2525', border: '2px solid white', textAlign: 'center', boxShadow: '0 3px 8px 0 rgba(0, 0, 0, 0.1), 0 6px 20px 0 rgba(0, 0, 0, 0.09)', marginTop: 5, paddingTop: 5, color: 'white', fontSize: 30, WebkitFlex: '0 0 auto', } return <div onClick={()=>{ this._createInputType(_node); this.setState({selected:"inputtypedef"})}} key={i} style={iconstyle}> <i className={`fa ${_node._def.icon} fa-fw`}></i> </div> }); } renderOutputTypeGenerators(){ const {node, outputs=[]} = this.props; return outputs.map((_node, i)=>{ const iconstyle = { alignSelf: 'center', height: 40, width: 40, color:'white', background: _node._def.color || '#ca2525', border: '2px solid white', textAlign: 'center', boxShadow: '0 3px 8px 0 rgba(0, 0, 0, 0.1), 0 6px 20px 0 rgba(0, 0, 0, 0.09)', marginTop: 5, paddingTop: 5, color: 'white', fontSize: 30, WebkitFlex: '0 0 auto', } return <div onClick={()=>{ this._createOutputType(_node); this.setState({selected:"outputtypedef"})}} key={i} style={iconstyle}> <i className={`fa ${_node._def.icon} fa-fw`}></i> </div> }); } renderTypeInput(){ const {node, values={}, updateNode} = this.props; const inputtypeprops = { onChange: (value)=>{ updateNode("inputtypedef", value); }, onFocus: ()=>{ this.setState({selected:"inputtypedef"}) }, onBlur: ()=>{ this.setState({selected:null}) }, value: values.inputtypedef || node.inputtypedef || "", mode: "json", theme: "github", name: `type-${node.id}`, editorProps:{$blockScrolling: true}, height: '200px', width: '100%', showPrintMargin: false, } const inputstyle = { height: this.state.selected === "inputtypedef" ? 200 : 50, overflowY: 'auto', } return <div className="flexrow" style={inputstyle}> <div style={{width:50, background:"#333", color:"white"}}> <div className="flexcolumn"> {this.renderInputTypeGenerators()} </div> </div> <AceEditor {...inputtypeprops}/> </div> } renderTypeOutput(){ const {node, values={}, updateNode} = this.props; const outputtypeprops = { onChange: (value)=>{ updateNode("outputtypedef", value); }, onFocus: ()=>{ this.setState({selected:"outputtypedef"}) }, onBlur: ()=>{ this.setState({selected:null}) }, value: values.outputtypedef || node.outputtypedef || "", mode: "json", theme: "github", name: `type-${node.id}`, editorProps:{$blockScrolling: true}, height: '200px', width: '100%', showPrintMargin: false, } const outputstyle = { height: this.state.selected === "outputtypedef" ? 200 : 50, overflowY: 'auto', } return <div className="flexrow" style={outputstyle}> <div style={{width:50, background:"#333", color:"white"}}> <div className="flexcolumn"> {this.renderOutputTypeGenerators()} </div> </div> <AceEditor {...outputtypeprops}/> </div> } renderCodeInput(){ const {node, values={}, updateNode} = this.props; const aceprops = { onChange: (value)=>{ console.log(`updating value *${value}*`); updateNode("func", value); }, value: values.func, mode: "javascript", theme: "github", name: node.id, editorProps:{$blockScrolling: true}, height: '300px', width: '100%', showPrintMargin: false, } return <div className="flexrow"> <div style={{width:50, background:"#333", color:"white"}}> <div className="flexcolumn"> <div style={{WebkitFlex: '0 0 auto'}}> <div className="centered"> <div style={{color:"white", fontSize:14}}>in</div> </div> </div> {this.renderInputCodeGenerators()} <div style={{WebkitFlex: '0 0 auto'}}> <div className="centered"> <div style={{color:"white", fontSize:14}}>out</div> </div> </div> {this.renderOutputCodeGenerators()} </div> </div> <AceEditor {...aceprops}/> </div> } renderSelectOutput(){ const {node, values={}, updateNode} = this.props; const outputprops = { options: [ {name: '1', value: 1}, {name: '2', value: 2}, {name: '3', value: 3}, {name: '4', value: 4}, {name: '5', value: 5}, ], onSelect: (event)=>{ updateNode("outputs", parseInt(event.target.value)); }, style: {width: '100%'}, value: values.outputs || node.outputs || "", } return <div className="centered"> <Select {...outputprops}/> </div> } renderNameInput(){ const {node, values={}, updateNode} = this.props; const nameprops = { value: values.name || node.name || "", id: "name", onChange:(property, event)=>{ updateNode(property, event.target.value); } } return <div className="centered"> <Textfield {...nameprops}/> </div> } renderLibraries(){ const {node, values={}} = this.props; return <div style={{padding: 8}}> <strong>{matchLibraries(values.func || node.func || "").join(", ")}</strong> </div> } //<Cell title="input schema" content={this.renderTypeInput()}/> render() { return <div> <Cells> <Cell title="name" content={this.renderNameInput()}/> <Cell title="external libraries" content={this.renderLibraries()}/> <Cell title="function" content={this.renderCodeInput()}/> <Cell title="outputs" content={this.renderSelectOutput()}/> <Cell title="output schema" content={this.renderTypeOutput()}/> </Cells> </div> } _createInputType(node){ const {values={}} = this.props; const typedef = node.schema ? node.schema.output : {}; this.props.updateNode("inputtypedef", JSON.stringify(typedef,null,4)); } _createOutputType(node){ const {values={}} = this.props; const typedef = node.schema ? node.schema.input : {}; this.props.updateNode("outputtypedef", JSON.stringify(typedef,null,4)); } _createInputCode(node){ const {values={}} = this.props; const schema = node.schema ? node.schema.output : {}; const code = codeFromSchema(schema, "input"); const func = `${values.func || ""}\n${code}`; this.props.updateNode("func", func); } _createOutputCode(node){ const {values={}} = this.props; const schema = node.schema ? node.schema.input : {}; const code = codeFromSchema(schema, "output"); const func = `${values.func || ""}\n${code}`; this.props.updateNode("func", func); } }
me-box/iot.red
src/client/assets/js/nodes/processors/function/node.js
JavaScript
mit
11,552
import utility from './Utility.js'; /** * @method queryAll * @param {String} expression * @return {Array} */ let queryAll = function queryAll(expression) { "use strict"; expression = Array.isArray(expression) ? expression.join(',') : expression; return utility.toArray(this.querySelectorAll(expression)); }; export default (function main() { "use strict"; return { /** * @method getCSSLinks * @param {HTMLElement|HTMLDocument} element * @return {Array} */ getCSSLinks(element) { return queryAll.call(element, 'link[rel="stylesheet"]'); }, /** * @method getCSSInlines * @param {HTMLElement|HTMLDocument} element * @return {Array} */ getCSSInlines(element) { return queryAll.call(element, ['style[type="text/css"]', 'style:not([type])']); }, /** * @method getImports * @param {HTMLElement|HTMLDocument} element * @return {Array} */ getImports(element) { return queryAll.call(element, 'link[rel="import"]:not([data-ignore])'); }, /** * @method getTemplates * @param {HTMLElement|HTMLDocument} element * @return {Array} */ getTemplates(element) { return queryAll.call(element, 'template[ref]'); }, /** * @method getScripts * @param {HTMLElement|HTMLDocument} element * @return {Array} */ getScripts(element) { var selectors = ['script[type="text/javascript"]', 'script[type="application/javascript"]', 'script[type="text/ecmascript"]', 'script[type="application/ecmascript"]', 'script:not([type])']; return queryAll.call(element, selectors); }, /** * @method getAllScripts * @param {HTMLElement|HTMLDocument} element * @return {Array} */ getAllScripts(element) { let jsxFiles = queryAll.call(element, 'script[type="text/jsx"]'); return [].concat(utility.toArray(this.getScripts(element)), utility.toArray(jsxFiles)); } }; })();
SerkanSipahi/Maple.js
src/helpers/Selectors.js
JavaScript
mit
2,254
global.options = { heartbeat: 1 }; require('./harness'); connects = 0; var closed = 0; var hb = setInterval(function() { puts(" -> heartbeat"); connection.heartbeat(); }, 1000); setTimeout(function() { assert.ok(!closed); clearInterval(hb); setTimeout(function() { assert.ok(closed); }, 3000); }, 5000); connection.on('heartbeat', function() { puts(" <- heartbeat"); }); connection.on('close', function() { puts("closed"); closed = 1; }); connection.addListener('ready', function () { connects++; puts("connected to " + connection.serverProperties.product); var e = connection.exchange(); var q = connection.queue('node-test-hearbeat', {autoDelete: true}); q.on('queueDeclareOk', function (args) { puts('queue opened.'); assert.equal(0, args.messageCount); assert.equal(0, args.consumerCount); q.bind(e, "#"); q.subscribe(function(json) { assert.ok(false); }); }); });
gotbadger/node-amqp
test/test-heartbeat.js
JavaScript
mit
935
type A = [AAAAAAAAAAAAAAAAAAAAAA | BBBBBBBBBBBBBBBBBBBBBB | CCCCCCCCCCCCCCCCCCCCCC | DDDDDDDDDDDDDDDDDDDDDD] type B = [ | AAAAAAAAAAAAAAAAAAAAAA | BBBBBBBBBBBBBBBBBBBBBB | CCCCCCCCCCCCCCCCCCCCCC | DDDDDDDDDDDDDDDDDDDDDD ] type C = [ | [AAAAAAAAAAAAAAAAAAAAAA | BBBBBBBBBBBBBBBBBBBBBB | CCCCCCCCCCCCCCCCCCCCCC | DDDDDDDDDDDDDDDDDDDDDD] | [AAAAAAAAAAAAAAAAAAAAAA | BBBBBBBBBBBBBBBBBBBBBB | CCCCCCCCCCCCCCCCCCCCCC | DDDDDDDDDDDDDDDDDDDDDD] ]
prettier/prettier
tests/format/flow/union/within-tuple.js
JavaScript
mit
453
// Karma configuration // Generated on Tue Aug 25 2015 19:01:57 GMT-0500 (CDT) module.exports = function(config) { config.set({ // base path that will be used to resolve all patterns (eg. files, exclude) basePath: '', // frameworks to use // available frameworks: https://npmjs.org/browse/keyword/karma-adapter frameworks: ['mocha', 'browserify', 'phantomjs-shim'], // list of files / patterns to load in the browser files: [ 'src/**/*.kmocha.js', 'src/**/*.kmocha.jsx' ], // list of files to exclude exclude: [ '**/flycheck_*' ], // preprocess matching files before serving them to the browser // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor preprocessors: { 'src/**/*.kmocha.js*': [ 'browserify' ] }, browserify: { debug: true, // transform: ['babelify'], // use package.json browserify field extensions: ['.js', '.jsx'] }, // test results reporter to use // possible values: 'dots', 'progress' // available reporters: https://npmjs.org/browse/keyword/karma-reporter reporters: ['mocha'], mochaReporter: { output: 'autowatch' }, // web server port port: 9876, // enable / disable colors in the output (reporters and logs) colors: true, // level of logging // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG logLevel: config.LOG_ERROR, // enable / disable watching file and executing tests whenever any file changes autoWatch: true, // start these browsers // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher browsers: ['PhantomJS'], // browsers: ['Chrome'], // Continuous Integration mode // if true, Karma captures browsers, runs the tests and exits singleRun: false }) }
KevinAst/ReduxEvaluation
karma.conf.js
JavaScript
mit
1,933
cordova.define("com.blackberry.ui.dialog.client", function(require, exports, module) { /* Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you 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. */ var _self = {}, _ID = "com.blackberry.ui.dialog", exec = cordova.require("cordova/exec"); function defineReadOnlyField(obj, field, value) { Object.defineProperty(obj, field, { "value": value, "writable": false }); } _self.customAskAsync = function (message, buttons, callback, settings) { var args = { "message" : message, "buttons" : buttons, "callback" : callback}; if (settings) { args.settings = settings; } exec(callback, function () {}, _ID, "customAskAsync", args); }; _self.standardAskAsync = function (message, type, callback, settings) { var args = { "message" : message, "type" : type, "callback" : callback }; if (settings) { args.settings = settings; } exec(callback, function () {}, _ID, "standardAskAsync", args); }; defineReadOnlyField(_self, "D_OK", 0); defineReadOnlyField(_self, "D_SAVE", 1); defineReadOnlyField(_self, "D_DELETE", 2); defineReadOnlyField(_self, "D_YES_NO", 3); defineReadOnlyField(_self, "D_OK_CANCEL", 4); defineReadOnlyField(_self, "D_PROMPT", 5); module.exports = _self; });
Pushwoosh/pushwoosh-blackberry-sdk
Samples/Blackberry-10-HTML5-Webworks/plugins/com.blackberry.ui.dialog/www/client.js
JavaScript
mit
1,967
define( [ 'jquery', 'jqueryui' ], function( $, jqueryui ) { var FieldConstructor = function() {}; FieldConstructor.prototype.__makeDom = function() { var self = this, dom = $("<div />"), div = $( "<div></div>" ) .addClass( 'field-list' ) .appendTo( dom ), lastVal = [this.field.options.min, this.field.options.max], changing, range = self.field.options.range, slider = $("<div />") .appendTo( div ) .slider( { min: this.field.options.min, max: this.field.options.max, step: this.field.options.step, range: this.field.options.range, change: function( event, ui ) { ui.value = range ? ui.values[ changing ] : ui.value; if( valueInput[ changing ] && lastVal[ changing ] !== ui.value && ! isNaN( ui.value ) ) { lastVal[ changing ] = ui.value; valueInput[ changing ].val( lastVal[ changing ] ); self.setValueSilent( lastVal ); } }, slide: function( event, ui ) { var index = $(ui.handle).index(); changing = index; if( range ) { changing --; } ui.value = range ? ui.values[ changing ] : ui.value; if( !isNaN( ui.value )) { if( valueInput[ changing ] && lastVal[ changing ] !== ui.value && ! isNaN( ui.value ) ) { lastVal[ changing ] = ui.value; if( valueInput[ changing ] ) { valueInput[ changing ].val( lastVal[ changing ] ); self.setValueSilent( lastVal ); } } } } }), valueWrap = $("<div />") .addClass( 'forms-field-slider-value') .appendTo( div ), valueInput = []; valueInput[ 0 ] = $("<input />").bind( 'keyup' , function( ) { var val = $( this ).val( ), floatVal = parseFloat( val ); if( !isNaN( val ) && isFinite( val ) ) { lastVal[ 0 ] = floatVal; changing = 0; if( range ) { self.slider.slider( 'values', changing, floatVal ); } else { self.slider.slider( 'value', floatVal ); } } }); valueWrap.append( this.field.options.range ? '<span>Min</span>' : '<span>Value</span>' ).append( valueInput[ 0 ] ); if( this.field.options.range ) { valueInput[ 1 ] = $("<input />").bind( 'keyup' , function( ) { var val = $( this ).val( ), floatVal = parseFloat( val ); if( !isNaN( val ) && isFinite( val ) ) { lastVal[ 1 ] = floatVal; changing = 1; self.slider.slider( 'values', changing, floatVal ); } }); valueWrap.append( '<span>Max</span>' ).append( valueInput[ 1 ] ); } this.fieldElement = div; this.div = div; this.dom = dom; this.slider = slider; this.inputs = valueInput; // this.checkValue(); return dom; }; FieldConstructor.prototype.checkValue = function() { if( this.slider && typeof this.value !== "undefined" ) { if( this.field.options.range ) { if( this.value instanceof Array ) { for( var i = 0, l = this.value.length; i < l ; i ++ ) { this.slider.slider( 'values', i, this.value[ i ] ); this.inputs[ i ].val( this.value[ i ] ); } } } else { this.slider.slider( 'value', this.value ); } } } return FieldConstructor; });
targos/VisuMol
lib/lib/forms/types/slider/element.js
JavaScript
mit
3,209
// This is a manifest file that'll be compiled into application.js, which will include all the files // listed below. // // Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts, // or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path. // // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the // the compiled file. // // WARNING: THE FIRST BLANK LINE MARKS THE END OF WHAT'S TO BE PROCESSED, ANY BLANK LINE SHOULD // GO AFTER THE REQUIRES BELOW. // //= require polyfills //= require jquery //= require jquery_ujs //= require bootstrap-sprockets //= require typeahead.min //= require jquery.timeago //= require jquery.datetimepicker //= require emojione //= require emoji //= require jquery.icheck //= require lodash //= require gmaps/google //= require_tree . //= stub maps //
arumoy-shome/24pullrequests
app/assets/javascripts/application.js
JavaScript
mit
908
/* eslint-env mocha */ import React from 'react'; import Dialog from './Dialog'; import {spy} from 'sinon'; import {mount} from 'enzyme'; import {assert} from 'chai'; import TestUtils from 'react-dom/test-utils'; import getMuiTheme from '../styles/getMuiTheme'; describe('<Dialog />', () => { const muiTheme = getMuiTheme(); const mountWithContext = (node) => mount(node, {context: {muiTheme}}); it('appends a dialog to the document body', () => { const testClass = 'test-dialog-class'; mountWithContext( <Dialog open={true} contentClassName={testClass} /> ); const dialogEl = document.getElementsByClassName(testClass)[0]; assert.ok(dialogEl); }); it('registers events on dialog actions', () => { const clickSpy = spy(); const testClass = 'dialog-action'; mountWithContext( <Dialog open={true} actions={[ <button key="a" onClick={clickSpy} className={testClass} > test </button>, ]} /> ); const actionEl = document.getElementsByClassName(testClass)[0]; assert.ok(actionEl); TestUtils.Simulate.click(actionEl); assert.ok(clickSpy.called); }); it('should render a inner content container with sharp corners', () => { const testClass = 'test-dialog-paper-rounded-class'; mountWithContext( <Dialog open={true} paperClassName={testClass} paperProps={{rounded: false}} /> ); const testEl = document.getElementsByClassName(testClass)[0]; assert.strictEqual(testEl.style.borderRadius, '0px'); }); describe('should render a custom className', () => { const testTitle = 'test-dialog-title'; const testAction = <button>test</button>; const testClasses = { root: 'test-dialog-root-class', overlay: 'test-dialog-overlay-class', body: 'test-dialog-body-class', content: 'test-dialog-content-class', innerContent: 'test-dialog-paper-class', titleContainer: 'test-dialog-title-container-class', actionsContainer: 'test-dialog-actions-container-class', }; mountWithContext( <Dialog open={true} title={testTitle} actionsContainerClassName={testClasses.actionsContainer} bodyClassName={testClasses.body} className={testClasses.root} contentClassName={testClasses.content} paperClassName={testClasses.innerContent} overlayClassName={testClasses.overlay} titleClassName={testClasses.titleContainer} actions={testAction} /> ); for (const key in testClasses) { if (testClasses.hasOwnProperty(key)) { const testClass = testClasses[key]; it(testClass, () => { assert.ok(document.getElementsByClassName(testClass)[0]); }); } } }); });
hai-cea/material-ui
src/Dialog/Dialog.spec.js
JavaScript
mit
2,906
'use strict'; var metadataExtract = require('./metadata-extract'); var fs = require('fs'); var Promise = require('bluebird'); var marklogic = require('marklogic'); var path = require('path'); var connection = { host: 'localhost', port: 8010, user: 'admin', password: 'admin' }; var db = marklogic.createDatabaseClient(connection); var param = process.argv[2]; //path var _moduleExists = function _moduleExists() { var promise = new Promise(function(resolve, reject) { db.config.extlibs.read('/ext/countrysemantics.sjs').result(). then(function (response) { resolve(true); }, function (error) { resolve(false); }); }); return promise; }; var _processImport = (param) => { var promise = new Promise((resolve, reject) => { var result = []; var exists = fs.existsSync(param); if (exists) { if (fs.statSync(param).isDirectory()) { fs.readdirSync(param).filter((file) => { var extension = path.extname(file).toLowerCase(); if (extension === '.jpg' || extension === '.jpeg') { result.push(param + '/' + file); resolve(result); } }); } else if (fs.statSync(param).isFile()) { var extension = path.extname(param).toLowerCase(); if (extension === '.jpg' || extension === '.jpeg') { result.push(param); resolve(result); } } else { reject(new Error('An error occured, path is not a file nor a folder: ' + path)); } } else { reject(new Error('Location specified does not exist: ' + param)); } }); return promise; }; _moduleExists().then((exists) => { if (!exists) { db.config.extlibs.write({ path: '/ext/countrysemantics.sjs', contentType: 'application/vnd.marklogic-javascript', source: fs.createReadStream('countrysemantics.sjs') }).result().then((response) => { console.log('Installed module: ' + response.path); }).catch((error) => { console.log('Error installing module ' + error); }); } else { console.log('Not installing /ext/countrysemantics.sjs'); } }); var _importer = (file) => { var file = file; var uri = file.split('/').pop().replace(/[&\/\\#,+()$~%'":*?<>{} ]/g, ''); var metadataExtractor = new metadataExtract(file); return metadataExtractor.getData() .then((response) => { var uri = file.split('/').pop().replace(/[&\/\\#,+()$~%'":*?<>{} ]/g, ''); var data = response; data.originalFilename = file; data.filename = uri; data.binary = '/binary/' + uri; return db.documents.write({ uri: '/image/' + uri + '.json', contentType: 'application/json', collections: ['image'], content: data }).result(); }) .then((response) => { console.log('Inserted document with URI ' + response.documents[0].uri); return db.documents.read(response.documents[0].uri).result(); }) .then((response) => { var country = response[0].content.location.country.replace(' ', '_'); var sparqlQuery = [ 'PREFIX db: <http://dbpedia.org/resource/>', 'PREFIX onto: <http://dbpedia.org/ontology/>', 'ASK { db:' + country + ' ?p ?o }' ]; db.graphs.sparql('application/sparql-results+json', sparqlQuery.join('\n')).result() .then((SPARQLresponse) => { if (!SPARQLresponse.boolean) { return db.invoke({ path: '/ext/countrysemantics.sjs', variables: { country: country } }).result(); } else { return { message: 'No semantic data inserted for ' + country }; } }) .then((response) => { if (response.message) { console.log(response.message) } else { console.log('Triple for ' + country + ' inserted with URI: ' + response[0].value); } }) .catch((error) => { console.log(error) }); }) .then(() => { var ws = db.documents.createWriteStream({ uri: '/binary/' + uri, contentType: 'image/jpeg', collections: ['binary'] }); var reader = fs.createReadStream(file); reader.pipe(ws); return ws.result(); }) .then((response) => { console.log('Inserted image with URI ' + response.documents[0].uri); }) .catch((error) => { console.log(error) }); }; _processImport(param).then((files) => { files.forEach((file, index) => { setTimeout(() => { _importer(file); }, 5000 + (index * 1000)); }); });
katsur0/ml8demo
webapp/import/import.js
JavaScript
mit
4,444
/** * [IL] * Library Import */ import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; /** * [IV] * View Import */ import Mobile from './Views/Mobile'; import Desktop from './Views/Desktop'; /** * [IBP] * Breakpoints */ import BP from 'lib/breakpoints'; /** * [ICONF] * Config Import */ // import config from './config'; /** * [IRDX] * Redux connect (optional) */ @connect((state) => { return { mediaType: state.browser.mediaType }; }) class Contacts extends Component { /** * [CPT] * Component prop types */ static propTypes = { mediaType: PropTypes.string.isRequired }; /** * [CDN] * Component display name */ // static displayName = config.id; /** * [CR] * Render function */ render = () => { /** * [RPD] * Props destructuring */ const { mediaType } = this.props; /** * [RV] * View */ let view; if (BP.isMobile(mediaType)) { view = ( <Mobile mediaType={ mediaType } /> ); } else { view = ( <Desktop mediaType={ mediaType } /> ); } /** * [RR] * Return Component */ return view; } } /** * [IE] * Export */ export default Contacts;
LifeSourceUA/lifesource.ua
src/components/Common/List/Components/Scroll/index.js
JavaScript
mit
1,527
exports.dir = "a/b/c";
marko-js/marko
packages/marko/test/taglib-finder/fixtures/deeply-nested/test.js
JavaScript
mit
23
var AGENDA_ALL_DAY_EVENT_LIMIT = 5; // potential nice values for the slot-duration and interval-duration // from largest to smallest var AGENDA_STOCK_SUB_DURATIONS = [ { hours: 1 }, { minutes: 30 }, { minutes: 15 }, { seconds: 30 }, { seconds: 15 } ]; fcViews.agenda = { 'class': AgendaView, defaults: { allDaySlot: true, slotDuration: '00:30:00', slotEventOverlap: true // a bad name. confused with overlap/constraint system } }; fcViews.agendaDay = { type: 'agenda', duration: { days: 1 } }; fcViews.agendaWeek = { type: 'agenda', duration: { weeks: 1 } };
pietervisser/fullcalendar
src/agenda/config.js
JavaScript
mit
581
var tag = "User::"; /** * 用户数据模型 */ angular.module("commons.models").service("User", [ '$q', '$filter', 'UserRest', 'constants', 'AdminRest', 'Security', userCreator ]); function userCreator($q, $filter, UserRest, constants, AdminRest, Security) { function User(attrs) { this.deptId = undefined; this.deptName = undefined; this.userId = undefined; this.signature = undefined; this.icon = undefined; this.realName = undefined; this.gender = undefined; this.birthday = undefined; this.age = undefined; this.hobby = undefined; this.jobTitle = undefined; this.city = undefined; this.major = undefined; this.mail = undefined; this.phone = undefined; this.mobile = undefined; this.agent = undefined; this.devices = undefined; attrs && angular.extend(this, attrs); if (this.birthday) { this.birthday = $filter("dateTime")(this.birthday, "YYYY-MM-DD"); } if (!this.deptId) { this.deptId = -1; this.deptName = '未分组联系人'; } } User.getLoginUser = function () { var delay = $q.defer(); UserRest.currentUserInfo.get().then(function (userInfo) { delay.resolve(new User(userInfo)); }).fail(function (err) { delay.reject(err); }); return delay.promise; }; User.prototype = { constructor: User, isAdmin: function () { return this.userType === constants.UserType.Administrator; }, isSecAdmin: function () { return this.userType === constants.UserType.SecondAdministrator; }, displayName: function () { return this.realName || this.userName; }, /** * 管理员修改用户信息 */ updateByAdmin: function () { var param = {}; if (this.pwd) { param = Security.getNonceDTO(this.userId, this.pwd); } angular.extend(param, { userId: this.userId, account: this.account, empNum: this.empNum, jobTitle: this.jobTitle, phone: this.phone }); return AdminRest.user.put(param); }, /** * 更改用户信息 */ updateUserInfo: function () { var param = { signature: this.signature, realName: this.realName, gender: this.gender, phone: this.phone, mobile: this.mobile }; if (this.birthday) { param.birthday = constants.getMillSec(this.birthday, "YYYY-MM-DD"); } if (this.mail && this.userName !== this.mail) { param.mail = this.mail; } if (this.mobile && this.userName !== this.mobile) { param.mobile = this.mobile; } return UserRest.currentUserInfo.post(param); }, getUserDevices: function () { var self = this; this.devices = []; UserRest.user.getUserDevices().then(function (devices) { _.each(devices, function (device) { if (device.onlineStatus === 'online') { self.devices.push(device.agent); } }); }); }, deleteContact: function () { return UserRest.contact.remove({ userid: this.userId }); }, addContact: function () { return UserRest.contact.post(null, { query: { userid: this.userId } }); }, contains: function (searchKey) { if (this.userName.indexOf(searchKey) !== -1) return true; if (this.realName && this.realName.indexOf(searchKey) !== -1) return true; return false; }, logout: function () { return UserRest.user.logout(); }, getDisplayName: function () { return $filter('displayName')(this); }, changeUserStatus: function (changeStatus) { var self = this; UserRest.status.post({ userId: cache.userId, entId: cache.entId, status: changeStatus, agent: webhelper.getAgent() }).then(function () { angular.extend(self, { onlineStatus: changeStatus, prevOnlineStatus: changeStatus }); }); }, isOffline: function () { return _.contains(["offline", "leave"], this.onlineStatus); } }; User.getAllDeptUsers = function (deptIds, userList) { return _.filter(userList, function (user) { return _.contains(deptIds, user.deptId); }); }; User.getOnlineUsers = function (userList) { return _.filter(userList, function (user) { return _.contains(['online', 'busy'], user.onlineStatus); }); }; return User; }
yliyun-team/yli-cmd
test/app/support/models/user/User.js
JavaScript
mit
5,496
#!/usr/bin/env node 'use strict'; var driver = require('../lib/driver'); var options = require('../lib/options'); driver(process.stdin, options(), function (err) { if (err) { process.nextTick(function () { process.exit(1); }); } }).pipe(process.stdout);
wenjoy/homePage
node_modules/geetest/node_modules/request/node_modules/karma/node_modules/grunt-coffeelint/node_modules/coffeelint-stylish/node_modules/del/node_modules/fs-extra/node_modules/secure-random/node_modules/mochify/node_modules/min-wd/bin/cmd.js
JavaScript
mit
275
const VALUE = '1'; export function fn1 ( value ) { switch ( value ) { case VALUE: return 'correct'; default: return 'not matched'; } }
corneliusweig/rollup
test/function/samples/switch-cases-are-deconflicted/mod1.js
JavaScript
mit
148
/** * ag-grid-community - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components * @version v20.0.0 * @link http://www.ag-grid.com/ * @license MIT */ "use strict"; var __extends = (this && this.__extends) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; Object.defineProperty(exports, "__esModule", { value: true }); var component_1 = require("../../widgets/component"); var context_1 = require("../../context/context"); var column_1 = require("../../entities/column"); var dragAndDropService_1 = require("../../dragAndDrop/dragAndDropService"); var columnApi_1 = require("../../columnController/columnApi"); var columnController_1 = require("../../columnController/columnController"); var horizontalResizeService_1 = require("../horizontalResizeService"); var gridOptionsWrapper_1 = require("../../gridOptionsWrapper"); var cssClassApplier_1 = require("../cssClassApplier"); var setLeftFeature_1 = require("../../rendering/features/setLeftFeature"); var gridApi_1 = require("../../gridApi"); var sortController_1 = require("../../sortController"); var eventService_1 = require("../../eventService"); var componentRecipes_1 = require("../../components/framework/componentRecipes"); var agCheckbox_1 = require("../../widgets/agCheckbox"); var componentAnnotations_1 = require("../../widgets/componentAnnotations"); var selectAllFeature_1 = require("./selectAllFeature"); var events_1 = require("../../events"); var columnHoverService_1 = require("../../rendering/columnHoverService"); var beans_1 = require("../../rendering/beans"); var hoverFeature_1 = require("../hoverFeature"); var touchListener_1 = require("../../widgets/touchListener"); var utils_1 = require("../../utils"); var HeaderWrapperComp = /** @class */ (function (_super) { __extends(HeaderWrapperComp, _super); function HeaderWrapperComp(column, dragSourceDropTarget, pinned) { var _this = _super.call(this, HeaderWrapperComp.TEMPLATE) || this; _this.column = column; _this.dragSourceDropTarget = dragSourceDropTarget; _this.pinned = pinned; return _this; } HeaderWrapperComp.prototype.getColumn = function () { return this.column; }; HeaderWrapperComp.prototype.init = function () { this.instantiate(this.context); var displayName = this.columnController.getDisplayNameForColumn(this.column, 'header', true); var enableSorting = this.column.getColDef().sortable; var enableMenu = this.menuFactory.isMenuEnabled(this.column) && !this.column.getColDef().suppressMenu; this.appendHeaderComp(displayName, enableSorting, enableMenu); this.setupWidth(); this.setupMovingCss(); this.setupTooltip(); this.setupResize(); this.setupMenuClass(); this.setupSortableClass(enableSorting); this.addColumnHoverListener(); this.addFeature(this.context, new hoverFeature_1.HoverFeature([this.column], this.getGui())); this.addDestroyableEventListener(this.column, column_1.Column.EVENT_FILTER_ACTIVE_CHANGED, this.onFilterChanged.bind(this)); this.onFilterChanged(); this.addFeature(this.context, new selectAllFeature_1.SelectAllFeature(this.cbSelectAll, this.column)); var setLeftFeature = new setLeftFeature_1.SetLeftFeature(this.column, this.getGui(), this.beans); setLeftFeature.init(); this.addDestroyFunc(setLeftFeature.destroy.bind(setLeftFeature)); this.addAttributes(); cssClassApplier_1.CssClassApplier.addHeaderClassesFromColDef(this.column.getColDef(), this.getGui(), this.gridOptionsWrapper, this.column, null); }; HeaderWrapperComp.prototype.addColumnHoverListener = function () { this.addDestroyableEventListener(this.eventService, events_1.Events.EVENT_COLUMN_HOVER_CHANGED, this.onColumnHover.bind(this)); this.onColumnHover(); }; HeaderWrapperComp.prototype.onColumnHover = function () { var isHovered = this.columnHoverService.isHovered(this.column); utils_1._.addOrRemoveCssClass(this.getGui(), 'ag-column-hover', isHovered); }; HeaderWrapperComp.prototype.setupSortableClass = function (enableSorting) { if (enableSorting) { var element = this.getGui(); utils_1._.addCssClass(element, 'ag-header-cell-sortable'); } }; HeaderWrapperComp.prototype.onFilterChanged = function () { var filterPresent = this.column.isFilterActive(); utils_1._.addOrRemoveCssClass(this.getGui(), 'ag-header-cell-filtered', filterPresent); }; HeaderWrapperComp.prototype.appendHeaderComp = function (displayName, enableSorting, enableMenu) { var _this = this; var params = { column: this.column, displayName: displayName, enableSorting: enableSorting, enableMenu: enableMenu, showColumnMenu: function (source) { _this.gridApi.showColumnMenuAfterButtonClick(_this.column, source); }, progressSort: function (multiSort) { _this.sortController.progressSort(_this.column, !!multiSort, "uiColumnSorted"); }, setSort: function (sort, multiSort) { _this.sortController.setSortForColumn(_this.column, sort, !!multiSort, "uiColumnSorted"); }, api: this.gridApi, columnApi: this.columnApi, context: this.gridOptionsWrapper.getContext() }; var callback = this.afterHeaderCompCreated.bind(this, displayName); this.componentRecipes.newHeaderComponent(params).then(callback); }; HeaderWrapperComp.prototype.afterHeaderCompCreated = function (displayName, headerComp) { this.appendChild(headerComp); this.setupMove(headerComp.getGui(), displayName); if (headerComp.destroy) { this.addDestroyFunc(headerComp.destroy.bind(headerComp)); } }; HeaderWrapperComp.prototype.onColumnMovingChanged = function () { // this function adds or removes the moving css, based on if the col is moving. // this is what makes the header go dark when it is been moved (gives impression to // user that the column was picked up). if (this.column.isMoving()) { utils_1._.addCssClass(this.getGui(), 'ag-header-cell-moving'); } else { utils_1._.removeCssClass(this.getGui(), 'ag-header-cell-moving'); } }; HeaderWrapperComp.prototype.setupMove = function (eHeaderCellLabel, displayName) { var _this = this; var suppressMove = this.gridOptionsWrapper.isSuppressMovableColumns() || this.column.getColDef().suppressMovable || this.column.isLockPosition(); if (suppressMove) { return; } if (eHeaderCellLabel) { var dragSource_1 = { type: dragAndDropService_1.DragSourceType.HeaderCell, eElement: eHeaderCellLabel, dragItemCallback: function () { return _this.createDragItem(); }, dragItemName: displayName, dragSourceDropTarget: this.dragSourceDropTarget, dragStarted: function () { return _this.column.setMoving(true, "uiColumnMoved"); }, dragStopped: function () { return _this.column.setMoving(false, "uiColumnMoved"); } }; this.dragAndDropService.addDragSource(dragSource_1, true); this.addDestroyFunc(function () { return _this.dragAndDropService.removeDragSource(dragSource_1); }); } }; HeaderWrapperComp.prototype.createDragItem = function () { var visibleState = {}; visibleState[this.column.getId()] = this.column.isVisible(); return { columns: [this.column], visibleState: visibleState }; }; HeaderWrapperComp.prototype.setupResize = function () { var _this = this; var colDef = this.column.getColDef(); // if no eResize in template, do nothing if (!this.eResize) { return; } if (!this.column.isResizable()) { utils_1._.removeFromParent(this.eResize); return; } var finishedWithResizeFunc = this.horizontalResizeService.addResizeBar({ eResizeBar: this.eResize, onResizeStart: this.onResizeStart.bind(this), onResizing: this.onResizing.bind(this, false), onResizeEnd: this.onResizing.bind(this, true) }); this.addDestroyFunc(finishedWithResizeFunc); var weWantAutoSize = !this.gridOptionsWrapper.isSuppressAutoSize() && !colDef.suppressAutoSize; if (weWantAutoSize) { this.addDestroyableEventListener(this.eResize, 'dblclick', function () { _this.columnController.autoSizeColumn(_this.column, "uiColumnResized"); }); var touchListener = new touchListener_1.TouchListener(this.eResize); this.addDestroyableEventListener(touchListener, touchListener_1.TouchListener.EVENT_DOUBLE_TAP, function () { _this.columnController.autoSizeColumn(_this.column, "uiColumnResized"); }); this.addDestroyFunc(touchListener.destroy.bind(touchListener)); } }; HeaderWrapperComp.prototype.onResizing = function (finished, resizeAmount) { var resizeAmountNormalised = this.normaliseResizeAmount(resizeAmount); var newWidth = this.resizeStartWidth + resizeAmountNormalised; this.columnController.setColumnWidth(this.column, newWidth, this.resizeWithShiftKey, finished, "uiColumnDragged"); if (finished) { utils_1._.removeCssClass(this.getGui(), 'ag-column-resizing'); } }; HeaderWrapperComp.prototype.onResizeStart = function (shiftKey) { this.resizeStartWidth = this.column.getActualWidth(); this.resizeWithShiftKey = shiftKey; utils_1._.addCssClass(this.getGui(), 'ag-column-resizing'); }; HeaderWrapperComp.prototype.setupTooltip = function () { var colDef = this.column.getColDef(); // add tooltip if exists if (colDef.headerTooltip) { this.getGui().title = colDef.headerTooltip; } }; HeaderWrapperComp.prototype.setupMovingCss = function () { this.addDestroyableEventListener(this.column, column_1.Column.EVENT_MOVING_CHANGED, this.onColumnMovingChanged.bind(this)); this.onColumnMovingChanged(); }; HeaderWrapperComp.prototype.addAttributes = function () { this.getGui().setAttribute("col-id", this.column.getColId()); }; HeaderWrapperComp.prototype.setupWidth = function () { this.addDestroyableEventListener(this.column, column_1.Column.EVENT_WIDTH_CHANGED, this.onColumnWidthChanged.bind(this)); this.onColumnWidthChanged(); }; HeaderWrapperComp.prototype.setupMenuClass = function () { this.addDestroyableEventListener(this.column, column_1.Column.EVENT_MENU_VISIBLE_CHANGED, this.onMenuVisible.bind(this)); this.onColumnWidthChanged(); }; HeaderWrapperComp.prototype.onMenuVisible = function () { this.addOrRemoveCssClass('ag-column-menu-visible', this.column.isMenuVisible()); }; HeaderWrapperComp.prototype.onColumnWidthChanged = function () { this.getGui().style.width = this.column.getActualWidth() + 'px'; }; // optionally inverts the drag, depending on pinned and RTL // note - this method is duplicated in RenderedHeaderGroupCell - should refactor out? HeaderWrapperComp.prototype.normaliseResizeAmount = function (dragChange) { var result = dragChange; if (this.gridOptionsWrapper.isEnableRtl()) { // for RTL, dragging left makes the col bigger, except when pinning left if (this.pinned !== column_1.Column.PINNED_LEFT) { result *= -1; } } else { // for LTR (ie normal), dragging left makes the col smaller, except when pinning right if (this.pinned === column_1.Column.PINNED_RIGHT) { result *= -1; } } return result; }; HeaderWrapperComp.TEMPLATE = '<div class="ag-header-cell" role="presentation" >' + '<div ref="eResize" class="ag-header-cell-resize" role="presentation"></div>' + '<ag-checkbox ref="cbSelectAll" class="ag-header-select-all" role="presentation"></ag-checkbox>' + // <inner component goes here> '</div>'; __decorate([ context_1.Autowired('gridOptionsWrapper'), __metadata("design:type", gridOptionsWrapper_1.GridOptionsWrapper) ], HeaderWrapperComp.prototype, "gridOptionsWrapper", void 0); __decorate([ context_1.Autowired('dragAndDropService'), __metadata("design:type", dragAndDropService_1.DragAndDropService) ], HeaderWrapperComp.prototype, "dragAndDropService", void 0); __decorate([ context_1.Autowired('columnController'), __metadata("design:type", columnController_1.ColumnController) ], HeaderWrapperComp.prototype, "columnController", void 0); __decorate([ context_1.Autowired('horizontalResizeService'), __metadata("design:type", horizontalResizeService_1.HorizontalResizeService) ], HeaderWrapperComp.prototype, "horizontalResizeService", void 0); __decorate([ context_1.Autowired('context'), __metadata("design:type", context_1.Context) ], HeaderWrapperComp.prototype, "context", void 0); __decorate([ context_1.Autowired('menuFactory'), __metadata("design:type", Object) ], HeaderWrapperComp.prototype, "menuFactory", void 0); __decorate([ context_1.Autowired('gridApi'), __metadata("design:type", gridApi_1.GridApi) ], HeaderWrapperComp.prototype, "gridApi", void 0); __decorate([ context_1.Autowired('columnApi'), __metadata("design:type", columnApi_1.ColumnApi) ], HeaderWrapperComp.prototype, "columnApi", void 0); __decorate([ context_1.Autowired('sortController'), __metadata("design:type", sortController_1.SortController) ], HeaderWrapperComp.prototype, "sortController", void 0); __decorate([ context_1.Autowired('eventService'), __metadata("design:type", eventService_1.EventService) ], HeaderWrapperComp.prototype, "eventService", void 0); __decorate([ context_1.Autowired('componentRecipes'), __metadata("design:type", componentRecipes_1.ComponentRecipes) ], HeaderWrapperComp.prototype, "componentRecipes", void 0); __decorate([ context_1.Autowired('columnHoverService'), __metadata("design:type", columnHoverService_1.ColumnHoverService) ], HeaderWrapperComp.prototype, "columnHoverService", void 0); __decorate([ context_1.Autowired('beans'), __metadata("design:type", beans_1.Beans) ], HeaderWrapperComp.prototype, "beans", void 0); __decorate([ componentAnnotations_1.RefSelector('eResize'), __metadata("design:type", HTMLElement) ], HeaderWrapperComp.prototype, "eResize", void 0); __decorate([ componentAnnotations_1.RefSelector('cbSelectAll'), __metadata("design:type", agCheckbox_1.AgCheckbox) ], HeaderWrapperComp.prototype, "cbSelectAll", void 0); __decorate([ context_1.PostConstruct, __metadata("design:type", Function), __metadata("design:paramtypes", []), __metadata("design:returntype", void 0) ], HeaderWrapperComp.prototype, "init", null); return HeaderWrapperComp; }(component_1.Component)); exports.HeaderWrapperComp = HeaderWrapperComp;
extend1994/cdnjs
ajax/libs/ag-grid/20.0.0/lib/headerRendering/header/headerWrapperComp.js
JavaScript
mit
17,045
var _ = require('underscore') , path = require('path') , passport = require('passport') , AuthCtrl = require('./controllers/auth') , UserCtrl = require('./controllers/user') , User = require('./models/User.js') , userRoles = require('../client/js/routingConfig').userRoles , accessLevels = require('../client/js/routingConfig').accessLevels; var routes = [ // Views { path: '/partials/*', httpMethod: 'GET', middleware: [function (req, res) { var requestedView = path.join('./', req.url); res.render(requestedView); }] }, // OAUTH { path: '/auth/twitter', httpMethod: 'GET', middleware: [passport.authenticate('twitter')] }, { path: '/auth/twitter/callback', httpMethod: 'GET', middleware: [passport.authenticate('twitter', { successRedirect: '/', failureRedirect: '/login' })] }, { path: '/auth/facebook', httpMethod: 'GET', middleware: [passport.authenticate('facebook')] }, { path: '/auth/facebook/callback', httpMethod: 'GET', middleware: [passport.authenticate('facebook', { successRedirect: '/', failureRedirect: '/login' })] }, { path: '/auth/google', httpMethod: 'GET', middleware: [passport.authenticate('google')] }, { path: '/auth/google/return', httpMethod: 'GET', middleware: [passport.authenticate('google', { successRedirect: '/', failureRedirect: '/login' })] }, { path: '/auth/linkedin', httpMethod: 'GET', middleware: [passport.authenticate('linkedin')] }, { path: '/auth/linkedin/callback', httpMethod: 'GET', middleware: [passport.authenticate('linkedin', { successRedirect: '/', failureRedirect: '/login' })] }, // Local Auth { path: '/register', httpMethod: 'POST', middleware: [AuthCtrl.register] }, { path: '/login', httpMethod: 'POST', middleware: [AuthCtrl.login] }, { path: '/logout', httpMethod: 'POST', middleware: [AuthCtrl.logout] }, // User resource { path: '/users', httpMethod: 'GET', middleware: [UserCtrl.index], accessLevel: accessLevels.admin }, // All other get requests should be handled by AngularJS's client-side routing system { path: '/*', httpMethod: 'GET', middleware: [function(req, res) { var role = userRoles.public, username = ''; if(req.user) { role = req.user.role; username = req.user.username; } res.cookie('user', JSON.stringify({ 'username': username, 'role': role })); res.render('index'); }] } ]; module.exports = function(app) { _.each(routes, function(route) { route.middleware.unshift(ensureAuthorized); var args = _.flatten([route.path, route.middleware]); switch(route.httpMethod.toUpperCase()) { case 'GET': app.get.apply(app, args); break; case 'POST': app.post.apply(app, args); break; case 'PUT': app.put.apply(app, args); break; case 'DELETE': app.delete.apply(app, args); break; default: throw new Error('Invalid HTTP method specified for route ' + route.path); break; } }); } function ensureAuthorized(req, res, next) { var role; if(!req.user) role = userRoles.public; else role = req.user.role; var accessLevel = _.findWhere(routes, { path: req.route.path }).accessLevel || accessLevels.public; if(!(accessLevel.bitMask & role.bitMask)) return res.send(403); return next(); }
edenchen123/front-end-security-POC
server/routes.js
JavaScript
mit
4,182
/* DO NOT MODIFY - This file has been generated and will be regenerated Semantic UI v2.1.5 */ /*! * # Semantic UI - Visibility * http://github.com/semantic-org/semantic-ui/ * * * Copyright 2015 Contributors * Released under the MIT license * http://opensource.org/licenses/MIT * */ ;(function ( $, window, document, undefined ) { "use strict"; $.fn.visibility = function(parameters) { var $allModules = $(this), moduleSelector = $allModules.selector || '', time = new Date().getTime(), performance = [], query = arguments[0], methodInvoked = (typeof query == 'string'), queryArguments = [].slice.call(arguments, 1), returnedValue ; $allModules .each(function() { var settings = ( $.isPlainObject(parameters) ) ? $.extend(true, {}, $.fn.visibility.settings, parameters) : $.extend({}, $.fn.visibility.settings), className = settings.className, namespace = settings.namespace, error = settings.error, metadata = settings.metadata, eventNamespace = '.' + namespace, moduleNamespace = 'module-' + namespace, $window = $(window), $module = $(this), $context = $(settings.context), $placeholder, selector = $module.selector || '', instance = $module.data(moduleNamespace), requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame || function(callback) { setTimeout(callback, 0); }, element = this, disabled = false, observer, module ; module = { initialize: function() { module.debug('Initializing', settings); module.setup.cache(); if( module.should.trackChanges() ) { if(settings.type == 'image') { module.setup.image(); } if(settings.type == 'fixed') { module.setup.fixed(); } if(settings.observeChanges) { module.observeChanges(); } module.bind.events(); } module.save.position(); if( !module.is.visible() ) { module.error(error.visible, $module); } if(settings.initialCheck) { module.checkVisibility(); } module.instantiate(); }, instantiate: function() { module.debug('Storing instance', module); $module .data(moduleNamespace, module) ; instance = module; }, destroy: function() { module.verbose('Destroying previous module'); if(observer) { observer.disconnect(); } $window .off('load' + eventNamespace, module.event.load) .off('resize' + eventNamespace, module.event.resize) ; $context .off('scrollchange' + eventNamespace, module.event.scrollchange) ; $module .off(eventNamespace) .removeData(moduleNamespace) ; }, observeChanges: function() { if('MutationObserver' in window) { observer = new MutationObserver(function(mutations) { module.verbose('DOM tree modified, updating visibility calculations'); module.timer = setTimeout(function() { module.verbose('DOM tree modified, updating sticky menu'); module.refresh(); }, 100); }); observer.observe(element, { childList : true, subtree : true }); module.debug('Setting up mutation observer', observer); } }, bind: { events: function() { module.verbose('Binding visibility events to scroll and resize'); if(settings.refreshOnLoad) { $window .on('load' + eventNamespace, module.event.load) ; } $window .on('resize' + eventNamespace, module.event.resize) ; // pub/sub pattern $context .off('scroll' + eventNamespace) .on('scroll' + eventNamespace, module.event.scroll) .on('scrollchange' + eventNamespace, module.event.scrollchange) ; } }, event: { resize: function() { module.debug('Window resized'); if(settings.refreshOnResize) { requestAnimationFrame(module.refresh); } }, load: function() { module.debug('Page finished loading'); requestAnimationFrame(module.refresh); }, // publishes scrollchange event on one scroll scroll: function() { if(settings.throttle) { clearTimeout(module.timer); module.timer = setTimeout(function() { $context.triggerHandler('scrollchange' + eventNamespace, [ $context.scrollTop() ]); }, settings.throttle); } else { requestAnimationFrame(function() { $context.triggerHandler('scrollchange' + eventNamespace, [ $context.scrollTop() ]); }); } }, // subscribes to scrollchange scrollchange: function(event, scrollPosition) { module.checkVisibility(scrollPosition); }, }, precache: function(images, callback) { if (!(images instanceof Array)) { images = [images]; } var imagesLength = images.length, loadedCounter = 0, cache = [], cacheImage = document.createElement('img'), handleLoad = function() { loadedCounter++; if (loadedCounter >= images.length) { if ($.isFunction(callback)) { callback(); } } } ; while (imagesLength--) { cacheImage = document.createElement('img'); cacheImage.onload = handleLoad; cacheImage.onerror = handleLoad; cacheImage.src = images[imagesLength]; cache.push(cacheImage); } }, enableCallbacks: function() { module.debug('Allowing callbacks to occur'); disabled = false; }, disableCallbacks: function() { module.debug('Disabling all callbacks temporarily'); disabled = true; }, should: { trackChanges: function() { if(methodInvoked) { module.debug('One time query, no need to bind events'); return false; } module.debug('Callbacks being attached'); return true; } }, setup: { cache: function() { module.cache = { occurred : {}, screen : {}, element : {}, }; }, image: function() { var src = $module.data(metadata.src) ; if(src) { module.verbose('Lazy loading image', src); settings.once = true; settings.observeChanges = false; // show when top visible settings.onOnScreen = function() { module.debug('Image on screen', element); module.precache(src, function() { module.set.image(src); }); }; } }, fixed: function() { module.debug('Setting up fixed'); settings.once = false; settings.observeChanges = false; settings.initialCheck = true; settings.refreshOnLoad = true; if(!parameters.transition) { settings.transition = false; } module.create.placeholder(); module.debug('Added placeholder', $placeholder); settings.onTopPassed = function() { module.debug('Element passed, adding fixed position', $module); module.show.placeholder(); module.set.fixed(); if(settings.transition) { if($.fn.transition !== undefined) { $module.transition(settings.transition, settings.duration); } } }; settings.onTopPassedReverse = function() { module.debug('Element returned to position, removing fixed', $module); module.hide.placeholder(); module.remove.fixed(); }; } }, create: { placeholder: function() { module.verbose('Creating fixed position placeholder'); $placeholder = $module .clone(false) .css('display', 'none') .addClass(className.placeholder) .insertAfter($module) ; } }, show: { placeholder: function() { module.verbose('Showing placeholder'); $placeholder .css('display', 'block') .css('visibility', 'hidden') ; } }, hide: { placeholder: function() { module.verbose('Hiding placeholder'); $placeholder .css('display', 'none') .css('visibility', '') ; } }, set: { fixed: function() { module.verbose('Setting element to fixed position'); $module .addClass(className.fixed) .css({ position : 'fixed', top : settings.offset + 'px', left : 'auto', zIndex : '1' }) ; }, image: function(src) { $module .attr('src', src) ; if(settings.transition) { if( $.fn.transition !== undefined ) { $module.transition(settings.transition, settings.duration); } else { $module.fadeIn(settings.duration); } } else { $module.show(); } } }, is: { onScreen: function() { var calculations = module.get.elementCalculations() ; return calculations.onScreen; }, offScreen: function() { var calculations = module.get.elementCalculations() ; return calculations.offScreen; }, visible: function() { if(module.cache && module.cache.element) { return !(module.cache.element.width === 0 && module.cache.element.offset.top === 0); } return false; } }, refresh: function() { module.debug('Refreshing constants (width/height)'); if(settings.type == 'fixed') { module.remove.fixed(); module.remove.occurred(); } module.reset(); module.save.position(); if(settings.checkOnRefresh) { module.checkVisibility(); } settings.onRefresh.call(element); }, reset: function() { module.verbose('Reseting all cached values'); if( $.isPlainObject(module.cache) ) { module.cache.screen = {}; module.cache.element = {}; } }, checkVisibility: function(scroll) { module.verbose('Checking visibility of element', module.cache.element); if( !disabled && module.is.visible() ) { // save scroll position module.save.scroll(scroll); // update calculations derived from scroll module.save.calculations(); // percentage module.passed(); // reverse (must be first) module.passingReverse(); module.topVisibleReverse(); module.bottomVisibleReverse(); module.topPassedReverse(); module.bottomPassedReverse(); // one time module.onScreen(); module.offScreen(); module.passing(); module.topVisible(); module.bottomVisible(); module.topPassed(); module.bottomPassed(); // on update callback if(settings.onUpdate) { settings.onUpdate.call(element, module.get.elementCalculations()); } } }, passed: function(amount, newCallback) { var calculations = module.get.elementCalculations(), amountInPixels ; // assign callback if(amount && newCallback) { settings.onPassed[amount] = newCallback; } else if(amount !== undefined) { return (module.get.pixelsPassed(amount) > calculations.pixelsPassed); } else if(calculations.passing) { $.each(settings.onPassed, function(amount, callback) { if(calculations.bottomVisible || calculations.pixelsPassed > module.get.pixelsPassed(amount)) { module.execute(callback, amount); } else if(!settings.once) { module.remove.occurred(callback); } }); } }, onScreen: function(newCallback) { var calculations = module.get.elementCalculations(), callback = newCallback || settings.onOnScreen, callbackName = 'onScreen' ; if(newCallback) { module.debug('Adding callback for onScreen', newCallback); settings.onOnScreen = newCallback; } if(calculations.onScreen) { module.execute(callback, callbackName); } else if(!settings.once) { module.remove.occurred(callbackName); } if(newCallback !== undefined) { return calculations.onOnScreen; } }, offScreen: function(newCallback) { var calculations = module.get.elementCalculations(), callback = newCallback || settings.onOffScreen, callbackName = 'offScreen' ; if(newCallback) { module.debug('Adding callback for offScreen', newCallback); settings.onOffScreen = newCallback; } if(calculations.offScreen) { module.execute(callback, callbackName); } else if(!settings.once) { module.remove.occurred(callbackName); } if(newCallback !== undefined) { return calculations.onOffScreen; } }, passing: function(newCallback) { var calculations = module.get.elementCalculations(), callback = newCallback || settings.onPassing, callbackName = 'passing' ; if(newCallback) { module.debug('Adding callback for passing', newCallback); settings.onPassing = newCallback; } if(calculations.passing) { module.execute(callback, callbackName); } else if(!settings.once) { module.remove.occurred(callbackName); } if(newCallback !== undefined) { return calculations.passing; } }, topVisible: function(newCallback) { var calculations = module.get.elementCalculations(), callback = newCallback || settings.onTopVisible, callbackName = 'topVisible' ; if(newCallback) { module.debug('Adding callback for top visible', newCallback); settings.onTopVisible = newCallback; } if(calculations.topVisible) { module.execute(callback, callbackName); } else if(!settings.once) { module.remove.occurred(callbackName); } if(newCallback === undefined) { return calculations.topVisible; } }, bottomVisible: function(newCallback) { var calculations = module.get.elementCalculations(), callback = newCallback || settings.onBottomVisible, callbackName = 'bottomVisible' ; if(newCallback) { module.debug('Adding callback for bottom visible', newCallback); settings.onBottomVisible = newCallback; } if(calculations.bottomVisible) { module.execute(callback, callbackName); } else if(!settings.once) { module.remove.occurred(callbackName); } if(newCallback === undefined) { return calculations.bottomVisible; } }, topPassed: function(newCallback) { var calculations = module.get.elementCalculations(), callback = newCallback || settings.onTopPassed, callbackName = 'topPassed' ; if(newCallback) { module.debug('Adding callback for top passed', newCallback); settings.onTopPassed = newCallback; } if(calculations.topPassed) { module.execute(callback, callbackName); } else if(!settings.once) { module.remove.occurred(callbackName); } if(newCallback === undefined) { return calculations.topPassed; } }, bottomPassed: function(newCallback) { var calculations = module.get.elementCalculations(), callback = newCallback || settings.onBottomPassed, callbackName = 'bottomPassed' ; if(newCallback) { module.debug('Adding callback for bottom passed', newCallback); settings.onBottomPassed = newCallback; } if(calculations.bottomPassed) { module.execute(callback, callbackName); } else if(!settings.once) { module.remove.occurred(callbackName); } if(newCallback === undefined) { return calculations.bottomPassed; } }, passingReverse: function(newCallback) { var calculations = module.get.elementCalculations(), callback = newCallback || settings.onPassingReverse, callbackName = 'passingReverse' ; if(newCallback) { module.debug('Adding callback for passing reverse', newCallback); settings.onPassingReverse = newCallback; } if(!calculations.passing) { if(module.get.occurred('passing')) { module.execute(callback, callbackName); } } else if(!settings.once) { module.remove.occurred(callbackName); } if(newCallback !== undefined) { return !calculations.passing; } }, topVisibleReverse: function(newCallback) { var calculations = module.get.elementCalculations(), callback = newCallback || settings.onTopVisibleReverse, callbackName = 'topVisibleReverse' ; if(newCallback) { module.debug('Adding callback for top visible reverse', newCallback); settings.onTopVisibleReverse = newCallback; } if(!calculations.topVisible) { if(module.get.occurred('topVisible')) { module.execute(callback, callbackName); } } else if(!settings.once) { module.remove.occurred(callbackName); } if(newCallback === undefined) { return !calculations.topVisible; } }, bottomVisibleReverse: function(newCallback) { var calculations = module.get.elementCalculations(), callback = newCallback || settings.onBottomVisibleReverse, callbackName = 'bottomVisibleReverse' ; if(newCallback) { module.debug('Adding callback for bottom visible reverse', newCallback); settings.onBottomVisibleReverse = newCallback; } if(!calculations.bottomVisible) { if(module.get.occurred('bottomVisible')) { module.execute(callback, callbackName); } } else if(!settings.once) { module.remove.occurred(callbackName); } if(newCallback === undefined) { return !calculations.bottomVisible; } }, topPassedReverse: function(newCallback) { var calculations = module.get.elementCalculations(), callback = newCallback || settings.onTopPassedReverse, callbackName = 'topPassedReverse' ; if(newCallback) { module.debug('Adding callback for top passed reverse', newCallback); settings.onTopPassedReverse = newCallback; } if(!calculations.topPassed) { if(module.get.occurred('topPassed')) { module.execute(callback, callbackName); } } else if(!settings.once) { module.remove.occurred(callbackName); } if(newCallback === undefined) { return !calculations.onTopPassed; } }, bottomPassedReverse: function(newCallback) { var calculations = module.get.elementCalculations(), callback = newCallback || settings.onBottomPassedReverse, callbackName = 'bottomPassedReverse' ; if(newCallback) { module.debug('Adding callback for bottom passed reverse', newCallback); settings.onBottomPassedReverse = newCallback; } if(!calculations.bottomPassed) { if(module.get.occurred('bottomPassed')) { module.execute(callback, callbackName); } } else if(!settings.once) { module.remove.occurred(callbackName); } if(newCallback === undefined) { return !calculations.bottomPassed; } }, execute: function(callback, callbackName) { var calculations = module.get.elementCalculations(), screen = module.get.screenCalculations() ; callback = callback || false; if(callback) { if(settings.continuous) { module.debug('Callback being called continuously', callbackName, calculations); callback.call(element, calculations, screen); } else if(!module.get.occurred(callbackName)) { module.debug('Conditions met', callbackName, calculations); callback.call(element, calculations, screen); } } module.save.occurred(callbackName); }, remove: { fixed: function() { module.debug('Removing fixed position'); $module .removeClass(className.fixed) .css({ position : '', top : '', left : '', zIndex : '' }) ; }, occurred: function(callback) { if(callback) { var occurred = module.cache.occurred ; if(occurred[callback] !== undefined && occurred[callback] === true) { module.debug('Callback can now be called again', callback); module.cache.occurred[callback] = false; } } else { module.cache.occurred = {}; } } }, save: { calculations: function() { module.verbose('Saving all calculations necessary to determine positioning'); module.save.direction(); module.save.screenCalculations(); module.save.elementCalculations(); }, occurred: function(callback) { if(callback) { if(module.cache.occurred[callback] === undefined || (module.cache.occurred[callback] !== true)) { module.verbose('Saving callback occurred', callback); module.cache.occurred[callback] = true; } } }, scroll: function(scrollPosition) { scrollPosition = scrollPosition + settings.offset || $context.scrollTop() + settings.offset; module.cache.scroll = scrollPosition; }, direction: function() { var scroll = module.get.scroll(), lastScroll = module.get.lastScroll(), direction ; if(scroll > lastScroll && lastScroll) { direction = 'down'; } else if(scroll < lastScroll && lastScroll) { direction = 'up'; } else { direction = 'static'; } module.cache.direction = direction; return module.cache.direction; }, elementPosition: function() { var element = module.cache.element, screen = module.get.screenSize() ; module.verbose('Saving element position'); // (quicker than $.extend) element.fits = (element.height < screen.height); element.offset = $module.offset(); element.width = $module.outerWidth(); element.height = $module.outerHeight(); // store module.cache.element = element; return element; }, elementCalculations: function() { var screen = module.get.screenCalculations(), element = module.get.elementPosition() ; // offset if(settings.includeMargin) { element.margin = {}; element.margin.top = parseInt($module.css('margin-top'), 10); element.margin.bottom = parseInt($module.css('margin-bottom'), 10); element.top = element.offset.top - element.margin.top; element.bottom = element.offset.top + element.height + element.margin.bottom; } else { element.top = element.offset.top; element.bottom = element.offset.top + element.height; } // visibility element.topVisible = (screen.bottom >= element.top); element.topPassed = (screen.top >= element.top); element.bottomVisible = (screen.bottom >= element.bottom); element.bottomPassed = (screen.top >= element.bottom); element.pixelsPassed = 0; element.percentagePassed = 0; // meta calculations element.onScreen = (element.topVisible && !element.bottomPassed); element.passing = (element.topPassed && !element.bottomPassed); element.offScreen = (!element.onScreen); // passing calculations if(element.passing) { element.pixelsPassed = (screen.top - element.top); element.percentagePassed = (screen.top - element.top) / element.height; } module.cache.element = element; module.verbose('Updated element calculations', element); return element; }, screenCalculations: function() { var scroll = module.get.scroll() ; module.save.direction(); module.cache.screen.top = scroll; module.cache.screen.bottom = scroll + module.cache.screen.height; return module.cache.screen; }, screenSize: function() { module.verbose('Saving window position'); module.cache.screen = { height: $context.height() }; }, position: function() { module.save.screenSize(); module.save.elementPosition(); } }, get: { pixelsPassed: function(amount) { var element = module.get.elementCalculations() ; if(amount.search('%') > -1) { return ( element.height * (parseInt(amount, 10) / 100) ); } return parseInt(amount, 10); }, occurred: function(callback) { return (module.cache.occurred !== undefined) ? module.cache.occurred[callback] || false : false ; }, direction: function() { if(module.cache.direction === undefined) { module.save.direction(); } return module.cache.direction; }, elementPosition: function() { if(module.cache.element === undefined) { module.save.elementPosition(); } return module.cache.element; }, elementCalculations: function() { if(module.cache.element === undefined) { module.save.elementCalculations(); } return module.cache.element; }, screenCalculations: function() { if(module.cache.screen === undefined) { module.save.screenCalculations(); } return module.cache.screen; }, screenSize: function() { if(module.cache.screen === undefined) { module.save.screenSize(); } return module.cache.screen; }, scroll: function() { if(module.cache.scroll === undefined) { module.save.scroll(); } return module.cache.scroll; }, lastScroll: function() { if(module.cache.screen === undefined) { module.debug('First scroll event, no last scroll could be found'); return false; } return module.cache.screen.top; } }, setting: function(name, value) { if( $.isPlainObject(name) ) { $.extend(true, settings, name); } else if(value !== undefined) { settings[name] = value; } else { return settings[name]; } }, internal: function(name, value) { if( $.isPlainObject(name) ) { $.extend(true, module, name); } else if(value !== undefined) { module[name] = value; } else { return module[name]; } }, debug: function() { if(settings.debug) { if(settings.performance) { module.performance.log(arguments); } else { module.debug = Function.prototype.bind.call(console.info, console, settings.name + ':'); module.debug.apply(console, arguments); } } }, verbose: function() { if(settings.verbose && settings.debug) { if(settings.performance) { module.performance.log(arguments); } else { module.verbose = Function.prototype.bind.call(console.info, console, settings.name + ':'); module.verbose.apply(console, arguments); } } }, error: function() { module.error = Function.prototype.bind.call(console.error, console, settings.name + ':'); module.error.apply(console, arguments); }, performance: { log: function(message) { var currentTime, executionTime, previousTime ; if(settings.performance) { currentTime = new Date().getTime(); previousTime = time || currentTime; executionTime = currentTime - previousTime; time = currentTime; performance.push({ 'Name' : message[0], 'Arguments' : [].slice.call(message, 1) || '', 'Element' : element, 'Execution Time' : executionTime }); } clearTimeout(module.performance.timer); module.performance.timer = setTimeout(module.performance.display, 500); }, display: function() { var title = settings.name + ':', totalTime = 0 ; time = false; clearTimeout(module.performance.timer); $.each(performance, function(index, data) { totalTime += data['Execution Time']; }); title += ' ' + totalTime + 'ms'; if(moduleSelector) { title += ' \'' + moduleSelector + '\''; } if( (console.group !== undefined || console.table !== undefined) && performance.length > 0) { console.groupCollapsed(title); if(console.table) { console.table(performance); } else { $.each(performance, function(index, data) { console.log(data['Name'] + ': ' + data['Execution Time']+'ms'); }); } console.groupEnd(); } performance = []; } }, invoke: function(query, passedArguments, context) { var object = instance, maxDepth, found, response ; passedArguments = passedArguments || queryArguments; context = element || context; if(typeof query == 'string' && object !== undefined) { query = query.split(/[\. ]/); maxDepth = query.length - 1; $.each(query, function(depth, value) { var camelCaseValue = (depth != maxDepth) ? value + query[depth + 1].charAt(0).toUpperCase() + query[depth + 1].slice(1) : query ; if( $.isPlainObject( object[camelCaseValue] ) && (depth != maxDepth) ) { object = object[camelCaseValue]; } else if( object[camelCaseValue] !== undefined ) { found = object[camelCaseValue]; return false; } else if( $.isPlainObject( object[value] ) && (depth != maxDepth) ) { object = object[value]; } else if( object[value] !== undefined ) { found = object[value]; return false; } else { module.error(error.method, query); return false; } }); } if ( $.isFunction( found ) ) { response = found.apply(context, passedArguments); } else if(found !== undefined) { response = found; } if($.isArray(returnedValue)) { returnedValue.push(response); } else if(returnedValue !== undefined) { returnedValue = [returnedValue, response]; } else if(response !== undefined) { returnedValue = response; } return found; } }; if(methodInvoked) { if(instance === undefined) { module.initialize(); } instance.save.scroll(); instance.save.calculations(); module.invoke(query); } else { if(instance !== undefined) { instance.invoke('destroy'); } module.initialize(); } }) ; return (returnedValue !== undefined) ? returnedValue : this ; }; $.fn.visibility.settings = { name : 'Visibility', namespace : 'visibility', debug : false, verbose : false, performance : true, // whether to use mutation observers to follow changes observeChanges : true, // check position immediately on init initialCheck : true, // whether to refresh calculations after all page images load refreshOnLoad : true, // whether to refresh calculations after page resize event refreshOnResize : true, // should call callbacks on refresh event (resize, etc) checkOnRefresh : true, // callback should only occur one time once : true, // callback should fire continuously whe evaluates to true continuous : false, // offset to use with scroll top offset : 0, // whether to include margin in elements position includeMargin : false, // scroll context for visibility checks context : window, // visibility check delay in ms (defaults to animationFrame) throttle : false, // special visibility type (image, fixed) type : false, // image only animation settings transition : 'fade in', duration : 1000, // array of callbacks for percentage onPassed : {}, // standard callbacks onOnScreen : false, onOffScreen : false, onPassing : false, onTopVisible : false, onBottomVisible : false, onTopPassed : false, onBottomPassed : false, // reverse callbacks onPassingReverse : false, onTopVisibleReverse : false, onBottomVisibleReverse : false, onTopPassedReverse : false, onBottomPassedReverse : false, // utility callbacks onUpdate : false, // disabled by default for performance onRefresh : function(){}, metadata : { src: 'src' }, className: { fixed : 'fixed', placeholder : 'placeholder' }, error : { method : 'The method you called is not defined.', visible : 'Element is hidden, you must call refresh after element becomes visible' } }; })( jQuery, window, document );
rubengarciam/dropbox-file-requests-audit
client/lib/semantic-ui/definitions/behaviors/visibility.js
JavaScript
mit
39,412
import { apiRunner, apiRunnerAsync } from "./api-runner-browser" import React from "react" import ReactDOM from "react-dom" import { Router, navigate, Location, BaseContext } from "@gatsbyjs/reach-router" import { ScrollContext } from "gatsby-react-router-scroll" import { StaticQueryContext } from "gatsby" import { shouldUpdateScroll, init as navigationInit, RouteUpdates, } from "./navigation" import emitter from "./emitter" import PageRenderer from "./page-renderer" import asyncRequires from "$virtual/async-requires" import { setLoader, ProdLoader, publicLoader, PageResourceStatus, getStaticQueryResults, } from "./loader" import EnsureResources from "./ensure-resources" import stripPrefix from "./strip-prefix" // Generated during bootstrap import matchPaths from "$virtual/match-paths.json" const loader = new ProdLoader(asyncRequires, matchPaths, window.pageData) setLoader(loader) loader.setApiRunner(apiRunner) window.asyncRequires = asyncRequires window.___emitter = emitter window.___loader = publicLoader navigationInit() const reloadStorageKey = `gatsby-reload-compilation-hash-match` apiRunnerAsync(`onClientEntry`).then(() => { // Let plugins register a service worker. The plugin just needs // to return true. if (apiRunner(`registerServiceWorker`).filter(Boolean).length > 0) { require(`./register-service-worker`) } // In gatsby v2 if Router is used in page using matchPaths // paths need to contain full path. // For example: // - page have `/app/*` matchPath // - inside template user needs to use `/app/xyz` as path // Resetting `basepath`/`baseuri` keeps current behaviour // to not introduce breaking change. // Remove this in v3 const RouteHandler = props => ( <BaseContext.Provider value={{ baseuri: `/`, basepath: `/`, }} > <PageRenderer {...props} /> </BaseContext.Provider> ) const DataContext = React.createContext({}) class GatsbyRoot extends React.Component { render() { const { children } = this.props return ( <Location> {({ location }) => ( <EnsureResources location={location}> {({ pageResources, location }) => { const staticQueryResults = getStaticQueryResults() return ( <StaticQueryContext.Provider value={staticQueryResults}> <DataContext.Provider value={{ pageResources, location }}> {children} </DataContext.Provider> </StaticQueryContext.Provider> ) }} </EnsureResources> )} </Location> ) } } class LocationHandler extends React.Component { render() { return ( <DataContext.Consumer> {({ pageResources, location }) => ( <RouteUpdates location={location}> <ScrollContext location={location} shouldUpdateScroll={shouldUpdateScroll} > <Router basepath={__BASE_PATH__} location={location} id="gatsby-focus-wrapper" > <RouteHandler path={ pageResources.page.path === `/404.html` || pageResources.page.path === `/500.html` ? stripPrefix(location.pathname, __BASE_PATH__) : encodeURI( ( pageResources.page.matchPath || pageResources.page.path ).split(`?`)[0] ) } {...this.props} location={location} pageResources={pageResources} {...pageResources.json} /> </Router> </ScrollContext> </RouteUpdates> )} </DataContext.Consumer> ) } } const { pagePath, location: browserLoc } = window // Explicitly call navigate if the canonical path (window.pagePath) // is different to the browser path (window.location.pathname). SSR // page paths might include search params, while SSG and DSG won't. // If page path include search params we also compare query params. // But only if NONE of the following conditions hold: // // - The url matches a client side route (page.matchPath) // - it's a 404 page // - it's the offline plugin shell (/offline-plugin-app-shell-fallback/) if ( pagePath && __BASE_PATH__ + pagePath !== browserLoc.pathname + (pagePath.includes(`?`) ? browserLoc.search : ``) && !( loader.findMatchPath(stripPrefix(browserLoc.pathname, __BASE_PATH__)) || pagePath.match(/^\/(404|500)(\/?|.html)$/) || pagePath.match(/^\/offline-plugin-app-shell-fallback\/?$/) ) ) { navigate( __BASE_PATH__ + pagePath + (!pagePath.includes(`?`) ? browserLoc.search : ``) + browserLoc.hash, { replace: true, } ) } // It's possible that sessionStorage can throw an exception if access is not granted, see https://github.com/gatsbyjs/gatsby/issues/34512 const getSessionStorage = () => { try { return sessionStorage } catch { return null } } publicLoader.loadPage(browserLoc.pathname + browserLoc.search).then(page => { const sessionStorage = getSessionStorage() if ( page?.page?.webpackCompilationHash && page.page.webpackCompilationHash !== window.___webpackCompilationHash ) { // Purge plugin-offline cache if ( `serviceWorker` in navigator && navigator.serviceWorker.controller !== null && navigator.serviceWorker.controller.state === `activated` ) { navigator.serviceWorker.controller.postMessage({ gatsbyApi: `clearPathResources`, }) } // We have not matching html + js (inlined `window.___webpackCompilationHash`) // with our data (coming from `app-data.json` file). This can cause issues such as // errors trying to load static queries (as list of static queries is inside `page-data` // which might not match to currently loaded `.js` scripts). // We are making attempt to reload if hashes don't match, but we also have to handle case // when reload doesn't fix it (possibly broken deploy) so we don't end up in infinite reload loop if (sessionStorage) { const isReloaded = sessionStorage.getItem(reloadStorageKey) === `1` if (!isReloaded) { sessionStorage.setItem(reloadStorageKey, `1`) window.location.reload(true) return } } } if (sessionStorage) { sessionStorage.removeItem(reloadStorageKey) } if (!page || page.status === PageResourceStatus.Error) { const message = `page resources for ${browserLoc.pathname} not found. Not rendering React` // if the chunk throws an error we want to capture the real error // This should help with https://github.com/gatsbyjs/gatsby/issues/19618 if (page && page.error) { console.error(message) throw page.error } throw new Error(message) } const SiteRoot = apiRunner( `wrapRootElement`, { element: <LocationHandler /> }, <LocationHandler />, ({ result }) => { return { element: result } } ).pop() const App = function App() { const onClientEntryRanRef = React.useRef(false) React.useEffect(() => { if (!onClientEntryRanRef.current) { onClientEntryRanRef.current = true if (performance.mark) { performance.mark(`onInitialClientRender`) } apiRunner(`onInitialClientRender`) } }, []) return <GatsbyRoot>{SiteRoot}</GatsbyRoot> } const renderer = apiRunner( `replaceHydrateFunction`, undefined, ReactDOM.hydrateRoot ? ReactDOM.hydrateRoot : ReactDOM.hydrate )[0] function runRender() { const rootElement = typeof window !== `undefined` ? document.getElementById(`___gatsby`) : null if (renderer === ReactDOM.hydrateRoot) { renderer(rootElement, <App />) } else { renderer(<App />, rootElement) } } // https://github.com/madrobby/zepto/blob/b5ed8d607f67724788ec9ff492be297f64d47dfc/src/zepto.js#L439-L450 // TODO remove IE 10 support const doc = document if ( doc.readyState === `complete` || (doc.readyState !== `loading` && !doc.documentElement.doScroll) ) { setTimeout(function () { runRender() }, 0) } else { const handler = function () { doc.removeEventListener(`DOMContentLoaded`, handler, false) window.removeEventListener(`load`, handler, false) runRender() } doc.addEventListener(`DOMContentLoaded`, handler, false) window.addEventListener(`load`, handler, false) } }) })
gatsbyjs/gatsby
packages/gatsby/cache-dir/production-app.js
JavaScript
mit
9,189
// Returns a random integer between 1 and max function randInt( max ) { return Math.floor( Math.random() * ( max - 1 ) ) + 1; } bot.registerCommand( "roll", function( name, _, _, arg_str, group ) { if ( /(\d+)?d\d+/.test( arg_str ) ) { var match = arg_str.match( /(\d+)?d(\d+)/ ); var num = match[1] ? Math.max( Math.min( parseInt( match[1] ), 10 ), 1 ) : 1; var max = parseInt( match[2] ); var results = []; for ( var x = 0; x < num; x++ ) results[ x ] = randInt( max ); var msg = name + " rolls "; msg += num == 1 ? "a" : num; msg += " d" + max; msg += num == 1 ? "" : "s"; msg += ": " + results.join( ", " ); bot.sendMessage( msg, group ); } else { // Just roll d20 bot.sendMessage( name + " rolls a d20: " + randInt( 20 ), group ) } }, "Rolls N dice with N sides. [Example: .roll 2d6]" );
SwadicalRag/hash.js
plugins/roll.js
JavaScript
cc0-1.0
842
/* jshint unused: false */ exports.excludeFile = function (file) { // The platform mapping is "not mapped" for the following tests, // and this has not changed during the ARIA + Core AAM 1.1 cycle. if (/aria-autocomplete_both-manual.html/.test(file)) return true; if (/aria-autocomplete_inline-manual.html/.test(file)) return true; if (/aria-autocomplete_list-manual.html/.test(file)) return true; if (/aria-dropeffect_none-manual.html/.test(file)) return true; if (/aria-haspopup_false-manual.html/.test(file)) return true; if (/aria-multiline_false-manual.html/.test(file)) return true; if (/aria-multiline_true-manual.html/.test(file)) return true; if (/aria-multiselectable_false-manual.html/.test(file)) return true; if (/aria-multiselectable_true-manual.html/.test(file)) return true; if (/aria-sort_none-manual.html/.test(file)) return true; // The platform mapping is "not mapped" for the following tests, // which cover features introduced during the 1.1 cycle. if (/aria-details_new-manual.html/.test(file)) return true; if (/aria-keyshortcuts_new-manual.html/.test(file)) return true; // There is no platform accessibility signal expected when the property // value changes in the following tests: if (/aria-current_value_changes-manual.html/.test(file)) return true; if (/aria-disabled_value_changes-manual.html/.test(file)) return true; if (/aria-dropeffect_value_changes-manual.html/.test(file)) return true; if (/aria-grabbed_value_changes-manual.html/.test(file)) return true; if (/aria-pressed_value_changes-manual.html/.test(file)) return true; if (/aria-readonly_value_changes-manual.html/.test(file)) return true; if (/aria-required_value_changes-manual.html/.test(file)) return true; return false; }; exports.excludeCase = function (file, name) { return false; };
w3c/test-results
core-aam-1.1/axapi/WK/filter.js
JavaScript
cc0-1.0
1,899
// http://microformat2-node.jit.su/h-review.html { "items": [{ "type": ["h-review"], "properties": { "item": [{ "value": "Crepes on Cole", "type": ["h-item"], "properties": { "photo": ["http://example.com/images/photo.gif"], "name": ["Crepes on Cole"], "url": ["http://example.com/crepeoncole"] } }], "rating": ["5"] } }] }
jeena/microformats2
spec/support/cases/microformat2-node.jit.su/h-review/h-review-4.js
JavaScript
cc0-1.0
519
/* * BEGIN NIGHTINGALE GPL * * This file is part of the Nightingale Media Player. * * Copyright(c) 2013 * http://getnightingale.com * * This file may be licensed under the terms of of the * GNU General Public License Version 2 (the "GPL"). * * Software distributed under the License is distributed * on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either * express or implied. See the GPL for the specific language * governing rights and limitations. * * You should have received a copy of the GPL along with this * program. If not, go to http://www.gnu.org/licenses/gpl.html * or write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * * END NIGHTINGALE GPL */ if (typeof(Ci) == "undefined") var Ci = Components.interfaces; if (typeof(Cc) == "undefined") var Cc = Components.classes; if (typeof(Cr) == "undefined") var Cr = Components.results; if (typeof(Cu) == "undefined") var Cu = Components.utils; try { Cu.import("resource://gre/modules/XPCOMUtils.jsm"); Cu.import("resource://app/jsmodules/sbProperties.jsm"); Cu.import("resource://app/jsmodules/sbCoverHelper.jsm"); } catch (error) { alert("lnNotifs: Unexpected error - module import error\n\n" + error) } lnNotifs = { mmService: null, strConv: null, lastItem: null, wm: null, mainwindow: null, prefs: null, lnNotifsService: null, ios: null, onLoad: function() { var mainwindow = window.QueryInterface(Ci.nsIInterfaceRequestor).getInterface(Ci.nsIWebNavigation) .QueryInterface(Ci.nsIDocShellTreeItem).rootTreeItem .QueryInterface(Ci.nsIInterfaceRequestor).getInterface(Ci.nsIDOMWindow); this.mmService = Cc["@songbirdnest.com/Songbird/Mediacore/Manager;1"].getService(Ci.sbIMediacoreManager); this.strConv = Cc["@mozilla.org/intl/scriptableunicodeconverter"].getService(Ci.nsIScriptableUnicodeConverter); this.lnNotifsService = Cc["@getnightingale.com/Nightingale/lnNotifs;1"].getService(Ci.ILNNotifs); this.wm = Cc["@mozilla.org/appshell/window-mediator;1"].getService(Ci.nsIWindowMediator); this.ios = Cc["@mozilla.org/network/io-service;1"].getService(Ci.nsIIOService); this.mainwindow = this.wm.getMostRecentWindow("Songbird:Main"); var windowTitle = this.mainwindow.document.getElementById("mainplayer").getAttribute("title"); this.prefs = Cc["@mozilla.org/preferences-service;1"].getService(Ci.nsIPrefService).getBranch("extensions.libnotify-notifs."); this.lnNotifsService.InitNotifs(windowTitle); this.strConv.charset = 'utf-8'; var mm = this.mmService; var that = this; this.mmService.addListener({ onMediacoreEvent: function(event) { // Get mediacore event if (that.mmService.sequencer.view == null) return; if (event.type == Ci.sbIMediacoreEvent.TRACK_CHANGE) { // Check if notifications are enabled var notifsEnabled = lnNotifs.prefs.getBoolPref("enableNotifications"); lnNotifs.lnNotifsService.EnableNotifications(notifsEnabled); var curItem = that.mmService.sequencer.currentItem; // Don't notify for mediacore sequencing oddities if (that.lastItem == curItem) return; else that.lastItem = curItem; var resourceURL = curItem.getProperty(SBProperties.primaryImageURL); var fileURI = null; if(resourceURL) { try{ fileURI = that.ios.newURI(decodeURI(resourceURL), null, null).QueryInterface(Ci.nsIFileURL).file.path; } catch(e) { Cu.reportError(e); } } var artist = that.strConv.ConvertFromUnicode(curItem.getProperty(SBProperties.artistName)); var album = that.strConv.ConvertFromUnicode(curItem.getProperty(SBProperties.albumName)); var track = that.strConv.ConvertFromUnicode(curItem.getProperty(SBProperties.trackName)); var timeout = that.prefs.getIntPref("notificationTimeout"); that.lnNotifsService.TrackChangeNotify(track, artist, album, fileURI, timeout); } } }); }, onUnload: function() { } }; window.addEventListener("load", function(e) { lnNotifs.onLoad(); }, false); window.addEventListener("unload", function(e) { lnNotifs.onUnload(); }, false);
freaktechnik/nightingale-hacking
extensions/libnotify-notifs/chrome/content/track-metadata.js
JavaScript
gpl-2.0
4,761
var searchData= [ ['false',['FALSE',['../core_8h.html#aa93f0eb578d23995850d61f7d61c55c1',1,'core.h']]] ];
SSS4910/CudaP
www/doc/search/defines_2.js
JavaScript
gpl-2.0
108
jQuery(document).ready(function(){ var flash = [[0, 2], [1, 6], [2,3], [3, 8], [4, 5], [5, 13], [6, 8]]; //for (var i = 0; i < 14; i += 0.5) // flash.push([i, Math.sin(i)]); function showTooltip(x, y, contents) { jQuery('<div id="tooltip" class="tooltipflot">' + contents + '</div>').css( { position: 'absolute', display: 'none', top: y + 5, left: x + 5 }).appendTo("body").fadeIn(200); } var plot = jQuery.plot(jQuery("#chartplace"), [ { data: flash, label: "Visits", color: "#069"} ], { series: { lines: { show: true, lineWidth: 1, fill: true, fillColor: { colors: [ { opacity: 0.1 }, { opacity: 0.5 } ] } }, points: { show: true, radius: 2 }, shadowSize: 0 }, legend: { position: 'nw'}, grid: { hoverable: true, clickable: true, labelMargin: 5, borderWidth: 1, borderColor: '#bbb' }, yaxis: { show: false, min: 0, max: 14 }, }); var previousPoint = null; jQuery("#chartplace").bind("plothover", function (event, pos, item) { jQuery("#x").text(pos.x.toFixed(2)); jQuery("#y").text(pos.y.toFixed(2)); if(item) { if (previousPoint != item.dataIndex) { previousPoint = item.dataIndex; jQuery("#tooltip").remove(); var x = item.datapoint[0].toFixed(2), y = item.datapoint[1].toFixed(2); showTooltip(item.pageX, item.pageY, item.series.label + " of " + x + " = " + y); } } else { jQuery("#tooltip").remove(); previousPoint = null; } }); jQuery("#chartplace").bind("plotclick", function (event, pos, item) { if (item) { jQuery("#clickdata").text("You clicked point " + item.dataIndex + " in " + item.series.label + "."); plot.highlight(item.series, item.datapoint); } }); //datepicker jQuery('#datepicker').datepicker(); //show tabbed widget jQuery('#tabs').tabs(); /*****SIMPLE CHART*****/ var flash = [[0, 2], [1, 6], [2,3], [3, 8], [4, 5], [5, 13], [6, 8]]; var html5 = [[0, 5], [1, 4], [2,4], [3, 1], [4, 9], [5, 10], [6, 13]]; function showTooltip(x, y, contents) { jQuery('<div id="tooltip" class="tooltipflot">' + contents + '</div>').css( { position: 'absolute', display: 'none', top: y + 5, left: x + 5 }).appendTo("body").fadeIn(200); } var plot = jQuery.plot(jQuery("#chartplace2"), [ { data: flash, label: "Flash(x)", color: "#ff6138"}, { data: html5, label: "HTML5(x)", color: "#00a388"} ], { series: { lines: { show: true, fill: true, fillColor: { colors: [ { opacity: 0.05 }, { opacity: 0.15 } ] } }, points: { show: true } }, legend: { position: 'nw'}, grid: { hoverable: true, clickable: true, borderColor: '#ccc', borderWidth: 1, labelMargin: 10 }, yaxis: { min: 0, max: 15 } }); var previousPoint = null; jQuery("#chartplace2").bind("plothover", function (event, pos, item) { jQuery("#x").text(pos.x.toFixed(2)); jQuery("#y").text(pos.y.toFixed(2)); if(item) { if (previousPoint != item.dataIndex) { previousPoint = item.dataIndex; jQuery("#tooltip").remove(); var x = item.datapoint[0].toFixed(2), y = item.datapoint[1].toFixed(2); showTooltip(item.pageX, item.pageY, item.series.label + " of " + x + " = " + y); } } else { jQuery("#tooltip").remove(); previousPoint = null; } }); jQuery("#chartplace2").bind("plotclick", function (event, pos, item) { if (item) { jQuery("#clickdata").text("You clicked point " + item.dataIndex + " in " + item.series.label + "."); plot.highlight(item.series, item.datapoint); } }); //get data from server and inject it next to row jQuery('.stdtable a.toggle').click(function(){ //show all hidden row and remove all showed data jQuery(this).parents('table').find('tr').each(function(){ jQuery(this).removeClass('hiderow'); if(jQuery(this).hasClass('togglerow')) jQuery(this).remove(); }); var parentRow = jQuery(this).parents('tr'); var numcols = parentRow.find('td').length + 1; //get the number of columns in a table. Added 1 for new row to be inserted var url = jQuery(this).attr('href'); //this will insert a new row next to this element's row parent parentRow.after('<tr class="togglerow"><td colspan="'+numcols+'"><div class="toggledata"></div></td></tr>'); var toggleData = parentRow.next().find('.toggledata'); parentRow.next().hide(); //get data from server jQuery.post(url,function(data){ toggleData.append(data); //inject data read from server parentRow.next().fadeIn(); //show inserted new row parentRow.addClass('hiderow'); //hide this row to look like replacing the newly inserted row }); return false; }); jQuery('.toggledata button.cancel, .toggledata button.submit').live('click',function(){ jQuery(this).parents('.toggledata').animate({height: 0},200, function(){ jQuery(this).parents('tr').prev().removeClass('hiderow'); jQuery(this).parents('tr').remove(); }); return false; }); /***** WIDGET LIST HOVER *****/ jQuery('.widgetlist a').hover(function(){ jQuery(this).switchClass('default', 'hover'); },function(){ jQuery(this).switchClass('hover', 'default'); }); });
mentordeveloper/ums
themes/starlight/js/custom/dashboard.js
JavaScript
gpl-2.0
5,608
// Copyright 2014 Todd Fleming // // This file is part of jscut. // // jscut is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // jscut is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with jscut. If not, see <http://www.gnu.org/licenses/>. function Tab(options, svgViewModel, tabsViewModel, tabsGroup, rawPaths, toolPathsChanged, loading) { "use strict"; var self = this; self.rawPaths = rawPaths; self.enabled = ko.observable(true); self.margin = ko.observable("0.0"); self.combinedGeometry = []; self.combinedGeometrySvg = null; tabsViewModel.unitConverter.addComputed(self.margin); self.enabled.subscribe(toolPathsChanged); self.removeCombinedGeometrySvg = function() { if (self.combinedGeometrySvg) { self.combinedGeometrySvg.remove(); self.combinedGeometrySvg = null; } } self.enabled.subscribe(function (newValue) { var v; if (newValue) v = "visible"; else v = "hidden"; if (self.combinedGeometrySvg) self.combinedGeometrySvg.attr("visibility", v); }); self.recombine = function () { if (loading) return; var startTime = Date.now(); if (options.profile) console.log("tabs recombine..."); self.removeCombinedGeometrySvg(); var all = []; for (var i = 0; i < self.rawPaths.length; ++i) { var geometry = jscut.priv.path.getClipperPathsFromSnapPath(self.rawPaths[i].path, svgViewModel.pxPerInch(), function (msg) { showAlert(msg, "alert-warning"); }); if (geometry != null) { var fillRule; if (self.rawPaths[i].nonzero) fillRule = ClipperLib.PolyFillType.pftNonZero; else fillRule = ClipperLib.PolyFillType.pftEvenOdd; all.push(jscut.priv.path.simplifyAndClean(geometry, fillRule)); } } if (all.length == 0) self.combinedGeometry = []; else { self.combinedGeometry = all[0]; for (var i = 1; i < all.length; ++i) self.combinedGeometry = jscut.priv.path.clip(self.combinedGeometry, all[i], ClipperLib.ClipType.ctUnion); } var offset = self.margin.toInch() * jscut.priv.path.inchToClipperScale; if (offset != 0) self.combinedGeometry = jscut.priv.path.offset(self.combinedGeometry, offset); if (self.combinedGeometry.length != 0) { var path = jscut.priv.path.getSnapPathFromClipperPaths(self.combinedGeometry, svgViewModel.pxPerInch()); if (path != null) self.combinedGeometrySvg = tabsGroup.path(path).attr("class", "tabsGeometry"); } if (options.profile) console.log("tabs recombine: " + (Date.now() - startTime)); self.enabled(true); toolPathsChanged(); } self.margin.subscribe(self.recombine); self.recombine(); self.toJson = function () { result = { 'rawPaths': self.rawPaths, 'enabled': self.enabled(), 'margin': self.margin(), }; return result; } self.fromJson = function (json) { function f(j, o) { if (typeof j !== "undefined") o(j); } if (json) { loading = true; self.rawPaths = json.rawPaths; f(json.margin, self.margin); loading = false; self.recombine(); f(json.enabled, self.enabled); } } } function TabsViewModel(miscViewModel, options, svgViewModel, materialViewModel, selectionViewModel, tabsGroup, toolPathsChanged) { "use strict"; var self = this; self.miscViewModel = miscViewModel; self.svgViewModel = svgViewModel; self.tabs = ko.observableArray(); self.units = ko.observable(materialViewModel.matUnits()); self.unitConverter = new UnitConverter(self.units); self.maxCutDepth = ko.observable(0); self.unitConverter.add(self.maxCutDepth); self.maxCutDepth.subscribe(toolPathsChanged); self.units.subscribe(function (newValue) { var tabs = self.tabs(); if (newValue == "inch") for (var i = 0; i < tabs.length ; ++i) { var tab = tabs[i]; tab.margin(tab.margin() / 25.4); } else for (var i = 0; i < tabs.length ; ++i) { var tab = tabs[i]; tab.margin(tab.margin() * 25.4); } }); svgViewModel.pxPerInch.subscribe(function () { var tabs = self.tabs(); for (var i = 0; i < tabs.length; ++i) tabs[i].recombine(); }); self.addTab = function () { var rawPaths = []; selectionViewModel.getSelection().forEach(function (element) { rawPaths.push({ 'path': Snap.parsePathString(element.attr('d')), 'nonzero': element.attr("fill-rule") != "evenodd", }); }); selectionViewModel.clearSelection(); var tab = new Tab(options, svgViewModel, self, tabsGroup, rawPaths, toolPathsChanged, false); self.tabs.push(tab); toolPathsChanged(); } self.removeTab = function (tab) { tab.removeCombinedGeometrySvg(); var i = self.tabs.indexOf(tab); self.tabs.remove(tab); toolPathsChanged(); } self.clickOnSvg = function (elem) { if (elem.attr("class") == "tabsGeometry") return true; return false; } self.toJson = function () { var tabs = self.tabs(); var jsonTabs = []; for (var i = 0; i < tabs.length; ++i) jsonTabs.push(tabs[i].toJson()); return { 'units': self.units(), 'maxCutDepth': self.maxCutDepth(), 'tabs': jsonTabs, }; } self.fromJson = function (json) { function f(j, o) { if (typeof j !== "undefined") o(j); } if (json) { f(json.units, self.units); f(json.maxCutDepth, self.maxCutDepth); var oldTabs = self.tabs(); for (var i = 0; i < oldTabs.length; ++i) { oldTabs[i].removeCombinedGeometrySvg(); } self.tabs.removeAll(); if ((typeof json.tabs !== "undefined")) { for (var i = 0; i < json.tabs.length; ++i) { var tab = new Tab(options, svgViewModel, self, tabsGroup, [], toolPathsChanged, true); self.tabs.push(tab); tab.fromJson(json.tabs[i]); } } } } }
jarretluft/bCNC
static/jscut/js/TabsViewModel.js
JavaScript
gpl-2.0
7,252
$(document).ready(function(){ $('#slideshow').cycle({ fx:'fade', pager:'#slideshow_nav', timeout:6000, before:function(currSlideElement, nextSlideElement, options, forwardFlag){ setTimeout ( function(){$(nextSlideElement).find('.slide-text').animate({height:'show'})} , 1500 ); }, after:function(currSlideElement, nextSlideElement, options, forwardFlag){ $(currSlideElement).find('.slide-text').hide(); } }); });
cumulusclips/cumulusclips
cc-content/themes/default/js/jcycle.js
JavaScript
gpl-2.0
500
(function ($) { /** * Attach the machine-readable name form element behavior. */ Drupal.behaviors.machineName = { /** * Attaches the behavior. * * @param settings.machineName * A list of elements to process, keyed by the HTML ID of the form element * containing the human-readable value. Each element is an object defining * the following properties: * - target: The HTML ID of the machine name form element. * - suffix: The HTML ID of a container to show the machine name preview in * (usually a field suffix after the human-readable name form element). * - label: The label to show for the machine name preview. * - replace_pattern: A regular expression (without modifiers) matching * disallowed characters in the machine name; e.g., '[^a-z0-9]+'. * - replace: A character to replace disallowed characters with; e.g., '_' * or '-'. * - standalone: Whether the preview should stay in its own element rather * than the suffix of the source element. * - field_prefix: The #field_prefix of the form element. * - field_suffix: The #field_suffix of the form element. */ attach: function (context, settings) { var self = this; $.each(settings.machineName, function (source_id, options) { var $source = $(source_id, context).addClass('machine-name-source'); var $target = $(options.target, context).addClass('machine-name-target'); var $suffix = $(options.suffix, context); var $wrapper = $target.closest('.form-item'); // All elements have to exist. if (!$source.length || !$target.length || !$suffix.length || !$wrapper.length) { return; } // Skip processing upon a form validation error on the machine name. if ($target.hasClass('error')) { return; } // Figure out the maximum length for the machine name. options.maxlength = $target.attr('maxlength'); // Hide the form item container of the machine name form element. $wrapper.hide(); // Determine the initial machine name value. Unless the machine name form // element is disabled or not empty, the initial default value is based on // the human-readable form element value. if ($target.is(':disabled') || $target.val() != '') { var machine = $target.val(); } else { var machine = self.transliterate($source.val(), options); } // Append the machine name preview to the source field. var $preview = $('<span class="machine-name-value">' + options.field_prefix + Drupal.checkPlain(machine) + options.field_suffix + '</span>'); $suffix.empty(); if (options.label) { $suffix.append(' ').append('<span class="machine-name-label">' + options.label + ':</span>'); } $suffix.append(' ').append($preview); // If the machine name cannot be edited, stop further processing. if ($target.is(':disabled')) { return; } // If it is editable, append an edit link. var $link = $('<span class="admin-link"><a href="#">' + Drupal.t('Edit') + '</a></span>') .click(function () { $wrapper.show(); $target.focus(); $suffix.hide(); $source.unbind('.machineName'); return false; }); $suffix.append(' ').append($link); // Preview the machine name in realtime when the human-readable name // changes, but only if there is no machine name yet; i.e., only upon // initial creation, not when editing. if ($target.val() == '') { $source.bind('keyup.machineName change.machineName input.machineName', function () { machine = self.transliterate($(this).val(), options); // Set the machine name to the transliterated value. if (machine != '') { if (machine != options.replace) { $target.val(machine); $preview.html(options.field_prefix + Drupal.checkPlain(machine) + options.field_suffix); } $suffix.show(); } else { $suffix.hide(); $target.val(machine); $preview.empty(); } }); // Initialize machine name preview. $source.keyup(); } }); }, /** * Transliterate a human-readable name to a machine name. * * @param source * A string to transliterate. * @param settings * The machine name settings for the corresponding field, containing: * - replace_pattern: A regular expression (without modifiers) matching * disallowed characters in the machine name; e.g., '[^a-z0-9]+'. * - replace: A character to replace disallowed characters with; e.g., '_' * or '-'. * - maxlength: The maximum length of the machine name. * * @return * The transliterated source string. */ transliterate: function (source, settings) { var rx = new RegExp(settings.replace_pattern, 'g'); return source.toLowerCase().replace(rx, settings.replace).substr(0, settings.maxlength); } }; })(jQuery); ; (function ($) { Drupal.behaviors.textarea = { attach: function (context, settings) { $('.form-textarea-wrapper.resizable', context).once('textarea', function () { var staticOffset = null; var textarea = $(this).addClass('resizable-textarea').find('textarea'); var grippie = $('<div class="grippie"></div>').mousedown(startDrag); grippie.insertAfter(textarea); function startDrag(e) { staticOffset = textarea.height() - e.pageY; textarea.css('opacity', 0.25); $(document).mousemove(performDrag).mouseup(endDrag); return false; } function performDrag(e) { textarea.height(Math.max(32, staticOffset + e.pageY) + 'px'); return false; } function endDrag(e) { $(document).unbind('mousemove', performDrag).unbind('mouseup', endDrag); textarea.css('opacity', 1); } }); } }; })(jQuery); ; /** * @file * Provides dependent visibility for form items in CTools' ajax forms. * * To your $form item definition add: * - '#process' => array('ctools_process_dependency'), * - '#dependency' => array('id-of-form-item' => array(list, of, values, that, * make, this, item, show), * * Special considerations: * - Radios are harder. Because Drupal doesn't give radio groups individual IDs, * use 'radio:name-of-radio'. * * - Checkboxes don't have their own id, so you need to add one in a div * around the checkboxes via #prefix and #suffix. You actually need to add TWO * divs because it's the parent that gets hidden. Also be sure to retain the * 'expand_checkboxes' in the #process array, because the CTools process will * override it. */ (function ($) { Drupal.CTools = Drupal.CTools || {}; Drupal.CTools.dependent = {}; Drupal.CTools.dependent.bindings = {}; Drupal.CTools.dependent.activeBindings = {}; Drupal.CTools.dependent.activeTriggers = []; Drupal.CTools.dependent.inArray = function(array, search_term) { var i = array.length; while (i--) { if (array[i] == search_term) { return true; } } return false; } Drupal.CTools.dependent.autoAttach = function() { // Clear active bindings and triggers. for (i in Drupal.CTools.dependent.activeTriggers) { $(Drupal.CTools.dependent.activeTriggers[i]).unbind('change.ctools-dependent'); } Drupal.CTools.dependent.activeTriggers = []; Drupal.CTools.dependent.activeBindings = {}; Drupal.CTools.dependent.bindings = {}; if (!Drupal.settings.CTools) { return; } // Iterate through all relationships for (id in Drupal.settings.CTools.dependent) { // Test to make sure the id even exists; this helps clean up multiple // AJAX calls with multiple forms. // Drupal.CTools.dependent.activeBindings[id] is a boolean, // whether the binding is active or not. Defaults to no. Drupal.CTools.dependent.activeBindings[id] = 0; // Iterate through all possible values for(bind_id in Drupal.settings.CTools.dependent[id].values) { // This creates a backward relationship. The bind_id is the ID // of the element which needs to change in order for the id to hide or become shown. // The id is the ID of the item which will be conditionally hidden or shown. // Here we're setting the bindings for the bind // id to be an empty array if it doesn't already have bindings to it if (!Drupal.CTools.dependent.bindings[bind_id]) { Drupal.CTools.dependent.bindings[bind_id] = []; } // Add this ID Drupal.CTools.dependent.bindings[bind_id].push(id); // Big long if statement. // Drupal.settings.CTools.dependent[id].values[bind_id] holds the possible values if (bind_id.substring(0, 6) == 'radio:') { var trigger_id = "input[name='" + bind_id.substring(6) + "']"; } else { var trigger_id = '#' + bind_id; } Drupal.CTools.dependent.activeTriggers.push(trigger_id); if ($(trigger_id).attr('type') == 'checkbox') { $(trigger_id).siblings('label').addClass('hidden-options'); } var getValue = function(item, trigger) { if ($(trigger).size() == 0) { return null; } if (item.substring(0, 6) == 'radio:') { var val = $(trigger + ':checked').val(); } else { switch ($(trigger).attr('type')) { case 'checkbox': var val = $(trigger).attr('checked') ? true : false; if (val) { $(trigger).siblings('label').removeClass('hidden-options').addClass('expanded-options'); } else { $(trigger).siblings('label').removeClass('expanded-options').addClass('hidden-options'); } break; default: var val = $(trigger).val(); } } return val; } var setChangeTrigger = function(trigger_id, bind_id) { // Triggered when change() is clicked. var changeTrigger = function() { var val = getValue(bind_id, trigger_id); if (val == null) { return; } for (i in Drupal.CTools.dependent.bindings[bind_id]) { var id = Drupal.CTools.dependent.bindings[bind_id][i]; // Fix numerous errors if (typeof id != 'string') { continue; } // This bit had to be rewritten a bit because two properties on the // same set caused the counter to go up and up and up. if (!Drupal.CTools.dependent.activeBindings[id]) { Drupal.CTools.dependent.activeBindings[id] = {}; } if (val != null && Drupal.CTools.dependent.inArray(Drupal.settings.CTools.dependent[id].values[bind_id], val)) { Drupal.CTools.dependent.activeBindings[id][bind_id] = 'bind'; } else { delete Drupal.CTools.dependent.activeBindings[id][bind_id]; } var len = 0; for (i in Drupal.CTools.dependent.activeBindings[id]) { len++; } var object = $('#' + id + '-wrapper'); if (!object.size()) { // Some elements can't use the parent() method or they can // damage things. They are guaranteed to have wrappers but // only if dependent.inc provided them. This check prevents // problems when multiple AJAX calls cause settings to build // up. var $original = $('#' + id); if ($original.is('fieldset') || $original.is('textarea')) { continue; } object = $('#' + id).parent(); } if (Drupal.settings.CTools.dependent[id].type == 'disable') { if (Drupal.settings.CTools.dependent[id].num <= len) { // Show if the element if criteria is matched object.attr('disabled', false); object.addClass('dependent-options'); object.children().attr('disabled', false); } else { // Otherwise hide. Use css rather than hide() because hide() // does not work if the item is already hidden, for example, // in a collapsed fieldset. object.attr('disabled', true); object.children().attr('disabled', true); } } else { if (Drupal.settings.CTools.dependent[id].num <= len) { // Show if the element if criteria is matched object.show(0); object.addClass('dependent-options'); } else { // Otherwise hide. Use css rather than hide() because hide() // does not work if the item is already hidden, for example, // in a collapsed fieldset. object.css('display', 'none'); } } } } $(trigger_id).bind('change.ctools-dependent', function() { // Trigger the internal change function // the attr('id') is used because closures are more confusing changeTrigger(trigger_id, bind_id); }); // Trigger initial reaction changeTrigger(trigger_id, bind_id); } setChangeTrigger(trigger_id, bind_id); } } } Drupal.behaviors.CToolsDependent = { attach: function (context) { Drupal.CTools.dependent.autoAttach(); // Really large sets of fields are too slow with the above method, so this // is a sort of hacked one that's faster but much less flexible. $("select.ctools-master-dependent") .once('ctools-dependent') .bind('change.ctools-dependent', function() { var val = $(this).val(); if (val == 'all') { $('.ctools-dependent-all').show(0); } else { $('.ctools-dependent-all').hide(0); $('.ctools-dependent-' + val).show(0); } }) .trigger('change.ctools-dependent'); } } })(jQuery); ; (function ($) { Drupal.toolbar = Drupal.toolbar || {}; /** * Attach toggling behavior and notify the overlay of the toolbar. */ Drupal.behaviors.toolbar = { attach: function(context) { // Set the initial state of the toolbar. $('#toolbar', context).once('toolbar', Drupal.toolbar.init); // Toggling toolbar drawer. $('#toolbar a.toggle', context).once('toolbar-toggle').click(function(e) { Drupal.toolbar.toggle(); // Allow resize event handlers to recalculate sizes/positions. $(window).triggerHandler('resize'); return false; }); } }; /** * Retrieve last saved cookie settings and set up the initial toolbar state. */ Drupal.toolbar.init = function() { // Retrieve the collapsed status from a stored cookie. var collapsed = $.cookie('Drupal.toolbar.collapsed'); // Expand or collapse the toolbar based on the cookie value. if (collapsed == 1) { Drupal.toolbar.collapse(); } else { Drupal.toolbar.expand(); } }; /** * Collapse the toolbar. */ Drupal.toolbar.collapse = function() { var toggle_text = Drupal.t('Show shortcuts'); $('#toolbar div.toolbar-drawer').addClass('collapsed'); $('#toolbar a.toggle') .removeClass('toggle-active') .attr('title', toggle_text) .html(toggle_text); $('body').removeClass('toolbar-drawer').css('paddingTop', Drupal.toolbar.height()); $.cookie( 'Drupal.toolbar.collapsed', 1, { path: Drupal.settings.basePath, // The cookie should "never" expire. expires: 36500 } ); }; /** * Expand the toolbar. */ Drupal.toolbar.expand = function() { var toggle_text = Drupal.t('Hide shortcuts'); $('#toolbar div.toolbar-drawer').removeClass('collapsed'); $('#toolbar a.toggle') .addClass('toggle-active') .attr('title', toggle_text) .html(toggle_text); $('body').addClass('toolbar-drawer').css('paddingTop', Drupal.toolbar.height()); $.cookie( 'Drupal.toolbar.collapsed', 0, { path: Drupal.settings.basePath, // The cookie should "never" expire. expires: 36500 } ); }; /** * Toggle the toolbar. */ Drupal.toolbar.toggle = function() { if ($('#toolbar div.toolbar-drawer').hasClass('collapsed')) { Drupal.toolbar.expand(); } else { Drupal.toolbar.collapse(); } }; Drupal.toolbar.height = function() { var $toolbar = $('#toolbar'); var height = $toolbar.outerHeight(); // In modern browsers (including IE9), when box-shadow is defined, use the // normal height. var cssBoxShadowValue = $toolbar.css('box-shadow'); var boxShadow = (typeof cssBoxShadowValue !== 'undefined' && cssBoxShadowValue !== 'none'); // In IE8 and below, we use the shadow filter to apply box-shadow styles to // the toolbar. It adds some extra height that we need to remove. if (!boxShadow && /DXImageTransform\.Microsoft\.Shadow/.test($toolbar.css('filter'))) { height -= $toolbar[0].filters.item("DXImageTransform.Microsoft.Shadow").strength; } return height; }; })(jQuery); ;
NROER/drupal-intranet
sites/default/files/js/js_KpSoYDDttoYJZ4QA9FeVWWfEWxhNl3ZbCi3QiZkj2us.js
JavaScript
gpl-2.0
17,659
jQuery( document ).ready( function ( $ ) { var xhr; $( '.job_listings' ).on( 'update_results', function ( event, page, append ) { if ( xhr ) { xhr.abort(); } var data = ''; var target = $( this ); var form = target.find( '.job_filters' ); var showing = target.find( '.showing_jobs' ); var results = target.find( '.job_listings' ); var per_page = target.data( 'per_page' ); var orderby = target.data( 'orderby' ); var order = target.data( 'order' ); if ( append ) { $( '.load_more_jobs', target ).addClass( 'loading' ); } else { $( results ).addClass( 'loading' ); $( 'li.job_listing', results ).css( 'visibility', 'hidden' ); } if ( target.data( 'show_filters' ) ) { var filter_job_type = []; $( ':input[name="filter_job_type[]"]:checked, :input[name="filter_job_type[]"][type="hidden"]', form ).each( function () { filter_job_type.push( $( this ).val() ); } ); var categories = form.find( ':input[name^=search_categories], :input[name^=search_categories]' ).map( function () { return $( this ).val(); } ).get(); var keywords = ''; var location = ''; var $keywords = form.find( ':input[name=search_keywords]' ); var $location = form.find( ':input[name=search_location]' ); // Workaround placeholder scripts if ( $keywords.val() !== $keywords.attr( 'placeholder' ) ) { keywords = $keywords.val(); } if ( $location.val() !== $location.attr( 'placeholder' ) ) { location = $location.val(); } data = { action: 'job_manager_get_listings', search_keywords: keywords, search_location: location, search_categories: categories, filter_job_type: filter_job_type, per_page: per_page, orderby: orderby, order: order, page: page, form_data: form.serialize() }; } else { data = { action: 'job_manager_get_listings', search_categories: target.data( 'categories' ).split( ',' ), search_keywords: target.data( 'keywords' ), search_location: target.data( 'location' ), per_page: per_page, orderby: orderby, order: order, page: page }; } xhr = $.ajax( { type: 'POST', url: job_manager_ajax_filters.ajax_url, data: data, success: function ( response ) { if ( response ) { try { // Get the valid JSON only from the returned string if ( response.indexOf( "<!--WPJM-->" ) >= 0 ) { response = response.split( "<!--WPJM-->" )[ 1 ]; // Strip off before WPJM } if ( response.indexOf( "<!--WPJM_END-->" ) >= 0 ) { response = response.split( "<!--WPJM_END-->" )[ 0 ]; // Strip off anything after WPJM_END } var result = $.parseJSON( response ); if ( result.showing ) { $( showing ).show().html( '' ).append( '<span>' + result.showing + '</span>' + result.showing_links ); } else { $( showing ).hide(); } if ( result.html ) { if ( append ) { $( results ).append( result.html ); } else { $( results ).html( result.html ); } } if ( !result.found_jobs || result.max_num_pages === page ) { $( '.load_more_jobs', target ).hide(); } else { $( '.load_more_jobs', target ).show().data( 'page', page ); } $( results ).removeClass( 'loading' ); $( '.load_more_jobs', target ).removeClass( 'loading' ); $( 'li.job_listing', results ).css( 'visibility', 'visible' ); } catch ( err ) { //console.log( err ); } } } } ); } ); $( '#search_keywords, #search_location, .job_types input, #search_categories' ).change( function () { var target = $( this ).closest( 'div.job_listings' ); target.trigger( 'update_results', [ 1, false ] ); } ); $( '.job_filters' ).each(function() { $( this ).find( '#search_keywords, #search_location, .job_types input, #search_categories' ).eq(0).change(); }); $( '.job_filters' ).on( 'click', '.reset', function () { var target = $( this ).closest( 'div.job_listings' ); var form = $( this ).closest( 'form' ); form.find( ':input[name=search_keywords]' ).val( '' ); form.find( ':input[name=search_location]' ).val( '' ); form.find( ':input[name^=search_categories]' ).val( 0 ); $( ':input[name="filter_job_type[]"]', form ).attr( 'checked', 'checked' ); target.trigger( 'reset' ); target.trigger( 'update_results', [ 1, false ] ); return false; } ); $( '.load_more_jobs' ).click( function () { var target = $( this ).closest( 'div.job_listings' ); var page = $( this ).data( 'page' ); if ( !page ) { page = 1; } else { page = parseInt( page ); } $( this ).data( 'page', ( page + 1 ) ); target.trigger( 'update_results', [ page + 1, true ] ); return false; } ); } );
ecreative-studios/cec
wp-content/plugins/wp-job-manager/assets/js/ajax-filters.js
JavaScript
gpl-2.0
4,757
Drupal.settings.spotlight_settings = Drupal.settings.spotlight_settings || {}; (function ($) { /** * Form behavior for Spotlight */ Drupal.behaviors.panopolySpotlight = { attach: function (context, settings) { if ($('.field-name-field-basic-spotlight-items').length) { var rotation_time = Drupal.settings.spotlight_settings.rotation_time; $('.field-name-field-basic-spotlight-items').tabs().tabs("rotate", rotation_time, true); // $('.field-name-field-basic-spotlight-items').css('height', $('.field-name-field-basic-spotlight-items').height()); // $('.field-name-field-basic-spotlight-items').css('overflow', 'hidden'); } } } /** * Automagically set te height of the Video Widget */ Drupal.behaviors.panopolyWidgetVideo = { attach: function (context, settings) { $('.pane-bundle-video .media-vimeo-outer-wrapper').each(function() { var width = $(this).width(); var height = width / 16 * 9; console.log(width); $(this).css('height', height); $(this).css('width', width); $(this).find('.media-vimeo-preview-wrapper').css('height', height); $(this).find('.media-vimeo-preview-wrapper').css('width', width); $(this).find('iframe.vimeo-player').css('height', height); $(this).find('iframe.vimeo-player').css('width', width); $(window).unbind('resize', Drupal.media_vimeo.resizeEmbeds); }); $('.pane-bundle-video .media-youtube-outer-wrapper').each(function() { var width = $(this).width(); var height = width / 16 * 9; console.log(width); $(this).css('height', height); $(this).css('width', width); $(this).find('.media-youtube-preview-wrapper').css('width', width); $(this).find('.media-youtube-preview-wrapper').css('height', height); $(this).find('iframe.youtube-player').css('width', width); $(this).find('iframe.youtube-player').css('height', height); $(window).unbind('resize', Drupal.media_youtube.resizeEmbeds); }); } } /** * Create responsive magic for Table Widget */ Drupal.behaviors.panopolyWidgetTables = { attach: function (context, settings) { $('table.tablefield', context).each(function() { var table = $(this); // cache table object. var head = table.find('thead th'); var rows = table.find('tbody tr').clone(); // appending afterwards does not break original table. // create new table var newtable = $( '<table class="mobile-table">' + ' <tbody>' + ' </tbody>' + '</table>' ); // cache tbody where we'll be adding data. var newtable_tbody = newtable.find('tbody'); rows.each(function(i) { var cols = $(this).find('td'); var classname = i % 2 ? 'even' : 'odd'; cols.each(function(k) { var new_tr = $('<tr class="' + classname + '"></tr>').appendTo(newtable_tbody); new_tr.append(head.clone().get(k)); new_tr.append($(this)); }); }); $(this).after(newtable); }); } } })(jQuery);
andikasulis/warkop-performance.older
profiles/panopoly/modules/panopoly/panopoly_widgets/panopoly-widgets.js
JavaScript
gpl-2.0
3,136
/* Copyright (C) YOOtheme GmbH, YOOtheme Proprietary Use License (http://www.yootheme.com/license) */ (function(d){var a=function(){};d.extend(a.prototype,{name:"accordionMenu",options:{mode:"default",display:null,collapseall:false,toggler:"span.level1.parent",content:"ul.level2"},initialize:function(a,b){var b=d.extend({},this.options,b),c=a.find(b.toggler);c.each(function(h){var a=d(this),c=a.next(b.content).wrap("<div>").parent();c.data("height",c.height());a.hasClass("active")||h==b.display?c.show():c.hide().css("height",0);a.bind("click",function(){f(h)})});var f=function(a){var a=d(c.get(a)), e=d([]);a.hasClass("active")&&(e=a,a=d([]));b.collapseall&&(e=c.filter(".active"));switch(b.mode){case "slide":a.next().stop().show().animate({height:a.next().data("height")});e.next().stop().animate({height:0},function(){e.next().hide()});break;default:a.next().show().css("height",a.next().data("height")),e.next().hide().css("height",0)}a.addClass("active").parent().addClass("active");e.removeClass("active").parent().removeClass("active")}}});d.fn[a.prototype.name]=function(){var g=arguments,b=g[0]? g[0]:null;return this.each(function(){var c=d(this);if(a.prototype[b]&&c.data(a.prototype.name)&&b!="initialize")c.data(a.prototype.name)[b].apply(c.data(a.prototype.name),Array.prototype.slice.call(g,1));else if(!b||d.isPlainObject(b)){var f=new a;a.prototype.initialize&&f.initialize.apply(f,d.merge([c],g));c.data(a.prototype.name,f)}else d.error("Method "+b+" does not exist on jQuery."+a.name)})}})(jQuery);
rzhamaletdinov/foolsday.ru
wp-content/themes/yoo_bigeasy_wp/warp/js/accordionmenu.js
JavaScript
gpl-2.0
1,526
/** * Copyright (C) 2015 Austin Peterson * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ function GoogleSearch(logger) { //the name of the command. this.name = "Google Search"; //help text to show for this command. this.helpText = "Returns the first result of a Google search."; //usage message. only include the parameters. the command name will be automatically added. this.usageText = "<query>"; //ways to call this command. this.aliases = ['g', 'googlesearch', 'google', 'search', 'askjeeves', 'askgamingg']; } GoogleSearch.prototype.execute = function(context) { if(!context.arguments.length) {return false;} var self = this; var cachedResponse = context.AKP48.cache.getCached(("GoogleSearch"+context.arguments.join(" ")).sha1()); if(cachedResponse) { context.AKP48.client.say(context.channel, cachedResponse); return true; } context.AKP48.getAPI("Google").search(context.arguments.join(" "), "web", function(msg) { var cacheExpire = (Date.now() / 1000 | 0) + 86400; //make cache expire in 1 day context.AKP48.cache.addToCache(("GoogleSearch"+context.arguments.join(" ")).sha1(), msg, cacheExpire); context.AKP48.client.say(context.channel, msg); }); return true; }; module.exports = GoogleSearch;
feildmaster/AKP48
AKP48/Processors/CommandResponders/googlesearch.js
JavaScript
gpl-3.0
1,920
import React from "react"; import PropTypes from "prop-types"; import CartSubTotals from "../container/cartSubTotalContainer"; import CartItems from "./cartItems"; const cartDrawer = ({ productItems, pdpPath, handleRemoveItem, handleCheckout, handleImage, handleLowInventory, handleShowProduct }) => { return ( <div> <div className="cart-drawer-swiper-container"> <div className="cart-drawer-swiper-wrapper"> <div className="cart-drawer-swiper-slide"> <CartSubTotals /> </div> {productItems.map(item => { return ( <div className="cart-drawer-swiper-slide" key={item._id}> <CartItems item={item} pdpPath={pdpPath} handleLowInventory={handleLowInventory} handleImage={handleImage} handleRemoveItem={handleRemoveItem} handleShowProduct={handleShowProduct} /> </div> ); })} </div> </div> <div className="cart-drawer-pagination" /> <div className="row"> <span className="rui btn btn-cta btn-lg btn-block" id="btn-checkout" data-i18n="cartDrawer.checkout" onClick={handleCheckout}> Checkout now </span> </div> </div> ); }; cartDrawer.propTypes = { handleCheckout: PropTypes.func, handleImage: PropTypes.func, handleLowInventory: PropTypes.func, handleRemoveItem: PropTypes.func, handleShowProduct: PropTypes.func, pdpPath: PropTypes.func, productItems: PropTypes.array }; export default cartDrawer;
spestushko/reaction
imports/plugins/core/checkout/client/components/cartDrawer.js
JavaScript
gpl-3.0
1,638
/*! * Express - request * Copyright(c) 2010 TJ Holowaychuk <tj@vision-media.ca> * MIT Licensed */ /** * Module dependencies. */ var http = require('http') , utils = require('./utils') , connect = require('connect') , parse = require('url').parse , mime = require('mime'); /** * Request prototype. */ var req = exports = module.exports = { __proto__: http.IncomingMessage.prototype }; /** * Return request header. * * The `Referrer` header field is special-cased, * both `Referrer` and `Referer` are interchangeable. * * Examples: * * req.get('Content-Type'); * // => "text/plain" * * req.get('content-type'); * // => "text/plain" * * req.get('Something'); * // => undefined * * Aliased as `req.header()`. * * @param {String} name * @return {String} * @api public */ req.get = req.header = function(name){ switch (name = name.toLowerCase()) { case 'referer': case 'referrer': return this.headers.referrer || this.headers.referer; default: return this.headers[name]; } }; /** * Check if the given `type(s)` is acceptable, returning * the best match when true, otherwise `undefined`, in which * case you should respond with 406 "Not Acceptable". * * The `type` value may be a single mime type string * such as "application/json", the extension name * such as "json", a comma-delimted list such as "json, html, text/plain", * or an array `["json", "html", "text/plain"]`. When a list * or array is given the _best_ match, if any is returned. * * Examples: * * // Accept: text/html * req.accepts('html'); * // => "html" * * // Accept: text/*, application/json * req.accepts('html'); * // => "html" * req.accepts('text/html'); * // => "text/html" * req.accepts('json, text'); * // => "json" * req.accepts('application/json'); * // => "application/json" * * // Accept: text/*, application/json * req.accepts('image/png'); * req.accepts('png'); * // => undefined * * // Accept: text/*;q=.5, application/json * req.accepts(['html', 'json']); * req.accepts('html, json'); * // => "json" * * @param {String|Array} type(s) * @return {String} * @api public */ req.accepts = function(type){ return utils.accepts(type, this.get('Accept')); }; /** * Check if the given `charset` is acceptable, * otherwise you should respond with 406 "Not Acceptable". * * @param {String} charset * @return {Boolean} * @api public */ req.acceptsCharset = function(charset){ var accepted = this.acceptedCharsets; return accepted.length ? ~accepted.indexOf(charset) : true; }; /** * Check if the given `lang` is acceptable, * otherwise you should respond with 406 "Not Acceptable". * * @param {String} lang * @return {Boolean} * @api public */ req.acceptsLanguage = function(lang){ var accepted = this.acceptedLanguages; return accepted.length ? ~accepted.indexOf(lang) : true; }; /** * Return an array of Accepted media types * ordered from highest quality to lowest. * * Examples: * * [ { value: 'application/json', * quality: 1, * type: 'application', * subtype: 'json' }, * { value: 'text/html', * quality: 0.5, * type: 'text', * subtype: 'html' } ] * * @return {Array} * @api public */ req.__defineGetter__('accepted', function(){ var accept = this.get('Accept'); return accept ? utils.parseAccept(accept) : []; }); /** * Return an array of Accepted languages * ordered from highest quality to lowest. * * Examples: * * Accept-Language: en;q=.5, en-us * ['en-us', 'en'] * * @return {Array} * @api public */ req.__defineGetter__('acceptedLanguages', function(){ var accept = this.get('Accept-Language'); return accept ? utils .parseQuality(accept) .map(function(obj){ return obj.value; }) : []; }); /** * Return an array of Accepted charsets * ordered from highest quality to lowest. * * Examples: * * Accept-Charset: iso-8859-5;q=.2, unicode-1-1;q=0.8 * ['unicode-1-1', 'iso-8859-5'] * * @return {Array} * @api public */ req.__defineGetter__('acceptedCharsets', function(){ var accept = this.get('Accept-Charset'); return accept ? utils .parseQuality(accept) .map(function(obj){ return obj.value; }) : []; }); /** * Return the value of param `name` when present or `defaultValue`. * * - Checks body params, ex: id=12, {"id":12} * - Checks route placeholders, ex: _/user/:id_ * - Checks query string params, ex: ?id=12 * * To utilize request bodies, `req.body` * should be an object. This can be done by using * the `connect.bodyParser()` middleware. * * @param {String} name * @param {Mixed} defaultValue * @return {String} * @api public */ req.param = function(name, defaultValue){ // req.body if (this.body && undefined !== this.body[name]) return this.body[name]; // route params if (this.params && this.params.hasOwnProperty(name) && undefined !== this.params[name]) { return this.params[name]; } // query-string if (undefined !== this.query[name]) return this.query[name]; return defaultValue; }; /** * Check if the incoming request contains the "Content-Type" * header field, and it contains the give mime `type`. * * Examples: * * // With Content-Type: text/html; charset=utf-8 * req.is('html'); * req.is('text/html'); * req.is('text/*'); * // => true * * // When Content-Type is application/json * req.is('json'); * req.is('application/json'); * req.is('application/*'); * // => true * * req.is('html'); * // => false * * Now within our route callbacks, we can use to to assert content types * such as "image/jpeg", "image/png", etc. * * app.post('/image/upload', function(req, res, next){ * if (req.is('image/*')) { * // do something * } else { * next(); * } * }); * * @param {String} type * @return {Boolean} * @api public */ req.is = function(type){ var ct = this.get('Content-Type'); if (!ct) return false; ct = ct.split(';')[0]; if (!~type.indexOf('/')) type = mime.lookup(type); if (~type.indexOf('*')) { type = type.split('/'); ct = ct.split('/'); if ('*' == type[0] && type[1] == ct[1]) return true; if ('*' == type[1] && type[0] == ct[0]) return true; return false; } return !! ~ct.indexOf(type); }; /** * Return the protocol string "http" or "https" * when requested with TLS. When the "trust proxy" * setting is enabled the "X-Forwarded-Proto" header * field will be trusted. If you're running behind * a reverse proxy that supplies https for you this * may be enabled. * * @return {String} * @api public */ req.__defineGetter__('protocol', function(){ var trustProxy = this.app.settings['trust proxy']; return this.connection.encrypted ? 'https' : trustProxy ? (this.get('X-Forwarded-Proto') || 'http') : 'http'; }); /** * Short-hand for: * * req.protocol == 'https' * * @return {Boolean} * @api public */ req.__defineGetter__('secure', function(){ return 'https' == this.protocol; }); /** * When "trust proxy" is `true`, parse * the "X-Forwarded-For" ip address list. * * For example if the value were "client, proxy1, proxy2" * you would receive the array `["proxy2", "proxy1", "client"]` * where "proxy2" is the furthest down-stream. * * @return {Array} * @api public */ req.__defineGetter__('ips', function(){ var val = this.get('X-Forwarded-For'); return val ? val.split(/ *, */).reverse() : []; }); /** * Return subdomains as an array. * * For example "tobi.ferrets.example.com" * would provide `["ferrets", "tobi"]`. * * @return {Array} * @api public */ req.__defineGetter__('subdomains', function(){ return this.get('Host') .split('.') .slice(0, -2) .reverse(); }); /** * Short-hand for `url.parse(req.url).pathname`. * * @return {String} * @api public */ req.__defineGetter__('path', function(){ return parse(this.url).pathname; }); /** * Check if the request is fresh, aka * Last-Modified and/or the ETag * still match. * * @return {Boolean} * @api public */ req.__defineGetter__('fresh', function(){ return ! this.stale; }); /** * Check if the request is stale, aka * "Last-Modified" and / or the "ETag" for the * resource has changed. * * @return {Boolean} * @api public */ req.__defineGetter__('stale', function(){ return connect.utils.modified(this, this.res); }); /** * Check if the request was an _XMLHttpRequest_. * * @return {Boolean} * @api public */ req.__defineGetter__('xhr', function(){ var val = this.get('X-Requested-With') || ''; return 'xmlhttprequest' == val.toLowerCase(); });
rj45/synphony
node_modules/express/lib/request.js
JavaScript
gpl-3.0
8,979
import {fragmentToQL} from 'relax-framework'; import actionTypes from './types'; import request from '../helpers/request'; import stringifyFields from '../helpers/stringify-fields'; const stringifiableFields = ['properties', 'data']; export function getSchema (fragments, slug) { return (dispatch) => ( request({ dispatch, type: actionTypes.getSchema, query: ` query schema ($slug: String!) { schema (slug: $slug) { ${fragmentToQL(fragments.schema)} } } `, variables: { slug } }) ); } export function updateSchema (fragments, data) { return (dispatch) => ( request({ dispatch, type: actionTypes.updateSchema, query: ` mutation updateSchema ($data: SchemaInput!) { updateSchema (data: $data) { ${fragmentToQL(fragments.schema)} } } `, variables: { data: stringifyFields(data, stringifiableFields) } }) ); } export function addSchema (fragments, data) { return (dispatch) => ( request({ dispatch, type: actionTypes.addSchema, query: ` mutation addSchema ($data: SchemaInput!) { addSchema (data: $data) { ${fragmentToQL(fragments.schema)} } } `, variables: { data: stringifyFields(data, stringifiableFields) } }) ); } export function restoreSchema (fragments, schemaId, version) { return (dispatch) => ( request({ dispatch, type: actionTypes.restoreSchema, query: ` mutation restoreSchema ($schemaId: ID!, $version: Int!) { restoreSchema (schemaId: $schemaId, version: $version) { ${fragmentToQL(fragments.schema)} } } `, variables: { schemaId, version } }) ); } export function validateSchemaSlug ({slug, schemaId}) { return (dispatch) => ( request({ dispatch, type: actionTypes.validateSchemaSlug, query: ` query validateSchemaSlug ($slug: String!, $schemaId: ID) { validateSchemaSlug (slug: $slug, schemaId: $schemaId) } `, variables: { slug, schemaId } }) ); } export function changeSchemaFields (values) { return { type: actionTypes.changeSchemaFields, values }; } export function changeSchemaToDefault () { return { type: actionTypes.changeSchemaToDefault }; }
ABaldwinHunter/relax-classic
lib/client/actions/schema.js
JavaScript
gpl-3.0
2,507
"use strict"; tutao.provide('tutao.tutanota.ctrl.MailFolderViewModel'); /** * A mail folder including mails. * @param {tutao.entity.tutanota.MailFolder} mailFolder The persistent mailFolder. * @param {?tutao.tutanota.ctrl.MailFolderViewModel} parentFolder The parent folder. Must be null if this is a system folder. */ tutao.tutanota.ctrl.MailFolderViewModel = function(mailFolder, parentFolder) { tutao.util.FunctionUtils.bindPrototypeMethodsToThis(this); this._eventTracker = null; this._mailFolder = mailFolder; this._mailFolderName = ko.observable(""); this._loadedMails = ko.observableArray(); this._lastSelectedMails = ko.observableArray(); this._selectedMails = ko.observableArray(); this.loading = ko.observable(false); this.moreAvailable = ko.observable(true); this.parentFolder = ko.observable(parentFolder); this.subFolders = ko.observableArray([]); this._loadedMails.subscribe(function(){ this._updateNumberOfUnreadMails(); }, this); }; tutao.tutanota.ctrl.MailFolderViewModel.prototype.loadMoreMails = function() { var self = this; if (this.loading() || !this.moreAvailable()) { return Promise.resolve(); } var stepRangeCount = (tutao.tutanota.util.ClientDetector.isMobileDevice()) ? 25 : 200; var startId = (this._loadedMails().length > 0) ? this._loadedMails()[this._loadedMails().length - 1].getId()[1] : tutao.rest.EntityRestInterface.GENERATED_MAX_ID; this.loading(true); return tutao.entity.tutanota.Mail.loadRange(self._mailFolder.getMails(), startId, stepRangeCount, true).then(function(mails) { if (mails.length < stepRangeCount) { self.moreAvailable(false); } self._loadedMails.splice.apply(self._loadedMails, [self._loadedMails().length, 0].concat(mails)); }).lastly(function() { self.loading(false); if (!self._eventTracker && tutao.locator.userController.isInternalUserLoggedIn()) { self._eventTracker = new tutao.event.PushListEventTracker(tutao.entity.tutanota.Mail, self._mailFolder.getMails(), "Mail"); self._eventTracker.addObserver(self.updateOnNewMails); var highestMailId = (self._loadedMails().length > 0) ? self._loadedMails()[0].getId()[1] : tutao.rest.EntityRestInterface.GENERATED_MIN_ID; self._eventTracker.observeList(highestMailId); } }); }; /** * This method gets invoked if new mails have been received from the server. * @param {Array.<Mail>} mails The mails that are new. */ tutao.tutanota.ctrl.MailFolderViewModel.prototype.updateOnNewMails = function(mails) { var unread = false; for (var i = 0; i < mails.length; i++) { // find the correct position for the email in the list var found = false; for (var a=0; a<this._loadedMails().length; a++) { if (tutao.rest.EntityRestInterface.firstBiggerThanSecond(mails[i].getId()[1], this._loadedMails()[a].getId()[1])) { this._loadedMails.splice(a, 0, mails[i]); found = true; break; } } if (!found) { this._loadedMails.push(mails[i]); } if (mails[i].getUnread()) { unread = true; } } if (this._mailFolder.getFolderType() == tutao.entity.tutanota.TutanotaConstants.MAIL_FOLDER_TYPE_INBOX && unread) { tutao.locator.notification.add(tutao.lang("newMails_msg")); } }; /** * Notifies the MailFolderListViewModel to update the total number of unread mails. */ tutao.tutanota.ctrl.MailFolderViewModel.prototype._updateNumberOfUnreadMails = function() { if (this.isInboxFolder()){ tutao.locator.mailFolderListViewModel.updateNumberOfUnreadMails(); } }; /** * Returns the number of all loaded unread mails for this folder including all subfolder. */ tutao.tutanota.ctrl.MailFolderViewModel.prototype.getNumberOfUnreadMails = function() { var unreadMails = 0; for (var i=0; i<this._loadedMails().length; i++) { if (this._loadedMails()[i].getUnread()) { unreadMails++; } } var currentSubFolders = this.subFolders(); for(var j=0; j<currentSubFolders.length;j++){ unreadMails = unreadMails + currentSubFolders[j].getNumberOfUnreadMails(); } return unreadMails; }; /** * Selects the given mails. * @return Promise */ tutao.tutanota.ctrl.MailFolderViewModel.prototype.selectMail = function(mail) { var self = this; if (mail.getUnread()) { mail.setUnread(false); mail.update().caught(tutao.NotFoundError, function(e) { // avoid exception for missing sync self.removeMails([mail]); }); this._updateNumberOfUnreadMails(); } this._selectedMails([mail]); this._lastSelectedMails([mail]); return tutao.locator.mailViewModel.showMail(mail); }; /** * Selects the last selected mails if any. If there are no last selected mails, all mails are unselected. */ tutao.tutanota.ctrl.MailFolderViewModel.prototype.selectPreviouslySelectedMails = function() { if (this._lastSelectedMails().length > 0) { this._selectedMails(this._lastSelectedMails()); tutao.locator.mailViewModel.showMail(this._selectedMails()[0]); } else { this.unselectAllMails(); } }; /** * Provides the information if a mail is selected. * @return {boolean} True if a mail is selected, false otherwise. */ tutao.tutanota.ctrl.MailFolderViewModel.prototype.isMailSelected = function() { return (this._selectedMails().length != 0); }; /** * Shows the previous mail in the list. */ tutao.tutanota.ctrl.MailFolderViewModel.prototype.selectPreviousMail = function() { if (!this.isMailSelected()) { return; } for (var i=1; i<this._loadedMails().length; i++) { if (this._loadedMails()[i] == this._selectedMails()[0]) { this.selectMail(this._loadedMails()[i - 1]); break; } } }; /** * Shows the next mail in the list. */ tutao.tutanota.ctrl.MailFolderViewModel.prototype.selectNextMail = function() { if (!this.isMailSelected()) { return; } for (var i=0; i<this._loadedMails().length - 1; i++) { if (this._loadedMails()[i] == this._selectedMails()[0]) { this.selectMail(this._loadedMails()[i + 1]); break; } } }; /** * Returns true if the first mail in the list is selected, false otherwise. * @return {bool} True if the last first in the list is selected, false otherwise. */ tutao.tutanota.ctrl.MailFolderViewModel.prototype.isFirstMailSelected = function() { return this.isMailSelected() && this._loadedMails()[0] == this._selectedMails()[0]; }; /** * Returns true if the last mail in the list is selected, false otherwise. * @return {bool} True if the last mail in the list is selected, false otherwise. */ tutao.tutanota.ctrl.MailFolderViewModel.prototype.isLastMailSelected = function() { return this.isMailSelected() && this._loadedMails()[this._loadedMails().length - 1] == this._selectedMails()[0]; }; tutao.tutanota.ctrl.MailFolderViewModel.prototype.getSelectedMailIndex = function() { if (!this.isMailSelected()) { return 0; } for (var i=0; i<this._loadedMails().length; i++) { if (this._loadedMails()[i] == this._selectedMails()[0]) { return i; } } return 0; }; tutao.tutanota.ctrl.MailFolderViewModel.prototype.getLoadedMails = function() { return this._loadedMails(); }; /** * Called when the folder was selected to show its mails. * @return {Promise} When finished. */ tutao.tutanota.ctrl.MailFolderViewModel.prototype.selected = function() { if (this._loadedMails().length == 0) { tutao.locator.mailViewModel.hideMail(); return this.loadMoreMails(); } else { if (this._selectedMails().length > 0) { tutao.locator.mailViewModel.showMail(this._selectedMails()[0]); } else { this.selectPreviouslySelectedMails(); } return Promise.resolve(); } }; /** * Provides the information if the given mail is selected. * @param {tutao.entity.tutanota.Mail} mail The mail to check * @return {bool} True if the mail is selected, false otherwise. */ tutao.tutanota.ctrl.MailFolderViewModel.prototype.isSelectedMail = function(mail) { return this._selectedMails.indexOf(mail) >= 0; }; /** * Unselects all mails. */ tutao.tutanota.ctrl.MailFolderViewModel.prototype.unselectAllMails = function() { tutao.locator.mailViewModel.hideMail(); this._selectedMails([]); // do not clear _lastSelectedMails here }; /** * Deltes all the given mails. Updates the mail list view accordingly. * @param {Array.<tutao.entity.tutanota.Mail>} mails The mails to delete finally. */ tutao.tutanota.ctrl.MailFolderViewModel.prototype.finallyDeleteMails = function(mails) { var self = this; var service = new tutao.entity.tutanota.DeleteMailData(); for (var i=0; i<mails.length; i++) { service.getMails().push(mails[i].getId()); } return service.erase({}, tutao.entity.EntityHelper.createAuthHeaders()).then(function(deleteMailReturn) { self.removeMails(mails); }); }; /** * Removes the given mails from the list and hides it if it is visible in the mail view. Selects the next mail in the list, if any. * @param {Array.<tutao.entity.tutanota.Mail>} mails The mails to remove. */ tutao.tutanota.ctrl.MailFolderViewModel.prototype.removeMails = function(mails) { var selectedMailIndex = -1; for (var i=0; i<mails.length; i++) { if (this.isSelectedMail(mails[i])) { selectedMailIndex = this.getSelectedMailIndex(); this._selectedMails.remove(mails[i]); tutao.locator.mailViewModel.hideMail(); } this._lastSelectedMails.remove(mails[i]); this._loadedMails.remove(mails[i]); } // select the next mail if (selectedMailIndex != -1) { selectedMailIndex = Math.min(selectedMailIndex, this._loadedMails().length - 1); } if (selectedMailIndex != -1) { this.selectMail(this._loadedMails()[selectedMailIndex]); } }; /** * Provides the folder type of this folder. * @return {string} One of tutao.entity.tutanota.TutanotaConstants.MAIL_FOLDER_TYPE_*. */ tutao.tutanota.ctrl.MailFolderViewModel.prototype.getFolderType = function() { return this._mailFolder.getFolderType(); }; /** * Provides the mail list id of this folder. * @return {string} The list id. */ tutao.tutanota.ctrl.MailFolderViewModel.prototype.getMailListId = function() { return this._mailFolder.getMails(); }; /** * Provides the mail folder id. * @return {Array.<string, string>} The mail folder id. */ tutao.tutanota.ctrl.MailFolderViewModel.prototype._getMailFolderId = function() { return this._mailFolder.getId(); }; /** * Provides the sub folder list id of this folder. * @return {string} The list id. */ tutao.tutanota.ctrl.MailFolderViewModel.prototype._getSubFolderListId = function() { return this._mailFolder.getSubFolders(); }; /** * Provides the name of the given folder. * @return {string} The name of the folder. */ tutao.tutanota.ctrl.MailFolderViewModel.prototype.getName = function() { if ( this._mailFolderName() == ""){ this._updateName(); } return this._mailFolderName(); }; /** * Provides the name of the given folder. * @return {string} The name of the folder. */ tutao.tutanota.ctrl.MailFolderViewModel.prototype._updateName = function() { if (this._mailFolder.getFolderType() == tutao.entity.tutanota.TutanotaConstants.MAIL_FOLDER_TYPE_CUSTOM) { this._mailFolderName(this._mailFolder.getName()); } else if (this._mailFolder.getFolderType() == tutao.entity.tutanota.TutanotaConstants.MAIL_FOLDER_TYPE_INBOX) { this._mailFolderName(tutao.lang("received_action")); } else if (this._mailFolder.getFolderType() == tutao.entity.tutanota.TutanotaConstants.MAIL_FOLDER_TYPE_SENT) { this._mailFolderName(tutao.lang("sent_action")); } else if (this._mailFolder.getFolderType() == tutao.entity.tutanota.TutanotaConstants.MAIL_FOLDER_TYPE_TRASH) { this._mailFolderName(tutao.lang("trash_action")); } else if (this._mailFolder.getFolderType() == tutao.entity.tutanota.TutanotaConstants.MAIL_FOLDER_TYPE_ARCHIVE) { this._mailFolderName(tutao.lang("archive_action")); }else{ throw new Error("No text id for tag"); } }; /** * Provides the tooltip for the given folder. * @return {string} The tooltip for the folder. */ tutao.tutanota.ctrl.MailFolderViewModel.prototype.getTooltipTextId = function() { if (this._mailFolder.getFolderType() == tutao.entity.tutanota.TutanotaConstants.MAIL_FOLDER_TYPE_INBOX) { return "receivedMails_alt"; } else if (this._mailFolder.getFolderType() == tutao.entity.tutanota.TutanotaConstants.MAIL_FOLDER_TYPE_SENT) { return "sentMails_alt"; } else if (this._mailFolder.getFolderType() == tutao.entity.tutanota.TutanotaConstants.MAIL_FOLDER_TYPE_TRASH) { return "trashedMails_alt"; } else if (this._mailFolder.getFolderType() == tutao.entity.tutanota.TutanotaConstants.MAIL_FOLDER_TYPE_ARCHIVE) { return "archivedMails_alt"; } else { return null; } }; /** * Provides the icon id for the given folder. * @return {string} The icon id for the folder. */ tutao.tutanota.ctrl.MailFolderViewModel.prototype.getIconId = function() { if (this._mailFolder.getFolderType() == tutao.entity.tutanota.TutanotaConstants.MAIL_FOLDER_TYPE_INBOX) { return "inbox"; } else if (this._mailFolder.getFolderType() == tutao.entity.tutanota.TutanotaConstants.MAIL_FOLDER_TYPE_SENT) { return "send"; } else if (this._mailFolder.getFolderType() == tutao.entity.tutanota.TutanotaConstants.MAIL_FOLDER_TYPE_TRASH) { return "trash"; } else if (this._mailFolder.getFolderType() == tutao.entity.tutanota.TutanotaConstants.MAIL_FOLDER_TYPE_ARCHIVE) { return "file"; } else { return "folder"; } }; /** * Provides the folder names of all sub-folders of this folder. * @returns {Array.<string>} The folder names. */ tutao.tutanota.ctrl.MailFolderViewModel.prototype.getSubFolderNames = function() { var folders = this.subFolders(); var folderNames = []; for (var i=0; i<folders.length; i++) { folderNames.push(folders[i].getName()); } return folderNames; }; tutao.tutanota.ctrl.MailFolderViewModel.prototype.createSubFolder = function() { var self = this; tutao.locator.folderNameDialogViewModel.showDialog("folderNameCreate_label", "", self.getSubFolderNames()).then(function(folderName) { if (folderName) { tutao.entity.EntityHelper.getListKey(self._getSubFolderListId()).then(function(subFolderListKey) { var createService = new tutao.entity.tutanota.CreateMailFolderData(); createService.setFolderName(folderName); createService.setParentFolder(self._getMailFolderId()); createService.setListEncSessionKey(tutao.locator.aesCrypter.encryptKey(subFolderListKey, createService.getEntityHelper().getSessionKey())); createService.setup({}, null).then(function(newFolderReturn){ self._loadSubFolder(newFolderReturn.getNewFolder()); }); }); } }); }; tutao.tutanota.ctrl.MailFolderViewModel.prototype.loadSubFolders = function() { var self = this; return tutao.rest.EntityRestInterface.loadAll(tutao.entity.tutanota.MailFolder, self._getSubFolderListId(), tutao.rest.EntityRestInterface.GENERATED_MIN_ID).then(function(loadedSubFolders) { return Promise.map(loadedSubFolders, function(loadedSubFolder) { return new tutao.tutanota.ctrl.MailFolderViewModel(loadedSubFolder, self); }).then(function(createdSubFolders) { // sort the custom folders by name createdSubFolders.sort(tutao.tutanota.ctrl.MailFolderViewModel._compareFolders); self.subFolders(createdSubFolders); }); }); }; tutao.tutanota.ctrl.MailFolderViewModel.prototype._loadSubFolder = function(subFolderId) { var self = this; return tutao.entity.tutanota.MailFolder.load(subFolderId).then(function(subFolder) { var newSubFolder = new tutao.tutanota.ctrl.MailFolderViewModel(subFolder, self); self.subFolders.push(newSubFolder); self.sortFolderNames(); }); }; /** * Deletes the given subfolder. * @param {tutao.tutanota.ctrl.MailFolderViewModel} subFolder The subfolder. * @returns {Promise} When finished. */ tutao.tutanota.ctrl.MailFolderViewModel.prototype._removeSubFolder = function(subFolder) { var self = this; var deleteService = new tutao.entity.tutanota.DeleteMailFolderData; deleteService.getFolders().push(subFolder._getMailFolderId()); return deleteService.erase({}, null).then(function(){ self.subFolders.remove(subFolder); }); }; tutao.tutanota.ctrl.MailFolderViewModel.prototype.rename = function() { var self = this; tutao.locator.folderNameDialogViewModel.showDialog("folderNameRename_label", self.getName(), self.parentFolder().getSubFolderNames()).then(function(newName) { if (newName) { self._mailFolder.setName(newName); self._mailFolder.update().then(function(){ self._updateName(); if (self.parentFolder()){ self.parentFolder().sortFolderNames(); } }); } }); }; /** * Moves a list of mails from this folder to the given target folder. * @param {tutao.tutanota.ctrl.MailFolderViewModel} targetMailFolder The target folder. * @param {Array.<tutao.entity.tutanota.Mail>} mails The mails to move. * @return {Promise} When finished. */ tutao.tutanota.ctrl.MailFolderViewModel.prototype.move = function(targetMailFolder, mails) { var sourceFolder = this; if (sourceFolder.getMailListId() == targetMailFolder.getMailListId()) { // source and target folder are the same return Promise.resolve(); } var data = new tutao.entity.tutanota.MoveMailData(); data.setTargetFolder(targetMailFolder._getMailFolderId()); for(var i=0; i<mails.length; i++){ data.getMails().push(mails[i].getId()); } return data.setup({}, null).then(function() { sourceFolder.removeMails(mails); }).caught(tutao.NotFoundError, function(e) { // avoid exception for missing sync sourceFolder.removeMails(mails); }); }; /** * Delete this folder. * @param {bool} confirm True if the user has to confirm the delete, false otherwise. */ tutao.tutanota.ctrl.MailFolderViewModel.prototype.deleteFolder = function(confirm) { var promise = null; if (confirm && this.isTrashFolder()) { var message = null; if (this.isCustomFolder()) { message = "confirmDeleteTrashCustomFolder_msg"; } else { message = "confirmDeleteTrashFolder_msg"; } promise = tutao.tutanota.gui.confirm(tutao.lang(message, { "{1}": this.getName() })); } else { promise = Promise.resolve(true); } var self = this; return promise.then(function(confirmed) { if (confirmed) { // we want to delete all mails in the trash, not only the visible ones, so load them now. load reverse to avoid caching errors return tutao.rest.EntityRestInterface.loadAllReverse(tutao.entity.tutanota.Mail, self.getMailListId()).then(function(allMails) { if (self.isTrashFolder()){ return self.finallyDeleteMails(allMails); } else { // move content to trash return self.move(tutao.locator.mailFolderListViewModel.getSystemFolder(tutao.entity.tutanota.TutanotaConstants.MAIL_FOLDER_TYPE_TRASH), allMails); } }).then(function(){ // Delete subfolders var subFolderList = self.subFolders(); return Promise.each(subFolderList, function(subFolder) { return subFolder.deleteFolder(false); }).then(function() { // Delete folder instance and remove from parent if (self.isCustomFolder()){ return self.parentFolder()._removeSubFolder(self); } else { return Promise.resolve(); } }); }); } else { return Promise.resolve(); } }); }; tutao.tutanota.ctrl.MailFolderViewModel.prototype.sortFolderNames = function() { this.subFolders.sort(tutao.tutanota.ctrl.MailFolderViewModel._compareFolders); }; tutao.tutanota.ctrl.MailFolderViewModel.prototype.isTrashFolder = function(){ if ( this.parentFolder() ){ return this.parentFolder().isTrashFolder(); }else{ return this.getFolderType() == tutao.entity.tutanota.TutanotaConstants.MAIL_FOLDER_TYPE_TRASH; } }; tutao.tutanota.ctrl.MailFolderViewModel.prototype.isInboxFolder = function(){ if ( this.parentFolder() ){ return this.parentFolder().isInboxFolder(); }else{ return this.getFolderType() == tutao.entity.tutanota.TutanotaConstants.MAIL_FOLDER_TYPE_INBOX; } }; tutao.tutanota.ctrl.MailFolderViewModel.prototype.isArchiveFolder = function(){ if (this.parentFolder()){ return this.parentFolder().isArchiveFolder(); }else{ return this.getFolderType() == tutao.entity.tutanota.TutanotaConstants.MAIL_FOLDER_TYPE_ARCHIVE; } }; tutao.tutanota.ctrl.MailFolderViewModel.prototype.isCustomFolder = function(){ return this.getFolderType() == tutao.entity.tutanota.TutanotaConstants.MAIL_FOLDER_TYPE_CUSTOM; }; tutao.tutanota.ctrl.MailFolderViewModel._compareFolders = function(a, b){ return a.getName().localeCompare(b.getName()); };
elninosi/tutanota
web/js/ctrl/MailFolderViewModel.js
JavaScript
gpl-3.0
22,136
// This file is part of Moodle - http://moodle.org/ // // Moodle is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Moodle is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Moodle. If not, see <http://www.gnu.org/licenses/>. /** * Display an embedded form, it is only loaded and reloaded inside its container * * Example: * import DynamicForm from 'core_form/dynamicform'; * * const dynamicForm = new DynamicForm(document.querySelector('#mycontainer', 'pluginname\\form\\formname'); * dynamicForm.addEventListener(dynamicForm.events.FORM_SUBMITTED, e => { * e.preventDefault(); * window.console.log(e.detail); * dynamicForm.container.innerHTML = 'Thank you, your form is submitted!'; * }); * dynamicForm.load(); * * See also https://docs.moodle.org/dev/Modal_and_AJAX_forms * * @module core_form/dynamicform * @copyright 2019 Marina Glancy * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ import * as FormChangeChecker from 'core_form/changechecker'; import * as FormEvents from 'core_form/events'; import Ajax from 'core/ajax'; import Fragment from 'core/fragment'; import Notification from 'core/notification'; import Pending from 'core/pending'; import Templates from 'core/templates'; import {get_strings as getStrings} from 'core/str'; /** * @class core_form/dynamicform */ export default class DynamicForm { /** * Various events that can be observed. * * @type {Object} */ events = { // Form was successfully submitted - the response is passed to the event listener. // Cancellable (in order to prevent default behavior to clear the container). FORM_SUBMITTED: 'core_form_dynamicform_formsubmitted', // Cancel button was pressed. // Cancellable (in order to prevent default behavior to clear the container). FORM_CANCELLED: 'core_form_dynamicform_formcancelled', // User attempted to submit the form but there was client-side validation error. CLIENT_VALIDATION_ERROR: 'core_form_dynamicform_clientvalidationerror', // User attempted to submit the form but server returned validation error. SERVER_VALIDATION_ERROR: 'core_form_dynamicform_validationerror', // Error occurred while performing request to the server. // Cancellable (by default calls Notification.exception). ERROR: 'core_form_dynamicform_error', // Right after user pressed no-submit button, // listen to this event if you want to add JS validation or processing for no-submit button. // Cancellable. NOSUBMIT_BUTTON_PRESSED: 'core_form_dynamicform_nosubmitbutton', // Right after user pressed submit button, // listen to this event if you want to add additional JS validation or confirmation dialog. // Cancellable. SUBMIT_BUTTON_PRESSED: 'core_form_dynamicform_submitbutton', // Right after user pressed cancel button, // listen to this event if you want to add confirmation dialog. // Cancellable. CANCEL_BUTTON_PRESSED: 'core_form_dynamicform_cancelbutton', }; /** * Constructor * * Creates an instance * * @param {Element} container - the parent element for the form * @param {string} formClass full name of the php class that extends \core_form\modal , must be in autoloaded location */ constructor(container, formClass) { this.formClass = formClass; this.container = container; // Ensure strings required for shortforms are always available. getStrings([ {key: 'collapseall', component: 'moodle'}, {key: 'expandall', component: 'moodle'} ]).catch(Notification.exception); // Register delegated events handlers in vanilla JS. this.container.addEventListener('click', e => { if (e.target.matches('form input[type=submit][data-cancel]')) { e.preventDefault(); const event = this.trigger(this.events.CANCEL_BUTTON_PRESSED, e.target); if (!event.defaultPrevented) { this.processCancelButton(); } } else if (e.target.matches('form input[type=submit][data-no-submit="1"]')) { e.preventDefault(); const event = this.trigger(this.events.NOSUBMIT_BUTTON_PRESSED, e.target); if (!event.defaultPrevented) { this.processNoSubmitButton(e.target); } } }); this.container.addEventListener('submit', e => { if (e.target.matches('form')) { e.preventDefault(); const event = this.trigger(this.events.SUBMIT_BUTTON_PRESSED); if (!event.defaultPrevented) { this.submitFormAjax(); } } }); } /** * Loads the form via AJAX and shows it inside a given container * * @param {Object} args * @return {Promise} * @public */ load(args = null) { const formData = new URLSearchParams(Object.entries(args || {})); const pendingPromise = new Pending('core_form/dynamicform:load'); return this.getBody(formData.toString()) .then((resp) => this.updateForm(resp)) .then(pendingPromise.resolve); } /** * Triggers a custom event * * @private * @param {String} eventName * @param {*} detail * @param {Boolean} cancelable * @return {CustomEvent<unknown>} */ trigger(eventName, detail = null, cancelable = true) { const e = new CustomEvent(eventName, {detail, cancelable}); this.container.dispatchEvent(e); return e; } /** * Add listener for an event * * Example: * const dynamicForm = new DynamicForm(...); * dynamicForm.addEventListener(dynamicForm.events.FORM_SUBMITTED, e => { * e.preventDefault(); * window.console.log(e.detail); * dynamicForm.container.innerHTML = 'Thank you, your form is submitted!'; * }); */ addEventListener(...args) { this.container.addEventListener(...args); } /** * Get form body * * @param {String} formDataString form data in format of a query string * @private * @return {Promise} */ getBody(formDataString) { return Ajax.call([{ methodname: 'core_form_dynamic_form', args: { formdata: formDataString, form: this.formClass, } }])[0] .then(response => { return {html: response.html, js: Fragment.processCollectedJavascript(response.javascript)}; }); } /** * On form submit * * @param {*} response Response received from the form's "process" method */ onSubmitSuccess(response) { const event = this.trigger(this.events.FORM_SUBMITTED, response); if (event.defaultPrevented) { return; } // Default implementation is to remove the form. Event listener should either remove or reload the form // since its contents is no longer correct. For example, if an element was created as a result of // form submission, the "id" in the form would be still zero. Also the server-side validation // errors from the previous submission may still be present. this.container.innerHTML = ''; } /** * On exception during form processing * * @private * @param {Object} exception */ onSubmitError(exception) { const event = this.trigger(this.events.ERROR, exception); if (event.defaultPrevented) { return; } Notification.exception(exception); } /** * Click on a "submit" button that is marked in the form as registerNoSubmitButton() * * @method submitButtonPressed * @param {Element} button that was pressed * @fires event:formSubmittedByJavascript */ processNoSubmitButton(button) { const pendingPromise = new Pending('core_form/dynamicform:nosubmit'); const form = this.getFormNode(); const formData = new URLSearchParams([...(new FormData(form)).entries()]); formData.append(button.getAttribute('name'), button.getAttribute('value')); FormEvents.notifyFormSubmittedByJavascript(form, true); // Add the button name to the form data and submit it. this.disableButtons(); this.getBody(formData.toString()) .then(this.updateForm) .then(pendingPromise.resolve) .catch(this.onSubmitError); } /** * Get the form node from the Dialogue. * * @returns {HTMLFormElement} */ getFormNode() { return this.container.querySelector('form'); } /** * Notifies listeners that form dirty state should be reset. * * @fires event:formSubmittedByJavascript */ notifyResetFormChanges() { FormEvents.notifyFormSubmittedByJavascript(this.getFormNode(), true); FormChangeChecker.resetFormDirtyState(this.getFormNode()); } /** * Click on a "cancel" button */ processCancelButton() { // Notify listeners that the form is about to be submitted (this will reset atto autosave). this.notifyResetFormChanges(); const event = this.trigger(this.events.FORM_CANCELLED); if (!event.defaultPrevented) { // By default removes the form from the DOM. this.container.innerHTML = ''; } } /** * Update form contents * * @param {string} html * @param {string} js * @returns {Promise} */ updateForm({html, js}) { return Templates.replaceNodeContents(this.container, html, js); } /** * Validate form elements * @return {Boolean} Whether client-side validation has passed, false if there are errors * @fires event:formSubmittedByJavascript */ validateElements() { // Notify listeners that the form is about to be submitted (this will reset atto autosave). FormEvents.notifyFormSubmittedByJavascript(this.getFormNode()); // Now the change events have run, see if there are any "invalid" form fields. const invalid = [...this.container.querySelectorAll('[aria-invalid="true"], .error')]; // If we found invalid fields, focus on the first one and do not submit via ajax. if (invalid.length) { invalid[0].focus(); return false; } return true; } /** * Disable buttons during form submission */ disableButtons() { this.container.querySelectorAll('form input[type="submit"]') .forEach(el => el.setAttribute('disabled', true)); } /** * Enable buttons after form submission (on validation error) */ enableButtons() { this.container.querySelectorAll('form input[type="submit"]') .forEach(el => el.removeAttribute('disabled')); } /** * Submit the form via AJAX call to the core_form_dynamic_form WS */ async submitFormAjax() { // If we found invalid fields, focus on the first one and do not submit via ajax. if (!(await this.validateElements())) { this.trigger(this.events.CLIENT_VALIDATION_ERROR, null, false); return; } this.disableButtons(); // Convert all the form elements values to a serialised string. const form = this.container.querySelector('form'); const formData = new URLSearchParams([...(new FormData(form)).entries()]); // Now we can continue... Ajax.call([{ methodname: 'core_form_dynamic_form', args: { formdata: formData.toString(), form: this.formClass } }])[0] .then((response) => { if (!response.submitted) { // Form was not submitted, it could be either because validation failed or because no-submit button was pressed. this.updateForm({html: response.html, js: Fragment.processCollectedJavascript(response.javascript)}); this.enableButtons(); this.trigger(this.events.SERVER_VALIDATION_ERROR, null, false); } else { // Form was submitted properly. const data = JSON.parse(response.data); this.enableButtons(); this.notifyResetFormChanges(); this.onSubmitSuccess(data); } return null; }) .catch(this.onSubmitError); } }
Roemke/moodle
lib/form/amd/src/dynamicform.js
JavaScript
gpl-3.0
13,276
/* .prependTo() Description: Insert every element in the set of matched elements to the beginning of the target. http://api.jquery.com/prependTo/ */ prependTo: function(target) { var ret = [], me = this, arr = $(target).e, last = arr.length - 1, elems; __ITERATE__(<@ arr @>, <@ function(t, idx) { elems = (idx == last ? me.clone(1) : me); $(t).prepend(elems); Array.prototype.push.apply(ret, elems); } @>); return __PUSH_STACK__(<@ ret @>) }
rosell-dk/picoQuery
0.6/builder/inc/methods/prependTo/prependTo.js
JavaScript
gpl-3.0
493
import 'angular/angular.min' import translation from 'angular-ui-translation/angular-translation' import NumberDirective from './NumberDirective' angular.module('FieldNumber', ['ui.translation']).directive('formNumber', () => new NumberDirective)
ClaroBot/Distribution
main/core/Resources/modules/form/Field/Number/module.js
JavaScript
gpl-3.0
249
odoo.define('base_import.import', function (require) { "use strict"; var ControlPanelMixin = require('web.ControlPanelMixin'); var core = require('web.core'); var time = require('web.time'); var ListView = require('web.ListView'); var KanbanView = require('web_kanban.KanbanView'); var Model = require('web.DataModel'); var session = require('web.session'); var Widget = require('web.Widget'); var QWeb = core.qweb; var _t = core._t; var _lt = core._lt; var StateMachine = window.StateMachine; /** * Safari does not deal well at all with raw JSON data being * returned. As a result, we're going to cheat by using a * pseudo-jsonp: instead of getting JSON data in the iframe, we're * getting a ``script`` tag which consists of a function call and * the returned data (the json dump). * * The function is an auto-generated name bound to ``window``, * which calls back into the callback provided here. * * @param {Object} form the form element (DOM or jQuery) to use in the call * @param {Object} attributes jquery.form attributes object * @param {Function} callback function to call with the returned data */ function jsonp(form, attributes, callback) { attributes = attributes || {}; var options = {jsonp: _.uniqueId('import_callback_')}; window[options.jsonp] = function () { delete window[options.jsonp]; callback.apply(null, arguments); }; if ('data' in attributes) { _.extend(attributes.data, options); } else { _.extend(attributes, {data: options}); } _.extend(attributes, { dataType: 'script', }); $(form).ajaxSubmit(attributes); } function execute_import_action () { var self = this; this.do_action({ type: 'ir.actions.client', tag: 'import', params: { model: this.dataset.model, // this.dataset.get_context() could be a compound? // not sure. action's context should be evaluated // so safer bet. Odd that timezone & al in it // though context: this.getParent().action.context, } }, { on_reverse_breadcrumb: function () { return self.reload(); }, }); return false; } // if true, the 'Import', 'Export', etc... buttons will be shown ListView.prototype.defaults.import_enabled = true; ListView.include({ /** * Extend the render_buttons function of ListView by adding an event listener * on the import button. * @return {jQuery} the rendered buttons */ render_buttons: function() { var self = this; var add_button = false; if (!this.$buttons) { // Ensures that this is only done once add_button = true; } this._super.apply(this, arguments); // Sets this.$buttons if(add_button) { this.$buttons.on('click', '.o_button_import', execute_import_action.bind(this)); } } }); KanbanView.include({ /** * Extend the render_buttons function of KanbanView by adding an event listener * on the import button. * @return {jQuery} the rendered buttons */ render_buttons: function() { var self = this; var add_button = false; if (!this.$buttons) { // Ensures that this is only done once add_button = true; } this._super.apply(this, arguments); // Sets this.$buttons if(add_button && this.$buttons) { this.$buttons.on('click', '.o_button_import', execute_import_action.bind(this)); } }, set_default_options: function (options) { this._super(_.defaults(options || {}, { import_enabled: true, })); }, }); var DataImport = Widget.extend(ControlPanelMixin, { template: 'ImportView', opts: [ {name: 'encoding', label: _lt("Encoding:"), value: 'utf-8'}, {name: 'separator', label: _lt("Separator:"), value: ','}, {name: 'quoting', label: _lt("Text Delimiter:"), value: '"'} ], parse_opts: [ {name: 'date_format', label: _lt("Date Format:"), value: ''}, {name: 'datetime_format', label: _lt("Datetime Format:"), value: ''}, {name: 'float_thousand_separator', label: _lt("Thousands Separator:"), value: ','}, {name: 'float_decimal_separator', label: _lt("Decimal Separator:"), value: '.'} ], events: { // 'change .oe_import_grid input': 'import_dryrun', 'change .oe_import_file': 'loaded_file', 'click .oe_import_file_reload': 'loaded_file', 'change input.oe_import_has_header, .js_import_options input': 'settings_changed', 'change input.oe_import_advanced_mode': function (e) { this.do_not_change_match = true; this['settings_changed'](); }, 'click a.oe_import_toggle': function (e) { e.preventDefault(); this.$('.oe_import_options').toggle(); }, 'click .oe_import_report a.oe_import_report_count': function (e) { e.preventDefault(); $(e.target).parent().toggleClass('oe_import_report_showmore'); }, 'click .oe_import_moreinfo_action a': function (e) { e.preventDefault(); // #data will parse the attribute on its own, we don't like // that sort of things var action = JSON.parse($(e.target).attr('data-action')); // FIXME: when JS-side clean_action action.views = _(action.views).map(function (view) { var id = view[0], type = view[1]; return [ id, type !== 'tree' ? type : action.view_type === 'form' ? 'list' : 'tree' ]; }); this.do_action(_.extend(action, { target: 'new', flags: { search_view: true, display_title: true, pager: true, list: {selectable: false} } })); }, }, init: function (parent, action) { this._super.apply(this, arguments); this.action_manager = parent; this.res_model = action.params.model; this.parent_context = action.params.context || {}; // import object id this.id = null; this.Import = new Model('base_import.import'); this.session = session; action.display_name = _t('Import a File'); // Displayed in the breadcrumbs this.do_not_change_match = false; }, start: function () { var self = this; this.setup_encoding_picker(); this.setup_separator_picker(); this.setup_float_format_picker(); return $.when( this._super(), self.create_model().done(function (id) { self.id = id; self.$('input[name=import_id]').val(id); self.render_buttons(); var status = { breadcrumbs: self.action_manager.get_breadcrumbs(), cp_content: {$buttons: self.$buttons}, }; self.update_control_panel(status); }) ); }, create_model: function() { return this.Import.call('create', [{ 'res_model': this.res_model }]); }, render_buttons: function() { var self = this; this.$buttons = $(QWeb.render("ImportView.buttons", this)); this.$buttons.filter('.o_import_validate').on('click', this.validate.bind(this)); this.$buttons.filter('.o_import_import').on('click', this.import.bind(this)); this.$buttons.filter('.o_import_cancel').on('click', function(e) { e.preventDefault(); self.exit(); }); }, setup_encoding_picker: function () { this.$('input.oe_import_encoding').select2({ width: '160px', query: function (q) { var make = function (term) { return {id: term, text: term}; }; var suggestions = _.map( ('utf-8 utf-16 windows-1252 latin1 latin2 big5 ' + 'gb18030 shift_jis windows-1251 koir8_r').split(/\s+/), make); if (q.term) { suggestions.unshift(make(q.term)); } q.callback({results: suggestions}); }, initSelection: function (e, c) { return c({id: 'utf-8', text: 'utf-8'}); } }).select2('val', 'utf-8'); }, setup_separator_picker: function () { this.$('input.oe_import_separator').select2({ width: '160px', query: function (q) { var suggestions = [ {id: ',', text: _t("Comma")}, {id: ';', text: _t("Semicolon")}, {id: '\t', text: _t("Tab")}, {id: ' ', text: _t("Space")} ]; if (q.term) { suggestions.unshift({id: q.term, text: q.term}); } q.callback({results: suggestions}); }, initSelection: function (e, c) { return c({id: ',', text: _t("Comma")}); }, }); }, setup_float_format_picker: function () { var sug_query = function (q) { var suggestions = [ {id: ',', text: _t("Comma")}, {id: '.', text: _t("Dot")}, ]; if (q.term) { suggestions.unshift({id: q.term, text: q.term}); } q.callback({results: suggestions}); }; this.$('input.oe_import_float_thousand_separator').select2({ width: '160px', query: sug_query, initSelection: function (e, c) { return c({id: ',', text: _t("Comma")}); }, }); this.$('input.oe_import_float_decimal_separator').select2({ width: '160px', query: sug_query, initSelection: function (e, c) { return c({id: ',', text: _t("Dot")}); }, }); }, import_options: function () { var self = this; var options = { headers: this.$('input.oe_import_has_header').prop('checked'), advanced: this.$('input.oe_import_advanced_mode').prop('checked'), keep_matches: this.do_not_change_match }; _(this.opts).each(function (opt) { options[opt.name] = self.$('input.oe_import_' + opt.name).val(); }); _(this.parse_opts).each(function (opt) { if (opt.name === 'date_format' || opt.name === 'datetime_format') { options[opt.name] = time.moment_to_strftime_format(self.$('input.oe_import_' + opt.name).val()); } else { options[opt.name] = self.$('input.oe_import_' + opt.name).val(); } }); options['fields'] = []; if (this.do_not_change_match) { options['fields'] = this.$('.oe_import_fields input.oe_import_match_field').map(function (index, el) { return $(el).select2('val') || false; }).get(); } this.do_not_change_match = false; return options; }, //- File & settings change section onfile_loaded: function () { var file = this.$('.oe_import_file')[0].files[0]; this.$('.oe_import_file_show').val(file !== undefined && file.name || ''); this.$buttons.filter('.o_import_button').add(this.$('.oe_import_file_reload')) .prop('disabled', true); if (!this.$('input.oe_import_file').val()) { return this['settings_changed'](); } this.$('.oe_import_date_format').val(''); this.$('.oe_import_datetime_format').val(''); this.$el.removeClass('oe_import_preview oe_import_error'); var import_toggle = false; var file = this.$('input.oe_import_file')[0].files[0]; // some platforms send text/csv, application/csv, or other things if Excel is prevent if ((file.type && _.last(file.type.split('/')) === "csv") || ( _.last(file.name.split('.')) === "csv")) { import_toggle = true; } this.$el.find('.oe_import_toggle').toggle(import_toggle); jsonp(this.$el, { url: '/base_import/set_file' }, this.proxy('settings_changed')); }, onpreviewing: function () { var self = this; this.$buttons.filter('.o_import_button').add(this.$('.oe_import_file_reload')) .prop('disabled', true); this.$el.addClass('oe_import_with_file'); // TODO: test that write // succeeded? this.$el.removeClass('oe_import_preview_error oe_import_error'); this.$el.toggleClass( 'oe_import_noheaders', !this.$('input.oe_import_has_header').prop('checked')); this.Import.call( 'parse_preview', [this.id, this.import_options()]) .done(function (result) { var signal = result.error ? 'preview_failed' : 'preview_succeeded'; self[signal](result); }); }, onpreview_error: function (event, from, to, result) { this.$('.oe_import_options').show(); this.$('.oe_import_file_reload').prop('disabled', false); this.$el.addClass('oe_import_preview_error oe_import_error'); this.$('.oe_import_error_report').html( QWeb.render('ImportView.preview.error', result)); }, onpreview_success: function (event, from, to, result) { var self = this; this.$buttons.filter('.o_import_import').removeClass('btn-primary'); this.$buttons.filter('.o_import_validate').addClass('btn-primary'); this.$buttons.filter('.o_import_button').add(this.$('.oe_import_file_reload')) .prop('disabled', false); this.$el.addClass('oe_import_preview'); this.$('.oe_import_grid').html(QWeb.render('ImportView.preview', result)); if (result.headers.length === 1) { this.$('.oe_import_options').show(); this.onresults(null, null, null, [{ type: 'warning', message: _t("A single column was found in the file, this often means the file separator is incorrect") }]); } this.$('.oe_import_date_format').val(time.strftime_to_moment_format(result.options.date_format)); this.$('.oe_import_datetime_format').val(time.strftime_to_moment_format(result.options.datetime_format)); this.$('.oe_import_float_thousand_separator').val(result.options.float_thousand_separator).change(); this.$('.oe_import_float_decimal_separator').val(result.options.float_decimal_separator).change(); if (result.debug === false){ this.$('.oe_import_tracking').hide(); } var $fields = this.$('.oe_import_fields input'); this.render_fields_matches(result, $fields); var data = this.generate_fields_completion(result); var item_finder = function (id, items) { items = items || data; for (var i=0; i < items.length; ++i) { var item = items[i]; if (item.id === id) { return item; } var val; if (item.children && (val = item_finder(id, item.children))) { return val; } } return ''; }; $fields.each(function (k,v) { var filtered_data = self.generate_fields_completion(result, k); $(v).select2({ allowClear: true, minimumInputLength: 0, data: filtered_data, initSelection: function (element, callback) { var default_value = element.val(); if (!default_value) { callback(''); return; } callback(item_finder(default_value)); }, placeholder: _t('Don\'t import'), width: 'resolve', dropdownCssClass: 'oe_import_selector' }); }); }, generate_fields_completion: function (root, index) { var basic = []; var regulars = []; var o2m = []; var headers_type = root.headers_type; function traverse(field, ancestors, collection, type) { var subfields = field.fields; var advanced_mode = self.$('input.oe_import_advanced_mode').prop('checked'); var field_path = ancestors.concat(field); var label = _(field_path).pluck('string').join(' / '); var id = _(field_path).pluck('name').join('/'); if (type === undefined || (type !== undefined && (type.indexOf('all') !== -1 || type.indexOf(field['type']) !== -1))){ // If non-relational, m2o or m2m, collection is regulars if (!collection) { if (field.name === 'id') { collection = basic; } else if (_.isEmpty(subfields) || _.isEqual(_.pluck(subfields, 'name'), ['id', '.id'])) { collection = regulars; } else { collection = o2m; } } collection.push({ id: id, text: label, required: field.required }); } if (advanced_mode){ for(var i=0, end=subfields.length; i<end; ++i) { traverse(subfields[i], field_path, collection, type); } } } _(root.fields).each(function (field) { if (index === undefined) { traverse(field, []); } else { if (self.$('input.oe_import_advanced_mode').prop('checked')){ traverse(field, [], undefined, ['all']); } else { traverse(field, [], undefined, headers_type[index]); } } }); var cmp = function (field1, field2) { return field1.text.localeCompare(field2.text); }; regulars.sort(cmp); o2m.sort(cmp); if (!_.isEmpty(regulars) && !_.isEmpty(o2m)){ basic = basic.concat([ { text: _t("Normal Fields"), children: regulars }, { text: _t("Relation Fields"), children: o2m }, ]); } else if (!_.isEmpty(regulars)) { basic = basic.concat(regulars); } else if (!_.isEmpty(o2m)) { basic = basic.concat(o2m); } return basic; }, render_fields_matches: function (result, $fields) { if (_(result.matches).isEmpty()) { return; } $fields.each(function (index, input) { var match = result.matches[index]; if (!match) { return; } var current_field = result; input.value = _(match).chain() .map(function (name) { // WARNING: does both mapping and folding (over the // ``field`` iterator variable) return current_field = _(current_field.fields).find(function (subfield) { return subfield.name === name; }); }) .pluck('name') .value() .join('/'); }); }, //- import itself call_import: function (kwargs) { var fields = this.$('.oe_import_fields input.oe_import_match_field').map(function (index, el) { return $(el).select2('val') || false; }).get(); var tracking_disable = 'tracking_disable' in kwargs ? kwargs.tracking_disable : !this.$('#oe_import_tracking').prop('checked') delete kwargs.tracking_disable kwargs.context = _.extend( {}, this.parent_context, {tracking_disable: tracking_disable} ); return this.Import.call('do', [this.id, fields, this.import_options()], kwargs) .then(undefined, function (error, event) { // In case of unexpected exception, convert // "JSON-RPC error" to an import failure, and // prevent default handling (warning dialog) if (event) { event.preventDefault(); } return $.when([{ type: 'error', record: false, message: error.data.arguments && error.data.arguments[1] || error.message, }]); }) ; }, onvalidate: function () { return this.call_import({ dryrun: true, tracking_disable: true }) .done(this.proxy('validated')); }, onimport: function () { var self = this; return this.call_import({ dryrun: false }).done(function (message) { if (!_.any(message, function (message) { return message.type === 'error'; })) { self['import_succeeded'](); return; } self['import_failed'](message); }); }, onimported: function () { this.exit(); }, exit: function () { this.do_action({ type: 'ir.actions.client', tag: 'history_back' }); }, onresults: function (event, from, to, message) { var no_messages = _.isEmpty(message); this.$buttons.filter('.o_import_import').toggleClass('btn-primary', no_messages); this.$buttons.filter('.o_import_import').toggleClass('btn-default', !no_messages); this.$buttons.filter('.o_import_validate').toggleClass('btn-primary', !no_messages); this.$buttons.filter('.o_import_validate').toggleClass('btn-default', no_messages); if (no_messages) { message.push({ type: 'info', message: _t("Everything seems valid.") }); } // row indexes come back 0-indexed, spreadsheets // display 1-indexed. var offset = 1; // offset more if header if (this.import_options().headers) { offset += 1; } this.$el.addClass('oe_import_error'); this.$('.oe_import_error_report').html( QWeb.render('ImportView.error', { errors: _(message).groupBy('message'), at: function (rows) { var from = rows.from + offset; var to = rows.to + offset; if (from === to) { return _.str.sprintf(_t("at row %d"), from); } return _.str.sprintf(_t("between rows %d and %d"), from, to); }, more: function (n) { return _.str.sprintf(_t("(%d more)"), n); }, info: function (msg) { if (typeof msg === 'string') { return _.str.sprintf( '<div class="oe_import_moreinfo oe_import_moreinfo_message">%s</div>', _.str.escapeHTML(msg)); } if (msg instanceof Array) { return _.str.sprintf( '<div class="oe_import_moreinfo oe_import_moreinfo_choices">%s <ul>%s</ul></div>', _.str.escapeHTML(_t("Here are the possible values:")), _(msg).map(function (msg) { return '<li>' + _.str.escapeHTML(msg) + '</li>'; }).join('')); } // Final should be object, action descriptor return [ '<div class="oe_import_moreinfo oe_import_moreinfo_action">', _.str.sprintf('<a href="#" data-action="%s">', _.str.escapeHTML(JSON.stringify(msg))), _.str.escapeHTML( _t("Get all possible values")), '</a>', '</div>' ].join(''); }, })); }, }); core.action_registry.add('import', DataImport); // FSM-ize DataImport StateMachine.create({ target: DataImport.prototype, events: [ { name: 'loaded_file', from: ['none', 'file_loaded', 'preview_error', 'preview_success', 'results'], to: 'file_loaded' }, { name: 'settings_changed', from: ['file_loaded', 'preview_error', 'preview_success', 'results'], to: 'previewing' }, { name: 'preview_failed', from: 'previewing', to: 'preview_error' }, { name: 'preview_succeeded', from: 'previewing', to: 'preview_success' }, { name: 'validate', from: 'preview_success', to: 'validating' }, { name: 'validate', from: 'results', to: 'validating' }, { name: 'validated', from: 'validating', to: 'results' }, { name: 'import', from: ['preview_success', 'results'], to: 'importing' }, { name: 'import_succeeded', from: 'importing', to: 'imported'}, { name: 'import_failed', from: 'importing', to: 'results' } ] }); return { DataImport: DataImport, } });
chienlieu2017/it_management
odoo/addons/base_import/static/src/js/base_import.js
JavaScript
gpl-3.0
25,954
var ControlBaseItemView = require( 'elementor-views/controls/base' ), ControlWPWidgetItemView; ControlWPWidgetItemView = ControlBaseItemView.extend( { ui: function() { var ui = ControlBaseItemView.prototype.ui.apply( this, arguments ); ui.form = 'form'; ui.loading = '.wp-widget-form-loading'; return ui; }, events: { 'keyup @ui.form :input': 'onFormChanged', 'change @ui.form :input': 'onFormChanged' }, onFormChanged: function() { var idBase = 'widget-' + this.model.get( 'id_base' ), settings = this.ui.form.elementorSerializeObject()[ idBase ].REPLACE_TO_ID; this.setValue( settings ); }, onReady: function() { elementor.ajax.send( 'editor_get_wp_widget_form', { data: { widget_type: this.model.get( 'widget' ), data: JSON.stringify( this.elementSettingsModel.toJSON() ) }, success: _.bind( function( data ) { this.ui.form.html( data ); }, this ) } ); } } ); module.exports = ControlWPWidgetItemView;
cobicarmel/elementor
assets/dev/js/editor/views/controls/wp_widget.js
JavaScript
gpl-3.0
969
initSidebarItems({"mod":[["mem","Basic functions for dealing with memory."],["raw","Raw OS-specific types for the current platform/architecture"]],"trait":[["Send","Types that can be transferred across thread boundaries."]]});
servo/doc.servo.org
glutin/api/x11/ffi/glx_extra/__gl_imports/sidebar-items.js
JavaScript
mpl-2.0
226
/** * Within tags -- meaning between < and > -- encode [\ ` * _ ~ =] so they * don't conflict with their use in Markdown for code, italics and strong. */ showdown.subParser('escapeSpecialCharsWithinTagAttributes', function (text, options, globals) { 'use strict'; text = globals.converter._dispatch('escapeSpecialCharsWithinTagAttributes.before', text, options, globals); // Build a regex to find HTML tags. var tags = /<\/?[a-z\d_:-]+(?:[\s]+[\s\S]+?)?>/gi, comments = /<!(--(?:(?:[^>-]|-[^>])(?:[^-]|-[^-])*)--)>/gi; text = text.replace(tags, function (wholeMatch) { return wholeMatch .replace(/(.)<\/?code>(?=.)/g, '$1`') .replace(/([\\`*_~=|])/g, showdown.helper.escapeCharactersCallback); }); text = text.replace(comments, function (wholeMatch) { return wholeMatch .replace(/([\\`*_~=|])/g, showdown.helper.escapeCharactersCallback); }); text = globals.converter._dispatch('escapeSpecialCharsWithinTagAttributes.after', text, options, globals); return text; });
mapcentia/vidi
bower_components/showdown/src/subParsers/escapeSpecialCharsWithinTagAttributes.js
JavaScript
agpl-3.0
1,030
const redis = require('redis') const client = redis.createClient(process.env.REDIS_URL) module.exports = client
ben-pr-p/assemble
server/redis/client.js
JavaScript
agpl-3.0
112