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
import NativeObject from '../NativeObject'; import Widget from '../Widget'; import {JSX} from '../JsxProcessor'; export default class RadioButton extends Widget { get _nativeType() { return 'tabris.RadioButton'; } _getXMLAttributes() { return super._getXMLAttributes().concat([ ['text', this.text], ['checked', this.checked] ]); } /** @this {import("../JsxProcessor").default} */ [JSX.jsxFactory](Type, attributes) { const children = this.getChildren(attributes); const normalAttributes = this.withoutChildren(attributes); return super[JSX.jsxFactory](Type, this.withContentText( normalAttributes, children, 'text' )); } } NativeObject.defineProperties(RadioButton.prototype, { text: {type: 'string', default: ''}, checked: {type: 'boolean', nocache: true}, textColor: {type: 'ColorValue', default: 'initial'}, tintColor: {type: 'ColorValue', default: 'initial'}, checkedTintColor: {type: 'ColorValue', default: 'initial'}, font: {type: 'FontValue', default: 'initial'} }); NativeObject.defineEvents(RadioButton.prototype, { select: {native: true, changes: 'checked'} });
eclipsesource/tabris-js
src/tabris/widgets/RadioButton.js
JavaScript
bsd-3-clause
1,165
/* Language: Go Author: Stephan Kountso aka StepLg <steplg@gmail.com> Contributors: Evgeny Stepanischev <imbolk@gmail.com> Description: Google go language (golang). For info about language Website: http://golang.org/ Category: common, system */ function(hljs) { var GO_KEYWORDS = { keyword: 'break default func interface select case map struct chan else goto package switch ' + 'const fallthrough if range type continue for import return var go defer ' + 'bool byte complex64 complex128 float32 float64 int8 int16 int32 int64 string uint8 ' + 'uint16 uint32 uint64 int uint uintptr rune', literal: 'true false iota nil', built_in: 'append cap close complex copy imag len make new panic print println real recover delete' }; return { aliases: ['golang'], keywords: GO_KEYWORDS, illegal: '</', contains: [ hljs.C_LINE_COMMENT_MODE, hljs.C_BLOCK_COMMENT_MODE, { className: 'string', variants: [ hljs.QUOTE_STRING_MODE, {begin: '\'', end: '[^\\\\]\''}, {begin: '`', end: '`'}, ] }, { className: 'number', variants: [ {begin: hljs.C_NUMBER_RE + '[i]', relevance: 1}, hljs.C_NUMBER_MODE ] }, { begin: /:=/ // relevance booster }, { className: 'function', beginKeywords: 'func', end: '\\s*(\\{|$)', excludeEnd: true, contains: [ hljs.TITLE_MODE, { className: 'params', begin: /\(/, end: /\)/, keywords: GO_KEYWORDS, illegal: /["']/ } ] } ] }; }
MakeNowJust/highlight.js
src/languages/go.js
JavaScript
bsd-3-clause
1,692
define(['App', 'underscore', 'backbone', 'jquery'], function(App, _, Backbone, $) { return Backbone.Model.extend({ parseAsCommentMoreLink: function(data) { if (data.children.length === 0) return null data.childrenCount = data.children.length if (data.childrenCount == 1) { data.replyVerb = 'reply' } else { data.replyVerb = 'replies' } return data }, parse: function(data) { if (!data) { return } if (typeof data.data !== 'undefined') { //the data from getmorechildren comes in this format data.data.kind = data.kind data = data.data } if (data.kind === 'more') { return this.parseAsCommentMoreLink(data) } var timeAgo = moment.unix(data.created_utc).fromNow(true) //"true" removes the "ago" timeAgo = timeAgo.replace("in ", ''); //why would it add the word "in" data.timeAgo = timeAgo data.timeUgly = moment.unix(data.created_utc).format() data.timePretty = moment.unix(data.created_utc).format("ddd MMM DD HH:mm:ss YYYY") + " UTC" //format Sun Aug 18 12:51:06 2013 UTC //if the comment is edited format its last edited time if (typeof data.edited !== 'undefined' && data.edited !== false) { timeAgo = moment.unix(data.edited).fromNow(true) //"true" removes the "ago" timeAgo = timeAgo.replace("in ", ''); //why would it add the word "in" data.editedTimeAgo = timeAgo } data.score = +data.ups - parseInt(data.downs, 10) data.scoreUp = +data.score + 1 data.scoreDown = +data.score - 1 if (data.likes === null) { data.voted = 'unvoted' data.downmod = 'down' data.upmod = 'up' } else if (data.likes === true) { data.voted = "likes" data.downmod = 'down' data.upmod = 'upmod' } else { data.voted = "dislikes" data.downmod = 'downmod' data.upmod = 'up' } //for the user view we can have comments if (typeof data.thumbnail !== 'undefined' && data.thumbnail == 'self') { data.thumbnail = 'img/self.png' } else if (data.thumbnail == 'nsfw') { data.thumbnail = 'img/nsfw.png' } else if (data.thumbnail === '' || data.thumbnail == 'default') { data.thumbnail = 'img/notsure.png' } data.body_html = (typeof data.body_html === 'undefined') ? '' : $('<div/>').html(data.body_html).text(); var linkName = data.link_id.replace('t3_', '') data.permalink = '/r/' + data.subreddit + '/comments/' + linkName + "/L/" + data.id if (typeof data.replies !== "undefined" && data.replies !== null && typeof data.replies.data !== "undefined") { // data.replies = parseComments(data.replies.data, data.link_id) data.childrenCount = data.replies.data.length if (data.replies.length == 1) { data.childOrChildren = 'child' } else { data.childOrChildren = 'children' } } else { data.childOrChildren = 'children' data.childrenCount = 0 } return data } }); });
BenjaminAdams/RedditJS
public/js/app/model/comment.js
JavaScript
bsd-3-clause
3,155
BaseExporter = function () {}; BaseExporter.prototype = {}; function niceWrite (writeStream, toWrite) { // NOTE: might need to break toWrite into multiple strings if (toWrite.length > 10000) { console.log("break toWrite into multiple strings"); } var keepWriting = writeStream.write(toWrite); if (keepWriting) { // return a promise that has already been resolved // any .then()s connected to this will fire immidiately return Q(); } // waits until the stream has drained, then resolves return new Q.Promise(function (resolve) { writeStream.once("drain", resolve); }); } BaseExporter.prototype.run = function (destination, options) { var self = this; return new Q.Promise(function (resolve, reject) { // make sure it's being called with new keyword if (!self.init) { console.log("not called with new keyword"); throw new Error("not called with new keyword"); } self.init.call(self, options); self.writeStream = createWriteStream(destination); var lineNumber = 1; // careful: starts at 1 function writeNextLine () { var chunks = []; var lineMaybePromise = self.getLine.call(self, function (chunk) { chunks.push(chunk); }, lineNumber); Q(lineMaybePromise) .then(function () { if (chunks.length) { lineNumber++; // write all chunks, wait for drain (if necessary), call itself niceWrite(self.writeStream, chunks.join("") + "\n") .then(writeNextLine) .catch(reject); } else { // end the write stream, close the file self.writeStream.end(resolve); } }); } writeNextLine(); // kick off the writing }); }; BaseExporter.prototype.init = function (write, lineNumber) { throw new Error("init not overridden"); }; BaseExporter.prototype.getLine = function (write, lineNumber) { throw new Error("getLine not overridden"); };
UCSC-MedBook/MedBook_
packages/adapters/export/BaseExporter.js
JavaScript
bsd-3-clause
1,984
import { put, select, takeEvery } from 'redux-saga/effects' import { getQuotes } from './quotes' import { has, toArray } from 'lodash' import { createAuthor, removeAuthor, updateAuthor } from "./authors"; import { createCategory, removeCategory, updateCategory } from "./categories"; import { createTag, removeTag, updateTag } from "./tags"; const FILTER_CHANGED = 'FILTER_CHANGED' const SEARCH_CHANGED = 'SEARCH_CHANGED' const initialState = { categories: new Set(), authors: new Set(), tags: new Set(), search: null, snapshot: { categories: new Set(), authors: new Set(), tags: new Set(), search: null, } } export function reducer(state = initialState, action = {}) { switch (action.type) { case FILTER_CHANGED: const id = action.payload.value const field = action.payload.field const checked = action.payload.checked let newState if (checked) { const newSet = new Set(state[field]) newSet.add(id) newState = newSet } else { const newSet = new Set(state[field]) newSet.delete(id) newState = newSet } return { ...state, [field]: newState } case SEARCH_CHANGED: return { ...state, search: action.payload.value } case 'SET_FILTERS': return { ...state, ...action.payload } default: return state } } export function* handleFilterChange() { const filters = yield select((state) => state.filters) const routing = yield select((state) => state.routing) const params = { category: toArray(filters.categories), author: toArray(filters.authors), tags: toArray(filters.tags), search: filters.search, user__username: has(routing.match.params, 'username') ? routing.match.params.username : null } yield put(getQuotes(params)) } export function* saga() { yield takeEvery(FILTER_CHANGED, handleFilterChange) yield takeEvery(SEARCH_CHANGED, handleFilterChange) } export const changeFilter = (field, value, checked) => ({ type: FILTER_CHANGED, payload: {field, value, checked} }) export const changeSearch = (value) => ({ type: SEARCH_CHANGED, payload: {value} }) export const createFilter = (type, data) => { switch (type) { case 'authors': return createAuthor(data) case 'categories': return createCategory(data) case 'tags': return createTag(data) default: return null } } export const updateFilter = (type, data) => { switch (type) { case 'authors': return updateAuthor(data) case 'categories': return updateCategory(data) case 'tags': return updateTag(data) default: return null } } export const removeFilter = (type, data) => { switch (type) { case 'authors': return removeAuthor(data) case 'categories': return removeCategory(data) case 'tags': return removeTag(data) default: return null } }
lucifurtun/myquotes
ui/src/redux/filters.js
JavaScript
bsd-3-clause
3,403
var RecipeReport = (function () { "use strict"; var standartThaaliCount = 100; var sum = function(array, prop) { return array.reduce( function(a, b){ return a + b[prop]; }, 0); }; var recipeReport = function (data, fromDate, toDate, recipe) { this.data = data; this.fromDate = fromDate; this.toDate = toDate; this.recipe = recipe; }; recipeReport.prototype.run = function() { var d = {}; d.dateWiseReport = this.getDateWiseReport(); d.ingredientWiseAverage = this.getIngredientWiseAverage(); return d; }; recipeReport.prototype.matchCriteria = function(meal) { return meal.recipe === this.recipe && meal.date<=this.toDate && meal.date>=this.fromDate; }; recipeReport.prototype.getDateWiseReport = function() { var report = []; for (var i = this.data.length - 1; i >= 0; i--) { var meal = this.data[i]; if(this.matchCriteria(meal)) { var cost = sum(meal.ingredients, 'amount'); report.push({ date: meal.date, noOfThaalis: meal.noOfThaalis, //total cost of recipe made on this date perThaaliCost: (cost/meal.noOfThaalis) * standartThaaliCount, totalCost: cost }); } } return report; }; recipeReport.prototype.getIngredientWiseAverage = function() { var report = {}; var faulty = {}; var isFaulty = false; for (var i = this.data.length - 1; i >= 0; i--) { var meal = this.data[i]; if(this.matchCriteria(meal)) { for (var k = meal.ingredients.length - 1; k >= 0; k--) { var ingredient = meal.ingredients[k]; var name = ingredient.item.toLowerCase(); report[name] = report[name] || {}; report[name].qty = report[name].qty || 0; report[name].qty+= ingredient.qty; if((report[name].unit !== undefined && report[name].unit !== ingredient.unit)) { fault[ingredient.item.toLowerCase() + '-' + meal.date] = fault[ingredient.item.toLowerCase() + '-' + meal.date] || 0; fault[ingredient.item.toLowerCase() + '-' + meal.date] += 1; isFaulty = true; } report[name].unit = ingredient.unit; report[name].amount = report[name].amount || 0; report[name].amount += ingredient.amount; report[name].count = report[name].count || 0; report[name].count++; } } } var finalReport = []; for (var prop in report) { finalReport.push({ "IngredientName": prop, "Quantity": report[prop].qty/report[prop].count, "Unit": report[prop].unit, "PerUnitCost": report[prop].amount/report[prop].qty, "Amount": report[prop].amount/report[prop].count }); } if(isFaulty) { console.log(faulty); //TODO add details for faulty items alert('Different units specified for same ingredient on saperate days. Invalid data. Please see what\'s wrong. Or contact maker of this application'); } return finalReport; }; return recipeReport; })();
ismusidhu/FaizBudget
public/js/recipeReport.js
JavaScript
bsd-3-clause
3,112
var fs = require("fs"); var express = require("express"), optimist = require("optimist"), gitstatic = require("../"); var argv = optimist.usage("Usage: $0") .options("h", { alias: "help", describe: "display this help text" }) .options("repository", { default: ".git", describe: "path to bare git repository" }) .options("port", { default: 3000, describe: "http port" }) .check(function(argv) { if (argv.help) throw ""; try { var stats = fs.statSync(argv.repository); } catch (e) { throw "Error: " + e.message; } if (!stats.isDirectory()) throw "Error: invalid --repository directory."; }) .argv; var server = express(); server.get(/^\/.*/, gitstatic.route() .repository(argv.repository)); server.listen(argv.port);
mbostock/git-static
examples/server.js
JavaScript
bsd-3-clause
822
$(document).ready(function() { $.viewMap = { 'install' : $('#coordinator_row'), 'repair' : $('#barcode_row, #equipment_row') }; $('#coordinator_row').hide(); $('#id_work_type').change(function() { // hide all $.each($.viewMap, function() { this.hide(); }); // show current $.viewMap[$(this).val()].show(); }); });
kreeger/etcetera
_media/js/workform.js
JavaScript
bsd-3-clause
348
jQuery(document).ready(function(){ var numSaves, _autoSaveChanges; module("TiddlyWiki options", { setup: function() { config.options.chkAutoSave = true; systemSettingSave = 0; _autoSaveChanges = autoSaveChanges; numSaves = 0; autoSaveChanges = function() { numSaves += 1; return _autoSaveChanges.apply(this, arguments); } }, teardown: function() { numSaves = null; config.options.chkAutoSave = false; autoSaveChanges = _autoSaveChanges; } }); test("save multiple system settings", function() { saveSystemSetting("foo", true); saveSystemSetting("foo", false); saveSystemSetting("foo", true); strictEqual(numSaves, 0, "The save is asynchronous so no saves have yet been made"); strictEqual(systemSettingSave > 0, true, "However there should be a timeout in progress"); }); });
TeravoxelTwoPhotonTomography/nd
doc/node_modules/tiddlywiki/editions/tw2/source/tiddlywiki/test/js/Options.js
JavaScript
bsd-3-clause
835
import React from 'react'; import { compose } from 'react-apollo'; import autoBind from 'react-autobind'; // graphql import textNodesQuery from '../../../textNodes/graphql/queries/textNodesQuery'; // components import CommentLemma from '../../components/CommentLemma'; import LoadingLemma from '../../../../components/loading/LoadingLemma'; // lib import Utils from '../../../../lib/utils'; import getCurrentSubdomain from '../../../../lib/getCurrentSubdomain'; import defaultWorksEditions from '../../lib/defaultWorksEditions'; class CommentLemmaContainer extends React.Component { constructor(props) { super(props); this.state = { selectedLemmaVersionIndex: null, selectedTranslationVersionIndex: null, }; autoBind(this); } toggleVersion(versionId) { const { selectedLemmaVersionIndex } = this.state; let textNodes = []; let versions = []; if ( this.props.textNodesQuery && this.props.textNodesQuery.textNodes ) { textNodes = this.props.textNodesQuery.textNodes; } if (textNodes && textNodes.length) { const allVersions = Utils.textFromTextNodesGroupedByVersion(textNodes); versions = allVersions.versions; } if (versions && versions.length) { if ( selectedLemmaVersionIndex === null || versions[selectedLemmaVersionIndex].id !== versionId ) { let newSelectedVersionIndex = 0; versions.forEach((version, index) => { if (version.id === versionId) { newSelectedVersionIndex = index; } }); this.setState({ selectedLemmaVersionIndex: newSelectedVersionIndex, }); } } } render() { const { commentGroup, multiline } = this.props; const { selectedLemmaVersionIndex } = this.state; const subdomain = getCurrentSubdomain(); let textNodes = []; let versionsWithText = []; let translationsWithText = []; let selectedLemmaVersion = { textNodes: [] }; let selectedTranslationVersion = { textNodes: [] }; if (this.props.textNodesQuery.loading) { return <LoadingLemma /> } // text nodes data if ( this.props.textNodesQuery && this.props.textNodesQuery.textNodes ) { textNodes = this.props.textNodesQuery.textNodes; } // TODO: potentially structure data from backend to prevent this transformation // in the future // set versions from textnodes data if (textNodes && textNodes.length) { const allVersions = Utils.textFromTextNodesGroupedByVersion(textNodes); versionsWithText = allVersions.versions; translationsWithText = allVersions.translations; } // if necessary, parse versions into multiline data versionsWithText = multiline ? Utils.parseMultilineVersion(versionsWithText, multiline) : versionsWithText; // set selected version if (versionsWithText.length) { if ( selectedLemmaVersionIndex !== null && versionsWithText[selectedLemmaVersionIndex] ) { selectedLemmaVersion = versionsWithText[selectedLemmaVersionIndex]; } else { selectedLemmaVersion = versionsWithText.find(version => (version.urn === defaultWorksEditions[subdomain].defaultVersionUrn)); } } return ( <CommentLemma commentGroup={commentGroup} versions={versionsWithText} translations={translationsWithText} selectedLemmaVersion={selectedLemmaVersion} selectedTranslationVersion={selectedTranslationVersion} showContextPanel={this.props.showContextPanel} index={this.props.index} setScrollPosition={this.props.setScrollPosition} hideLemma={this.props.hideLemma} selectMultiLine={this.props.selectMultiLine} multiline={this.props.multiline} toggleVersion={this.toggleVersion} lemmaCitation={this.props.lemmaCitation} /> ); } } export default compose( textNodesQuery, )(CommentLemmaContainer);
CtrHellenicStudies/Commentary
src/modules/comments/containers/CommentLemmaContainer/CommentLemmaContainer.js
JavaScript
bsd-3-clause
3,752
version https://git-lfs.github.com/spec/v1 oid sha256:eb830b3ada371c6f6af6bd512f864699a8123c5922f0376292ece99b8fc9e602 size 105460
yogeshsaroya/new-cdnjs
ajax/libs/mathjax/2.3/jax/output/SVG/fonts/STIX-Web/Operators/Regular/Main.js
JavaScript
mit
131
import _ from 'lodash' import URLJoin from 'url-join' import request from 'request' import bitcore from 'bitcore-lib' import config from './config' import logger from './logger' /** * @typedef {Object} Insight~UnspentObject * @property {string} address * @property {string} txId * @property {number} outputIndex * @property {string} script * @property {number} satoshis */ /** * @class Insight */ export default class Insight { /** * @constructor */ constructor () { this._insightURL = config.get('insight.url') this._requestTimeout = config.get('insight.timeout') } /** * @private * @param {Object} opts * @return {Promise<Object>} */ async _request (opts) { return new Promise((resolve, reject) => { opts = _.extend({ method: 'GET', timeout: this._requestTimeout, json: true, zip: true }, opts) logger.verbose(`Make request: ${opts.uri}`) request(opts, (err, response) => { if (err === null) { if (response.statusCode === 200) { return resolve(response) } err = new Error(`Expected statusCode is 200, got ${response.statusCode} (body: ${response.body})`) } reject(err) }) }) } /** * @return {string} */ getURL () { return this._insightURL } /** * @param {string[]} addresses * @return {Promise<Insight~UnspentObject[]>} */ async getUnspent (addresses) { logger.verbose(`getUnspent for addresses: ${addresses}`) let response = await this._request({ uri: URLJoin(this._insightURL, 'addrs', addresses.join(','), 'utxo') }) return response.body.map((item) => { return { address: item.address, txId: item.txid, outputIndex: item.vout, script: item.scriptPubKey, satoshis: bitcore.Unit.fromBTC(item.amount).toSatoshis() } }) } /** * @param {bitcore.Transaction} tx * @return {Promise} */ async sendTx (tx) { let rawTx = tx.serialize() logger.verbose(`sendTx ${tx.id} (size: ${rawTx.length / 2})`) await this._request({ method: 'POST', uri: URLJoin(this._insightURL, '/tx/send'), json: {rawtx: rawTx} }) } }
fanatid/bitcoin-faucet
app.es6/insight.js
JavaScript
mit
2,257
(function(exports) { "use strict"; exports.dontIgnoreComposerLockFile = function(grunt, init, done) { grunt.verbose.write("Removing composer.lock from .gitignore."); var content = grunt.file.read('build/.gitignore').replace(/composer.lock[\r\n]/m, ''); grunt.file.write('build/.gitignore', content); grunt.verbose.ok(); done(); }; })(typeof exports === 'object' && exports || this);
fendy-susanto/themonkeys-technical-test
lib/laravel/gitignore.js
JavaScript
mit
413
import core from 'core-js'; import * as LogManager from 'aurelia-logging'; import {Metadata} from 'aurelia-metadata'; var logger = LogManager.getLogger('aurelia'); function loadPlugin(aurelia, loader, info){ logger.debug(`Loading plugin ${info.moduleId}.`); aurelia.currentPluginId = info.moduleId; return loader.loadModule(info.moduleId).then(m => { if('configure' in m){ return Promise.resolve(m.configure(aurelia, info.config || {})).then(() => { aurelia.currentPluginId = null; logger.debug(`Configured plugin ${info.moduleId}.`); }); }else{ aurelia.currentPluginId = null; logger.debug(`Loaded plugin ${info.moduleId}.`); } }); } /** * Manages loading and configuring plugins. * * @class Plugins * @constructor * @param {Aurelia} aurelia An instance of Aurelia. */ export class Plugins { constructor(aurelia){ this.aurelia = aurelia; this.info = []; this.processed = false; } /** * Configures a plugin before Aurelia starts. * * @method plugin * @param {moduleId} moduleId The ID of the module to configure. * @param {config} config The configuration for the specified module. * @return {Plugins} Returns the current Plugins instance. */ plugin(moduleId, config){ var plugin = {moduleId:moduleId, config:config || {}}; if(this.processed){ loadPlugin(this.aurelia, this.aurelia.loader, plugin); }else{ this.info.push(plugin); } return this; } _process(){ var aurelia = this.aurelia, loader = aurelia.loader, info = this.info, current; if(this.processed){ return; } var next = () => { if(current = info.shift()){ return loadPlugin(aurelia, loader, current).then(next); } this.processed = true; return Promise.resolve(); }; return next(); } }
ctoran/aurelia-ts-port
aurelia-latest/framework/plugins.js
JavaScript
mit
1,886
/* * Copyright (C) 2007 Apple Inc. All rights reserved. * Copyright (C) 2009 Joseph Pecoraro * * 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 Apple Computer, Inc. ("Apple") nor the names of * its contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ Elements.StylesSidebarPane = class extends Elements.ElementsSidebarPane { constructor() { super(); this.setMinimumSize(96, 26); this.registerRequiredCSS('elements/stylesSidebarPane.css'); this.element.tabIndex = -1; Common.moduleSetting('colorFormat').addChangeListener(this.update.bind(this)); Common.moduleSetting('textEditorIndent').addChangeListener(this.update.bind(this)); /** @type {?UI.Widget} */ this._currentToolbarPane = null; /** @type {?UI.Widget} */ this._animatedToolbarPane = null; /** @type {?UI.Widget} */ this._pendingWidget = null; /** @type {?UI.ToolbarToggle} */ this._pendingWidgetToggle = null; this._toolbarPaneElement = this._createStylesSidebarToolbar(); this._noMatchesElement = this.contentElement.createChild('div', 'gray-info-message hidden'); this._noMatchesElement.textContent = ls`No matching selector or style`; this._sectionsContainer = this.contentElement.createChild('div'); UI.ARIAUtils.markAsTree(this._sectionsContainer); this._sectionsContainer.addEventListener('keydown', this._sectionsContainerKeyDown.bind(this), false); this._sectionsContainer.addEventListener('focusin', this._sectionsContainerFocusChanged.bind(this), false); this._sectionsContainer.addEventListener('focusout', this._sectionsContainerFocusChanged.bind(this), false); this._swatchPopoverHelper = new InlineEditor.SwatchPopoverHelper(); this._linkifier = new Components.Linkifier(Elements.StylesSidebarPane._maxLinkLength, /* useLinkDecorator */ true); /** @type {?Elements.StylePropertyHighlighter} */ this._decorator = null; this._userOperation = false; this._isEditingStyle = false; /** @type {?RegExp} */ this._filterRegex = null; this.contentElement.classList.add('styles-pane'); /** @type {!Array<!Elements.SectionBlock>} */ this._sectionBlocks = []; Elements.StylesSidebarPane._instance = this; UI.context.addFlavorChangeListener(SDK.DOMNode, this.forceUpdate, this); this.contentElement.addEventListener('copy', this._clipboardCopy.bind(this)); this._resizeThrottler = new Common.Throttler(100); } /** * @return {!InlineEditor.SwatchPopoverHelper} */ swatchPopoverHelper() { return this._swatchPopoverHelper; } /** * @param {boolean} userOperation */ setUserOperation(userOperation) { this._userOperation = userOperation; } /** * @param {!SDK.CSSProperty} property * @return {!Element} */ static createExclamationMark(property) { const exclamationElement = createElement('label', 'dt-icon-label'); exclamationElement.className = 'exclamation-mark'; if (!Elements.StylesSidebarPane.ignoreErrorsForProperty(property)) exclamationElement.type = 'smallicon-warning'; exclamationElement.title = SDK.cssMetadata().isCSSPropertyName(property.name) ? Common.UIString('Invalid property value') : Common.UIString('Unknown property name'); return exclamationElement; } /** * @param {!SDK.CSSProperty} property * @return {boolean} */ static ignoreErrorsForProperty(property) { /** * @param {string} string */ function hasUnknownVendorPrefix(string) { return !string.startsWith('-webkit-') && /^[-_][\w\d]+-\w/.test(string); } const name = property.name.toLowerCase(); // IE hack. if (name.charAt(0) === '_') return true; // IE has a different format for this. if (name === 'filter') return true; // Common IE-specific property prefix. if (name.startsWith('scrollbar-')) return true; if (hasUnknownVendorPrefix(name)) return true; const value = property.value.toLowerCase(); // IE hack. if (value.endsWith('\\9')) return true; if (hasUnknownVendorPrefix(value)) return true; return false; } /** * @param {string} placeholder * @param {!Element} container * @param {function(?RegExp)} filterCallback * @return {!Element} */ static createPropertyFilterElement(placeholder, container, filterCallback) { const input = createElementWithClass('input'); input.placeholder = placeholder; function searchHandler() { const regex = input.value ? new RegExp(input.value.escapeForRegExp(), 'i') : null; filterCallback(regex); } input.addEventListener('input', searchHandler, false); /** * @param {!Event} event */ function keydownHandler(event) { if (event.key !== 'Escape' || !input.value) return; event.consume(true); input.value = ''; searchHandler(); } input.addEventListener('keydown', keydownHandler, false); input.setFilterValue = setFilterValue; /** * @param {string} value */ function setFilterValue(value) { input.value = value; input.focus(); searchHandler(); } return input; } /** * @param {!SDK.CSSProperty} cssProperty */ revealProperty(cssProperty) { this._decorator = new Elements.StylePropertyHighlighter(this, cssProperty); this._decorator.perform(); this.update(); } forceUpdate() { this._swatchPopoverHelper.hide(); this._resetCache(); this.update(); } /** * @param {!Event} event */ _sectionsContainerKeyDown(event) { const activeElement = this._sectionsContainer.ownerDocument.deepActiveElement(); if (!activeElement) return; const section = activeElement._section; if (!section) return; switch (event.key) { case 'ArrowUp': case 'ArrowLeft': const sectionToFocus = section.previousSibling() || section.lastSibling(); sectionToFocus.element.focus(); event.consume(true); break; case 'ArrowDown': case 'ArrowRight': { const sectionToFocus = section.nextSibling() || section.firstSibling(); sectionToFocus.element.focus(); event.consume(true); break; } case 'Home': section.firstSibling().element.focus(); event.consume(true); break; case 'End': section.lastSibling().element.focus(); event.consume(true); break; } } _sectionsContainerFocusChanged() { // When a styles section is focused, shift+tab should leave the section. // Leaving tabIndex = 0 on the first element would cause it to be focused instead. if (this._sectionBlocks[0] && this._sectionBlocks[0].sections[0]) this._sectionBlocks[0].sections[0].element.tabIndex = this._sectionsContainer.hasFocus() ? -1 : 0; } /** * @param {!Event} event */ _onAddButtonLongClick(event) { const cssModel = this.cssModel(); if (!cssModel) return; const headers = cssModel.styleSheetHeaders().filter(styleSheetResourceHeader); /** @type {!Array.<{text: string, handler: function()}>} */ const contextMenuDescriptors = []; for (let i = 0; i < headers.length; ++i) { const header = headers[i]; const handler = this._createNewRuleInStyleSheet.bind(this, header); contextMenuDescriptors.push({text: Bindings.displayNameForURL(header.resourceURL()), handler: handler}); } contextMenuDescriptors.sort(compareDescriptors); const contextMenu = new UI.ContextMenu(event); for (let i = 0; i < contextMenuDescriptors.length; ++i) { const descriptor = contextMenuDescriptors[i]; contextMenu.defaultSection().appendItem(descriptor.text, descriptor.handler); } contextMenu.footerSection().appendItem( 'inspector-stylesheet', this._createNewRuleInViaInspectorStyleSheet.bind(this)); contextMenu.show(); /** * @param {!{text: string, handler: function()}} descriptor1 * @param {!{text: string, handler: function()}} descriptor2 * @return {number} */ function compareDescriptors(descriptor1, descriptor2) { return String.naturalOrderComparator(descriptor1.text, descriptor2.text); } /** * @param {!SDK.CSSStyleSheetHeader} header * @return {boolean} */ function styleSheetResourceHeader(header) { return !header.isViaInspector() && !header.isInline && !!header.resourceURL(); } } /** * @param {?RegExp} regex */ _onFilterChanged(regex) { this._filterRegex = regex; this._updateFilter(); } /** * @param {!Elements.StylePropertiesSection} editedSection * @param {!Elements.StylePropertyTreeElement=} editedTreeElement */ _refreshUpdate(editedSection, editedTreeElement) { if (editedTreeElement) { for (const section of this.allSections()) { if (section.isBlank) continue; section._updateVarFunctions(editedTreeElement); } } if (this._isEditingStyle) return; const node = this.node(); if (!node) return; for (const section of this.allSections()) { if (section.isBlank) continue; section.update(section === editedSection); } if (this._filterRegex) this._updateFilter(); this._nodeStylesUpdatedForTest(node, false); } /** * @override * @return {!Promise.<?>} */ doUpdate() { return this._fetchMatchedCascade().then(this._innerRebuildUpdate.bind(this)); } /** * @override */ onResize() { this._resizeThrottler.schedule(this._innerResize.bind(this)); } /** * @return {!Promise} */ _innerResize() { const width = this.contentElement.getBoundingClientRect().width + 'px'; this.allSections().forEach(section => section.propertiesTreeOutline.element.style.width = width); return Promise.resolve(); } _resetCache() { if (this.cssModel()) this.cssModel().discardCachedMatchedCascade(); } /** * @return {!Promise.<?SDK.CSSMatchedStyles>} */ _fetchMatchedCascade() { const node = this.node(); if (!node || !this.cssModel()) return Promise.resolve(/** @type {?SDK.CSSMatchedStyles} */ (null)); return this.cssModel().cachedMatchedCascadeForNode(node).then(validateStyles.bind(this)); /** * @param {?SDK.CSSMatchedStyles} matchedStyles * @return {?SDK.CSSMatchedStyles} * @this {Elements.StylesSidebarPane} */ function validateStyles(matchedStyles) { return matchedStyles && matchedStyles.node() === this.node() ? matchedStyles : null; } } /** * @param {boolean} editing */ setEditingStyle(editing) { if (this._isEditingStyle === editing) return; this.contentElement.classList.toggle('is-editing-style', editing); this._isEditingStyle = editing; } /** * @override * @param {!Common.Event=} event */ onCSSModelChanged(event) { const edit = event && event.data ? /** @type {?SDK.CSSModel.Edit} */ (event.data.edit) : null; if (edit) { for (const section of this.allSections()) section._styleSheetEdited(edit); return; } if (this._userOperation || this._isEditingStyle) return; this._resetCache(); this.update(); } /** * @return {number} */ _focusedSectionIndex() { let index = 0; for (const block of this._sectionBlocks) { for (const section of block.sections) { if (section.element.hasFocus()) return index; index++; } } return -1; } /** * @param {?SDK.CSSMatchedStyles} matchedStyles * @return {!Promise} */ async _innerRebuildUpdate(matchedStyles) { const focusedIndex = this._focusedSectionIndex(); this._linkifier.reset(); this._sectionsContainer.removeChildren(); this._sectionBlocks = []; const node = this.node(); if (!matchedStyles || !node) { this._noMatchesElement.classList.remove('hidden'); return; } this._sectionBlocks = await this._rebuildSectionsForMatchedStyleRules(/** @type {!SDK.CSSMatchedStyles} */ (matchedStyles)); let pseudoTypes = []; const keys = matchedStyles.pseudoTypes(); if (keys.delete(Protocol.DOM.PseudoType.Before)) pseudoTypes.push(Protocol.DOM.PseudoType.Before); pseudoTypes = pseudoTypes.concat(keys.valuesArray().sort()); for (const pseudoType of pseudoTypes) { const block = Elements.SectionBlock.createPseudoTypeBlock(pseudoType); for (const style of matchedStyles.pseudoStyles(pseudoType)) { const section = new Elements.StylePropertiesSection(this, matchedStyles, style); block.sections.push(section); } this._sectionBlocks.push(block); } for (const keyframesRule of matchedStyles.keyframes()) { const block = Elements.SectionBlock.createKeyframesBlock(keyframesRule.name().text); for (const keyframe of keyframesRule.keyframes()) block.sections.push(new Elements.KeyframePropertiesSection(this, matchedStyles, keyframe.style)); this._sectionBlocks.push(block); } let index = 0; for (const block of this._sectionBlocks) { const titleElement = block.titleElement(); if (titleElement) this._sectionsContainer.appendChild(titleElement); for (const section of block.sections) { this._sectionsContainer.appendChild(section.element); if (index === focusedIndex) section.element.focus(); index++; } } if (focusedIndex >= index) this._sectionBlocks[0].sections[0].element.focus(); this._sectionsContainerFocusChanged(); if (this._filterRegex) this._updateFilter(); else this._noMatchesElement.classList.toggle('hidden', this._sectionBlocks.length > 0); this._nodeStylesUpdatedForTest(/** @type {!SDK.DOMNode} */ (node), true); if (this._decorator) { this._decorator.perform(); this._decorator = null; } } /** * @param {!SDK.DOMNode} node * @param {boolean} rebuild */ _nodeStylesUpdatedForTest(node, rebuild) { // For sniffing in tests. } /** * @param {!SDK.CSSMatchedStyles} matchedStyles * @return {!Promise<!Array.<!Elements.SectionBlock>>} */ async _rebuildSectionsForMatchedStyleRules(matchedStyles) { const blocks = [new Elements.SectionBlock(null)]; let lastParentNode = null; for (const style of matchedStyles.nodeStyles()) { const parentNode = matchedStyles.isInherited(style) ? matchedStyles.nodeForStyle(style) : null; if (parentNode && parentNode !== lastParentNode) { lastParentNode = parentNode; const block = await Elements.SectionBlock._createInheritedNodeBlock(lastParentNode); blocks.push(block); } const section = new Elements.StylePropertiesSection(this, matchedStyles, style); blocks.peekLast().sections.push(section); } return blocks; } async _createNewRuleInViaInspectorStyleSheet() { const cssModel = this.cssModel(); const node = this.node(); if (!cssModel || !node) return; this.setUserOperation(true); const styleSheetHeader = await cssModel.requestViaInspectorStylesheet(/** @type {!SDK.DOMNode} */ (node)); this.setUserOperation(false); await this._createNewRuleInStyleSheet(styleSheetHeader); } /** * @param {?SDK.CSSStyleSheetHeader} styleSheetHeader */ async _createNewRuleInStyleSheet(styleSheetHeader) { if (!styleSheetHeader) return; const text = await styleSheetHeader.requestContent() || ''; const lines = text.split('\n'); const range = TextUtils.TextRange.createFromLocation(lines.length - 1, lines[lines.length - 1].length); this._addBlankSection(this._sectionBlocks[0].sections[0], styleSheetHeader.id, range); } /** * @param {!Elements.StylePropertiesSection} insertAfterSection * @param {string} styleSheetId * @param {!TextUtils.TextRange} ruleLocation */ _addBlankSection(insertAfterSection, styleSheetId, ruleLocation) { const node = this.node(); const blankSection = new Elements.BlankStylePropertiesSection( this, insertAfterSection._matchedStyles, node ? node.simpleSelector() : '', styleSheetId, ruleLocation, insertAfterSection._style); this._sectionsContainer.insertBefore(blankSection.element, insertAfterSection.element.nextSibling); for (const block of this._sectionBlocks) { const index = block.sections.indexOf(insertAfterSection); if (index === -1) continue; block.sections.splice(index + 1, 0, blankSection); blankSection.startEditingSelector(); } } /** * @param {!Elements.StylePropertiesSection} section */ removeSection(section) { for (const block of this._sectionBlocks) { const index = block.sections.indexOf(section); if (index === -1) continue; block.sections.splice(index, 1); section.element.remove(); } } /** * @return {?RegExp} */ filterRegex() { return this._filterRegex; } _updateFilter() { let hasAnyVisibleBlock = false; for (const block of this._sectionBlocks) hasAnyVisibleBlock |= block.updateFilter(); this._noMatchesElement.classList.toggle('hidden', hasAnyVisibleBlock); } /** * @override */ willHide() { this._swatchPopoverHelper.hide(); super.willHide(); } /** * @return {!Array<!Elements.StylePropertiesSection>} */ allSections() { let sections = []; for (const block of this._sectionBlocks) sections = sections.concat(block.sections); return sections; } /** * @param {!Event} event */ _clipboardCopy(event) { Host.userMetrics.actionTaken(Host.UserMetrics.Action.StyleRuleCopied); } /** * @return {!Element} */ _createStylesSidebarToolbar() { const container = this.contentElement.createChild('div', 'styles-sidebar-pane-toolbar-container'); const hbox = container.createChild('div', 'hbox styles-sidebar-pane-toolbar'); const filterContainerElement = hbox.createChild('div', 'styles-sidebar-pane-filter-box'); const filterInput = Elements.StylesSidebarPane.createPropertyFilterElement(ls`Filter`, hbox, this._onFilterChanged.bind(this)); UI.ARIAUtils.setAccessibleName(filterInput, Common.UIString('Filter Styles')); filterContainerElement.appendChild(filterInput); const toolbar = new UI.Toolbar('styles-pane-toolbar', hbox); toolbar.makeToggledGray(); toolbar.appendLocationItems('styles-sidebarpane-toolbar'); const toolbarPaneContainer = container.createChild('div', 'styles-sidebar-toolbar-pane-container'); const toolbarPaneContent = toolbarPaneContainer.createChild('div', 'styles-sidebar-toolbar-pane'); return toolbarPaneContent; } /** * @param {?UI.Widget} widget * @param {?UI.ToolbarToggle} toggle */ showToolbarPane(widget, toggle) { if (this._pendingWidgetToggle) this._pendingWidgetToggle.setToggled(false); this._pendingWidgetToggle = toggle; if (this._animatedToolbarPane) this._pendingWidget = widget; else this._startToolbarPaneAnimation(widget); if (widget && toggle) toggle.setToggled(true); } /** * @param {?UI.Widget} widget */ _startToolbarPaneAnimation(widget) { if (widget === this._currentToolbarPane) return; if (widget && this._currentToolbarPane) { this._currentToolbarPane.detach(); widget.show(this._toolbarPaneElement); this._currentToolbarPane = widget; this._currentToolbarPane.focus(); return; } this._animatedToolbarPane = widget; if (this._currentToolbarPane) this._toolbarPaneElement.style.animationName = 'styles-element-state-pane-slideout'; else if (widget) this._toolbarPaneElement.style.animationName = 'styles-element-state-pane-slidein'; if (widget) widget.show(this._toolbarPaneElement); const listener = onAnimationEnd.bind(this); this._toolbarPaneElement.addEventListener('animationend', listener, false); /** * @this {!Elements.StylesSidebarPane} */ function onAnimationEnd() { this._toolbarPaneElement.style.removeProperty('animation-name'); this._toolbarPaneElement.removeEventListener('animationend', listener, false); if (this._currentToolbarPane) this._currentToolbarPane.detach(); this._currentToolbarPane = this._animatedToolbarPane; if (this._currentToolbarPane) this._currentToolbarPane.focus(); this._animatedToolbarPane = null; if (this._pendingWidget) { this._startToolbarPaneAnimation(this._pendingWidget); this._pendingWidget = null; } } } }; Elements.StylesSidebarPane._maxLinkLength = 30; Elements.SectionBlock = class { /** * @param {?Element} titleElement */ constructor(titleElement) { this._titleElement = titleElement; this.sections = []; } /** * @param {!Protocol.DOM.PseudoType} pseudoType * @return {!Elements.SectionBlock} */ static createPseudoTypeBlock(pseudoType) { const separatorElement = createElement('div'); separatorElement.className = 'sidebar-separator'; separatorElement.textContent = Common.UIString('Pseudo ::%s element', pseudoType); return new Elements.SectionBlock(separatorElement); } /** * @param {string} keyframesName * @return {!Elements.SectionBlock} */ static createKeyframesBlock(keyframesName) { const separatorElement = createElement('div'); separatorElement.className = 'sidebar-separator'; separatorElement.textContent = Common.UIString('@keyframes ' + keyframesName); return new Elements.SectionBlock(separatorElement); } /** * @param {!SDK.DOMNode} node * @return {!Promise<!Elements.SectionBlock>} */ static async _createInheritedNodeBlock(node) { const separatorElement = createElement('div'); separatorElement.className = 'sidebar-separator'; separatorElement.createTextChild(Common.UIString('Inherited from') + ' '); const link = await Common.Linkifier.linkify(node); separatorElement.appendChild(link); return new Elements.SectionBlock(separatorElement); } /** * @return {boolean} */ updateFilter() { let hasAnyVisibleSection = false; for (const section of this.sections) hasAnyVisibleSection |= section._updateFilter(); if (this._titleElement) this._titleElement.classList.toggle('hidden', !hasAnyVisibleSection); return hasAnyVisibleSection; } /** * @return {?Element} */ titleElement() { return this._titleElement; } }; Elements.StylePropertiesSection = class { /** * @param {!Elements.StylesSidebarPane} parentPane * @param {!SDK.CSSMatchedStyles} matchedStyles * @param {!SDK.CSSStyleDeclaration} style */ constructor(parentPane, matchedStyles, style) { this._parentPane = parentPane; this._style = style; this._matchedStyles = matchedStyles; this.editable = !!(style.styleSheetId && style.range); /** @type {?number} */ this._hoverTimer = null; this._willCauseCancelEditing = false; this._forceShowAll = false; this._originalPropertiesCount = style.leadingProperties().length; const rule = style.parentRule; this.element = createElementWithClass('div', 'styles-section matched-styles monospace'); this.element.tabIndex = -1; UI.ARIAUtils.markAsTreeitem(this.element); this._editing = false; this.element.addEventListener('keydown', this._onKeyDown.bind(this), false); this.element._section = this; this._innerElement = this.element.createChild('div'); this._titleElement = this._innerElement.createChild('div', 'styles-section-title ' + (rule ? 'styles-selector' : '')); this.propertiesTreeOutline = new UI.TreeOutlineInShadow(); this.propertiesTreeOutline.setFocusable(false); this.propertiesTreeOutline.registerRequiredCSS('elements/stylesSectionTree.css'); this.propertiesTreeOutline.element.classList.add('style-properties', 'matched-styles', 'monospace'); this.propertiesTreeOutline.section = this; this._innerElement.appendChild(this.propertiesTreeOutline.element); this._showAllButton = UI.createTextButton('', this._showAllItems.bind(this), 'styles-show-all'); this._innerElement.appendChild(this._showAllButton); const selectorContainer = createElement('div'); this._selectorElement = createElementWithClass('span', 'selector'); this._selectorElement.textContent = this._headerText(); selectorContainer.appendChild(this._selectorElement); this._selectorElement.addEventListener('mouseenter', this._onMouseEnterSelector.bind(this), false); this._selectorElement.addEventListener('mouseleave', this._onMouseOutSelector.bind(this), false); const openBrace = createElement('span'); openBrace.textContent = ' {'; selectorContainer.appendChild(openBrace); selectorContainer.addEventListener('mousedown', this._handleEmptySpaceMouseDown.bind(this), false); selectorContainer.addEventListener('click', this._handleSelectorContainerClick.bind(this), false); const closeBrace = this._innerElement.createChild('div', 'sidebar-pane-closing-brace'); closeBrace.textContent = '}'; this._createHoverMenuToolbar(closeBrace); this._selectorElement.addEventListener('click', this._handleSelectorClick.bind(this), false); this.element.addEventListener('mousedown', this._handleEmptySpaceMouseDown.bind(this), false); this.element.addEventListener('click', this._handleEmptySpaceClick.bind(this), false); this.element.addEventListener('mousemove', this._onMouseMove.bind(this), false); this.element.addEventListener('mouseleave', this._setSectionHovered.bind(this, false), false); if (rule) { // Prevent editing the user agent and user rules. if (rule.isUserAgent() || rule.isInjected()) { this.editable = false; } else { // Check this is a real CSSRule, not a bogus object coming from Elements.BlankStylePropertiesSection. if (rule.styleSheetId) { const header = rule.cssModel().styleSheetHeaderForId(rule.styleSheetId); this.navigable = !header.isAnonymousInlineStyleSheet(); } } } this._mediaListElement = this._titleElement.createChild('div', 'media-list media-matches'); this._selectorRefElement = this._titleElement.createChild('div', 'styles-section-subtitle'); this._updateMediaList(); this._updateRuleOrigin(); this._titleElement.appendChild(selectorContainer); this._selectorContainer = selectorContainer; if (this.navigable) this.element.classList.add('navigable'); if (!this.editable) { this.element.classList.add('read-only'); this.propertiesTreeOutline.element.classList.add('read-only'); } const throttler = new Common.Throttler(100); this._scheduleHeightUpdate = () => throttler.schedule(this._manuallySetHeight.bind(this)); this._hoverableSelectorsMode = false; this._markSelectorMatches(); this.onpopulate(); } /** * @param {!SDK.CSSMatchedStyles} matchedStyles * @param {!Components.Linkifier} linkifier * @param {?SDK.CSSRule} rule * @return {!Node} */ static createRuleOriginNode(matchedStyles, linkifier, rule) { if (!rule) return createTextNode(''); let ruleLocation; if (rule instanceof SDK.CSSStyleRule) ruleLocation = rule.style.range; else if (rule instanceof SDK.CSSKeyframeRule) ruleLocation = rule.key().range; const header = rule.styleSheetId ? matchedStyles.cssModel().styleSheetHeaderForId(rule.styleSheetId) : null; if (ruleLocation && rule.styleSheetId && header && !header.isAnonymousInlineStyleSheet()) { return Elements.StylePropertiesSection._linkifyRuleLocation( matchedStyles.cssModel(), linkifier, rule.styleSheetId, ruleLocation); } if (rule.isUserAgent()) return createTextNode(Common.UIString('user agent stylesheet')); if (rule.isInjected()) return createTextNode(Common.UIString('injected stylesheet')); if (rule.isViaInspector()) return createTextNode(Common.UIString('via inspector')); if (header && header.ownerNode) { const link = Elements.DOMLinkifier.linkifyDeferredNodeReference(header.ownerNode); link.textContent = '<style>…</style>'; return link; } return createTextNode(''); } /** * @param {!SDK.CSSModel} cssModel * @param {!Components.Linkifier} linkifier * @param {string} styleSheetId * @param {!TextUtils.TextRange} ruleLocation * @return {!Node} */ static _linkifyRuleLocation(cssModel, linkifier, styleSheetId, ruleLocation) { const styleSheetHeader = cssModel.styleSheetHeaderForId(styleSheetId); const lineNumber = styleSheetHeader.lineNumberInSource(ruleLocation.startLine); const columnNumber = styleSheetHeader.columnNumberInSource(ruleLocation.startLine, ruleLocation.startColumn); const matchingSelectorLocation = new SDK.CSSLocation(styleSheetHeader, lineNumber, columnNumber); return linkifier.linkifyCSSLocation(matchingSelectorLocation); } /** * @param {!Event} event */ _onKeyDown(event) { if (this._editing || !this.editable || event.altKey || event.ctrlKey || event.metaKey) return; switch (event.key) { case 'Enter': case ' ': this._startEditingAtFirstPosition(); event.consume(true); break; default: // Filter out non-printable key strokes. if (event.key.length === 1) this.addNewBlankProperty(0).startEditing(); break; } } /** * @param {boolean} isHovered */ _setSectionHovered(isHovered) { this.element.classList.toggle('styles-panel-hovered', isHovered); this.propertiesTreeOutline.element.classList.toggle('styles-panel-hovered', isHovered); if (this._hoverableSelectorsMode !== isHovered) { this._hoverableSelectorsMode = isHovered; this._markSelectorMatches(); } } /** * @param {!Event} event */ _onMouseMove(event) { const hasCtrlOrMeta = UI.KeyboardShortcut.eventHasCtrlOrMeta(/** @type {!MouseEvent} */ (event)); this._setSectionHovered(hasCtrlOrMeta); } /** * @param {!Element} container */ _createHoverMenuToolbar(container) { if (!this.editable) return; const items = []; const textShadowButton = new UI.ToolbarButton(Common.UIString('Add text-shadow'), 'largeicon-text-shadow'); textShadowButton.addEventListener( UI.ToolbarButton.Events.Click, this._onInsertShadowPropertyClick.bind(this, 'text-shadow')); textShadowButton.element.tabIndex = -1; items.push(textShadowButton); const boxShadowButton = new UI.ToolbarButton(Common.UIString('Add box-shadow'), 'largeicon-box-shadow'); boxShadowButton.addEventListener( UI.ToolbarButton.Events.Click, this._onInsertShadowPropertyClick.bind(this, 'box-shadow')); boxShadowButton.element.tabIndex = -1; items.push(boxShadowButton); const colorButton = new UI.ToolbarButton(Common.UIString('Add color'), 'largeicon-foreground-color'); colorButton.addEventListener(UI.ToolbarButton.Events.Click, this._onInsertColorPropertyClick, this); colorButton.element.tabIndex = -1; items.push(colorButton); const backgroundButton = new UI.ToolbarButton(Common.UIString('Add background-color'), 'largeicon-background-color'); backgroundButton.addEventListener(UI.ToolbarButton.Events.Click, this._onInsertBackgroundColorPropertyClick, this); backgroundButton.element.tabIndex = -1; items.push(backgroundButton); let newRuleButton = null; if (this._style.parentRule) { newRuleButton = new UI.ToolbarButton(Common.UIString('Insert Style Rule Below'), 'largeicon-add'); newRuleButton.addEventListener(UI.ToolbarButton.Events.Click, this._onNewRuleClick, this); newRuleButton.element.tabIndex = -1; items.push(newRuleButton); } const sectionToolbar = new UI.Toolbar('sidebar-pane-section-toolbar', container); for (let i = 0; i < items.length; ++i) sectionToolbar.appendToolbarItem(items[i]); const menuButton = new UI.ToolbarButton('', 'largeicon-menu'); menuButton.element.tabIndex = -1; sectionToolbar.appendToolbarItem(menuButton); setItemsVisibility.call(this, items, false); sectionToolbar.element.addEventListener('mouseenter', setItemsVisibility.bind(this, items, true)); sectionToolbar.element.addEventListener('mouseleave', setItemsVisibility.bind(this, items, false)); UI.ARIAUtils.markAsHidden(sectionToolbar.element); /** * @param {!Array<!UI.ToolbarButton>} items * @param {boolean} value * @this {Elements.StylePropertiesSection} */ function setItemsVisibility(items, value) { for (let i = 0; i < items.length; ++i) items[i].setVisible(value); menuButton.setVisible(!value); if (this._isSASSStyle()) newRuleButton.setVisible(false); } } /** * @return {boolean} */ _isSASSStyle() { const header = this._style.styleSheetId ? this._style.cssModel().styleSheetHeaderForId(this._style.styleSheetId) : null; if (!header) return false; const sourceMap = header.cssModel().sourceMapManager().sourceMapForClient(header); return sourceMap ? sourceMap.editable() : false; } /** * @return {!SDK.CSSStyleDeclaration} */ style() { return this._style; } /** * @return {string} */ _headerText() { const node = this._matchedStyles.nodeForStyle(this._style); if (this._style.type === SDK.CSSStyleDeclaration.Type.Inline) return this._matchedStyles.isInherited(this._style) ? Common.UIString('Style Attribute') : 'element.style'; if (this._style.type === SDK.CSSStyleDeclaration.Type.Attributes) return node.nodeNameInCorrectCase() + '[' + Common.UIString('Attributes Style') + ']'; return this._style.parentRule.selectorText(); } _onMouseOutSelector() { if (this._hoverTimer) clearTimeout(this._hoverTimer); SDK.OverlayModel.hideDOMNodeHighlight(); } _onMouseEnterSelector() { if (this._hoverTimer) clearTimeout(this._hoverTimer); this._hoverTimer = setTimeout(this._highlight.bind(this), 300); } _highlight() { SDK.OverlayModel.hideDOMNodeHighlight(); const node = this._parentPane.node(); if (!node) return; const selectors = this._style.parentRule ? this._style.parentRule.selectorText() : undefined; node.domModel().overlayModel().highlightDOMNodeWithConfig( node.id, {mode: 'all', showInfo: undefined, selectors: selectors}); } /** * @return {?Elements.StylePropertiesSection} */ firstSibling() { const parent = this.element.parentElement; if (!parent) return null; let childElement = parent.firstChild; while (childElement) { if (childElement._section) return childElement._section; childElement = childElement.nextSibling; } return null; } /** * @return {?Elements.StylePropertiesSection} */ lastSibling() { const parent = this.element.parentElement; if (!parent) return null; let childElement = parent.lastChild; while (childElement) { if (childElement._section) return childElement._section; childElement = childElement.previousSibling; } return null; } /** * @return {?Elements.StylePropertiesSection} */ nextSibling() { let curElement = this.element; do curElement = curElement.nextSibling; while (curElement && !curElement._section); return curElement ? curElement._section : null; } /** * @return {?Elements.StylePropertiesSection} */ previousSibling() { let curElement = this.element; do curElement = curElement.previousSibling; while (curElement && !curElement._section); return curElement ? curElement._section : null; } /** * @param {!Common.Event} event */ _onNewRuleClick(event) { event.data.consume(); const rule = this._style.parentRule; const range = TextUtils.TextRange.createFromLocation(rule.style.range.endLine, rule.style.range.endColumn + 1); this._parentPane._addBlankSection(this, /** @type {string} */ (rule.styleSheetId), range); } /** * @param {string} propertyName * @param {!Common.Event} event */ _onInsertShadowPropertyClick(propertyName, event) { event.data.consume(true); const treeElement = this.addNewBlankProperty(); treeElement.property.name = propertyName; treeElement.property.value = '0 0 black'; treeElement.updateTitle(); const shadowSwatchPopoverHelper = Elements.ShadowSwatchPopoverHelper.forTreeElement(treeElement); if (shadowSwatchPopoverHelper) shadowSwatchPopoverHelper.showPopover(); } /** * @param {!Common.Event} event */ _onInsertColorPropertyClick(event) { event.data.consume(true); const treeElement = this.addNewBlankProperty(); treeElement.property.name = 'color'; treeElement.property.value = 'black'; treeElement.updateTitle(); const colorSwatch = Elements.ColorSwatchPopoverIcon.forTreeElement(treeElement); if (colorSwatch) colorSwatch.showPopover(); } /** * @param {!Common.Event} event */ _onInsertBackgroundColorPropertyClick(event) { event.data.consume(true); const treeElement = this.addNewBlankProperty(); treeElement.property.name = 'background-color'; treeElement.property.value = 'white'; treeElement.updateTitle(); const colorSwatch = Elements.ColorSwatchPopoverIcon.forTreeElement(treeElement); if (colorSwatch) colorSwatch.showPopover(); } /** * @param {!SDK.CSSModel.Edit} edit */ _styleSheetEdited(edit) { const rule = this._style.parentRule; if (rule) rule.rebase(edit); else this._style.rebase(edit); this._updateMediaList(); this._updateRuleOrigin(); } /** * @param {!Array.<!SDK.CSSMedia>} mediaRules */ _createMediaList(mediaRules) { for (let i = mediaRules.length - 1; i >= 0; --i) { const media = mediaRules[i]; // Don't display trivial non-print media types. if (!media.text.includes('(') && media.text !== 'print') continue; const mediaDataElement = this._mediaListElement.createChild('div', 'media'); const mediaContainerElement = mediaDataElement.createChild('span'); const mediaTextElement = mediaContainerElement.createChild('span', 'media-text'); switch (media.source) { case SDK.CSSMedia.Source.LINKED_SHEET: case SDK.CSSMedia.Source.INLINE_SHEET: mediaTextElement.textContent = 'media="' + media.text + '"'; break; case SDK.CSSMedia.Source.MEDIA_RULE: const decoration = mediaContainerElement.createChild('span'); mediaContainerElement.insertBefore(decoration, mediaTextElement); decoration.textContent = '@media '; mediaTextElement.textContent = media.text; if (media.styleSheetId) { mediaDataElement.classList.add('editable-media'); mediaTextElement.addEventListener( 'click', this._handleMediaRuleClick.bind(this, media, mediaTextElement), false); } break; case SDK.CSSMedia.Source.IMPORT_RULE: mediaTextElement.textContent = '@import ' + media.text; break; } } } _updateMediaList() { this._mediaListElement.removeChildren(); if (this._style.parentRule && this._style.parentRule instanceof SDK.CSSStyleRule) this._createMediaList(this._style.parentRule.media); } /** * @param {string} propertyName * @return {boolean} */ isPropertyInherited(propertyName) { if (this._matchedStyles.isInherited(this._style)) { // While rendering inherited stylesheet, reverse meaning of this property. // Render truly inherited properties with black, i.e. return them as non-inherited. return !SDK.cssMetadata().isPropertyInherited(propertyName); } return false; } /** * @return {?Elements.StylePropertiesSection} */ nextEditableSibling() { let curSection = this; do curSection = curSection.nextSibling(); while (curSection && !curSection.editable); if (!curSection) { curSection = this.firstSibling(); while (curSection && !curSection.editable) curSection = curSection.nextSibling(); } return (curSection && curSection.editable) ? curSection : null; } /** * @return {?Elements.StylePropertiesSection} */ previousEditableSibling() { let curSection = this; do curSection = curSection.previousSibling(); while (curSection && !curSection.editable); if (!curSection) { curSection = this.lastSibling(); while (curSection && !curSection.editable) curSection = curSection.previousSibling(); } return (curSection && curSection.editable) ? curSection : null; } /** * @param {!Elements.StylePropertyTreeElement} editedTreeElement */ refreshUpdate(editedTreeElement) { this._parentPane._refreshUpdate(this, editedTreeElement); } /** * @param {!Elements.StylePropertyTreeElement} editedTreeElement */ _updateVarFunctions(editedTreeElement) { let child = this.propertiesTreeOutline.firstChild(); while (child) { if (child !== editedTreeElement) child.updateTitleIfComputedValueChanged(); child = child.traverseNextTreeElement(false /* skipUnrevealed */, null /* stayWithin */, true /* dontPopulate */); } } /** * @param {boolean} full */ update(full) { this._selectorElement.textContent = this._headerText(); this._markSelectorMatches(); if (full) { this.onpopulate(); } else { let child = this.propertiesTreeOutline.firstChild(); while (child) { child.setOverloaded(this._isPropertyOverloaded(child.property)); child = child.traverseNextTreeElement(false /* skipUnrevealed */, null /* stayWithin */, true /* dontPopulate */); } } } /** * @param {!Event=} event */ _showAllItems(event) { if (event) event.consume(); if (this._forceShowAll) return; this._forceShowAll = true; this.onpopulate(); } onpopulate() { this.propertiesTreeOutline.removeChildren(); const style = this._style; let count = 0; const properties = style.leadingProperties(); const maxProperties = Elements.StylePropertiesSection.MaxProperties + properties.length - this._originalPropertiesCount; for (const property of properties) { if (!this._forceShowAll && count >= maxProperties) break; count++; const isShorthand = !!style.longhandProperties(property.name).length; const inherited = this.isPropertyInherited(property.name); const overloaded = this._isPropertyOverloaded(property); const item = new Elements.StylePropertyTreeElement( this._parentPane, this._matchedStyles, property, isShorthand, inherited, overloaded, false); this.propertiesTreeOutline.appendChild(item); } if (count < properties.length) { this._showAllButton.classList.remove('hidden'); this._showAllButton.textContent = ls`Show All Properties (${properties.length - count} more)`; } else { this._showAllButton.classList.add('hidden'); } } /** * @param {!SDK.CSSProperty} property * @return {boolean} */ _isPropertyOverloaded(property) { return this._matchedStyles.propertyState(property) === SDK.CSSMatchedStyles.PropertyState.Overloaded; } /** * @return {boolean} */ _updateFilter() { let hasMatchingChild = false; this._showAllItems(); for (const child of this.propertiesTreeOutline.rootElement().children()) hasMatchingChild |= child._updateFilter(); const regex = this._parentPane.filterRegex(); const hideRule = !hasMatchingChild && !!regex && !regex.test(this.element.deepTextContent()); this.element.classList.toggle('hidden', hideRule); if (!hideRule && this._style.parentRule) this._markSelectorHighlights(); return !hideRule; } _markSelectorMatches() { const rule = this._style.parentRule; if (!rule) return; this._mediaListElement.classList.toggle('media-matches', this._matchedStyles.mediaMatches(this._style)); const selectorTexts = rule.selectors.map(selector => selector.text); const matchingSelectorIndexes = this._matchedStyles.matchingSelectors(/** @type {!SDK.CSSStyleRule} */ (rule)); const matchingSelectors = /** @type {!Array<boolean>} */ (new Array(selectorTexts.length).fill(false)); for (const matchingIndex of matchingSelectorIndexes) matchingSelectors[matchingIndex] = true; if (this._parentPane._isEditingStyle) return; const fragment = this._hoverableSelectorsMode ? this._renderHoverableSelectors(selectorTexts, matchingSelectors) : this._renderSimplifiedSelectors(selectorTexts, matchingSelectors); this._selectorElement.removeChildren(); this._selectorElement.appendChild(fragment); this._markSelectorHighlights(); } /** * @param {!Array<string>} selectors * @param {!Array<boolean>} matchingSelectors * @return {!DocumentFragment} */ _renderHoverableSelectors(selectors, matchingSelectors) { const fragment = createDocumentFragment(); for (let i = 0; i < selectors.length; ++i) { if (i) fragment.createTextChild(', '); fragment.appendChild(this._createSelectorElement(selectors[i], matchingSelectors[i], i)); } return fragment; } /** * @param {string} text * @param {boolean} isMatching * @param {number=} navigationIndex * @return {!Element} */ _createSelectorElement(text, isMatching, navigationIndex) { const element = createElementWithClass('span', 'simple-selector'); element.classList.toggle('selector-matches', isMatching); if (typeof navigationIndex === 'number') element._selectorIndex = navigationIndex; element.textContent = text; return element; } /** * @param {!Array<string>} selectors * @param {!Array<boolean>} matchingSelectors * @return {!DocumentFragment} */ _renderSimplifiedSelectors(selectors, matchingSelectors) { const fragment = createDocumentFragment(); let currentMatching = false; let text = ''; for (let i = 0; i < selectors.length; ++i) { if (currentMatching !== matchingSelectors[i] && text) { fragment.appendChild(this._createSelectorElement(text, currentMatching)); text = ''; } currentMatching = matchingSelectors[i]; text += selectors[i] + (i === selectors.length - 1 ? '' : ', '); } if (text) fragment.appendChild(this._createSelectorElement(text, currentMatching)); return fragment; } _markSelectorHighlights() { const selectors = this._selectorElement.getElementsByClassName('simple-selector'); const regex = this._parentPane.filterRegex(); for (let i = 0; i < selectors.length; ++i) { const selectorMatchesFilter = !!regex && regex.test(selectors[i].textContent); selectors[i].classList.toggle('filter-match', selectorMatchesFilter); } } /** * @return {boolean} */ _checkWillCancelEditing() { const willCauseCancelEditing = this._willCauseCancelEditing; this._willCauseCancelEditing = false; return willCauseCancelEditing; } /** * @param {!Event} event */ _handleSelectorContainerClick(event) { if (this._checkWillCancelEditing() || !this.editable) return; if (event.target === this._selectorContainer) { this.addNewBlankProperty(0).startEditing(); event.consume(true); } } /** * @param {number=} index * @return {!Elements.StylePropertyTreeElement} */ addNewBlankProperty(index = this.propertiesTreeOutline.rootElement().childCount()) { const property = this._style.newBlankProperty(index); const item = new Elements.StylePropertyTreeElement( this._parentPane, this._matchedStyles, property, false, false, false, true); this.propertiesTreeOutline.insertChild(item, property.index); return item; } _handleEmptySpaceMouseDown() { this._willCauseCancelEditing = this._parentPane._isEditingStyle; } /** * @param {!Event} event */ _handleEmptySpaceClick(event) { if (!this.editable || this.element.hasSelection() || this._checkWillCancelEditing()) return; if (event.target.classList.contains('header') || this.element.classList.contains('read-only') || event.target.enclosingNodeOrSelfWithClass('media')) { event.consume(); return; } const deepTarget = event.deepElementFromPoint(); if (deepTarget.treeElement) this.addNewBlankProperty(deepTarget.treeElement.property.index + 1).startEditing(); else this.addNewBlankProperty().startEditing(); event.consume(true); } /** * @param {!SDK.CSSMedia} media * @param {!Element} element * @param {!Event} event */ _handleMediaRuleClick(media, element, event) { if (UI.isBeingEdited(element)) return; if (UI.KeyboardShortcut.eventHasCtrlOrMeta(/** @type {!MouseEvent} */ (event)) && this.navigable) { const location = media.rawLocation(); if (!location) { event.consume(true); return; } const uiLocation = Bindings.cssWorkspaceBinding.rawLocationToUILocation(location); if (uiLocation) Common.Revealer.reveal(uiLocation); event.consume(true); return; } if (!this.editable || this._isSASSStyle()) return; const config = new UI.InplaceEditor.Config( this._editingMediaCommitted.bind(this, media), this._editingMediaCancelled.bind(this, element), undefined, this._editingMediaBlurHandler.bind(this)); UI.InplaceEditor.startEditing(element, config); this.startEditing(); element.getComponentSelection().selectAllChildren(element); this._parentPane.setEditingStyle(true); const parentMediaElement = element.enclosingNodeOrSelfWithClass('media'); parentMediaElement.classList.add('editing-media'); event.consume(true); } /** * @param {!Element} element */ _editingMediaFinished(element) { this._parentPane.setEditingStyle(false); const parentMediaElement = element.enclosingNodeOrSelfWithClass('media'); parentMediaElement.classList.remove('editing-media'); this.stopEditing(); } /** * @param {!Element} element */ _editingMediaCancelled(element) { this._editingMediaFinished(element); // Mark the selectors in group if necessary. // This is overridden by BlankStylePropertiesSection. this._markSelectorMatches(); element.getComponentSelection().collapse(element, 0); } /** * @param {!Element} editor * @param {!Event} blurEvent * @return {boolean} */ _editingMediaBlurHandler(editor, blurEvent) { return true; } /** * @param {!SDK.CSSMedia} media * @param {!Element} element * @param {string} newContent * @param {string} oldContent * @param {(!Elements.StylePropertyTreeElement.Context|undefined)} context * @param {string} moveDirection */ _editingMediaCommitted(media, element, newContent, oldContent, context, moveDirection) { this._parentPane.setEditingStyle(false); this._editingMediaFinished(element); if (newContent) newContent = newContent.trim(); /** * @param {boolean} success * @this {Elements.StylePropertiesSection} */ function userCallback(success) { if (success) { this._matchedStyles.resetActiveProperties(); this._parentPane._refreshUpdate(this); } this._parentPane.setUserOperation(false); this._editingMediaTextCommittedForTest(); } // This gets deleted in finishOperation(), which is called both on success and failure. this._parentPane.setUserOperation(true); this._parentPane.cssModel().setMediaText(media.styleSheetId, media.range, newContent).then(userCallback.bind(this)); } _editingMediaTextCommittedForTest() { } /** * @param {!Event} event */ _handleSelectorClick(event) { if (UI.KeyboardShortcut.eventHasCtrlOrMeta(/** @type {!MouseEvent} */ (event)) && this.navigable && event.target.classList.contains('simple-selector')) { this._navigateToSelectorSource(event.target._selectorIndex, true); event.consume(true); return; } this._startEditingAtFirstPosition(); event.consume(true); } /** * @param {number} index * @param {boolean} focus */ _navigateToSelectorSource(index, focus) { const cssModel = this._parentPane.cssModel(); const rule = this._style.parentRule; const header = cssModel.styleSheetHeaderForId(/** @type {string} */ (rule.styleSheetId)); if (!header) return; const rawLocation = new SDK.CSSLocation(header, rule.lineNumberInSource(index), rule.columnNumberInSource(index)); const uiLocation = Bindings.cssWorkspaceBinding.rawLocationToUILocation(rawLocation); if (uiLocation) Common.Revealer.reveal(uiLocation, !focus); } _startEditingAtFirstPosition() { if (!this.editable || this._isSASSStyle()) return; if (!this._style.parentRule) { this.moveEditorFromSelector('forward'); return; } this.startEditingSelector(); } startEditingSelector() { const element = this._selectorElement; if (UI.isBeingEdited(element)) return; element.scrollIntoViewIfNeeded(false); // Reset selector marks in group, and normalize whitespace. element.textContent = element.textContent.replace(/\s+/g, ' ').trim(); const config = new UI.InplaceEditor.Config(this.editingSelectorCommitted.bind(this), this.editingSelectorCancelled.bind(this)); UI.InplaceEditor.startEditing(this._selectorElement, config); this.startEditing(); element.getComponentSelection().selectAllChildren(element); this._parentPane.setEditingStyle(true); if (element.classList.contains('simple-selector')) this._navigateToSelectorSource(0, false); } /** * @param {string} moveDirection */ moveEditorFromSelector(moveDirection) { this._markSelectorMatches(); if (!moveDirection) return; if (moveDirection === 'forward') { let firstChild = this.propertiesTreeOutline.firstChild(); while (firstChild && firstChild.inherited()) firstChild = firstChild.nextSibling; if (!firstChild) this.addNewBlankProperty().startEditing(); else firstChild.startEditing(firstChild.nameElement); } else { const previousSection = this.previousEditableSibling(); if (!previousSection) return; previousSection.addNewBlankProperty().startEditing(); } } /** * @param {!Element} element * @param {string} newContent * @param {string} oldContent * @param {(!Elements.StylePropertyTreeElement.Context|undefined)} context * @param {string} moveDirection */ editingSelectorCommitted(element, newContent, oldContent, context, moveDirection) { this._editingSelectorEnded(); if (newContent) newContent = newContent.trim(); if (newContent === oldContent) { // Revert to a trimmed version of the selector if need be. this._selectorElement.textContent = newContent; this.moveEditorFromSelector(moveDirection); return; } const rule = this._style.parentRule; if (!rule) return; /** * @this {Elements.StylePropertiesSection} */ function headerTextCommitted() { this._parentPane.setUserOperation(false); this.moveEditorFromSelector(moveDirection); this._editingSelectorCommittedForTest(); } // This gets deleted in finishOperationAndMoveEditor(), which is called both on success and failure. this._parentPane.setUserOperation(true); this._setHeaderText(rule, newContent).then(headerTextCommitted.bind(this)); } /** * @param {!SDK.CSSRule} rule * @param {string} newContent * @return {!Promise} */ _setHeaderText(rule, newContent) { /** * @param {!SDK.CSSStyleRule} rule * @param {boolean} success * @return {!Promise} * @this {Elements.StylePropertiesSection} */ function onSelectorsUpdated(rule, success) { if (!success) return Promise.resolve(); return this._matchedStyles.recomputeMatchingSelectors(rule).then(updateSourceRanges.bind(this, rule)); } /** * @param {!SDK.CSSStyleRule} rule * @this {Elements.StylePropertiesSection} */ function updateSourceRanges(rule) { const doesAffectSelectedNode = this._matchedStyles.matchingSelectors(rule).length > 0; this.propertiesTreeOutline.element.classList.toggle('no-affect', !doesAffectSelectedNode); this._matchedStyles.resetActiveProperties(); this._parentPane._refreshUpdate(this); } console.assert(rule instanceof SDK.CSSStyleRule); const oldSelectorRange = rule.selectorRange(); if (!oldSelectorRange) return Promise.resolve(); return rule.setSelectorText(newContent) .then(onSelectorsUpdated.bind(this, /** @type {!SDK.CSSStyleRule} */ (rule), oldSelectorRange)); } _editingSelectorCommittedForTest() { } _updateRuleOrigin() { this._selectorRefElement.removeChildren(); this._selectorRefElement.appendChild(Elements.StylePropertiesSection.createRuleOriginNode( this._matchedStyles, this._parentPane._linkifier, this._style.parentRule)); } _editingSelectorEnded() { this._parentPane.setEditingStyle(false); this.stopEditing(); } editingSelectorCancelled() { this._editingSelectorEnded(); // Mark the selectors in group if necessary. // This is overridden by BlankStylePropertiesSection. this._markSelectorMatches(); } startEditing() { this._manuallySetHeight(); this.element.addEventListener('input', this._scheduleHeightUpdate, true); this._editing = true; } /** * @return {!Promise} */ _manuallySetHeight() { this.element.style.height = (this._innerElement.clientHeight + 1) + 'px'; this.element.style.contain = 'strict'; return Promise.resolve(); } stopEditing() { this.element.style.removeProperty('height'); this.element.style.removeProperty('contain'); this.element.removeEventListener('input', this._scheduleHeightUpdate, true); this._editing = false; if (this._parentPane.element === this._parentPane.element.ownerDocument.deepActiveElement()) this.element.focus(); } }; Elements.BlankStylePropertiesSection = class extends Elements.StylePropertiesSection { /** * @param {!Elements.StylesSidebarPane} stylesPane * @param {!SDK.CSSMatchedStyles} matchedStyles * @param {string} defaultSelectorText * @param {string} styleSheetId * @param {!TextUtils.TextRange} ruleLocation * @param {!SDK.CSSStyleDeclaration} insertAfterStyle */ constructor(stylesPane, matchedStyles, defaultSelectorText, styleSheetId, ruleLocation, insertAfterStyle) { const cssModel = /** @type {!SDK.CSSModel} */ (stylesPane.cssModel()); const rule = SDK.CSSStyleRule.createDummyRule(cssModel, defaultSelectorText); super(stylesPane, matchedStyles, rule.style); this._normal = false; this._ruleLocation = ruleLocation; this._styleSheetId = styleSheetId; this._selectorRefElement.removeChildren(); this._selectorRefElement.appendChild(Elements.StylePropertiesSection._linkifyRuleLocation( cssModel, this._parentPane._linkifier, styleSheetId, this._actualRuleLocation())); if (insertAfterStyle && insertAfterStyle.parentRule) this._createMediaList(insertAfterStyle.parentRule.media); this.element.classList.add('blank-section'); } /** * @return {!TextUtils.TextRange} */ _actualRuleLocation() { const prefix = this._rulePrefix(); const lines = prefix.split('\n'); const editRange = new TextUtils.TextRange(0, 0, lines.length - 1, lines.peekLast().length); return this._ruleLocation.rebaseAfterTextEdit(TextUtils.TextRange.createFromLocation(0, 0), editRange); } /** * @return {string} */ _rulePrefix() { return this._ruleLocation.startLine === 0 && this._ruleLocation.startColumn === 0 ? '' : '\n\n'; } /** * @return {boolean} */ get isBlank() { return !this._normal; } /** * @override * @param {!Element} element * @param {string} newContent * @param {string} oldContent * @param {!Elements.StylePropertyTreeElement.Context|undefined} context * @param {string} moveDirection */ editingSelectorCommitted(element, newContent, oldContent, context, moveDirection) { if (!this.isBlank) { super.editingSelectorCommitted(element, newContent, oldContent, context, moveDirection); return; } /** * @param {?SDK.CSSStyleRule} newRule * @return {!Promise} * @this {Elements.BlankStylePropertiesSection} */ function onRuleAdded(newRule) { if (!newRule) { this.editingSelectorCancelled(); this._editingSelectorCommittedForTest(); return Promise.resolve(); } return this._matchedStyles.addNewRule(newRule, this._matchedStyles.node()) .then(onAddedToCascade.bind(this, newRule)); } /** * @param {!SDK.CSSStyleRule} newRule * @this {Elements.BlankStylePropertiesSection} */ function onAddedToCascade(newRule) { const doesSelectorAffectSelectedNode = this._matchedStyles.matchingSelectors(newRule).length > 0; this._makeNormal(newRule); if (!doesSelectorAffectSelectedNode) this.propertiesTreeOutline.element.classList.add('no-affect'); this._updateRuleOrigin(); this._parentPane.setUserOperation(false); this._editingSelectorEnded(); if (this.element.parentElement) // Might have been detached already. this.moveEditorFromSelector(moveDirection); this._markSelectorMatches(); this._editingSelectorCommittedForTest(); } if (newContent) newContent = newContent.trim(); this._parentPane.setUserOperation(true); const cssModel = this._parentPane.cssModel(); const ruleText = this._rulePrefix() + newContent + ' {}'; cssModel.addRule(this._styleSheetId, ruleText, this._ruleLocation).then(onRuleAdded.bind(this)); } /** * @override */ editingSelectorCancelled() { this._parentPane.setUserOperation(false); if (!this.isBlank) { super.editingSelectorCancelled(); return; } this._editingSelectorEnded(); this._parentPane.removeSection(this); } /** * @param {!SDK.CSSRule} newRule */ _makeNormal(newRule) { this.element.classList.remove('blank-section'); this._style = newRule.style; // FIXME: replace this instance by a normal Elements.StylePropertiesSection. this._normal = true; } }; Elements.StylePropertiesSection.MaxProperties = 50; Elements.KeyframePropertiesSection = class extends Elements.StylePropertiesSection { /** * @param {!Elements.StylesSidebarPane} stylesPane * @param {!SDK.CSSMatchedStyles} matchedStyles * @param {!SDK.CSSStyleDeclaration} style */ constructor(stylesPane, matchedStyles, style) { super(stylesPane, matchedStyles, style); this._selectorElement.className = 'keyframe-key'; } /** * @override * @return {string} */ _headerText() { return this._style.parentRule.key().text; } /** * @override * @param {!SDK.CSSRule} rule * @param {string} newContent * @return {!Promise} */ _setHeaderText(rule, newContent) { /** * @param {boolean} success * @this {Elements.KeyframePropertiesSection} */ function updateSourceRanges(success) { if (!success) return; this._parentPane._refreshUpdate(this); } console.assert(rule instanceof SDK.CSSKeyframeRule); const oldRange = rule.key().range; if (!oldRange) return Promise.resolve(); return rule.setKeyText(newContent).then(updateSourceRanges.bind(this)); } /** * @override * @param {string} propertyName * @return {boolean} */ isPropertyInherited(propertyName) { return false; } /** * @override * @param {!SDK.CSSProperty} property * @return {boolean} */ _isPropertyOverloaded(property) { return false; } /** * @override */ _markSelectorHighlights() { } /** * @override */ _markSelectorMatches() { this._selectorElement.textContent = this._style.parentRule.key().text; } /** * @override */ _highlight() { } }; Elements.StylesSidebarPane.CSSPropertyPrompt = class extends UI.TextPrompt { /** * @param {!Elements.StylePropertyTreeElement} treeElement * @param {boolean} isEditingName */ constructor(treeElement, isEditingName) { // Use the same callback both for applyItemCallback and acceptItemCallback. super(); this.initialize(this._buildPropertyCompletions.bind(this), UI.StyleValueDelimiters); this._isColorAware = SDK.cssMetadata().isColorAwareProperty(treeElement.property.name); this._cssCompletions = []; if (isEditingName) { this._cssCompletions = SDK.cssMetadata().allProperties(); if (!treeElement.node().isSVGNode()) this._cssCompletions = this._cssCompletions.filter(property => !SDK.cssMetadata().isSVGProperty(property)); } else { this._cssCompletions = SDK.cssMetadata().propertyValues(treeElement.nameElement.textContent); } this._treeElement = treeElement; this._isEditingName = isEditingName; this._cssVariables = treeElement.matchedStyles().availableCSSVariables(treeElement.property.ownerStyle); if (this._cssVariables.length < 1000) this._cssVariables.sort(String.naturalOrderComparator); else this._cssVariables.sort(); if (!isEditingName) { this.disableDefaultSuggestionForEmptyInput(); // If a CSS value is being edited that has a numeric or hex substring, hint that precision modifier shortcuts are available. if (treeElement && treeElement.valueElement) { const cssValueText = treeElement.valueElement.textContent; if (cssValueText.match(/#[\da-f]{3,6}$/i)) { this.setTitle(Common.UIString( 'Increment/decrement with mousewheel or up/down keys. %s: R ±1, Shift: G ±1, Alt: B ±1', Host.isMac() ? 'Cmd' : 'Ctrl')); } else if (cssValueText.match(/\d+/)) { this.setTitle(Common.UIString( 'Increment/decrement with mousewheel or up/down keys. %s: ±100, Shift: ±10, Alt: ±0.1', Host.isMac() ? 'Cmd' : 'Ctrl')); } } } } /** * @override * @param {!Event} event */ onKeyDown(event) { switch (event.key) { case 'ArrowUp': case 'ArrowDown': case 'PageUp': case 'PageDown': if (this._handleNameOrValueUpDown(event)) { event.preventDefault(); return; } break; case 'Enter': // Accept any available autocompletions and advance to the next field. this.tabKeyPressed(); event.preventDefault(); return; } super.onKeyDown(event); } /** * @override * @param {!Event} event */ onMouseWheel(event) { if (this._handleNameOrValueUpDown(event)) { event.consume(true); return; } super.onMouseWheel(event); } /** * @override * @return {boolean} */ tabKeyPressed() { this.acceptAutoComplete(); // Always tab to the next field. return false; } /** * @param {!Event} event * @return {boolean} */ _handleNameOrValueUpDown(event) { /** * @param {string} originalValue * @param {string} replacementString * @this {Elements.StylesSidebarPane.CSSPropertyPrompt} */ function finishHandler(originalValue, replacementString) { // Synthesize property text disregarding any comments, custom whitespace etc. this._treeElement.applyStyleText( this._treeElement.nameElement.textContent + ': ' + this._treeElement.valueElement.textContent, false); } /** * @param {string} prefix * @param {number} number * @param {string} suffix * @return {string} * @this {Elements.StylesSidebarPane.CSSPropertyPrompt} */ function customNumberHandler(prefix, number, suffix) { if (number !== 0 && !suffix.length && SDK.cssMetadata().isLengthProperty(this._treeElement.property.name)) suffix = 'px'; return prefix + number + suffix; } // Handle numeric value increment/decrement only at this point. if (!this._isEditingName && this._treeElement.valueElement && UI.handleElementValueModifications( event, this._treeElement.valueElement, finishHandler.bind(this), this._isValueSuggestion.bind(this), customNumberHandler.bind(this))) return true; return false; } /** * @param {string} word * @return {boolean} */ _isValueSuggestion(word) { if (!word) return false; word = word.toLowerCase(); return this._cssCompletions.indexOf(word) !== -1 || word.startsWith('--'); } /** * @param {string} expression * @param {string} query * @param {boolean=} force * @return {!Promise<!UI.SuggestBox.Suggestions>} */ _buildPropertyCompletions(expression, query, force) { const lowerQuery = query.toLowerCase(); const editingVariable = !this._isEditingName && expression.trim().endsWith('var('); if (!query && !force && !editingVariable && (this._isEditingName || expression)) return Promise.resolve([]); const prefixResults = []; const anywhereResults = []; if (!editingVariable) this._cssCompletions.forEach(completion => filterCompletions.call(this, completion, false /* variable */)); if (this._isEditingName || editingVariable) this._cssVariables.forEach(variable => filterCompletions.call(this, variable, true /* variable */)); const results = prefixResults.concat(anywhereResults); if (!this._isEditingName && !results.length && query.length > 1 && '!important'.startsWith(lowerQuery)) results.push({text: '!important'}); const userEnteredText = query.replace('-', ''); if (userEnteredText && (userEnteredText === userEnteredText.toUpperCase())) { for (let i = 0; i < results.length; ++i) { if (!results[i].text.startsWith('--')) results[i].text = results[i].text.toUpperCase(); } } if (editingVariable) { results.forEach(result => { result.title = result.text; result.text += ')'; }); } if (this._isColorAware && !this._isEditingName) { results.stableSort((a, b) => { if (!!a.subtitleRenderer === !!b.subtitleRenderer) return 0; return a.subtitleRenderer ? -1 : 1; }); } return Promise.resolve(results); /** * @param {string} completion * @param {boolean} variable * @this {Elements.StylesSidebarPane.CSSPropertyPrompt} */ function filterCompletions(completion, variable) { const index = completion.toLowerCase().indexOf(lowerQuery); const result = {text: completion}; if (variable) { const computedValue = this._treeElement.matchedStyles().computeCSSVariable(this._treeElement.property.ownerStyle, completion); if (computedValue) { const color = Common.Color.parse(computedValue); if (color) result.subtitleRenderer = swatchRenderer.bind(null, color); } } if (index === 0) { result.priority = this._isEditingName ? SDK.cssMetadata().propertyUsageWeight(completion) : 1; prefixResults.push(result); } else if (index > -1) { anywhereResults.push(result); } } /** * @param {!Common.Color} color * @return {!Element} */ function swatchRenderer(color) { const swatch = InlineEditor.ColorSwatch.create(); swatch.hideText(true); swatch.setColor(color); swatch.style.pointerEvents = 'none'; return swatch; } } }; Elements.StylesSidebarPropertyRenderer = class { /** * @param {?SDK.CSSRule} rule * @param {?SDK.DOMNode} node * @param {string} name * @param {string} value */ constructor(rule, node, name, value) { this._rule = rule; this._node = node; this._propertyName = name; this._propertyValue = value; /** @type {?function(string):!Node} */ this._colorHandler = null; /** @type {?function(string):!Node} */ this._bezierHandler = null; /** @type {?function(string, string):!Node} */ this._shadowHandler = null; /** @type {?function(string):!Node} */ this._varHandler = createTextNode; } /** * @param {function(string):!Node} handler */ setColorHandler(handler) { this._colorHandler = handler; } /** * @param {function(string):!Node} handler */ setBezierHandler(handler) { this._bezierHandler = handler; } /** * @param {function(string, string):!Node} handler */ setShadowHandler(handler) { this._shadowHandler = handler; } /** * @param {function(string):!Node} handler */ setVarHandler(handler) { this._varHandler = handler; } /** * @return {!Element} */ renderName() { const nameElement = createElement('span'); nameElement.className = 'webkit-css-property'; nameElement.textContent = this._propertyName; nameElement.normalize(); return nameElement; } /** * @return {!Element} */ renderValue() { const valueElement = createElement('span'); valueElement.className = 'value'; if (!this._propertyValue) return valueElement; if (this._shadowHandler && (this._propertyName === 'box-shadow' || this._propertyName === 'text-shadow' || this._propertyName === '-webkit-box-shadow') && !SDK.CSSMetadata.VariableRegex.test(this._propertyValue)) { valueElement.appendChild(this._shadowHandler(this._propertyValue, this._propertyName)); valueElement.normalize(); return valueElement; } const regexes = [SDK.CSSMetadata.VariableRegex, SDK.CSSMetadata.URLRegex]; const processors = [this._varHandler, this._processURL.bind(this)]; if (this._bezierHandler && SDK.cssMetadata().isBezierAwareProperty(this._propertyName)) { regexes.push(UI.Geometry.CubicBezier.Regex); processors.push(this._bezierHandler); } if (this._colorHandler && SDK.cssMetadata().isColorAwareProperty(this._propertyName)) { regexes.push(Common.Color.Regex); processors.push(this._colorHandler); } const results = TextUtils.TextUtils.splitStringByRegexes(this._propertyValue, regexes); for (let i = 0; i < results.length; i++) { const result = results[i]; const processor = result.regexIndex === -1 ? createTextNode : processors[result.regexIndex]; valueElement.appendChild(processor(result.value)); } valueElement.normalize(); return valueElement; } /** * @param {string} text * @return {!Node} */ _processURL(text) { // Strip "url(" and ")" along with whitespace. let url = text.substring(4, text.length - 1).trim(); const isQuoted = /^'.*'$/.test(url) || /^".*"$/.test(url); if (isQuoted) url = url.substring(1, url.length - 1); const container = createDocumentFragment(); container.createTextChild('url('); let hrefUrl = null; if (this._rule && this._rule.resourceURL()) hrefUrl = Common.ParsedURL.completeURL(this._rule.resourceURL(), url); else if (this._node) hrefUrl = this._node.resolveURL(url); container.appendChild(Components.Linkifier.linkifyURL(hrefUrl || url, {text: url, preventClick: true})); container.createTextChild(')'); return container; } }; /** * @implements {UI.ToolbarItem.Provider} */ Elements.StylesSidebarPane.ButtonProvider = class { constructor() { this._button = new UI.ToolbarButton(Common.UIString('New Style Rule'), 'largeicon-add'); this._button.addEventListener(UI.ToolbarButton.Events.Click, this._clicked, this); const longclickTriangle = UI.Icon.create('largeicon-longclick-triangle', 'long-click-glyph'); this._button.element.appendChild(longclickTriangle); new UI.LongClickController(this._button.element, this._longClicked.bind(this)); UI.context.addFlavorChangeListener(SDK.DOMNode, onNodeChanged.bind(this)); onNodeChanged.call(this); /** * @this {Elements.StylesSidebarPane.ButtonProvider} */ function onNodeChanged() { let node = UI.context.flavor(SDK.DOMNode); node = node ? node.enclosingElementOrSelf() : null; this._button.setEnabled(!!node); } } /** * @param {!Common.Event} event */ _clicked(event) { Elements.StylesSidebarPane._instance._createNewRuleInViaInspectorStyleSheet(); } /** * @param {!Event} e */ _longClicked(e) { Elements.StylesSidebarPane._instance._onAddButtonLongClick(e); } /** * @override * @return {!UI.ToolbarItem} */ item() { return this._button; } };
weexteam/weex-toolkit
packages/@weex/plugins/debug/frontend/src/assets/inspector/elements/StylesSidebarPane.js
JavaScript
mit
78,980
var searchData= [ ['uniquecount',['UniqueCount',['../class_standard_trie_1_1cs_1_1_prefix_trie.html#a82986e28b3191486a98cf874a1ae1b06',1,'StandardTrie::cs::PrefixTrie']]] ];
tylervanover/ACH-Clerk
StandardTrie.cs/Documentation/html/search/properties_5.js
JavaScript
mit
176
/* * RegExp instance properties. * * RegExp instance 'source' property must behave as specified in E5 Section * 15.10.4.1 paragraphcs 5 and 6. Note: there is no one required form of source. * Tests are for the source form that we want. */ /* * FIXME: when does '\' in source need to be escaped? */ /* * FIXME: add property attribute checks */ function getflags(r) { var res = '' if (r.global) { res += 'g'; } if (r.ignoreCase) { res += 'i'; } if (r.multiline) { res += 'm'; } return res; } /* * Empty string */ /*=== (?:) ===*/ try { t = new RegExp(''); print(t.source); t = eval('/' + t.source + '/' + getflags(t)); t = t.exec(''); print(t[0]); } catch (e) { print(e.name); } /* * Forward slash */ /*=== \/ / ===*/ try { t = new RegExp('/'); /* matches one forward slash (only) */ print(t.source); t = eval('/' + t.source + '/' + getflags(t)); t = t.exec('/'); print(t[0]); } catch (e) { print(e.name); } /* * Backslash */ /*=== \d 9 ===*/ try { t = new RegExp('\\d'); /* matches a digit */ print(t.source); t = eval('/' + t.source + '/' + getflags(t)); t = t.exec('9'); print(t[0]); } catch (e) { print(e.name); } /* * Flags */ /*=== foo false true false foo false true false Foo foo true false false foo true false false foo false false true foo false false true ===*/ try { t = new RegExp('foo', 'i'); print(t.source, t.global, t.ignoreCase, t.multiline); t = eval('/' + t.source + '/' + getflags(t)); print(t.source, t.global, t.ignoreCase, t.multiline); t = t.exec('Foo'); print(t[0]); } catch (e) { print(e.name); } try { t = new RegExp('foo', 'g'); print(t.source, t.global, t.ignoreCase, t.multiline); t = eval('/' + t.source + '/' + getflags(t)); print(t.source, t.global, t.ignoreCase, t.multiline); } catch (e) { print(e.name); } try { t = new RegExp('foo', 'm'); print(t.source, t.global, t.ignoreCase, t.multiline); t = eval('/' + t.source + '/' + getflags(t)); print(t.source, t.global, t.ignoreCase, t.multiline); } catch (e) { print(e.name); } /* * lastIndex */ /*=== 0 ===*/ try { t = new RegExp('foo', 'i'); print(t.lastIndex); } catch (e) { print(e.name); }
andoma/duktape
ecmascript-testcases/test-regexp-instance-properties.js
JavaScript
mit
2,345
version https://git-lfs.github.com/spec/v1 oid sha256:ac9e4d0cf97f46d8fcb1545ff017272b57a2c9a45f74cc1e57792311dd060f6e size 603
yogeshsaroya/new-cdnjs
ajax/libs/mathjax/2.2/jax/output/HTML-CSS/fonts/TeX/Main/Bold/LatinExtendedA.js
JavaScript
mit
128
import {HttpClientConfiguration} from './http-client-configuration'; import {RequestInit, Interceptor} from './interfaces'; import 'core-js'; /** * An HTTP client based on the Fetch API. * * @constructor */ export class HttpClient { activeRequestCount: number = 0; isRequesting: boolean = false; interceptors: Interceptor[] = []; isConfigured: boolean = false; baseUrl: string = ''; defaults: RequestInit = null; /** * Configure this client with default settings to be used by all requests. * * @param config - A function that takes a config argument, * or a config object, or a string to use as the client's baseUrl. * @chainable */ configure(config: string|RequestInit|(config: HttpClientConfiguration) => void): HttpClient { let normalizedConfig; if (typeof config === 'string') { normalizedConfig = { baseUrl: config }; } else if (typeof config === 'object') { normalizedConfig = { defaults: config }; } else if (typeof config === 'function') { normalizedConfig = new HttpClientConfiguration(); config(normalizedConfig); } else { throw new Error('invalid config'); } let defaults = normalizedConfig.defaults; if (defaults && defaults.headers instanceof Headers) { // Headers instances are not iterable in all browsers. Require a plain // object here to allow default headers to be merged into request headers. throw new Error('Default headers must be a plain object.'); } this.baseUrl = normalizedConfig.baseUrl; this.defaults = defaults; this.interceptors.push(...normalizedConfig.interceptors || []); this.isConfigured = true; return this; } /** * Starts the process of fetching a resource. Default configuration parameters * will be applied to the Request. The constructed Request will be passed to * registered request interceptors before being sent. The Response will be passed * to registered Response interceptors before it is returned. * * See also https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API * * @param input - The resource that you wish to fetch. Either a * Request object, or a string containing the URL of the resource. * @param - An options object containing settings to be applied to * the Request. */ fetch(input: Request|string, init?: RequestInit): Promise<Response> { this::trackRequestStart(); let request = Promise.resolve().then(() => this::buildRequest(input, init, this.defaults)); let promise = processRequest(request, this.interceptors) .then(result => { let response = null; if (result instanceof Response) { response = result; } else if (result instanceof Request) { response = fetch(result); } else { throw new Error(`An invalid result was returned by the interceptor chain. Expected a Request or Response instance, but got [${result}]`); } return processResponse(response, this.interceptors); }); return this::trackRequestEndWith(promise); } } function trackRequestStart() { this.isRequesting = !!(++this.activeRequestCount); } function trackRequestEnd() { this.isRequesting = !!(--this.activeRequestCount); } function trackRequestEndWith(promise) { let handle = this::trackRequestEnd; promise.then(handle, handle); return promise; } function buildRequest(input, init = {}) { let defaults = this.defaults || {}; let source; let url; let body; if (input instanceof Request) { if (!this.isConfigured) { // don't copy the request if there are no defaults configured return input; } source = input; url = input.url; body = input.blob(); } else { source = init; url = input; body = init.body; } let requestInit = Object.assign({}, defaults, source, { body }); let request = new Request((this.baseUrl || '') + url, requestInit); setDefaultHeaders(request.headers, defaults.headers); return request; } function setDefaultHeaders(headers, defaultHeaders) { for (let name in defaultHeaders || {}) { if (defaultHeaders.hasOwnProperty(name) && !headers.has(name)) { headers.set(name, defaultHeaders[name]); } } } function processRequest(request, interceptors) { return applyInterceptors(request, interceptors, 'request', 'requestError'); } function processResponse(response, interceptors) { return applyInterceptors(response, interceptors, 'response', 'responseError'); } function applyInterceptors(input, interceptors, successName, errorName) { return (interceptors || []) .reduce((chain, interceptor) => { let successHandler = interceptor[successName]; let errorHandler = interceptor[errorName]; return chain.then( successHandler && interceptor::successHandler, errorHandler && interceptor::errorHandler); }, Promise.resolve(input)); }
alexmills/fetch-client
src/http-client.js
JavaScript
mit
4,916
export * from './aurelia-pal-worker';
aurelia/pal-worker
dist/native-modules/index.js
JavaScript
mit
37
const validate = (value, options) => { if (Array.isArray(value)) { return value.every(val => validate(val, options)); } // eslint-disable-next-line return ! options.filter(option => option == value).length; }; export default validate;
dfcook/vee-validate
src/rules/notIn.js
JavaScript
mit
249
version https://git-lfs.github.com/spec/v1 oid sha256:8b057c8d60d76759e6a75285bd1fcea8ba4acea65ffe3b8e5ff4a1937cb3dacd size 2530
yogeshsaroya/new-cdnjs
ajax/libs/yui/3.15.0/view-node-map/view-node-map.js
JavaScript
mit
129
import createSvgIcon from './utils/createSvgIcon'; import { jsx as _jsx } from "react/jsx-runtime"; export default createSvgIcon([/*#__PURE__*/_jsx("path", { d: "m8 6.83-4 4V18h3v-3h2v3h3v-7.17l-4-4zM9 13H7v-2h2v2z", opacity: ".3" }, "0"), /*#__PURE__*/_jsx("path", { d: "m8 4-6 6v10h12V10L8 4zm4 14H9v-3H7v3H4v-7.17l4-4 4 4V18zm-3-5H7v-2h2v2zm9 7V8.35L13.65 4h-2.83L16 9.18V20h2zm4 0V6.69L19.31 4h-2.83L20 7.52V20h2z" }, "1")], 'HolidayVillageTwoTone');
oliviertassinari/material-ui
packages/mui-icons-material/lib/esm/HolidayVillageTwoTone.js
JavaScript
mit
460
import Binding from 'virtualdom/items/Element/Binding/Binding'; import handleDomEvent from 'virtualdom/items/Element/Binding/shared/handleDomEvent'; var CheckboxBinding = Binding.extend({ name: 'checked', render: function () { var node = this.element.node; node.addEventListener( 'change', handleDomEvent, false ); if ( node.attachEvent ) { node.addEventListener( 'click', handleDomEvent, false ); } }, unrender: function () { var node = this.element.node; node.removeEventListener( 'change', handleDomEvent, false ); node.removeEventListener( 'click', handleDomEvent, false ); }, getValue: function () { return this.element.node.checked; } }); export default CheckboxBinding;
rstacruz/ractive
src/virtualdom/items/Element/Binding/CheckboxBinding.js
JavaScript
mit
711
var fs = require('fs'); var path = require('path'); var md_parser = require('./md_parser'); var $ = require('./helper'); var rootDir = path.join(__dirname, '../') + path.sep; var assetsDir = path.join(rootDir, 'assets') + path.sep; var templateDir = path.join(rootDir, 'template') + path.sep; //1. 只导出文件nodeppt generate file.md //2. 导出文件+目录 nodeppt generate ./ --all -o publish module.exports = function(filepath, outputDir, isAll) { filepath = fs.realpathSync(filepath); outputDir = outputDir ? $.getDirPath(outputDir) : $.getDirPath(path.join(process.cwd(), './publish')); isAll = !!isAll; if (isAll) { //1.导出assets $.copy(assetsDir, outputDir, function(filename, dir, subdir) { if (!subdir || subdir === 'scss') { //不复制scss return false; } return true; }); } //2.导出复制filepath除根目录下img、css和js等到assets,遇见/*.md就解析 generate(filepath, outputDir); console.log('生成结束!'.bold.green + require('path').relative('b:/', outputDir).yellow); }; function parser(content, template) { try { var html = md_parser(content, null, null, null, { generate: true }); return html; } catch (e) { console.log('ERROR: '.bold.red + e.toString()); } return false; } /** * 生成 * @param {[type]} filepath [description] * @param {[type]} outputDir [description] * @return {[type]} [description] */ function generate(filepath, outputDir) { var filename = ''; var templateMd = $.readFile(templateDir + 'markdown.ejs'); var templateList = $.readFile(templateDir + 'list.ejs'); if ($.isDir(filepath, true)) { //遍历目录生成htm var indexList = ''; $.copy(filepath, outputDir, function(filename, dir, subdir) { if (!subdir && /\.(?:md|markdown)$/i.test(filename)) { var content = $.readFile(path.join(filepath, filename)); var html = parser(content); if (html) { var title = html.match(/<title>(.*?)<\/title>/); if (title[1]) { title = title[1]; } else { title = filename; } var url = filename.replace(/\.(?:md|markdown)$/i, '.htm'); indexList += '<li><a class="star" href="' + url + '" target="_blank">' + title + '</a> &nbsp; [<a href="' + url + '?_multiscreen=1" target="_blank" title="多窗口打开">多窗口</a>]</li>'; copyLinkToOutput(content, filepath, outputDir); html = handlerHTML(html); $.writeFile(path.join(outputDir, filename.replace(/\.(?:md|markdown)$/i, '.htm')), html); } return false; } return true; }); //输出index文件 var packageJson = require(rootDir + 'package.json'); var data = { version: packageJson.version, site: packageJson.site, date: Date.now(), list: indexList, dir: '/' }; indexList = $.renderStr(templateList, data); $.writeFile(path.join(outputDir, 'index.html'), indexList); } else { var content; if ($.exists(filepath)) { content = $.readFile(filepath); } else { return console.log('ERROR: '.bold.red + filepath + ' is not exists!'); } filename = path.basename(filepath); copyLinkToOutput(content, filepath, outputDir); var html = parser(content); if (html) { html = handlerHTML(html); $.writeFile(path.join(outputDir, filename.replace(/\.(?:md|markdown)$/i, '.htm')), html); } } } //处理绝对路径的url function handlerHTML(html) { html = html.replace(/([src|href])=["']\//gi, '$1="./') .replace("loadJS('/js", "loadJS('./js").replace("dir: '/js/',", "dir: './js/',"); return html; } //处理页面相对url,到目标文件夹 function copyLinkToOutput(content, filepath, outputDir) { //[inline模式](/assets/box-fe-road/img/inline-mode.png) var files = []; content.replace(/\[.+?\]\(\s?(.*?)\s?\)/g, function(i, file) { files.push(file); }).replace(/href=(['"])(.+?)\1/g, function(i, q, file) { files.push(file); }); //解析cover var json = md_parser.parseCover(content.split(/\[slide.*\]/i)[0]); if (json.files) { files = files.concat(json.files.split(/\s?,\s?/)); } files.filter(function(f) { return !/^http[s]?:\/\//.test(f); }).forEach(function(f) { var topath = path.join(outputDir, f); var realpath = path.join(path.dirname(filepath), f); if ($.exists(realpath)) { var data = fs.readFileSync(String(realpath)); $.writeFile(topath, data); } }); }
wangjun/nodePPT
lib/generate.js
JavaScript
mit
5,060
/** * Sample React Native App * https://github.com/facebook/react-native * @flow */ import React, { Component } from 'react'; import { AppRegistry } from 'react-native'; import Navigation from './app/config/entry'; export default class RNJueJin extends Component { render() { return ( <Navigation /> ); } } AppRegistry.registerComponent('RNJueJin', () => RNJueJin);
noprom/RNJueJin
index.ios.js
JavaScript
mit
391
'use strict'; module.exports = ({ strapi }) => ({ getWelcomeMessage() { return 'Welcome to Strapi 🚀'; }, });
wistityhq/strapi
packages/generators/generators/lib/files/plugin/server/services/my-service.js
JavaScript
mit
121
/* */ (function(Buffer) { var crypto = require("crypto"); var sign = require("./sign"); var m = new Buffer('AF2BDBE1AA9B6EC1E2ADE1D694F41FC71A831D0268E9891562113D8A62ADD1BF', 'hex'); var xbuf = new Buffer('009A4D6792295A7F730FC3F2B49CBC0F62E862272F', 'hex'); var bn = require("bn.js"); var x = new bn(xbuf); var q = new Buffer('04000000000000000000020108A2E0CC0D99F8A5EF', 'hex'); var qbuf = new Buffer('04000000000000000000020108A2E0CC0D99F8A5EF', 'hex'); var q = new bn(qbuf); var kv = sign.getKay(x, q, m, 'sha256', crypto); var k = sign.makeKey(q, kv, 'sha256', crypto); console.log('k', k); })(require("buffer").Buffer);
thomjoy/turftest
src/jspm_packages/npm/browserify-sign@2.8.0/repl.js
JavaScript
mit
651
;(function () { var defaults = { "wrap": "this",//下拉列表用什么包裹,"this"为按钮自身,主流的插件放在"body"中 "data": null, "formName": "", "zIndex": 999 }; function Dropdown(opt) { var $this = $(this), id = $this.attr("id"), height = $this.outerHeight(), name = !!opt.formName ? opt.formName : id, liArray = [], aTop = height / 2 - 3; $this.css("position", "relative").append("<i class='dropdown_arrow' style='top:" + aTop + "px; right:10px'></i>"); if ($this.find("span").length < 1) { $this.append("<span></span>"); } $this.append("<input type='hidden' name='" + name + "'>"); if ($(".dropdown_menu[data-target='#" + id + "']").length < 1 && !!opt.data) { var wrap; if (opt.wrap == "this") { wrap = $this } else { wrap = $(opt.wrap) } wrap.append("<ul class='dropdown_menu' data-target='#" + id + "'></ul>") } var $menu = $(".dropdown_menu[data-target='#" + id + "']").hide().css({"position": "absolute", "zIndex": opt.zIndex}); if (!!opt.data) { for (var i = 0; i < opt.data.length; i++) { liArray.push("<li data-text='" + opt.data[i].text + "' data-value='" + opt.data[i].value + "' >" + opt.data[i].text + "</li>"); } $menu.html(liArray.join("")); } BindEvents($this, $menu, true); } function Reload(data) { var $this = $(this), id = $this.attr("id"), $menu = $(".dropdown_menu[data-target='#" + id + "']"), liArray = []; if (typeof data != "object") { return } for (var i = 0; i < data.length; i++) { liArray.push("<li data-text='" + data[i].text + "' data-value='" + data[i].value + "' >" + data[i].text + "</li>"); } $menu.html(liArray.join("")); BindEvents($this, $menu, false); } function setValue(text, value) { var $this = $(this); $this.data("value", value).find("span:eq(0)").html(text).end().find("input:hidden").val(value); } function setDisable (val){ } function BindEvents($this, $menu, init) { if(init){ $("body").on("click",function(){ $menu.hide(); }); } $this.off("click").on("click", function () { var width = $this.outerWidth(), height = $this.outerHeight(), offset = $this.offset(); var border = parseInt($menu.css("borderLeftWidth")) + parseInt($menu.css("borderRightWidth")); var padding = parseInt($menu.css("paddingLeft")) + parseInt($menu.css("paddingRight")); $menu.css({"width": (width - border - padding), "top": offset.top + height, "left": offset.left}).show(); $this.trigger("dropdown.show"); return false; }); $menu.delegate("li", "click", function () { var text = $(this).data("text"); var value = $(this).data("value"); setValue.call($this[0], text, value); $this.trigger("dropdown.set", [text, value]); $menu.hide(); }).delegate("li", "mouseenter", function () { $(this).addClass("cursor").siblings("li").removeClass("cursor"); }).mouseleave(function () { $menu.hide(); }); } //初始化下拉组件的方法 $.fn.dropdown = function (opt) { var opts = defaults; $.extend(true, opts, opt); return this.each(function () { Dropdown.call(this, opts); }); }; //重载下拉框数据的方法 $.fn.menuReload = function (data) { return this.each(function () { Reload.call(this, data); }); }; //设置下拉框的值 $.fn.setValue = function (data) { return this.each(function () { setValue.call(this, data.text, data.value); }); }; $.fn.setDisable = function (val) { return this.each(function () { setDisable.call(this, val); }); }; })();
hbest123/php183fxn
php183/public/home/meizu/person_files/dropdown.js
JavaScript
mit
4,286
const findIndex = require('lodash/findIndex'); module.exports = (req, res, next) => { const pageData = req.pageData || {}; const siblings = pageData.meta ? pageData.meta.siblings : []; const pagination = pageData.pagination || {}; if (pageData && pageData.guide && siblings) { const currentIndex = findIndex(siblings, (p) => { return pageData.slug.indexOf(p.slug) !== -1; }); if (currentIndex > 0) { pagination.previous = siblings[currentIndex - 1]; } if (siblings && currentIndex < siblings.length) { pagination.next = siblings[currentIndex + 1]; } pageData.pagination = pagination; } // eslint-disable-next-line no-param-reassign req.pageData = pageData; next(); };
nhsuk/betahealth
app/middleware/pagination.js
JavaScript
mit
736
var cheerio = require('cheerio') , request = require('request') , url = 'http://theroyalamerican.com/schedule/' , shows = [] , months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'] function royalamerican (done) { request(url, function(err, response, body) { var $ = cheerio.load(body) $('.gig').each(function(i, elem) { var price, time var $$ = cheerio.load(elem) var title = $$('.title').text().trim() if($$('.with').text().trim()) title += $$('.with').text().trim() var date = $$('.date').text().trim() var timePrice = $$('.details').text().trim().split('Show: ').join('').split('|') if(timePrice[0]) time = timePrice[0].trim() if(timePrice[1] && timePrice[1].trim().slice(0,1) === '$') price = timePrice[1].split('Cover')[0].trim() else price = '' var year = $('#gigs_left').children().attr('name') date = normalizeDate(date, year) var show = { venue: 'The Royal American', venueUrl: 'http://theroyalamerican.com/', title: title, time: time.slice(0,5).trim(), price: price, url: $$('.details').first().find('a').attr('href'), date: date } shows.push(show) }) done(null, shows) }) } module.exports = royalamerican function normalizeDate(date, year) { var newDate = [] date = date.split(' ') var day = date.pop() if(day.length < 2) day = '0'+day var month = date.pop() month = (months.indexOf(month)+1).toString() if(month.length < 2) month = '0'+month year = year.split('_')[1] newDate.push(year) newDate.push(month) newDate.push(day) return newDate.join('-') }
hethcox/chs-source
sources/royal-american.js
JavaScript
mit
1,903
<div ng-include="'components/navbar/navbar.html'"></div> <div class="container"> <div class="row"> <div class="col-lg-12"> <h1 class="page-header">Delete A ${model["name"]} :</h1> </div> </div> </div>
ErgoDelta/BigGenerator
templates/AngularJS_Swagger/views/object_delete.bigg.js
JavaScript
mit
220
var vows = require('vows'), assert = require('assert'), fs = require('fs'), jscheckstyle = require('../lib/jscheckstyle'); function given(inputFile, expectedOutput) { var context = {}; context['(' + inputFile + ') '] = { topic: function() { return jscheckstyle.analyse('/pants/file1.js', fs.readFileSync(__dirname + '/fixtures/' + inputFile, 'utf8')); } }; context['(' + inputFile + ') ']['passed to the renderer'] = expectedOutput; return context; } function expect(outputFile) { var context = { topic: function(results) { return jscheckstyle.renderers.checkstyle(results); } }; context['the output should match ' + outputFile] = function(output) { assert.equal(output, fs.readFileSync(__dirname + '/fixtures/' + outputFile, 'utf8')); }; return context; } vows.describe("checkstyle renderer").addBatch({ 'should be exported as a command line option': function() { assert.equal(jscheckstyle.renderers.checkstyle, jscheckstyle.renderers['--checkstyle']); }, 'with simple input': given('simple.js', expect('no-errors.xml')), 'with a cyclomatic complexity violation': given('complex-function.js', expect('complex-output.xml')), 'with a function length violation': given('long-function.js', expect('long-output.xml')), 'with a configured function length violation': given('configured-long-function.js', expect('configured-long-output.xml')), 'with a number of arguments violation': given('too-many-arguments.js', expect('too-many-arguments-output.xml')), 'with multiple violations in a single function': given('lots-of-args-and-long.js', expect('lots-of-args-and-long-output.xml')), 'module.exports should not trigger function length violation': given('a-long-module.js', expect('no-errors.xml')), 'module.exports should trigger number of arguments violation': given('a-module-function.js', expect('module-arguments.xml')), 'violations only': { 'when no rules are broken': { topic: jscheckstyle.violationsOnly([{ filename: "file1.js", results: [ { lineStart: 1, shortName: "cheese", lines: 5, complexity: 1, ins: 1 }, { lineStart: 10, shortName: "biscuits", lines: 2, complexity: 5, ins: 0 } ] }]), 'should return an empty array': function(results) { assert.lengthOf(results, 0); } }, 'when one rule is broken': { topic: jscheckstyle.violationsOnly([{ filename: "file1.js", results: [ { lineStart: 1, shortName: "cheese", lines:5, complexity:15, ins: 1 }, { lineStart: 10, shortName: "biscuits", lines: 2, complexity: 5, ins: 0 } ] }]), 'should return an array with one result': function(results) { assert.deepEqual(results, [{ filename: "file1.js", results: [ { lineStart:1, shortName: "cheese", lines: 5, complexity: 15, ins: 1, violations: [{ source: "CyclomaticComplexity", message: "cheese has a cyclomatic complexity of 15, maximum should be 10" }] } ] }]); } }, 'when one rule is broken in two functions': { topic: jscheckstyle.violationsOnly([{ filename: "file1.js", results: [ { lineStart: 1, shortName: "cheese", lines:5, complexity:15, ins: 1 }, { lineStart: 10, shortName: "biscuits", lines: 2, complexity: 15, ins: 0 } ] }]), 'should return an array with two results': function(results) { assert.deepEqual( results, [{ filename: "file1.js", results: [ { lineStart:1, shortName: "cheese", lines: 5, complexity: 15, ins: 1, violations: [{ source: "CyclomaticComplexity", message: "cheese has a cyclomatic complexity of 15, maximum should be 10" }] }, { lineStart:10, shortName: "biscuits", lines: 2, complexity: 15, ins: 0, violations: [{ source: "CyclomaticComplexity", message: "biscuits has a cyclomatic complexity of 15, maximum should be 10" }] } ] }] ); } }, 'when two rules are broken in one function': { topic: jscheckstyle.violationsOnly([{ filename: "file1.js", results: [ { lineStart: 1, shortName: "cheese", lines:5, complexity:15, ins: 8 }, { lineStart: 10, shortName: "biscuits", lines: 2, complexity: 1, ins: 0 } ] }]), 'should return an array with one result and two violations': function(results) { assert.deepEqual( results, [{ filename: "file1.js", results: [ { lineStart:1, shortName: "cheese", lines: 5, complexity: 15, ins: 8, violations: [ { source: "CyclomaticComplexity", message: "cheese has a cyclomatic complexity of 15, maximum should be 10" }, { source: "NumberOfArguments", message: "cheese has 8 arguments, maximum allowed is 5" } ]} ] }] ); } } } }).exportTo(module);
nomiddlename/jscheckstyle
test/checkstyle.js
JavaScript
mit
6,089
version https://git-lfs.github.com/spec/v1 oid sha256:5b06c8bb34dea0d08a98bb98d8fc80c43e4c6e36f6051a72b41fd447afd37cfc size 1253
yogeshsaroya/new-cdnjs
ajax/libs/yui/3.17.0/cache-plugin/cache-plugin.js
JavaScript
mit
129
Hilary.scope('node-example').register({ name: 'breweriesController', dependencies: ['newGidgetModule', 'GidgetRoute', 'viewEngine'], factory: function (self, GidgetRoute, viewEngine) { 'use strict'; self.get['/breweries/:brewery'] = new GidgetRoute({ routeHandler: function (err, req, next) { req.title = req.params.brewery; viewEngine.setVM({ template: 't-brewery', data: { heading: '/breweries/:brewery', param0: req.params.splat[0], brewery: req.params.brewery } }); next(err, req); }, before: function (err, req, next) { console.log('before breweries route', req); next(err, req); }, after: function (err, req, next) { console.log('after breweries route', req); next(err, req); } }); self.get['/breweries/:brewery/beers/:beer'] = function (err, req, next) { req.title = req.params.brewery.concat(' ', req.params.beer); viewEngine.setVM({ template: 't-beer', data: { heading: '/breweries/:brewery/beers/:beer', param0: req.params.splat[0], param1: req.params.splat[1], brewery: req.params.brewery, beer: req.params.beer } }); next(err, req); }; return self; } });
losandes/gidget
examples/node-example/public/scripts/src/controllers/breweriesController.js
JavaScript
mit
1,666
/** * utils * * @namespace mix.util * * @author Yang,junlong at 2016-07-28 20:27:54 build. * @version $Id$ */ var fs = require('fs'); var url = require('url'); var pth = require('path'); var util = require('util'); //var iconv = require('iconv-lite'); var crypto = require('crypto'); var PLATFORM = process.platform; var ISWIN = PLATFORM.indexOf('win') === 0; /** * text file exts * * @type <Array> */ var TEXT_FILE_EXTS = [ 'css', 'tpl', 'js', 'php', 'txt', 'json', 'xml', 'htm', 'text', 'xhtml', 'html', 'md', 'conf', 'po', 'config', 'tmpl', 'coffee', 'less', 'sass', 'jsp', 'scss', 'manifest', 'bak', 'asp', 'tmp', 'haml', 'jade', 'aspx', 'ashx', 'java', 'py', 'c', 'cpp', 'h', 'cshtml', 'asax', 'master', 'ascx', 'cs', 'ftl', 'vm', 'ejs', 'styl', 'jsx', 'handlebars' ]; /** * image file exts * * @type <Array> */ var IMAGE_FILE_EXTS = [ 'svg', 'tif', 'tiff', 'wbmp', 'png', 'bmp', 'fax', 'gif', 'ico', 'jfif', 'jpe', 'jpeg', 'jpg', 'woff', 'cur', 'webp', 'swf', 'ttf', 'eot', 'woff2' ]; /** * mime types * * @type <Object> */ var MIME_TYPES = { //text 'css': 'text/css', 'tpl': 'text/html', 'js': 'text/javascript', 'jsx': 'text/javascript', 'php': 'text/html', 'asp': 'text/html', 'jsp': 'text/jsp', 'txt': 'text/plain', 'json': 'application/json', 'xml': 'text/xml', 'htm': 'text/html', 'text': 'text/plain', 'md': 'text/plain', 'xhtml': 'text/html', 'html': 'text/html', 'conf': 'text/plain', 'po': 'text/plain', 'config': 'text/plain', 'coffee': 'text/javascript', 'less': 'text/css', 'sass': 'text/css', 'scss': 'text/css', 'styl': 'text/css', 'manifest': 'text/cache-manifest', //image 'svg': 'image/svg+xml', 'tif': 'image/tiff', 'tiff': 'image/tiff', 'wbmp': 'image/vnd.wap.wbmp', 'webp': 'image/webp', 'png': 'image/png', 'bmp': 'image/bmp', 'fax': 'image/fax', 'gif': 'image/gif', 'ico': 'image/x-icon', 'jfif': 'image/jpeg', 'jpg': 'image/jpeg', 'jpe': 'image/jpeg', 'jpeg': 'image/jpeg', 'eot': 'application/vnd.ms-fontobject', 'woff': 'application/font-woff', 'woff2': 'application/font-woff', 'ttf': 'application/octet-stream', 'cur': 'application/octet-stream' }; /** * 通用唯一识别码 (Universally Unique Identifier) * * @return string */ exports.uuid = function () { var _uuid = [], _stra = "0123456789ABCDEF".split(''); for (var i = 0; i < 36; i++){ _uuid[i] = Math.floor(Math.random() * 16); } _uuid[14] = 4; _uuid[19] = (_uuid[19] & 3) | 8; for (i = 0; i < 36; i++) { _uuid[i] = _stra[_uuid[i]]; } _uuid[8] = _uuid[13] = _uuid[18] = _uuid[23] = '-'; return _uuid.join(''); }; /** * md5 crypto * * @param <String> | <Binary> data * @param <Number> len * @return <String> */ exports.md5 = function(data, len) { var md5sum = crypto.createHash('md5'); var encoding = typeof data === 'string' ? 'utf8' : 'binary'; md5sum.update(data, encoding); len = len || mix.config.get('project.md5Length', 7); return md5sum.digest('hex').substring(0, len); }; /** * base64 encode * * @param <Buffer | Array | String> data * @return <String> */ exports.base64 = function(data) { if(data instanceof Buffer){ //do nothing for quickly determining. } else if(data instanceof Array){ data = new Buffer(data); } else { //convert to string. data = new Buffer(String(data || '')); } return data.toString('base64'); }; exports.map = function(obj, callback, scope) { if (obj.length === +obj.length) { for (var i = 0, l = obj.length; i < l; i++) { if (callback.call(scope, obj[i], i, obj) === false) { return; } } } else { for (var key in obj) { if (obj.hasOwnProperty(key)) { if (callback.call(scope, obj[key], key, obj) === false) { return; } } } } }; /** * camel format * * @usage * aaa-bbb_ccc ddd -> AaaBbbCccDdd * * @param {String} string * @return {String} */ exports.camelcase = (function(){ var list = {}; return function(string){ var result = ''; if(string){ string.split(/[-_ ]+/).forEach(function(ele){ result += ele[0].toUpperCase() + ele.substring(1); }); } else { result = string; } return list[string] || (list[string] = result); } })(); /** * 数据类型判断 * * @param <Mixed> source * @param <String> type * @return <Boolean> */ exports.is = function (source, type) { type = exports.camelcase(type); return toString.call(source) === '[object ' + type + ']'; }; // 简单的浅拷贝, 覆盖已经存在的属性 exports.extend = function (destination) { if (!destination) { return; } var args = Array.prototype.slice.call(arguments, 1); for (i = 0, l = args.length; i < l; i++) { var source = args[i]; for(var property in source){ var value = source[property]; if (value !== undefined){ destination[property] = value; } } } return destination; }; /** * print object to terminal * * @param <Object> object * @param <String> prefix * @return <Void> */ exports.print = function (object, prefix) { prefix = prefix || ''; for(var key in object){ if(object.hasOwnProperty(key)){ if(typeof object[key] === 'object'){ arguments.callee(object[key], prefix + key + '.'); } else { console.log(prefix + key + '=' + object[key]); } } } } /** * hostname & ip address * * @return <String> */ exports.hostname = function () { var net = require('os').networkInterfaces(); for(var key in net){ if(net.hasOwnProperty(key)){ var details = net[key]; if(details && details.length){ for(var i = 0, len = details.length; i < len; i++){ var ip = String(details[i].address).trim(); if(ip && /^\d+(?:\.\d+){3}$/.test(ip) && ip !== '127.0.0.1'){ return ip; } } } } } return '127.0.0.1'; }; /** * if text file * * @param <String> file * @return <Boolean> */ exports.isTxt = function(file) { return fileTypeReg('text').test(file || ''); }; /** * if image file * * @param <String> file * @return <Boolean> */ exports.isImg = function(file) { return fileTypeReg('image').test(file || ''); }; /** * if platform windows * * @return <Boolean> */ exports.isWin = function() { return ISWIN; } /** * if buffer utf8 charset * * @param <Buffer> bytes * @return <Boolean> */ exports.isUtf8 = function(bytes) { var i = 0; while(i < bytes.length) { if((// ASCII 0x00 <= bytes[i] && bytes[i] <= 0x7F )) { i += 1; continue; } if((// non-overlong 2-byte (0xC2 <= bytes[i] && bytes[i] <= 0xDF) && (0x80 <= bytes[i+1] && bytes[i+1] <= 0xBF) )) { i += 2; continue; } if( (// excluding overlongs bytes[i] == 0xE0 && (0xA0 <= bytes[i + 1] && bytes[i + 1] <= 0xBF) && (0x80 <= bytes[i + 2] && bytes[i + 2] <= 0xBF) ) || (// straight 3-byte ((0xE1 <= bytes[i] && bytes[i] <= 0xEC) || bytes[i] == 0xEE || bytes[i] == 0xEF) && (0x80 <= bytes[i + 1] && bytes[i + 1] <= 0xBF) && (0x80 <= bytes[i + 2] && bytes[i + 2] <= 0xBF) ) || (// excluding surrogates bytes[i] == 0xED && (0x80 <= bytes[i + 1] && bytes[i + 1] <= 0x9F) && (0x80 <= bytes[i + 2] && bytes[i + 2] <= 0xBF) ) ) { i += 3; continue; } if( (// planes 1-3 bytes[i] == 0xF0 && (0x90 <= bytes[i + 1] && bytes[i + 1] <= 0xBF) && (0x80 <= bytes[i + 2] && bytes[i + 2] <= 0xBF) && (0x80 <= bytes[i + 3] && bytes[i + 3] <= 0xBF) ) || (// planes 4-15 (0xF1 <= bytes[i] && bytes[i] <= 0xF3) && (0x80 <= bytes[i + 1] && bytes[i + 1] <= 0xBF) && (0x80 <= bytes[i + 2] && bytes[i + 2] <= 0xBF) && (0x80 <= bytes[i + 3] && bytes[i + 3] <= 0xBF) ) || (// plane 16 bytes[i] == 0xF4 && (0x80 <= bytes[i + 1] && bytes[i + 1] <= 0x8F) && (0x80 <= bytes[i + 2] && bytes[i + 2] <= 0xBF) && (0x80 <= bytes[i + 3] && bytes[i + 3] <= 0xBF) ) ) { i += 4; continue; } return false; } return true; }; /** * if path is file * * @param <String> path * @return <Boolean> */ exports.isFile = function(path) { return exports.exists(path) && fs.statSync(path).isFile(); }; /** * if path is dir * * @param <String> path * @return {Boolean} */ exports.isDir = function(path) { return exports.exists(path) && fs.statSync(path).isDirectory(); }; /** * adapt buffer charset * * @param <Buffer> buffer * @return <Buffer> */ exports.buffer = function(buffer) { if(exports.isUtf8(buffer)) { buffer = buffer.toString('utf8'); if (buffer.charCodeAt(0) === 0xFEFF) { buffer = buffer.substring(1); } } else { buffer = iconv.decode(buffer, 'gbk'); } return buffer; }; /** * reads the entire contents of a file * * If the encoding option is specified then this function returns a string. * Otherwise it returns a buffer. * * @param <String> file * @param <Boolean> convert * @return <String> | <Buffer> */ exports.read = function(file, convert) { var content = false; if(exports.exists(file)) { content = fs.readFileSync(file); if(convert || exports.isTxt(file)) { content = exports.buffer(content); } } return content; }; /** * read file to json * * @param <String> path * @return <Object> */ exports.readJSON = (function(){ var cache = {}; return function(path) { if(cache[path]) { return cache[path]; } var json = exports.read(path, true); var result = {}; if(!json) { return false; } try { result = JSON.parse(json); } catch(e){ mix.log.error('parse json file[' + path + '] fail, error [' + e.message + ']'); } return (cache[path] = result); } })(); /** * Makes directory * * @param <String> path * @param <Integer> mode * @return <undefined> */ exports.mkdir = function(path, mode) { var exists = exports.exists; if(exists(path)) { return; } path.split('/').reduce(function(prev, next) { if(prev && !exists(prev)) { fs.mkdirSync(prev, mode); } return prev + '/' + next; }); if(!exists(path)) { fs.mkdirSync(path, mode); } }; /** * write data to a file, * replacing the file if it already exists. * data can be a string or a buffer * * @param <String> | <Buffer> | <Integer> file * @param <String> | <Buffer> data * @param <Object> | <String> options * @param <Boolean> append * @return <undefined> */ exports.write = function(file, data, options, append) { if(!exports.exists(file)){ exports.mkdir(exports.pathinfo(file).dirname); } if(append) { fs.appendFileSync(file, data, options); } else { fs.writeFileSync(file, data, options); } }; /** * Gets file modification time * * @param <String> path * @return <Timestamp> */ exports.mtime = function(path) { var time = 0; if(exports.exists(path)){ time = fs.statSync(path).mtime; } return time; }; /** * Touch a file * * @param <String> path * @param <timestamp> mtime * @return <undefined> */ exports.touch = function(path, mtime) { if(!exports.exists(path)){ exports.write(path, ''); } if(mtime instanceof Date){ //do nothing for quickly determining. } else if(typeof mtime === 'number') { var time = new Date(); time.setTime(mtime); mtime = time; } else { mix.log.error('invalid argument [mtime]'); } fs.utimesSync(path, mtime, mtime); }; exports.del = function(rPath, include, exclude){ var removedAll = true; var path; if(rPath && exports.exists(rPath)) { var stat = fs.lstatSync(rPath); var isFile = stat.isFile() || stat.isSymbolicLink(); if (stat.isSymbolicLink()) { path = rPath; } else { path = exports.realpath(rPath); } if(/^(?:\w:)?\/$/.test(path)){ mix.log.error('unable to delete directory [' + rPath + '].'); } if(stat.isDirectory()){ fs.readdirSync(path).forEach(function(name){ if(name != '.' && name != '..') { removedAll = exports.del(path + '/' + name, include, exclude) && removedAll; } }); if(removedAll) { fs.rmdirSync(path); } } else if(isFile && exports.filter(path, include, exclude)) { fs.unlinkSync(path); } else { removedAll = false; } } else { mix.log.error('unable to delete [' + rPath + ']: No such file or directory.'); } return removedAll; }, /** * Node.js file system * * @type <Object> */ exports.fs = fs; /** * Test whether or not the given path exists by checking with the file system. * * @param <String> | <Buffer> path * @return <Boolean> Returns true if the file exists, false otherwise. */ exports.exists = fs.existsSync; /** * Create path by arguments. * * @param <String> | <Array> path * @return <String> */ exports.path = function(path) { var type = typeof path; if(arguments.length > 1) { path = Array.prototype.join.call(arguments, '/'); } else if(type === 'string') { // do nothing for quickly determining. } else if(type === 'object') { // array object path = Array.prototype.join.call(path, '/'); } else if(type === 'undefined') { path = ''; } if(path){ path = pth.normalize(path.replace(/[\/\\]+/g, '/')).replace(/\\/g, '/'); if(path !== '/'){ path = path.replace(/\/$/, ''); } } return path; }; /** * Only paths that can be converted to UTF8 strings are supported. * * @param {String} path [description] * @param {Object} options [description] * @return <String>|<False> Returns the resolved path. */ exports.realpath = function(path, options){ if(path && exports.exists(path)){ path = fs.realpathSync(path, options); if(ISWIN){ path = path.replace(/\\/g, '/'); } if(path !== '/'){ path = path.replace(/\/$/, ''); } return path; } else { return false; } }; /** * Returns a parent directory's path * * @param <String> path * @return <String> */ exports.dirname = function(path) { return pth.resolve(path, '..'); }; /** * Returns an object whose properties represent significant elements of the path * * @param <String> path * @return <Object> * * The returned object will have the following properties: * { * origin: './test.js?ddd=11', * rest: './test', * hash: '', * query: '?ddd=11', * fullname: './test.js', * dirname: '.', * ext: '.js', * filename: 'test', * basename: 'test.js' * } */ exports.pathinfo = function(path) { /** * parse path by url.parse * * { * protocol: null, * slashes: null, * auth: null, * host: null, * port: null, * hostname: null, * hash: null, * search: '?dfad=121', * query: 'dfad=121', * pathname: './test.js', * path: './test.js?dfad=121', * href: './test.js?dfad=121' * } * @type {[type]} */ var urls = url.parse(path); /** * parse path by path.parse * * { * root: '', * dir: '.', * base: 'test.js?dfad=121', * ext: '.js?dfad=121', * name: 'test' * } * @type <Object> */ var pths = pth.parse(urls.pathname || path); // tobe output var var origin = urls.path; var root = pths.root; var hash = urls.hash; var query = urls.search; var fullname = origin.replace(query, ''); var dirname = pths.dir || '.'; var filename = pths.name; var basename = (pths.base || '').replace(query, ''); var rest = dirname + '/' + filename; var ext = (pths.ext || '').replace(query, ''); return { 'origin': origin, 'dirname': dirname, 'fullname': fullname, 'filename': filename, 'basename': basename, 'query': query, 'rest': rest, 'hash': hash, 'root': root, 'ext': ext }; }; /** * Escape special regular charset * * @param <String> str * @return <String> */ exports.escapeReg = function(str) { return str.replace(/[\.\\\+\*\?\[\^\]\$\(\){}=!<>\|:\/]/g, '\\$&'); }; /** * Escape shell cmd * * @param <String> str * @return <String> */ exports.escapeShellCmd = function(str){ return str.replace(/ /g, '"$&"'); }; exports.escapeShellArg = function(cmd){ return '"' + cmd + '"'; }; exports.stringQuote = function(str, quotes){ var info = { origin : str, rest : str = str.trim(), quote : '' }; if(str){ quotes = quotes || '\'"'; var strLen = str.length - 1; for(var i = 0, len = quotes.length; i < len; i++){ var c = quotes[i]; if(str[0] === c && str[strLen] === c){ info.quote = c; info.rest = str.substring(1, strLen); break; } } } return info; }; /** * Replace var * * @return <String> * @example * replaceVar('/${namespace}/path/to/*.js', true); * -> '/common/path/to/*.js' */ exports.replaceVar = function(value, escape){ return value.replace(/\$\{([^\}]+)\}/g, function(all, $1){ var val = mix.config.get($1) || 'test'; if(typeof val === 'undefined'){ mix.log.error('undefined property [' + $1 + '].'); } else { return escape ? exports.escapeReg(val) : val; } return all; }); }; /** * Replace Matches * * @param <String> value * @param <Array> matches * @return <String> * @example * replaceMatches('/$1/path/to.js', ['aa', 'bb']); * -> '/bb/path/to.js' */ exports.replaceMatches = function(value, matches) { return value.replace(/\$(\d+|&)/g, function(all, $1){ var key = $1 === '&' ? '0' : $1; return matches.hasOwnProperty(key) ? (matches[key] || '') : all; }); }; /** * Replace roadmap.path Props * Extend Props to File * * @param <Object> source * @param <Array> matches * @param <Object> scope * @return <Object> * @example * replaceProps(road.path[0], ['aa', 'bb', 'cc'], this); */ exports.replaceProps = function(source, matches, scope) { var type = typeof source; if(type === 'object'){ if(exports.is(source, 'Array')){ scope = scope || []; } else { scope = scope || {}; } exports.map(source, function(value, key){ scope[key] = exports.replaceProps(value, matches); }); return scope; } else if(type === 'string'){ return exports.replaceVar(exports.replaceMatches(source, matches)); } else if(type === 'function'){ return source(scope, matches); } else { return source; } }; // check lib version exports.matchVersion = function(str) { var version = false; var reg = /\b\d+(\.\d+){2}/; var match = str.match(reg); if(match){ version = match[0]; } return version; }; /** * Filter path by include&exclude regular * * @param <String> str [description] * @param <Regular> | <Array> include [description] * @param <Regular> | <Array> exclude [description] * @return <Boolean> */ exports.filter = function(str, include, exclude){ function normalize(pattern){ var type = toString.call(pattern); switch (type){ case '[object String]': return exports.glob(pattern); case '[object RegExp]': return pattern; default: mix.log.error('invalid regexp [' + pattern + '].'); } } function match(str, patterns){ var matched = false; if (!exports.is(patterns, 'Array')){ patterns = [patterns]; } patterns.every(function(pattern){ if (!pattern){ return true; } matched = matched || str.search(normalize(pattern)) > -1; return !matched; }); return matched; } var isInclude, isExclude; if (include) { isInclude = match(str, include); }else{ isInclude = true; } if (exclude) { isExclude = match(str, exclude); } return isInclude && !isExclude; }; /** * match files using the pattern * * @see npm node-glob * * @param <Regular> pattern * @param <String> str * @return <Boolean> | <Regular> */ exports.glob = function(pattern, str){ var sep = exports.escapeReg('/'); pattern = new RegExp('^' + sep + '?' + exports.escapeReg( pattern .replace(/\\/g, '/') .replace(/^\//, '') ) .replace(new RegExp(sep + '\\*\\*' + sep, 'g'), sep + '.*(?:' + sep + ')?') .replace(new RegExp(sep + '\\*\\*', 'g'), sep + '.*') .replace(/\\\*\\\*/g, '.*') .replace(/\\\*/g, '[^' + sep + ']*') .replace(/\\\?/g, '[^' + sep + ']') + '$', 'i' ); if(typeof str === 'string'){ return pattern.test(str); } else { return pattern; } }; /** * find project source(files) * * @param <String> path * @param <String | Function> include * @param <String | Function> exclude * @param <String> root * @param <Function> callback * @return <Object> */ exports.find = function(rPath, include, exclude, root) { var args = Array.prototype.slice.call(arguments, 0); var last = args[args.length-1]; var list = []; var path = exports.realpath(rPath); var filterPath = root ? path.substring(root.length) : path; include = exports.is(include, 'function') ? undefined : include; exclude = exports.is(exclude, 'function') ? undefined : exclude; if(path){ var stat = fs.statSync(path); if(stat.isDirectory() && (include || exports.filter(filterPath, include, exclude))){ fs.readdirSync(path).forEach(function(p){ if(p[0] != '.') { list = list.concat(exports.find(path + '/' + p, include, exclude, root, last)); } }); } else if(stat.isFile() && exports.filter(filterPath, include, exclude)) { list.push(path); if(exports.is(last, 'function')) { last(path); } } } else { mix.log.error('unable to find [' + rPath + ']: No such file or directory.'); } return list.sort(); }; /** * File pipe process core impl * * @param <String> type * @param <Function> callback * @param <Function> | <String> def * @return <undefined> */ exports.pipe = function(type, callback, def) { var processors = mix.config.get('modules.' + type, def); if(processors){ var typeOf = typeof processors; if(typeOf === 'string'){ processors = processors.trim().split(/\s*,\s*/); } else if(typeOf === 'function'){ processors = [ processors ]; } type = type.split('.')[0]; processors.forEach(function(processor, index){ var typeOf = typeof processor, key; if(typeOf === 'string'){ key = type + '.' + processor; processor = mix.require(type, processor); } else { key = type + '.' + index; } if(typeof processor === 'function'){ var settings = mix.config.get('settings.' + key, {}); if(processor.defaultOptions){ settings = exports.extend(processor.settings, settings); } callback(processor, settings, key); } else { mix.log.warning('invalid processor [modules.' + key + ']'); } }); } }; /** * Open path or url from terminal * * @param <String> path | url * @param <Function> callback * @return <undefined> */ exports.open = function(path, callback) { var child_process = require('child_process'); var cmd = exports.escapeShellArg(path); if(ISWIN) { cmd = 'start "" ' + cmd; } else { if(process.env['XDG_SESSION_COOKIE']){ cmd = 'xdg-open ' + cmd; } else if(process.env['GNOME_DESKTOP_SESSION_ID']){ cmd = 'gnome-open ' + cmd; } else { cmd = 'open ' + cmd; } } child_process.exec(cmd, function(){ typeof callback == 'function' && callback(path); }); }; /** * file type regular * * @param <String> type * @return <Regular> */ function fileTypeReg(type) { var map = [], ext = mix.config.get('project.fileType.' + type); if(type === 'text'){ map = TEXT_FILE_EXTS; } else if(type === 'image'){ map = IMAGE_FILE_EXTS; } else { mix.log.error('invalid file type [' + type + ']'); } // custom file type if(ext && ext.length){ if(typeof ext === 'string'){ ext = ext.split(/\s*,\s*/); } map = map.concat(ext); } map = map.join('|'); return new RegExp('\\.(?:' + map + ')$', 'i'); }
yangjunlong/xpage
lib/util.js
JavaScript
mit
26,977
/** * Created by OTHREE on 7/17/2016. */ function my_special_notification_callback(data) { var badge = document.getElementById('live_notify_badge2'); if (badge) { badge.innerHTML = data.unread_count; } var template = "<li> <a href='/user/dashboard/notifications/' id='{{id}}'> <i class='fa fa-info text-aqua'></i> {{level}} "+ "<br><small> {{ description }} </small></a></li>"; var menu = document.getElementById('live_notify_list'); if (menu) { menu.innerHTML = ""; for (var i=0; i < data.unread_list.length; i++) { var item = data.unread_list[i]; var message = ""; if(typeof item.actor !== 'undefined'){ message = item.actor; } if(typeof item.verb !== 'undefined'){ message = message + " " + item.verb; } if(typeof item.target !== 'undefined'){ message = message + " " + item.target; } if(typeof item.timestamp !== 'undefined'){ message = message + " " + item.timestamp; } menu.innerHTML = menu.innerHTML + Mustache.render(template,item) } } }
othreecodes/MY-RIDE
static/app/customnotify/cusnot.js
JavaScript
mit
1,259
var crypto = require('crypto') var multimatch = require('multimatch') var path = require('path') var KEY = 'metalsmith' module.exports = plugin function plugin(options) { return function (files, metalsmith, done) { var metadata = metalsmith.metadata() metadata.fingerprint = (metadata.fingerprint || {}) Object.keys(files) .filter(function (p) { return multimatch(p, options.pattern).length > 0 }) .forEach(function (p) { var hash = crypto.createHmac('md5', KEY).update(files[p].contents).digest('hex') var ext = path.extname(p) var fingerprint = [p.substring(0, p.lastIndexOf(ext)), '-', hash, ext].join('').replace(/\\/g, '/') files[fingerprint] = files[p] metadata.fingerprint[p] = fingerprint }) return process.nextTick(done) } }
christophercliff/metalsmith-fingerprint
lib/index.js
JavaScript
mit
923
import { ActionHandler, Evented, FrameworkObject, deprecateUnderscoreActions } from 'ember-runtime'; import { initViewElement } from '../system/utils'; import { cloneStates, states } from './states'; /** `Ember.CoreView` is an abstract class that exists to give view-like behavior to both Ember's main view class `Ember.Component` and other classes that don't need the full functionality of `Ember.Component`. Unless you have specific needs for `CoreView`, you will use `Ember.Component` in your applications. @class CoreView @namespace Ember @extends Ember.Object @deprecated Use `Ember.Component` instead. @uses Ember.Evented @uses Ember.ActionHandler @private */ const CoreView = FrameworkObject.extend(Evented, ActionHandler, { isView: true, _states: cloneStates(states), init() { this._super(...arguments); this._state = 'preRender'; this._currentState = this._states.preRender; initViewElement(this); if (!this.renderer) { throw new Error(`Cannot instantiate a component without a renderer. Please ensure that you are creating ${this} with a proper container/registry.`); } }, /** If the view is currently inserted into the DOM of a parent view, this property will point to the parent of the view. @property parentView @type Ember.View @default null @private */ parentView: null, instrumentDetails(hash) { hash.object = this.toString(); hash.containerKey = this._debugContainerKey; hash.view = this; return hash; }, /** Override the default event firing from `Ember.Evented` to also call methods with the given name. @method trigger @param name {String} @private */ trigger(name, ...args) { this._super(...arguments); let method = this[name]; if (typeof method === 'function') { return method.apply(this, args); } }, has(name) { return typeof this[name] === 'function' || this._super(name); } }); deprecateUnderscoreActions(CoreView); CoreView.reopenClass({ isViewFactory: true }); export default CoreView;
patricksrobertson/ember.js
packages/ember-views/lib/views/core_view.js
JavaScript
mit
2,109
"use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; var _createSvgIcon = _interopRequireDefault(require("./utils/createSvgIcon")); var _jsxRuntime = require("react/jsx-runtime"); var _default = (0, _createSvgIcon.default)( /*#__PURE__*/(0, _jsxRuntime.jsx)("path", { d: "M7.77 6.76 6.23 5.48.82 12l5.41 6.52 1.54-1.28L3.42 12l4.35-5.24zM7 13h2v-2H7v2zm10-2h-2v2h2v-2zm-6 2h2v-2h-2v2zm6.77-7.52-1.54 1.28L20.58 12l-4.35 5.24 1.54 1.28L23.18 12l-5.41-6.52z" }), 'SettingsEthernet'); exports.default = _default;
oliviertassinari/material-ui
packages/mui-icons-material/lib/SettingsEthernet.js
JavaScript
mit
655
import m from 'mithril'; import _ from 'underscore'; import h from '../h'; const adminItem = { oninit: function(vnode) { vnode.state = { displayDetailBox: h.toggleProp(false, true) }; }, view: function({state, attrs}) { const item = attrs.item, listWrapper = attrs.listWrapper || {}, selectedItem = (_.isFunction(listWrapper.isSelected) ? listWrapper.isSelected(item.id) : false); return m('.w-clearfix.card.u-radius.u-marginbottom-20.results-admin-items', { class: (selectedItem ? 'card-alert' : '') }, [ m(attrs.listItem, { item, listWrapper: attrs.listWrapper, }), m('button.w-inline-block.arrow-admin.fa.fa-chevron-down.fontcolor-secondary', { onclick: state.displayDetailBox.toggle }), ( state.displayDetailBox() ? m(attrs.listDetail, { item, }) : '' ) ]); } }; export default adminItem;
catarse/catarse_admin
legacy/src/c/admin-item.js
JavaScript
mit
1,178
module.exports={A:{A:{"1":"E B A","2":"K C G WB"},B:{"1":"D u Y I M H"},C:{"1":"0 1 2 3 5 6 7 UB z F J K C G E B A D u Y I M H N O P Q R S T U V W X w Z a b c d e f L h i j k l m n o p q r s t y v g SB RB"},D:{"1":"0 1 2 3 5 6 7 F J K C G E B A D u Y I M H N O P Q R S T U V W X w Z a b c d e f L h i j k l m n o p q r s t y v g GB BB DB VB EB"},E:{"1":"F J K C G E B A HB IB JB KB LB MB","2":"FB AB"},F:{"1":"8 9 A D I M H N O P Q R S T U V W X w Z a b c d e f L h i j k l m n o p q r s t NB OB PB QB TB x","2":"E"},G:{"1":"4 G A CB XB YB ZB aB bB cB dB eB","16":"AB"},H:{"1":"fB"},I:{"1":"4 z F v gB hB iB jB kB lB"},J:{"1":"C B"},K:{"1":"8 9 B A D L x"},L:{"1":"BB"},M:{"1":"g"},N:{"1":"B A"},O:{"1":"mB"},P:{"1":"F J"},Q:{"1":"nB"},R:{"1":"oB"}},B:2,C:"CSS currentColor value"};
mattstryfe/theWeatherHub
node_modules/caniuse-lite/data/features/currentcolor.js
JavaScript
mit
783
'use strict'; var React = require('react'); var SvgIcon = require('../../svg-icon'); var NavigationChevronRight = React.createClass({ displayName: 'NavigationChevronRight', render: function render() { return React.createElement( SvgIcon, this.props, React.createElement('path', { d: 'M10 6L8.59 7.41 13.17 12l-4.58 4.59L10 18l6-6z' }) ); } }); module.exports = NavigationChevronRight;
checkraiser/material-ui2
lib/svg-icons/navigation/chevron-right.js
JavaScript
mit
421
version https://git-lfs.github.com/spec/v1 oid sha256:7191d4054034f882d0333e067f484abf20e9d176d5c0297c8824f5e0cafc8e12 size 2389
yogeshsaroya/new-cdnjs
ajax/libs/mathjax/2.2/jax/output/SVG/fonts/TeX/SansSerif/Italic/CombDiacritMarks.js
JavaScript
mit
129
/* Chinese initialisation for the jQuery UI date picker plugin. */ /* Written by Ressol (ressol@gmail.com). */ (function (factory) { // AMD. Register as an anonymous module. module.exports = factory(require('../datepicker'));; }(function (datepicker) { datepicker.regional['zh-TW'] = { closeText: '\u95DC\u9589', prevText: '&#x3C;\u4E0A\u6708', nextText: '\u4E0B\u6708&#x3E;', currentText: '\u4ECA\u5929', monthNames: [ '\u4E00\u6708', '\u4E8C\u6708', '\u4E09\u6708', '\u56DB\u6708', '\u4E94\u6708', '\u516D\u6708', '\u4E03\u6708', '\u516B\u6708', '\u4E5D\u6708', '\u5341\u6708', '\u5341\u4E00\u6708', '\u5341\u4E8C\u6708' ], monthNamesShort: [ '\u4E00\u6708', '\u4E8C\u6708', '\u4E09\u6708', '\u56DB\u6708', '\u4E94\u6708', '\u516D\u6708', '\u4E03\u6708', '\u516B\u6708', '\u4E5D\u6708', '\u5341\u6708', '\u5341\u4E00\u6708', '\u5341\u4E8C\u6708' ], dayNames: [ '\u661F\u671F\u65E5', '\u661F\u671F\u4E00', '\u661F\u671F\u4E8C', '\u661F\u671F\u4E09', '\u661F\u671F\u56DB', '\u661F\u671F\u4E94', '\u661F\u671F\u516D' ], dayNamesShort: [ '\u5468\u65E5', '\u5468\u4E00', '\u5468\u4E8C', '\u5468\u4E09', '\u5468\u56DB', '\u5468\u4E94', '\u5468\u516D' ], dayNamesMin: [ '\u65E5', '\u4E00', '\u4E8C', '\u4E09', '\u56DB', '\u4E94', '\u516D' ], weekHeader: '\u5468', dateFormat: 'yy/mm/dd', firstDay: 1, isRTL: false, showMonthAfterYear: true, yearSuffix: '\u5E74' }; datepicker.setDefaults(datepicker.regional['zh-TW']); return datepicker.regional['zh-TW']; }));
yanhaijing/allorigin
components/jquery-ui/i18n/datepicker-zh-TW.js
JavaScript
mit
2,185
/** * Copyright 2015 Telerik AD * * 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(f, define){ define([], f); })(function(){ (function( window, undefined ) { var kendo = window.kendo || (window.kendo = { cultures: {} }); kendo.cultures["nso-ZA"] = { name: "nso-ZA", numberFormat: { pattern: ["-n"], decimals: 2, ",": ",", ".": ".", groupSize: [3], percent: { pattern: ["-%n","%n"], decimals: 2, ",": ",", ".": ".", groupSize: [3], symbol: "%" }, currency: { pattern: ["$-n","$ n"], decimals: 2, ",": ",", ".": ".", groupSize: [3], symbol: "R" } }, calendars: { standard: { days: { names: ["Lamorena","Mošupologo","Labobedi","Laboraro","Labone","Labohlano","Mokibelo"], namesAbbr: ["Lam","Moš","Lbb","Lbr","Lbn","Lbh","Mok"], namesShort: ["L","M","L","L","L","L","M"] }, months: { names: ["Pherekgong","Hlakola","Mopitlo","Moranang","Mosegamanye","Ngoatobošego","Phuphu","Phato","Lewedi","Diphalana","Dibatsela","Manthole",""], namesAbbr: ["Pher","Hlak","Mop","Mor","Mos","Ngwat","Phup","Phat","Lew","Dip","Dib","Man",""] }, AM: ["AM","am","AM"], PM: ["PM","pm","PM"], patterns: { d: "yyyy/MM/dd", D: "dd MMMM yyyy", F: "dd MMMM yyyy hh:mm:ss tt", g: "yyyy/MM/dd hh:mm tt", G: "yyyy/MM/dd hh:mm:ss tt", m: "dd MMMM", M: "dd MMMM", s: "yyyy'-'MM'-'dd'T'HH':'mm':'ss", t: "hh:mm tt", T: "hh:mm:ss tt", u: "yyyy'-'MM'-'dd HH':'mm':'ss'Z'", y: "MMMM yyyy", Y: "MMMM yyyy" }, "/": "/", ":": ":", firstDay: 0 } } } })(this); return window.kendo; }, typeof define == 'function' && define.amd ? define : function(_, f){ f(); });
walgheraibi/StemCells
ui/js/bower_components/kendo-ui-core/src/js/cultures/kendo.culture.nso-ZA.js
JavaScript
mit
2,964
/* =================================================== * bootstrap-transition.js v2.0.1 * http://twitter.github.com/bootstrap/javascript.html#transitions * =================================================== * Copyright 2012 Twitter, 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. * ========================================================== */ !function( $ ) { $(function () { "use strict" /* CSS TRANSITION SUPPORT (https://gist.github.com/373874) * ======================================================= */ $.support.transition = (function () { var thisBody = document.body || document.documentElement , thisStyle = thisBody.style , support = thisStyle.transition !== undefined || thisStyle.WebkitTransition !== undefined || thisStyle.MozTransition !== undefined || thisStyle.MsTransition !== undefined || thisStyle.OTransition !== undefined return support && { end: (function () { var transitionEnd = "TransitionEnd" if ( $.browser.webkit ) { transitionEnd = "webkitTransitionEnd" } else if ( $.browser.mozilla ) { transitionEnd = "transitionend" } else if ( $.browser.opera ) { transitionEnd = "oTransitionEnd" } return transitionEnd }()) } })() }) }( window.jQuery ); /* ========================================================= * bootstrap-modal.js v2.0.1 * http://twitter.github.com/bootstrap/javascript.html#modals * ========================================================= * Copyright 2012 Twitter, 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. * ========================================================= */ !function( $ ){ "use strict" /* MODAL CLASS DEFINITION * ====================== */ var Modal = function ( content, options ) { this.options = options this.$element = $(content) .delegate('[data-dismiss="modal"]', 'click.dismiss.modal', $.proxy(this.hide, this)) } Modal.prototype = { constructor: Modal , toggle: function () { return this[!this.isShown ? 'show' : 'hide']() } , show: function () { var that = this if (this.isShown) return $('body').addClass('modal-open') this.isShown = true this.$element.trigger('show') escape.call(this) backdrop.call(this, function () { var transition = $.support.transition && that.$element.hasClass('fade') !that.$element.parent().length && that.$element.appendTo(document.body) //don't move modals dom position that.$element .show() if (transition) { that.$element[0].offsetWidth // force reflow } that.$element.addClass('in') transition ? that.$element.one($.support.transition.end, function () { that.$element.trigger('shown') }) : that.$element.trigger('shown') }) } , hide: function ( e ) { e && e.preventDefault() if (!this.isShown) return var that = this this.isShown = false $('body').removeClass('modal-open') escape.call(this) this.$element .trigger('hide') .removeClass('in') $.support.transition && this.$element.hasClass('fade') ? hideWithTransition.call(this) : hideModal.call(this) } } /* MODAL PRIVATE METHODS * ===================== */ function hideWithTransition() { var that = this , timeout = setTimeout(function () { that.$element.off($.support.transition.end) hideModal.call(that) }, 500) this.$element.one($.support.transition.end, function () { clearTimeout(timeout) hideModal.call(that) }) } function hideModal( that ) { this.$element .hide() .trigger('hidden') backdrop.call(this) } function backdrop( callback ) { var that = this , animate = this.$element.hasClass('fade') ? 'fade' : '' if (this.isShown && this.options.backdrop) { var doAnimate = $.support.transition && animate this.$backdrop = $('<div class="modal-backdrop ' + animate + '" />') .appendTo(document.body) if (this.options.backdrop != 'static') { this.$backdrop.click($.proxy(this.hide, this)) } if (doAnimate) this.$backdrop[0].offsetWidth // force reflow this.$backdrop.addClass('in') doAnimate ? this.$backdrop.one($.support.transition.end, callback) : callback() } else if (!this.isShown && this.$backdrop) { this.$backdrop.removeClass('in') $.support.transition && this.$element.hasClass('fade')? this.$backdrop.one($.support.transition.end, $.proxy(removeBackdrop, this)) : removeBackdrop.call(this) } else if (callback) { callback() } } function removeBackdrop() { this.$backdrop.remove() this.$backdrop = null } function escape() { var that = this if (this.isShown && this.options.keyboard) { $(document).on('keyup.dismiss.modal', function ( e ) { e.which == 27 && that.hide() }) } else if (!this.isShown) { $(document).off('keyup.dismiss.modal') } } /* MODAL PLUGIN DEFINITION * ======================= */ $.fn.modal = function ( option ) { return this.each(function () { var $this = $(this) , data = $this.data('modal') , options = $.extend({}, $.fn.modal.defaults, $this.data(), typeof option == 'object' && option) if (!data) $this.data('modal', (data = new Modal(this, options))) if (typeof option == 'string') data[option]() else if (options.show) data.show() }) } $.fn.modal.defaults = { backdrop: true , keyboard: true , show: true } $.fn.modal.Constructor = Modal /* MODAL DATA-API * ============== */ $(function () { $('body').on('click.modal.data-api', '[data-toggle="modal"]', function ( e ) { var $this = $(this), href , $target = $($this.attr('data-target') || (href = $this.attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '')) //strip for ie7 , option = $target.data('modal') ? 'toggle' : $.extend({}, $target.data(), $this.data()) e.preventDefault() $target.modal(option) }) }) }( window.jQuery ); /* =========================================================== * bootstrap-tooltip.js v2.0.1 * http://twitter.github.com/bootstrap/javascript.html#tooltips * Inspired by the original jQuery.tipsy by Jason Frame * =========================================================== * Copyright 2012 Twitter, 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. * ========================================================== */ !function( $ ) { "use strict" /* TOOLTIP PUBLIC CLASS DEFINITION * =============================== */ var Tooltip = function ( element, options ) { this.init('tooltip', element, options) } Tooltip.prototype = { constructor: Tooltip , init: function ( type, element, options ) { var eventIn , eventOut this.type = type this.$element = $(element) this.options = this.getOptions(options) this.enabled = true if (this.options.trigger != 'manual') { eventIn = this.options.trigger == 'hover' ? 'mouseenter' : 'focus' eventOut = this.options.trigger == 'hover' ? 'mouseleave' : 'blur' this.$element.on(eventIn, this.options.selector, $.proxy(this.enter, this)) this.$element.on(eventOut, this.options.selector, $.proxy(this.leave, this)) } this.options.selector ? (this._options = $.extend({}, this.options, { trigger: 'manual', selector: '' })) : this.fixTitle() } , getOptions: function ( options ) { options = $.extend({}, $.fn[this.type].defaults, options, this.$element.data()) if (options.delay && typeof options.delay == 'number') { options.delay = { show: options.delay , hide: options.delay } } return options } , enter: function ( e ) { var self = $(e.currentTarget)[this.type](this._options).data(this.type) if (!self.options.delay || !self.options.delay.show) { self.show() } else { self.hoverState = 'in' setTimeout(function() { if (self.hoverState == 'in') { self.show() } }, self.options.delay.show) } } , leave: function ( e ) { var self = $(e.currentTarget)[this.type](this._options).data(this.type) if (!self.options.delay || !self.options.delay.hide) { self.hide() } else { self.hoverState = 'out' setTimeout(function() { if (self.hoverState == 'out') { self.hide() } }, self.options.delay.hide) } } , show: function () { var $tip , inside , pos , actualWidth , actualHeight , placement , tp if (this.hasContent() && this.enabled) { $tip = this.tip() this.setContent() if (this.options.animation) { $tip.addClass('fade') } placement = typeof this.options.placement == 'function' ? this.options.placement.call(this, $tip[0], this.$element[0]) : this.options.placement inside = /in/.test(placement) $tip .remove() .css({ top: 0, left: 0, display: 'block' }) .appendTo(inside ? this.$element : document.body) pos = this.getPosition(inside) actualWidth = $tip[0].offsetWidth actualHeight = $tip[0].offsetHeight switch (inside ? placement.split(' ')[1] : placement) { case 'bottom': tp = {top: pos.top + pos.height, left: pos.left + pos.width / 2 - actualWidth / 2} break case 'top': tp = {top: pos.top - actualHeight, left: pos.left + pos.width / 2 - actualWidth / 2} break case 'left': tp = {top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left - actualWidth} break case 'right': tp = {top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left + pos.width} break } $tip .css(tp) .addClass(placement) .addClass('in') } } , setContent: function () { var $tip = this.tip() $tip.find('.tooltip-inner').html(this.getTitle()) $tip.removeClass('fade in top bottom left right') } , hide: function () { var that = this , $tip = this.tip() $tip.removeClass('in') function removeWithAnimation() { var timeout = setTimeout(function () { $tip.off($.support.transition.end).remove() }, 500) $tip.one($.support.transition.end, function () { clearTimeout(timeout) $tip.remove() }) } $.support.transition && this.$tip.hasClass('fade') ? removeWithAnimation() : $tip.remove() } , fixTitle: function () { var $e = this.$element if ($e.attr('title') || typeof($e.attr('data-original-title')) != 'string') { $e.attr('data-original-title', $e.attr('title') || '').removeAttr('title') } } , hasContent: function () { return this.getTitle() } , getPosition: function (inside) { return $.extend({}, (inside ? {top: 0, left: 0} : this.$element.offset()), { width: this.$element[0].offsetWidth , height: this.$element[0].offsetHeight }) } , getTitle: function () { var title , $e = this.$element , o = this.options title = $e.attr('data-original-title') || (typeof o.title == 'function' ? o.title.call($e[0]) : o.title) title = title.toString().replace(/(^\s*|\s*$)/, "") return title } , tip: function () { return this.$tip = this.$tip || $(this.options.template) } , validate: function () { if (!this.$element[0].parentNode) { this.hide() this.$element = null this.options = null } } , enable: function () { this.enabled = true } , disable: function () { this.enabled = false } , toggleEnabled: function () { this.enabled = !this.enabled } , toggle: function () { this[this.tip().hasClass('in') ? 'hide' : 'show']() } } /* TOOLTIP PLUGIN DEFINITION * ========================= */ $.fn.tooltip = function ( option ) { return this.each(function () { var $this = $(this) , data = $this.data('tooltip') , options = typeof option == 'object' && option if (!data) $this.data('tooltip', (data = new Tooltip(this, options))) if (typeof option == 'string') data[option]() }) } $.fn.tooltip.Constructor = Tooltip $.fn.tooltip.defaults = { animation: true , delay: 0 , selector: false , placement: 'top' , trigger: 'hover' , title: '' , template: '<div class="tooltip"><div class="tooltip-arrow"></div><div class="tooltip-inner"></div></div>' } }( window.jQuery );
kwikiel/flask-split
flask_split/static/js/bootstrap.js
JavaScript
mit
14,782
'use strict'; exports = module.exports = function(service) { return { message: function(user) { return '<p>' + 'Welcome to ' + service + ' ' + user.fullname + '!' + '</p>' + '<p>' + 'You have now linked your Google+ account to this service' + '</p>'; }, title: function() { return 'You linked your Google+ account to our service'; } }; };
SIB-Colombia/cygnus
src/app/modules/mailer/templates/google/link.js
JavaScript
mit
360
/** * @typedef {object} SalesAPI * @property {Activities} Activities **/ function SalesAPI(options) { const _Activities = require('./Activities'); return { Activities: new _Activities(options), }; } module.exports = SalesAPI;
zifu/connectwise-rest
src/SalesAPI/index.js
JavaScript
mit
242
/* Input Mask plugin extensions http://github.com/RobinHerbots/jquery.inputmask Copyright (c) 2010 - 2014 Robin Herbots Licensed under the MIT license (http://www.opensource.org/licenses/mit-license.php) Version: 2.5.0 Optional extensions on the jquery.inputmask base */ (function ($) { //number aliases $.extend($.inputmask.defaults.aliases, { 'decimal': { mask: "~", placeholder: "", repeat: "*", greedy: false, numericInput: false, isNumeric: true, digits: "*", //number of fractionalDigits groupSeparator: "",//",", // | "." radixPoint: ".", groupSize: 3, autoGroup: false, allowPlus: true, allowMinus: true, //todo integerDigits: "*", //number of integerDigits defaultValue: "", prefix: "", suffix: "", //todo getMaskLength: function (buffer, greedy, repeat, currentBuffer, opts) { //custom getMaskLength to take the groupSeparator into account var calculatedLength = buffer.length; if (!greedy) { if (repeat == "*") { calculatedLength = currentBuffer.length + 1; } else if (repeat > 1) { calculatedLength += (buffer.length * (repeat - 1)); } } var escapedGroupSeparator = $.inputmask.escapeRegex.call(this, opts.groupSeparator); var escapedRadixPoint = $.inputmask.escapeRegex.call(this, opts.radixPoint); var currentBufferStr = currentBuffer.join(''), strippedBufferStr = currentBufferStr.replace(new RegExp(escapedGroupSeparator, "g"), "").replace(new RegExp(escapedRadixPoint), ""), groupOffset = currentBufferStr.length - strippedBufferStr.length; return calculatedLength + groupOffset; }, postFormat: function (buffer, pos, reformatOnly, opts) { if (opts.groupSeparator == "") return pos; var cbuf = buffer.slice(), radixPos = $.inArray(opts.radixPoint, buffer); if (!reformatOnly) { cbuf.splice(pos, 0, "?"); //set position indicator } var bufVal = cbuf.join(''); if (opts.autoGroup || (reformatOnly && bufVal.indexOf(opts.groupSeparator) != -1)) { var escapedGroupSeparator = $.inputmask.escapeRegex.call(this, opts.groupSeparator); bufVal = bufVal.replace(new RegExp(escapedGroupSeparator, "g"), ''); var radixSplit = bufVal.split(opts.radixPoint); bufVal = radixSplit[0]; var reg = new RegExp('([-\+]?[\\d\?]+)([\\d\?]{' + opts.groupSize + '})'); while (reg.test(bufVal)) { bufVal = bufVal.replace(reg, '$1' + opts.groupSeparator + '$2'); bufVal = bufVal.replace(opts.groupSeparator + opts.groupSeparator, opts.groupSeparator); } if (radixSplit.length > 1) bufVal += opts.radixPoint + radixSplit[1]; } buffer.length = bufVal.length; //align the length for (var i = 0, l = bufVal.length; i < l; i++) { buffer[i] = bufVal.charAt(i); } var newPos = $.inArray("?", buffer); if (!reformatOnly) buffer.splice(newPos, 1); return reformatOnly ? pos : newPos; }, regex: { number: function (opts) { var escapedGroupSeparator = $.inputmask.escapeRegex.call(this, opts.groupSeparator); var escapedRadixPoint = $.inputmask.escapeRegex.call(this, opts.radixPoint); var digitExpression = isNaN(opts.digits) ? opts.digits : '{0,' + opts.digits + '}'; var signedExpression = opts.allowPlus || opts.allowMinus ? "[" + (opts.allowPlus ? "\+" : "") + (opts.allowMinus ? "-" : "") + "]?" : ""; return new RegExp("^" + signedExpression + "(\\d+|\\d{1," + opts.groupSize + "}((" + escapedGroupSeparator + "\\d{" + opts.groupSize + "})?)+)(" + escapedRadixPoint + "\\d" + digitExpression + ")?$"); } }, onKeyDown: function (e, buffer, opts) { var $input = $(this), input = this; if (e.keyCode == opts.keyCode.TAB) { var radixPosition = $.inArray(opts.radixPoint, buffer); if (radixPosition != -1) { var masksets = $input.data('_inputmask')['masksets']; var activeMasksetIndex = $input.data('_inputmask')['activeMasksetIndex']; for (var i = 1; i <= opts.digits && i < opts.getMaskLength(masksets[activeMasksetIndex]["_buffer"], masksets[activeMasksetIndex]["greedy"], masksets[activeMasksetIndex]["repeat"], buffer, opts) ; i++) { if (buffer[radixPosition + i] == undefined || buffer[radixPosition + i] == "") buffer[radixPosition + i] = "0"; } input._valueSet(buffer.join('')); } } else if (e.keyCode == opts.keyCode.DELETE || e.keyCode == opts.keyCode.BACKSPACE) { opts.postFormat(buffer, 0, true, opts); input._valueSet(buffer.join('')); return true; } }, definitions: { '~': { //real number validator: function (chrs, buffer, pos, strict, opts) { if (chrs == "") return false; if (!strict && pos <= 1 && buffer[0] === '0' && new RegExp("[\\d-]").test(chrs) && buffer.join('').length == 1) { //handle first char buffer[0] = ""; return { "pos": 0 }; } var cbuf = strict ? buffer.slice(0, pos) : buffer.slice(); cbuf.splice(pos, 0, chrs); var bufferStr = cbuf.join(''); //strip groupseparator var escapedGroupSeparator = $.inputmask.escapeRegex.call(this, opts.groupSeparator); bufferStr = bufferStr.replace(new RegExp(escapedGroupSeparator, "g"), ''); var isValid = opts.regex.number(opts).test(bufferStr); if (!isValid) { //let's help the regex a bit bufferStr += "0"; isValid = opts.regex.number(opts).test(bufferStr); if (!isValid) { //make a valid group var lastGroupSeparator = bufferStr.lastIndexOf(opts.groupSeparator); for (var i = bufferStr.length - lastGroupSeparator; i <= 3; i++) { bufferStr += "0"; } isValid = opts.regex.number(opts).test(bufferStr); if (!isValid && !strict) { if (chrs == opts.radixPoint) { isValid = opts.regex.number(opts).test("0" + bufferStr + "0"); if (isValid) { buffer[pos] = "0"; pos++; return { "pos": pos }; } } } } } if (isValid != false && !strict && chrs != opts.radixPoint) { var newPos = opts.postFormat(buffer, pos, false, opts); return { "pos": newPos }; } return isValid; }, cardinality: 1, prevalidator: null } }, insertMode: true, autoUnmask: false }, 'integer': { regex: { number: function (opts) { var escapedGroupSeparator = $.inputmask.escapeRegex.call(this, opts.groupSeparator); var signedExpression = opts.allowPlus || opts.allowMinus ? "[" + (opts.allowPlus ? "\+" : "") + (opts.allowMinus ? "-" : "") + "]?" : ""; return new RegExp("^" + signedExpression + "(\\d+|\\d{1," + opts.groupSize + "}((" + escapedGroupSeparator + "\\d{" + opts.groupSize + "})?)+)$"); } }, alias: "decimal" } }); })(jQuery);
davicompu/FacSal
Facsal/Scripts/jquery.inputmask/jquery.inputmask.numeric.extensions-2.5.0.js
JavaScript
mit
9,118
(function () { function RunningInNode () { return( (typeof require) == "function" && (typeof exports) == "object" && (typeof module) == "object" && (typeof __filename) == "string" && (typeof __dirname) == "string" ); } if (!RunningInNode()) { if (!this.Tautologistics) this.Tautologistics = {}; if (!this.Tautologistics.NodeHtmlParser) this.Tautologistics.NodeHtmlParser = {}; if (!this.Tautologistics.NodeHtmlParser.Tests) this.Tautologistics.NodeHtmlParser.Tests = []; exports = {}; this.Tautologistics.NodeHtmlParser.Tests.push(exports); } exports.name = "XML Namespace"; exports.options = { handler: {} , parser: {} }; exports.html = "<ns:tag>text</ns:tag>"; exports.expected = [ { raw: 'ns:tag', data: 'ns:tag', type: 'tag', name: 'ns:tag', children: [ { raw: 'text', data: 'text', type: 'text' } ] } ]; })();
robashton/zombify
src/node_modules/zombie/node_modules/jsdom/node_modules/htmlparser/tests/17-xml_namespace.js
JavaScript
mit
895
import Ember from 'ember'; import DS from 'ember-data'; const secondsInDay = 86400; const days = [ 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday', ]; export default DS.Model.extend(Ember.Copyable, { temp: DS.attr('number', { defaultValue: 18, }), // Seconds since 00:00 Monday. seconds: DS.attr('number', { defaultValue: 0, }), day: Ember.computed('seconds', { get() { return Math.floor(this.get('seconds') / secondsInDay); }, set(key, day) { day = day % days.length; if (day < 0) { day += days.length; } const newDayOffset = day * secondsInDay; const oldDayOffset = this.get('day') * secondsInDay; const secondsRemaining = this.get('seconds') - oldDayOffset; this.set('seconds', newDayOffset + secondsRemaining); return day; }, }), dayLabel: Ember.computed('day', { get() { return days[this.get('day')]; }, set(key, dayLabel) { this.set('day', days.indexOf(dayLabel)); return dayLabel; }, }), secondsToday: Ember.computed('seconds', 'day', { get() { const dayOffset = this.get('day') * secondsInDay; const secondsToday = this.get('seconds') - dayOffset; return secondsToday; }, set(key, secondsToday) { const dayOffset = this.get('day') * secondsInDay; const seconds = secondsToday + dayOffset; this.set('seconds', seconds); return secondsToday; }, }), time: Ember.computed('secondsToday', { get() { const time = moment({ hours: 0 }).seconds(this.get('secondsToday')); return time.format('HH:mm'); }, set(key, time) { const duration = moment.duration(time); this.set('secondsToday', duration.asSeconds()); return time; }, }), copy() { return this.store.createRecord('event', { temp: this.get('temp'), seconds: this.get('seconds'), }); } });
erbridge/iris
app/models/event.js
JavaScript
mit
1,999
var sheet = cssx(); (function () { var _1 = {}, _2 = {}, _3 = {}; _2['color'] = '#000'; _3['color'] = '#F00'; _1['body'] = _2; _1['body.error'] = _3; return _1; }.apply(this)) ; sheet.add((function () { var _5 = {}, _6 = {}, _7 = {}; _6['font-size'] = '10px'; _6['line-height'] = '12px'; _7['margin'] = 0; _7['padding'] = '2em'; _5['p'] = _6; _5['ul > foo'] = _7; return _5; }.apply(this))); var test = (function () { var _9 = {}; _9['border'] = 'solid 1px #000'; _9['background'] = '#F00'; return _9; }.apply(this));
krasimir/cssx
test/fixtures/cssx-transpiler/21/expected.js
JavaScript
mit
580
"use strict"; var Cylon = require("cylon"); Cylon .robot() .connection("arduino", { adaptor: "firmata", port: "/dev/ttyACM0" }) .device("bmp180", { driver: "bmp180" }) .on("ready", function(bot) { bot.bmp180.getTemperature(function(err, val) { if (err) { console.log(err); } else { console.log("getTemperature call:"); console.log("\tTemp: " + val.temp + " C"); } }); setTimeout(function() { bot.bmp180.getPressure(1, function(err, val) { if (err) { console.log(err); } else { console.log("getPressure call:"); console.log("\tTemperature: " + val.temp + " C"); console.log("\tPressure: " + val.press + " Pa"); } }); }, 1000); setTimeout(function() { bot.bmp180.getAltitude(1, null, function(err, val) { if (err) { console.log(err); } else { console.log("getAltitude call:"); console.log("\tTemperature: " + val.temp + " C"); console.log("\tPressure: " + val.press + " Pa"); console.log("\tAltitude: " + val.alt + " m"); } }); }, 2000); }); Cylon.start();
adrianpomilio/drones
node_modules/cylon-firmata/examples/bmp180/fluent-bmp180.js
JavaScript
mit
1,198
'use strict'; var _Object$assign = require('babel-runtime/core-js/object/assign')['default']; var _getIterator = require('babel-runtime/core-js/get-iterator')['default']; var fs = require('fs'), path = require('path'), resolve = require('resolve'); var CASE_INSENSITIVE = fs.existsSync(path.join(__dirname, 'reSOLVE.js')); // http://stackoverflow.com/a/27382838 function fileExistsWithCaseSync(_x) { var _again = true; _function: while (_again) { var filepath = _x; dir = filenames = undefined; _again = false; // shortcut exit if (!fs.existsSync(filepath)) return false; var dir = path.dirname(filepath); if (dir === '/' || dir === '.' || /^[A-Z]:\\$/.test(dir)) return true; var filenames = fs.readdirSync(dir); if (filenames.indexOf(path.basename(filepath)) === -1) { return false; } _x = dir; _again = true; continue _function; } } function fileExists(filepath) { if (CASE_INSENSITIVE) { return fileExistsWithCaseSync(filepath); } else { return fs.existsSync(filepath); } } function opts(basedir, settings) { // pulls all items from 'import/resolve' return _Object$assign({}, settings['import/resolve'], { basedir: basedir }); } /** * wrapper around resolve * @param {string} p - module path * @param {object} context - ESLint context * @return {string} - the full module filesystem path */ module.exports = function (p, context) { function withResolver(resolver) { // resolve just returns the core module id, which won't appear to exist if (resolver.isCore(p)) return p; try { var file = resolver.sync(p, opts(path.dirname(context.getFilename()), context.settings)); if (!fileExists(file)) return null; return file; } catch (err) { // probably want something more general here if (err.message.indexOf('Cannot find module') === 0) { return null; } throw err; } } var resolvers = (context.settings['import/resolvers'] || ['resolve']).map(require); var _iteratorNormalCompletion = true; var _didIteratorError = false; var _iteratorError = undefined; try { for (var _iterator = _getIterator(resolvers), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { var resolver = _step.value; var file = withResolver(resolver); if (file) return file; } } catch (err) { _didIteratorError = true; _iteratorError = err; } finally { try { if (!_iteratorNormalCompletion && _iterator['return']) { _iterator['return'](); } } finally { if (_didIteratorError) { throw _iteratorError; } } } return null; }; module.exports.relative = function (p, r, settings) { try { var file = resolve.sync(p, opts(path.dirname(r), settings)); if (!fileExists(file)) return null; return file; } catch (err) { if (err.message.indexOf('Cannot find module') === 0) return null; throw err; // else } };
NathanBWaters/website
node_modules/eslint-plugin-import/lib/core/resolve.js
JavaScript
mit
3,043
(function(){ <?php print (new \tomk79\pickles2\px2dthelper\main($px))->document_modules()->build_js(); ?> })();
tomk79/mz2-baser-cms
tests/testdata/standard/common/scripts/contents.js
JavaScript
mit
115
//jshint strict: false module.exports = function(config) { config.set({ basePath: './app', files: [ 'bower_components/angular/angular.js', 'bower_components/angular-route/angular-route.js', 'bower_components/angular-mocks/angular-mocks.js', '*.js' ], autoWatch: true, frameworks: ['jasmine'], browsers: ['Chrome'], plugins: [ 'karma-chrome-launcher', 'karma-firefox-launcher', 'karma-jasmine', 'karma-junit-reporter' ], junitReporter: { outputFile: 'test_out/unit.xml', suite: 'unit' } }); };
ssxjim/angularJS
karma.conf.js
JavaScript
mit
605
angular.module('umbraco').directive('maxlen', function () { return { require: 'ngModel', link: function (scope, el, attrs, ctrl) { var validate = false; var length = 999999; if (attrs.name === 'title') { validate = scope.model.config.allowLongTitles !== '1'; length = scope.serpTitleLength; } else if (attrs.name === 'description') { validate = scope.model.config.allowLongDescriptions !== '1'; length = scope.serpDescriptionLength; } ctrl.$parsers.unshift(function (viewValue) { if (validate && viewValue.length > length) { ctrl.$setValidity('maxlen', false); } else { ctrl.$setValidity('maxlen', true); } return viewValue; }); } }; });
ryanmcdonough/seo-metadata
app/scripts/directives/maxlen.directive.js
JavaScript
mit
929
var nock = require('nock'); var Mockaroo = require('../lib/mockaroo'); require('chai').should(); describe('Client', function() { describe('constructor', function() { it('should require an api key', function() { (function() { new Mockaroo.Client({}); }).should.throw('apiKey is required'); }); }); describe('convertError', function() { var client = new Mockaroo.Client({ apiKey: 'xxx' }); it('should convert Invalid API Key to InvalidApiKeyError', function() { client.convertError({ data: { error: 'Invalid API Key' }}).should.be.a.instanceOf(Mockaroo.errors.InvalidApiKeyError) }); it('should convert errors containing "limited" to UsageLimitExceededError', function() { client.convertError({ data: { error: 'Silver plans are limited to 1,000,000 records per day.' }}).should.be.a.instanceOf(Mockaroo.errors.UsageLimitExceededError) }); }); describe('getUrl', function() { it('should default to https://mockaroo.com', function() { var client = new Mockaroo.Client({ apiKey: 'xxx' }); client.getUrl().should.equal('https://mockaroo.com/api/generate.json?client=node&key=xxx&count=1') }); it('should allow you to change the port', function() { var client = new Mockaroo.Client({ apiKey: 'xxx', secure: false, port: 3000 }); client.getUrl().should.equal('http://mockaroo.com:3000/api/generate.json?client=node&key=xxx&count=1'); }); it('should use http when secure:false', function() { var client = new Mockaroo.Client({ apiKey: 'xxx', secure: false }); client.getUrl().should.equal('http://mockaroo.com/api/generate.json?client=node&key=xxx&count=1'); }); it('should allow you to set a count > 1', function() { var client = new Mockaroo.Client({ apiKey: 'xxx', }); client.getUrl({count: 10}).should.equal('https://mockaroo.com/api/generate.json?client=node&key=xxx&count=10'); }); it('should allow you to customize the host', function() { var client = new Mockaroo.Client({ apiKey: 'xxx', host: 'foo' }); client.getUrl().should.equal('https://foo/api/generate.json?client=node&key=xxx&count=1'); }); it('should include schema', function() { var client = new Mockaroo.Client({ apiKey: 'xxx' }); client.getUrl({schema: 'MySchema'}).should.equal('https://mockaroo.com/api/generate.json?client=node&key=xxx&count=1&schema=MySchema'); }); it('should allow you to generate csv', function() { var client = new Mockaroo.Client({ apiKey: 'xxx' }); client.getUrl({format: 'csv'}).should.equal('https://mockaroo.com/api/generate.csv?client=node&key=xxx&count=1'); }); it('should allow you to remove the header from csv', function() { var client = new Mockaroo.Client({ apiKey: 'xxx' }); client.getUrl({format: 'csv', header: false}).should.equal('https://mockaroo.com/api/generate.csv?client=node&key=xxx&count=1&header=false'); }) }); describe('generate', function() { var client = new Mockaroo.Client({ secure: false, apiKey: 'xxx' }); it('should require fields or schema', function() { (function() { client.generate() }).should.throw('Either fields or schema option must be specified'); }); describe('when successful', function() { var api = nock('http://mockaroo.com') .post('/api/generate.json?client=node&key=xxx&count=1') .reply(200, JSON.stringify([{ foo: 'bar' }])) it('should resolve', function() { return client.generate({ fields: [{ name: 'foo', type: 'Custom List', values: ['bar'] }] }).then(function(records) { records.should.deep.equal([{ foo: 'bar' }]); }) }); }) describe('when unsuccessful', function() { var api = nock('http://mockaroo.com') .post('/api/generate.json?client=node&key=xxx&count=1') .reply(500, JSON.stringify({ error: 'Invalid API Key' })) it('should handle errors', function() { return client.generate({ fields: [] }).catch(function(error) { error.should.be.instanceOf(Mockaroo.errors.InvalidApiKeyError) }) }); }); it('should required fields to be an array', function() { (function() { client.generate({ fields: 'foo' }) }).should.throw('fields must be an array'); }); it('should required a name for each field', function() { (function() { client.generate({ fields: [{ type: 'Row Number' }] }) }).should.throw('each field must have a name'); }); it('should required a type for each field', function() { (function() { client.generate({ fields: [{ name: 'ID' }] }) }).should.throw('each field must have a type'); }); }); });
m4dz/mockaroo-node
test/client.js
JavaScript
mit
5,757
"use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; var _createSvgIcon = _interopRequireDefault(require("./utils/createSvgIcon")); var _jsxRuntime = require("react/jsx-runtime"); var _default = (0, _createSvgIcon.default)( /*#__PURE__*/(0, _jsxRuntime.jsx)("path", { d: "M4 15h16v-2H4v2zm0 4h16v-2H4v2zm0-8h16V9H4v2zm0-6v2h16V5H4z" }), 'ViewHeadlineSharp'); exports.default = _default;
oliviertassinari/material-ui
packages/mui-icons-material/lib/ViewHeadlineSharp.js
JavaScript
mit
532
import React from 'react' import Icon from 'react-icon-base' const GoColorMode = props => ( <Icon viewBox="0 0 40 40" {...props}> <g><path d="m5 5v30h30v-30h-30z m2.5 27.5v-25h25l-25 25z"/></g> </Icon> ) export default GoColorMode
bengimbel/Solstice-React-Contacts-Project
node_modules/react-icons/go/color-mode.js
JavaScript
mit
250
/* * Copyright (c) 2015 by Rafael Angel Aznar Aparici (rafaaznar at gmail dot com) * * openAUSIAS: The stunning micro-library that helps you to develop easily * AJAX web applications by using Java and jQuery * openAUSIAS is distributed under the MIT License (MIT) * Sources at https://github.com/rafaelaznar/ * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * */ 'use strict'; moduloTipocompeticion.controller('TipocompeticionRemoveController', ['$scope', '$routeParams', 'serverService', function ($scope, $routeParams, serverService) { $scope.result = ""; $scope.back = function () { window.history.back(); }; $scope.ob = 'tipocompeticion'; $scope.id = $routeParams.id; $scope.title = "Borrado de un Tipo de Competicion"; $scope.icon = "fa-futbol-o"; serverService.getDataFromPromise(serverService.promise_getOne($scope.ob, $scope.id)).then(function (data) { $scope.bean = data.message; }); $scope.remove = function () { serverService.getDataFromPromise(serverService.promise_removeOne($scope.ob, $scope.id)).then(function (data) { $scope.result = data; }); } ; }]);
Sanferc/FutbolAngular
src/main/webapp/js/tipocompeticion/remove.js
JavaScript
mit
2,306
/* 基本测试,ejs 模版 测试 例子 */ var should = require('should'); var request = require('request'); var path = require('path'); var testconf = require('./testconf.js'); module.exports.rrestjsconfig = { listenPort:3000, tempSet:'ejs', tempFolder :'/static', baseDir: path.join(__dirname), }; var chtml=''; var dhtml = ''; var fhtml = ''; var http = require('http'), rrest = require('../'), i=0, server = http.createServer(function (req, res) { var pname = req.pathname; if(pname === '/a'){ res.render('/ejs'); } else if(pname === '/b'){ res.render('/ejs.ejs', {"name":'hello world'}); } else if(pname === '/c'){ res.render('/ejs',function(err, html){//测试不加后缀名是否可以render成功 chtml = html; }); } else if(pname === '/d'){ res.render('/ejs.ejs', {"name":'hello world'}, function(err, html){ dhtml = html; }); } else if(pname === '/e'){ res.render('/ejs.ejs', 1, {"usersex":'hello world'}); } else if(pname === '/f'){ res.render('/ejs', 2, {}, function(err, html){ fhtml = html; }); } else if(pname === '/g'){ res.compiletemp('/ejs.ejs', function(err, html){ res.sendjson({'data':html}); }); } else if(pname === '/h'){ res.compiletemp('/ejs.ejs', 3, {"name":'hello world'}, function(err, html){ res.sendjson({'data':html}); }); } else if(pname === '/i'){ res.compiletemp('/ejs2', 3, {"name":'hello world'}, function(err, html){ res.sendjson({'data':html}); }); } }).listen(rrest.config.listenPort); //设置全局的模版option rrest.tploption.userid = function(req,res){return req.ip}; rrest.tploption.name = 'rrestjs default'; rrest.tploption.usersex = 'male'; http.globalAgent.maxSockets = 10; var i = 9; var r = 0 var result = function(name){ var num = ++r; console.log('%s test done, receive %d/%d', name, num, i); if(num>=i){ console.log('ejs.js test done.') process.exit(); } } request({ method:'get', uri:'http://'+testconf.hostname+':3000/a', }, function(error, res, body){ should.strictEqual(res.statusCode, 200); should.strictEqual(body, '<li>rrestjs default</li><li>'+testconf.hostname+'</li><li>male</li><form></form>') result('/a request') }); request({ method:'get', uri:'http://'+testconf.hostname+':3000/b', }, function(error, res, body){ should.strictEqual(res.statusCode, 200); should.strictEqual(body, '<li>hello world</li><li>'+testconf.hostname+'</li><li>male</li><form></form>') result('/b request') }); request({ method:'get', uri:'http://'+testconf.hostname+':3000/c', }, function(error, res, body){ should.strictEqual(res.statusCode, 200); should.strictEqual(body, '<li>rrestjs default</li><li>'+testconf.hostname+'</li><li>male</li><form></form>'); setTimeout(function(){ should.strictEqual(chtml, '<li>rrestjs default</li><li>'+testconf.hostname+'</li><li>male</li><form></form>'); result('/c request') },100) }); request({ method:'get', uri:'http://'+testconf.hostname+':3000/d', }, function(error, res, body){ should.strictEqual(res.statusCode, 200); should.strictEqual(body, '<li>hello world</li><li>'+testconf.hostname+'</li><li>male</li><form></form>'); setTimeout(function(){ should.strictEqual(dhtml, '<li>hello world</li><li>'+testconf.hostname+'</li><li>male</li><form></form>'); result('/d request') },100) }); request({ method:'get', uri:'http://'+testconf.hostname+':3000/e', }, function(error, res, body){ should.strictEqual(res.statusCode, 200); should.strictEqual(body, '<li>rrestjs default</li><li>'+testconf.hostname+'</li><li>hello world</li><form></form>'); result('/e request') }); request({ method:'get', uri:'http://'+testconf.hostname+':3000/f', }, function(error, res, body){ should.strictEqual(res.statusCode, 200); should.strictEqual(body, '<li>rrestjs default</li><li>'+testconf.hostname+'</li><li>male</li><form></form>'); setTimeout(function(){ should.strictEqual(fhtml, '<li>rrestjs default</li><li>'+testconf.hostname+'</li><li>male</li><form></form>'); result('/f request') },100) }); request({ method:'get', uri:'http://'+testconf.hostname+':3000/g', }, function(error, res, body){ should.strictEqual(res.statusCode, 200); should.strictEqual(body, '{\"data\":\"<li>rrestjs default</li><li>'+testconf.hostname+'</li><li>male</li><form></form>\"}'); result('/g request') }); request({ method:'get', uri:'http://'+testconf.hostname+':3000/h', }, function(error, res, body){ should.strictEqual(res.statusCode, 200); should.strictEqual(body, '{\"data\":\"<li>hello world</li><li>'+testconf.hostname+'</li><li>male</li><form></form>\"}'); result('/h request') }); setTimeout(function(){ rrest.ejs.open ='{{' rrest.ejs.close ='}}' request({ method:'get', uri:'http://'+testconf.hostname+':3000/i', }, function(error, res, body){ should.strictEqual(res.statusCode, 200); should.strictEqual(body, '{\"data\":\"<li>hello world</li><li>'+testconf.hostname+'</li><li>male</li><form></form>\"}'); result('/h request') }); },1000)
kuitos/jsgen-v0.3.5
node_modules/rrestjs/test/ejs.js
JavaScript
mit
5,211
"use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; var _createSvgIcon = _interopRequireDefault(require("./utils/createSvgIcon")); var _jsxRuntime = require("react/jsx-runtime"); var _default = (0, _createSvgIcon.default)([/*#__PURE__*/(0, _jsxRuntime.jsx)("path", { d: "M5 18h14V8H5v10zm3.82-6.42 2.12 2.12 4.24-4.24 1.41 1.41-5.66 5.66L7.4 13l1.42-1.42z", opacity: ".3" }, "0"), /*#__PURE__*/(0, _jsxRuntime.jsx)("path", { d: "m16.6 10.88-1.42-1.42-4.24 4.25-2.12-2.13L7.4 13l3.54 3.54z" }, "1"), /*#__PURE__*/(0, _jsxRuntime.jsx)("path", { d: "M19 4H5c-1.11 0-2 .9-2 2v12c0 1.1.89 2 2 2h14c1.1 0 2-.9 2-2V6c0-1.1-.89-2-2-2zm0 14H5V8h14v10z" }, "2")], 'DomainVerificationTwoTone'); exports.default = _default;
oliviertassinari/material-ui
packages/mui-icons-material/lib/DomainVerificationTwoTone.js
JavaScript
mit
864
var _ = require('lodash'), Promise = require('bluebird'), IndexMapGenerator = require('./index-generator'), PagesMapGenerator = require('./page-generator'), PostsMapGenerator = require('./post-generator'), UsersMapGenerator = require('./user-generator'), TagsMapGenerator = require('./tag-generator'), SiteMapManager; SiteMapManager = function (opts) { opts = opts || {}; this.initialized = false; this.pages = opts.pages || this.createPagesGenerator(opts); this.posts = opts.posts || this.createPostsGenerator(opts); this.authors = opts.authors || this.createUsersGenerator(opts); this.tags = opts.tags || this.createTagsGenerator(opts); this.index = opts.index || this.createIndexGenerator(opts); }; _.extend(SiteMapManager.prototype, { createIndexGenerator: function () { return new IndexMapGenerator(_.pick(this, 'pages', 'posts', 'authors', 'tags')); }, createPagesGenerator: function (opts) { return new PagesMapGenerator(opts); }, createPostsGenerator: function (opts) { return new PostsMapGenerator(opts); }, createUsersGenerator: function (opts) { return new UsersMapGenerator(opts); }, createTagsGenerator: function (opts) { return new TagsMapGenerator(opts); }, init: function () { var self = this, initOps = [ this.pages.init(), this.posts.init(), this.authors.init(), this.tags.init() ]; return Promise.all(initOps).then(function () { self.initialized = true; }); }, getIndexXml: function () { if (!this.initialized) { return ''; } return this.index.getIndexXml(); }, getSiteMapXml: function (type) { if (!this.initialized || !this[type]) { return null; } return this[type].siteMapContent; }, pageAdded: function (page) { if (!this.initialized) { return; } if (page.get('status') !== 'published') { return; } this.pages.addUrl(page.toJSON()); }, pageEdited: function (page) { if (!this.initialized) { return; } var pageData = page.toJSON(), wasPublished = page.updated('status') === 'published', isPublished = pageData.status === 'published'; // Published status hasn't changed and it's published if (isPublished === wasPublished && isPublished) { this.pages.updateUrl(pageData); } else if (!isPublished && wasPublished) { // Handle page going from published to draft this.pageDeleted(page); } else if (isPublished && !wasPublished) { // ... and draft to published this.pageAdded(page); } }, pageDeleted: function (page) { if (!this.initialized) { return; } this.pages.removeUrl(page.toJSON()); }, postAdded: function (post) { if (!this.initialized) { return; } if (post.get('status') !== 'published') { return; } this.posts.addUrl(post.toJSON()); }, postEdited: function (post) { if (!this.initialized) { return; } var postData = post.toJSON(), wasPublished = post.updated('status') === 'published', isPublished = postData.status === 'published'; // Published status hasn't changed and it's published if (isPublished === wasPublished && isPublished) { this.posts.updateUrl(postData); } else if (!isPublished && wasPublished) { // Handle post going from published to draft this.postDeleted(post); } else if (isPublished && !wasPublished) { // ... and draft to published this.postAdded(post); } }, postDeleted: function (post) { if (!this.initialized) { return; } this.posts.removeUrl(post.toJSON()); }, userAdded: function (user) { if (!this.initialized) { return; } this.authors.addUrl(user.toJSON()); }, userEdited: function (user) { if (!this.initialized) { return; } var userData = user.toJSON(); this.authors.updateUrl(userData); }, userDeleted: function (user) { if (!this.initialized) { return; } this.authors.removeUrl(user.toJSON()); }, tagAdded: function (tag) { if (!this.initialized) { return; } this.tags.addUrl(tag.toJSON()); }, tagEdited: function (tag) { if (!this.initialized) { return; } this.tags.updateUrl(tag.toJSON()); }, tagDeleted: function (tag) { if (!this.initialized) { return; } this.tags.removeUrl(tag.toJSON()); }, // TODO: Call this from settings model when it's changed permalinksUpdated: function (permalinks) { if (!this.initialized) { return; } this.posts.updatePermalinksValue(permalinks.toJSON ? permalinks.toJSON() : permalinks); }, _refreshAllPosts: _.throttle(function () { this.posts.refreshAllPosts(); }, 3000, { leading: false, trailing: true }) }); module.exports = SiteMapManager;
PHILIP-2014/philip-blog
core/server/data/sitemap/manager.js
JavaScript
mit
5,793
/** * Draws rectangles */ Y.Rect = Y.Base.create("rect", Y.Shape, [], { /** * Indicates the type of shape * * @property _type * @readOnly * @type String */ _type: "rect", /** * @private */ _draw: function() { var x = this.get("x"), y = this.get("y"), w = this.get("width"), h = this.get("height"), fill = this.get("fill"), stroke = this.get("stroke"); this.drawRect(x, y, w, h); this._paint(); } });
inikoo/fact
libs/yui/yui3-gallery/src/gallery-graphics/js/CanvasRect.js
JavaScript
mit
553
/** * Test helpers for the tap tests that use material-ui as a front end */ import {saveToken, elements} from '../demo'; /** * * @param {object} aBrowser * @param {string} accessToken * @param {boolean} isOneOnOne * @param {string} to */ export default function loginAndOpenWidget(aBrowser, accessToken, isOneOnOne, to) { saveToken(aBrowser, accessToken); if (isOneOnOne) { aBrowser.element(elements.toPersonRadioButton).click(); aBrowser.element(elements.toPersonInput).setValue(to); } else { aBrowser.element(elements.toSpaceRadioButton).click(); aBrowser.element(elements.toSpaceInput).setValue(to); } aBrowser.element(elements.openSpaceWidgetButton).click(); aBrowser.waitUntil(() => aBrowser.element(elements.spaceWidgetContainer).isVisible(), 3500, 'widget failed to open'); }
adamweeks/react-ciscospark-1
test/journeys/lib/test-helpers/tap/space.js
JavaScript
mit
824
import browserColor from 'tap-browser-color'; browserColor(); import test from 'tape'; import React from 'react'; import universal from '../../client'; import routes from '../fixtures/routes'; import reducers from '../fixtures/reducers'; const app = universal({ React, routes, reducers }); const store = app(); test('Client app', nest => { nest.test('...without Express instance', assert => { const msg = 'should not return an Express instance'; const actual = typeof app.use; const expected = 'undefined'; assert.equal(actual, expected, msg); assert.end(); }); nest.test('...initalState', assert => { const msg = 'should render initialState'; const text = 'Untitled'; const actual = document.querySelectorAll('.title')[0].innerHTML; const expected = text; assert.equal(actual, expected, msg); assert.end(); }); nest.test('...client call', assert => { const msg = 'should return store instance'; const actual = typeof store.dispatch; const expected = 'function'; assert.equal(actual, expected, msg); assert.end(); }); nest.test('...with dispatch', assert => { const msg = 'should render new output'; const text = 'Client render'; store.dispatch({ type: 'SET_TITLE', title: text }); setTimeout(() => { const actual = document.querySelectorAll('.title')[0].innerHTML; const expected = text; assert.equal(actual, expected, msg); assert.end(); }, 100); }); nest.test('...with second dispatch', assert => { const msg = 'should render new output'; const text = 'Client render 2'; store.dispatch({ type: 'SET_TITLE', title: text }); setTimeout(() => { const actual = document.querySelectorAll('.title')[0].innerHTML; const expected = text; assert.equal(actual, expected, msg); assert.end(); }, 100); }); });
ericelliott/react-easy-universal
source/test/client/index.js
JavaScript
mit
1,927
import fs from "fs"; import { parse } from "babylon"; import CodeGenerator from "../CodeGenerator"; import processTokens from "../process-tokens"; import {timeLogStart, timeLog} from "../utils"; function parseText(text) { timeLogStart("started parsing text"); let ast = parse(text, { preserveParens: true, sourceType: "module", plugins: [ "*" ] }); timeLog("parsed input"); let tokens = ast.tokens; let semicolons = ast.tokens.filter(token => token.type.label === ";"); timeLogStart(); const modifiedTokens = processTokens(text, tokens, semicolons); timeLog(`processed ${tokens.length} -> ${modifiedTokens.length} tokens`); return { ast: ast.program, tokens: modifiedTokens, semicolons }; } export function formatText(text) { const { ast, tokens, semicolons } = parseText(text); let generator = new CodeGenerator(ast, text, tokens, semicolons); return generator.generate(); } export function formatFile(filename) { try { timeLogStart(); const text = fs.readFileSync(filename).toString(); timeLog("finished reading file"); return formatText(text); } catch (error) { error.message = `${filename}: ${error.message}`; throw error; } }
Mark-Simulacrum/pretty-generator
src/api/node.js
JavaScript
mit
1,278
var Thoonk = require('../thoonk').Thoonk; var thoonk = new Thoonk(); var jobs = {}; var stats = thoonk.feed('thoonk_job_stats'); thoonk.mredis.smembers('feeds', function(err, feeds) { feeds.forEach(function(name) { thoonk.mredis.hget('feed.config:' + name, 'type', function(err, reply) { if(reply == 'job') { jobs[name] = thoonk.job(name); } }); }); }); thoonk.on('create', function(name, instance) { thoonk.mredis.hget('feed.config:' + name, 'type', function(err, reply) { if(reply == 'job') { jobs[name] = thoonk.job(name); } }); }); thoonk.on('delete', function(name, instance) { if(jobs.hasOwnProperty(name)) { jobs[name].quit(); delete jobs[name]; }; }); var update = function() { for(key in jobs) { //function(job, key) { (function(key, jobs) { var multi = thoonk.mredis.multi(); multi.llen('feed.ids:' + key); multi.getset('feed.publishes:' + key, '0'); multi.getset('feed.finishes:' + key, '0'); multi.zcount('feed.claimed:' + key,'0', '999999999999999'); multi.hlen('feed.items:' + key); multi.exec(function(err, reply) { console.log('----' + key + '----'); console.log('available:', reply[0]); console.log('publishes:', reply[1]); console.log('finishes:', reply[1]); console.log('claimed:', reply[3]); console.log('total:', reply[4]); stats.publish(JSON.stringify({available: reply[0], publishes: reply[1], finishes: reply[2], claimed: reply[3], total:reply[4]}), key) }); })(key, jobs); } setTimeout(update, 1000); }; update(); var http = require('http'); var static = require('node-static'); var fileServer = new(static.Server)('./monitor-html'); var server = http.createServer(function(request, response) { request.addListener('end', function () { fileServer.serve(request, response); }); }); server.listen(8000); var io = require('socket.io').listen(8001); io.sockets.on('connection', function (socket) { var thissocket = socket; var statupdate = function(feed, id, item) { var uitem = JSON.parse(item); uitem.id = id; console.log('msg', feed, item, id); socket.emit('message', uitem); }; stats.subscribe({ edit: statupdate, publish: statupdate }); socket.once('disconnect', function() { stats.unsubscribe({edit: statupdate, publish: statupdate}); }); });
fritzy/thoonk.js
tools/monitor.js
JavaScript
mit
2,645
import {writeArray} from 'event-stream'; import gulp from 'gulp'; import license from '../../tasks/helpers/license-helper'; describe('license', () => { let result; beforeEach(done => { const licenseStream = gulp.src('src/pivotal-ui/components/alerts') .pipe(license()); licenseStream.on('error', (error) => { console.error(error); callback(); }); licenseStream.pipe(writeArray((error, data) => { result = data; done(); })); }); it('creates an MIT license for the component', () => { expect(result[0].path).toEqual('alerts/LICENSE'); expect(result[0].contents.toString()).toContain('The MIT License'); }); });
CanopyCloud/pivotal-ui
spec/task-helpers/license-helper-spec.js
JavaScript
mit
683
/*globals define, _*/ /*jshint browser: true*/ /** * @author rkereskenyi / https://github.com/rkereskenyi */ define(['js/KeyboardManager/IKeyTarget'], function (IKeyTarget) { 'use strict'; var DiagramDesignerWidgetKeyboard; DiagramDesignerWidgetKeyboard = function () { }; _.extend(DiagramDesignerWidgetKeyboard.prototype, IKeyTarget.prototype); DiagramDesignerWidgetKeyboard.prototype.onKeyDown = function (eventArgs) { var ret = true; switch (eventArgs.combo) { case 'del': this.onSelectionDelete(this.selectionManager.getSelectedElements()); ret = false; break; case 'ctrl+a': this.selectAll(); ret = false; break; case 'ctrl+q': this.selectNone(); ret = false; break; case 'ctrl+i': this.selectItems(); ret = false; break; case 'ctrl+u': this.selectConnections(); ret = false; break; case 'ctrl+l': this.selectInvert(); ret = false; break; case 'up': this._moveSelection(0, -this.gridSize); ret = false; break; case 'down': this._moveSelection(0, this.gridSize); ret = false; break; case 'left': this._moveSelection(-this.gridSize, 0); ret = false; break; case 'right': this._moveSelection(this.gridSize, 0); ret = false; break; case this.CONSTANTS.KEY_SHORT_CUT_MOVE_TO_TOP: this.onAlignSelection(this.selectionManager.getSelectedElements(), this.CONSTANTS.MOVE_TO_TOP); ret = false; break; case this.CONSTANTS.KEY_SHORT_CUT_MOVE_TO_BOTTOM: this.onAlignSelection(this.selectionManager.getSelectedElements(), this.CONSTANTS.MOVE_TO_BOTTOM); ret = false; break; case this.CONSTANTS.KEY_SHORT_CUT_MOVE_TO_LEFT: this.onAlignSelection(this.selectionManager.getSelectedElements(), this.CONSTANTS.MOVE_TO_LEFT); ret = false; break; case this.CONSTANTS.KEY_SHORT_CUT_MOVE_TO_RIGHT: this.onAlignSelection(this.selectionManager.getSelectedElements(), this.CONSTANTS.MOVE_TO_RIGHT); ret = false; break; default: break; /*case 'ctrl+c': this.onClipboardCopy(this.selectionManager.getSelectedElements()); ret = false; break; case 'ctrl+v': this.onClipboardPaste(); ret = false; break;*/ } return ret; }; DiagramDesignerWidgetKeyboard.prototype.onKeyUp = function (eventArgs) { var ret = true; switch (eventArgs.combo) { case 'up': this._endMoveSelection(); ret = false; break; case 'down': this._endMoveSelection(); ret = false; break; case 'left': this._endMoveSelection(); ret = false; break; case 'right': this._endMoveSelection(); ret = false; break; } return ret; }; DiagramDesignerWidgetKeyboard.prototype._moveSelection = function (dX, dY) { if (!this._keyMoveDelta) { this._keyMoveDelta = {x: 0, y: 0}; this.dragManager._initDrag(0, 0); this.dragManager._startDrag(undefined); } this._keyMoveDelta.x += dX; this._keyMoveDelta.y += dY; this.dragManager._updateDraggedItemPositions(this._keyMoveDelta.x, this._keyMoveDelta.y); }; DiagramDesignerWidgetKeyboard.prototype._endMoveSelection = function () { if (this._keyMoveDelta) { // reinitialize keyMove data this._keyMoveDelta = undefined; this.dragManager._endDragAction(); } }; return DiagramDesignerWidgetKeyboard; });
pillforge/webgme
src/client/js/Widgets/DiagramDesigner/DiagramDesignerWidget.Keyboard.js
JavaScript
mit
4,450
import "core-js/modules/web.dom.iterable"; import "core-js/modules/es6.promise"; var p = Promise.resolve(0); Promise.all([p]).then(function (outcome) { alert("OK"); });
guybedford/babel
packages/babel-preset-env/test/fixtures/preset-options-add-used-built-ins/promise-all/output.js
JavaScript
mit
171
fn() => x
wcjohnson/babylon-lightscript
test/fixtures/lightscript/named-arrow-functions/fat-oneline/actual.js
JavaScript
mit
10
"use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; var _createSvgIcon = _interopRequireDefault(require("./utils/createSvgIcon")); var _jsxRuntime = require("react/jsx-runtime"); var _default = (0, _createSvgIcon.default)([/*#__PURE__*/(0, _jsxRuntime.jsx)("circle", { cx: "12", cy: "23", r: "1" }, "0"), /*#__PURE__*/(0, _jsxRuntime.jsx)("circle", { cx: "8", cy: "23", r: "1" }, "1"), /*#__PURE__*/(0, _jsxRuntime.jsx)("circle", { cx: "16", cy: "23", r: "1" }, "2"), /*#__PURE__*/(0, _jsxRuntime.jsx)("path", { d: "M13.41 10 17 6.42c.39-.39.39-1.02 0-1.42L12.21.21c-.14-.14-.32-.21-.5-.21-.39 0-.71.32-.71.71v6.88L7.11 3.71a.9959.9959 0 0 0-1.41 0c-.39.39-.39 1.02 0 1.41L10.59 10 5.7 14.89c-.39.39-.39 1.02 0 1.41.39.39 1.02.39 1.41 0L11 12.41v6.88c0 .39.32.71.71.71.19 0 .37-.07.5-.21L17 15c.39-.39.39-1.02 0-1.42L13.41 10zM13 3.83l1.88 1.88L13 7.59V3.83zm0 12.34v-3.76l1.88 1.88L13 16.17z" }, "3")], 'SettingsBluetoothRounded'); exports.default = _default;
oliviertassinari/material-ui
packages/mui-icons-material/lib/SettingsBluetoothRounded.js
JavaScript
mit
1,125
'use strict'; module.exports = { db: { dbName:'sean-dev', username : 'SeanDB', password : 'HU7XQQBNWq', dialect: "postgres", // 'sqlite', 'postgres', 'mariadb','mysql' port : 5432 // 5432 for postgres, 3306 for mysql and mariaDB , }, app: { title: 'SEAN - Development Environment' }, facebook: { clientID: process.env.FACEBOOK_ID || 'APP_ID', clientSecret: process.env.FACEBOOK_SECRET || 'APP_SECRET', callbackURL: 'http://localhost:3000/auth/facebook/callback' }, twitter: { clientID: process.env.TWITTER_KEY || 'CONSUMER_KEY', clientSecret: process.env.TWITTER_SECRET || 'CONSUMER_SECRET', callbackURL: 'http://localhost:3000/auth/twitter/callback' }, google: { clientID: process.env.GOOGLE_ID || 'APP_ID', clientSecret: process.env.GOOGLE_SECRET || 'APP_SECRET', callbackURL: 'http://localhost:3000/auth/google/callback' }, linkedin: { clientID: process.env.LINKEDIN_ID || 'APP_ID', clientSecret: process.env.LINKEDIN_SECRET || 'APP_SECRET', callbackURL: 'http://localhost:3000/auth/linkedin/callback' }, github: { clientID: process.env.GITHUB_ID || 'APP_ID', clientSecret: process.env.GITHUB_SECRET || 'APP_SECRET', callbackURL: 'http://localhost:3000/auth/github/callback' }, mailer: { from: process.env.MAILER_FROM || 'MAILER_FROM', options: { service: process.env.MAILER_SERVICE_PROVIDER || 'MAILER_SERVICE_PROVIDER', auth: { user: process.env.MAILER_EMAIL_ID || 'MAILER_EMAIL_ID', pass: process.env.MAILER_PASSWORD || 'MAILER_PASSWORD' } } } };
MangoTools/sean
config/env/development.js
JavaScript
mit
1,566
(function () { 'use strict'; angular .module('nama.common') .directive('namaNav', namaNav); namaNav.$inject = []; function namaNav() { return { restrict: 'E', templateUrl: '/nama-framework/common/nav/nav.html', controller: 'NavController', controllerAs: 'vm', bindToController: true, scope: { brand: '@' } }; } }());
jasonody/NamaBeer
NamaBeer.Client/nama-framework/common/nav/navDirective.js
JavaScript
mit
362
var module = angular.module("example", ["agGrid"]); module.controller("exampleCtrl", function($scope, $http) { var columnDefs = [ {headerName: "Gold", field: "gold", width: 100}, {headerName: "Silver", field: "silver", width: 100}, {headerName: "Bronze", field: "bronze", width: 100}, {headerName: "Total", field: "total", width: 100}, {headerName: "Age", field: "age", width: 90, checkboxSelection: true}, {headerName: "Country", field: "country", width: 120, rowGroupIndex: 0}, {headerName: "Year", field: "year", width: 90}, {headerName: "Date", field: "date", width: 110}, {headerName: "Sport", field: "sport", width: 110, rowGroupIndex: 1} ]; $scope.gridOptions = { columnDefs: columnDefs, rowData: null, rowSelection: 'multiple', groupAggFunction: groupAggFunction, groupSelectsChildren: true, suppressRowClickSelection: true, groupColumnDef: {headerName: "Athlete", field: "athlete", width: 200, cellRenderer: { renderer: "group", checkbox: true }} }; function groupAggFunction(rows) { var sums = { gold: 0, silver: 0, bronze: 0, total: 0 }; rows.forEach(function(row) { var data = row.data; sums.gold += data.gold; sums.silver += data.silver; sums.bronze += data.bronze; sums.total += data.total; }); return sums; } $http.get("../olympicWinners.json") .then(function(res){ $scope.gridOptions.api.setRowData(res.data); }); });
jainpiyush111/ng-admin
example1/blog/ag-grid/docs/angular-grid-selection/groupSelection.js
JavaScript
mit
1,734
import CalendarDayNamesHeader from "../base/CalendarDayNamesHeader.js"; import { template } from "../base/internal.js"; import { fragmentFrom } from "../core/htmlLiterals.js"; /** * CalendarDayNamesHeader component in the Plain reference design system * * @inherits CalendarDayNamesHeader */ class PlainCalendarDayNamesHeader extends CalendarDayNamesHeader { get [template]() { const result = super[template]; result.content.append( fragmentFrom.html` <style> :host { font-size: smaller; } [part~="day-name"] { padding: 0.3em; text-align: center; white-space: nowrap; } [weekend] { color: gray; } </style> ` ); return result; } } export default PlainCalendarDayNamesHeader;
JanMiksovsky/elix
src/plain/PlainCalendarDayNamesHeader.js
JavaScript
mit
850
/*global describe, beforeEach, it*/ 'use strict'; var assert = require('assert'); describe('video generator', function () { it('can be imported without blowing up', function () { var app = require('../app'); assert(app !== undefined); }); });
aloysious/generator-video
test/test-load.js
JavaScript
mit
258
'use strict'; module.exports = function modify(config) { console.log('Razzle comes with React! This package is a stub.'); return config; };
jaredpalmer/razzle
packages/razzle-plugin-react/index.js
JavaScript
mit
145
var path = require("path"); var webpack = require("webpack"); var ExtractTextPlugin = require('extract-text-webpack-plugin'); var pkg = require(path.join(process.cwd(), 'package.json')); var assetsPath = path.join(__dirname, "public","js"); var publicPath = "/public/"; var commonLoaders = [ { test: /\.js$|\.jsx$/, loaders: ["babel"], include: path.join(__dirname, "app") }, { test: /\.css$/, loader: ExtractTextPlugin.extract( 'css?sourceMap&-restructuring!' + 'autoprefixer-loader' ) }, { test: /\.less$/, loader: ExtractTextPlugin.extract( 'css?sourceMap!' + 'autoprefixer-loader!' + 'less?{"sourceMap":true,"modifyVars":' + JSON.stringify(pkg.theme || {})+'}' ) } ]; module.exports = { // The configuration for the client name: "browser", /* The entry point of the bundle * Entry points for multi page app could be more complex * A good example of entry points would be: * entry: { * pageA: "./pageA", * pageB: "./pageB", * pageC: "./pageC", * adminPageA: "./adminPageA", * adminPageB: "./adminPageB", * adminPageC: "./adminPageC" * } * * We can then proceed to optimize what are the common chunks * plugins: [ * new CommonsChunkPlugin("admin-commons.js", ["adminPageA", "adminPageB"]), * new CommonsChunkPlugin("common.js", ["pageA", "pageB", "admin-commons.js"], 2), * new CommonsChunkPlugin("c-commons.js", ["pageC", "adminPageC"]); * ] */ context: path.join(__dirname, "app"), entry: { app: "./app.js" }, output: { // The output directory as absolute path path: assetsPath, // The filename of the entry chunk as relative path inside the output.path directory filename: "bundle.js", // The output path from the view of the Javascript publicPath: publicPath }, module: { loaders: commonLoaders }, plugins: [ new webpack.HotModuleReplacementPlugin(), new webpack.NoErrorsPlugin(), new ExtractTextPlugin('ant.css', { disable: false, allChunks: true }), ] };
gitoneman/react-webpack-redux-starter
webpack.config.js
JavaScript
mit
2,348
module.exports={A:{A:{"2":"H D G E A B EB"},B:{"2":"C p x J L N I"},C:{"2":"0 1 2 3 4 5 6 8 9 ZB BB F K H D G E A B C p x J L N I O P Q R S T U V W X Y Z b c d e f g h i j k l m n o M q r s t u v w y XB RB"},D:{"1":"8 9 LB GB FB bB a HB IB JB","2":"0 F K H D G E A B C p x J L N I O P Q R S T U V W X Y Z b c d e f g h i j k l m n o M q r s t u v w","66":"1 2 3 4 5 6 y"},E:{"2":"F K H D G E A B C KB CB MB NB OB PB QB z SB"},F:{"1":"r s t u v w","2":"0 7 E B C J L N I O P Q R S T U V W X Y Z b c d e f g h i j TB UB VB WB z AB YB","66":"k l m n o M q"},G:{"2":"G CB aB DB cB dB eB fB gB hB iB jB kB lB"},H:{"2":"mB"},I:{"2":"BB F a nB oB pB qB DB rB sB"},J:{"2":"D A"},K:{"2":"7 A B C M z AB"},L:{"1":"a"},M:{"2":"y"},N:{"2":"A B"},O:{"2":"tB"},P:{"2":"F K uB vB"},Q:{"2":"wB"},R:{"2":"xB"}},B:7,C:"WebUSB"};
gabz75/ember-cli-deploy-redis-publish
node_modules/caniuse-lite/data/features/webusb.js
JavaScript
mit
811
<Card> <Card.Header> <Nav variant="tabs" defaultActiveKey="#first"> <Nav.Item> <Nav.Link href="#first">Active</Nav.Link> </Nav.Item> <Nav.Item> <Nav.Link href="#link">Link</Nav.Link> </Nav.Item> <Nav.Item> <Nav.Link href="#disabled" disabled> Disabled </Nav.Link> </Nav.Item> </Nav> </Card.Header> <Card.Body> <Card.Title>Special title treatment</Card.Title> <Card.Text> With supporting text below as a natural lead-in to additional content. </Card.Text> <Button variant="primary">Go somewhere</Button> </Card.Body> </Card>;
glenjamin/react-bootstrap
www/src/examples/Card/NavTabs.js
JavaScript
mit
641
'use strict'; /* global describe, it, beforeEach */ var jsdomHelper = require('../testHelpers/jsdomHelper'); var sinon = require('sinon'); var unexpected = require('unexpected'); var unexpectedDom = require('unexpected-dom'); var unexpectedSinon = require('unexpected-sinon'); var expect = unexpected .clone() .installPlugin(unexpectedDom) .installPlugin(unexpectedSinon) .installPlugin(require('../testHelpers/nodeListType')); jsdomHelper(); var React = require('react'); var ReactDOM = require('react-dom'); var TestUtils = require('react-addons-test-utils'); var Select = require('../src/Select'); // The displayed text of the currently selected item, when items collapsed var DISPLAYED_SELECTION_SELECTOR = '.Select-value'; var FORM_VALUE_SELECTOR = '.Select > input'; var PLACEHOLDER_SELECTOR = '.Select-placeholder'; class PropsWrapper extends React.Component { constructor(props) { super(props); this.state = props || {}; } setPropsForChild(props) { this.setState(props); } getChild() { return this.refs.child; } render() { var Component = this.props.childComponent; // eslint-disable-line react/prop-types return <Component {...this.state} ref="child" />; } } describe('Select', () => { var options, onChange, onInputChange; var instance, wrapper; var searchInputNode; var getSelectControl = (instance) => { return ReactDOM.findDOMNode(instance).querySelector('.Select-control'); }; var enterSingleCharacter = () =>{ TestUtils.Simulate.keyDown(searchInputNode, { keyCode: 65, key: 'a' }); }; var pressEnterToAccept = () => { TestUtils.Simulate.keyDown(searchInputNode, { keyCode: 13, key: 'Enter' }); }; var pressTabToAccept = () => { TestUtils.Simulate.keyDown(searchInputNode, { keyCode: 9, key: 'Tab' }); }; var pressEscape = () => { TestUtils.Simulate.keyDown(searchInputNode, { keyCode: 27, key: 'Escape' }); }; var pressBackspace = () => { TestUtils.Simulate.keyDown(searchInputNode, { keyCode: 8, key: 'Backspace' }); }; var pressUp = () => { TestUtils.Simulate.keyDown(getSelectControl(instance), { keyCode: 38, key: 'ArrowUp' }); }; var pressDown = () => { TestUtils.Simulate.keyDown(getSelectControl(instance), { keyCode: 40, key: 'ArrowDown' }); }; var typeSearchText = (text) => { TestUtils.Simulate.change(searchInputNode, { target: { value: text } }); }; var clickArrowToOpen = () => { var selectArrow = ReactDOM.findDOMNode(instance).querySelector('.Select-arrow'); TestUtils.Simulate.mouseDown(selectArrow); }; var clickDocument = () => { var clickEvent = document.createEvent('MouseEvents'); clickEvent.initEvent('click', true, true); document.dispatchEvent(clickEvent); }; var findAndFocusInputControl = () => { // Focus on the input, such that mouse events are accepted var searchInstance = ReactDOM.findDOMNode(instance.refs.input); searchInputNode = null; if (searchInstance) { searchInputNode = searchInstance.querySelector('input'); if (searchInputNode) { TestUtils.Simulate.focus(searchInputNode); } } }; var createControl = (props) => { onChange = sinon.spy(); onInputChange = sinon.spy(); // Render an instance of the component instance = TestUtils.renderIntoDocument( <Select onChange={onChange} onInputChange={onInputChange} {...props} /> ); findAndFocusInputControl(); return instance; }; var createControlWithWrapper = (props) => { onChange = sinon.spy(); onInputChange = sinon.spy(); wrapper = TestUtils.renderIntoDocument( <PropsWrapper childComponent={Select} onChange={onChange} onInputChange={onInputChange} {...props} /> ); instance = wrapper.getChild(); findAndFocusInputControl(); return wrapper; }; var defaultOptions = [ { value: 'one', label: 'One' }, { value: 'two', label: '222' }, { value: 'three', label: 'Three' }, { value: 'four', label: 'AbcDef' } ]; describe('with simple options', () => { beforeEach(() => { options = [ { value: 'one', label: 'One' }, { value: 'two', label: 'Two' }, { value: 'three', label: 'Three' } ]; instance = createControl({ name: 'form-field-name', value: 'one', options: options, simpleValue: true, }); }); it('should assign the given name', () => { var selectInputElement = TestUtils.scryRenderedDOMComponentsWithTag(instance, 'input')[0]; expect(ReactDOM.findDOMNode(selectInputElement).name, 'to equal', 'form-field-name'); }); it('should show the options on mouse click', function () { TestUtils.Simulate.mouseDown(ReactDOM.findDOMNode(instance).querySelector('.Select-control')); var node = ReactDOM.findDOMNode(instance); expect(node, 'queried for', '.Select-option', 'to have length', 3); }); it('should display the labels on mouse click', () => { TestUtils.Simulate.mouseDown(ReactDOM.findDOMNode(instance).querySelector('.Select-control')); var node = ReactDOM.findDOMNode(instance); expect(node, 'queried for', '.Select-option:nth-child(1)', 'to have items satisfying', 'to have text', 'One'); expect(node, 'queried for', '.Select-option:nth-child(2)', 'to have items satisfying', 'to have text', 'Two'); expect(node, 'queried for', '.Select-option:nth-child(3)', 'to have items satisfying', 'to have text', 'Three'); }); it('should filter after entering some text', () => { typeSearchText('T'); var node = ReactDOM.findDOMNode(instance); expect(node, 'queried for', '.Select-option:nth-child(1)', 'to have items satisfying', 'to have text', 'Two'); expect(node, 'queried for', '.Select-option:nth-child(2)', 'to have items satisfying', 'to have text', 'Three'); expect(node, 'queried for', '.Select-option', 'to have length', 2); }); it('should pass input value when entering text', () => { typeSearchText('a'); enterSingleCharacter('a'); expect(onInputChange, 'was called with', 'a'); }); it('should filter case insensitively', () => { typeSearchText('t'); var node = ReactDOM.findDOMNode(instance); expect(node, 'queried for', '.Select-option:nth-child(1)', 'to have items satisfying', 'to have text', 'Two'); expect(node, 'queried for', '.Select-option:nth-child(2)', 'to have items satisfying', 'to have text', 'Three'); expect(node, 'queried for', '.Select-option', 'to have length', 2); }); it('should filter using "contains"', () => { // Search 'h', should only show 'Three' typeSearchText('h'); var node = ReactDOM.findDOMNode(instance); expect(node, 'queried for', '.Select-option:nth-child(1)', 'to have items satisfying', 'to have text', 'Three'); expect(node, 'queried for', '.Select-option', 'to have length', 1); }); it('should accept when enter is pressed', () => { // Search 'h', should only show 'Three' typeSearchText('h'); pressEnterToAccept(); expect(onChange, 'was called with', 'three'); }); it('should accept when tab is pressed', () => { // Search 'h', should only show 'Three' typeSearchText('h'); pressTabToAccept(); expect(onChange, 'was called with', 'three'); }); describe('pressing escape', () => { beforeEach(() => { typeSearchText('h'); pressTabToAccept(); expect(onChange, 'was called with', 'three'); onChange.reset(); pressEscape(); }); it('should call onChange with a empty value', () => { expect(onChange, 'was called with', null); }); it('should clear the display', () => { expect(ReactDOM.findDOMNode(instance), 'queried for', PLACEHOLDER_SELECTOR, 'to have text', 'Select...'); }); }); it('should focus the first value on mouse click', () => { TestUtils.Simulate.mouseDown(ReactDOM.findDOMNode(instance).querySelector('.Select-control')); expect(ReactDOM.findDOMNode(instance), 'queried for', '.Select-option.is-focused', 'to have items satisfying', 'to have text', 'One'); }); it('should move the focused value to the second value when down pressed', () => { var selectControl = getSelectControl(instance); TestUtils.Simulate.mouseDown(selectControl); TestUtils.Simulate.keyDown(selectControl, { keyCode: 40, key: 'ArrowDown' }); expect(ReactDOM.findDOMNode(instance), 'queried for', '.Select-option.is-focused', 'to have items satisfying', 'to have text', 'Two'); }); it('should move the focused value to the second value when down pressed', () => { var selectControl = getSelectControl(instance); TestUtils.Simulate.mouseDown(selectControl); TestUtils.Simulate.keyDown(selectControl, { keyCode: 40, key: 'ArrowDown' }); TestUtils.Simulate.keyDown(selectControl, { keyCode: 40, key: 'ArrowDown' }); expect(ReactDOM.findDOMNode(instance), 'queried for', '.Select-option.is-focused', 'to have items satisfying', 'to have text', 'Three'); }); it('should loop round to top item when down is pressed on the last item', () => { var selectControl = getSelectControl(instance); TestUtils.Simulate.mouseDown(selectControl); TestUtils.Simulate.keyDown(selectControl, { keyCode: 40, key: 'ArrowDown' }); TestUtils.Simulate.keyDown(selectControl, { keyCode: 40, key: 'ArrowDown' }); TestUtils.Simulate.keyDown(selectControl, { keyCode: 40, key: 'ArrowDown' }); expect(ReactDOM.findDOMNode(instance), 'queried for', '.Select-option.is-focused', 'to have items satisfying', 'to have text', 'One'); }); it('should loop round to bottom item when up is pressed on the first item', () => { var selectControl = getSelectControl(instance); TestUtils.Simulate.mouseDown(selectControl); TestUtils.Simulate.keyDown(selectControl, { keyCode: 38, key: 'ArrowUp' }); expect(ReactDOM.findDOMNode(instance), 'queried for', '.Select-option.is-focused', 'to have items satisfying', 'to have text', 'Three'); }); it('should move the focused value to the second item when up pressed twice', () => { var selectControl = getSelectControl(instance); TestUtils.Simulate.mouseDown(selectControl); TestUtils.Simulate.keyDown(selectControl, { keyCode: 38, key: 'ArrowUp' }); TestUtils.Simulate.keyDown(selectControl, { keyCode: 38, key: 'ArrowUp' }); expect(ReactDOM.findDOMNode(instance), 'queried for', '.Select-option.is-focused', 'to have items satisfying', 'to have text', 'Two'); }); it('should clear the selection on escape', () => { var selectControl = getSelectControl(instance); TestUtils.Simulate.mouseDown(selectControl); TestUtils.Simulate.keyDown(selectControl, { keyCode: 27, key: 'Escape' }); expect(ReactDOM.findDOMNode(instance), 'to contain no elements matching', '.Select-option'); }); it('should open the options on arrow down with the top option focused, when the options are closed', () => { var selectControl = getSelectControl(instance); var domNode = ReactDOM.findDOMNode(instance); TestUtils.Simulate.keyDown(selectControl, { keyCode: 38, key: 'ArrowDown' }); expect(domNode, 'queried for', '.Select-option.is-focused', 'to have items satisfying', 'to have text', 'One'); }); it('should open the options on arrow up with the top option focused, when the options are closed', () => { var selectControl = getSelectControl(instance); var domNode = ReactDOM.findDOMNode(instance); TestUtils.Simulate.keyDown(selectControl, { keyCode: 40, key: 'ArrowDown' }); expect(domNode, 'queried for', '.Select-option.is-focused', 'to have items satisfying', 'to have text', 'One'); }); it('should close the options one the second click on the arrow', () => { var selectArrow = ReactDOM.findDOMNode(instance).querySelector('.Select-arrow'); TestUtils.Simulate.mouseDown(selectArrow); expect(ReactDOM.findDOMNode(instance).querySelectorAll('.Select-option'), 'to have length', 3); TestUtils.Simulate.mouseDown(selectArrow); expect(ReactDOM.findDOMNode(instance), 'to contain no elements matching', '.Select-option'); }); it('should ignore a right mouse click on the arrow', () => { var selectArrow = ReactDOM.findDOMNode(instance).querySelector('.Select-arrow'); TestUtils.Simulate.mouseDown(selectArrow, { type: 'mousedown', button: 1 }); expect(ReactDOM.findDOMNode(instance), 'to contain no elements matching', '.Select-option'); }); describe('after mouseEnter and leave of an option', () => { // TODO: this behaviour has changed, and we no longer lose option focus on mouse out return; beforeEach(() => { // Show the options var selectControl = getSelectControl(instance); TestUtils.Simulate.keyDown(selectControl, { keyCode: 40, key: 'ArrowDown' }); var optionTwo = ReactDOM.findDOMNode(instance).querySelectorAll('.Select-option')[1]; TestUtils.SimulateNative.mouseOver(optionTwo); TestUtils.SimulateNative.mouseOut(optionTwo); }); it('should have no focused options', () => { var domNode = ReactDOM.findDOMNode(instance); expect(domNode, 'to contain no elements matching', '.Select-option.is-focused'); }); it('should focus top option after down arrow pressed', () => { var selectControl = getSelectControl(instance); TestUtils.Simulate.keyDown(selectControl, { keyCode: 40, key: 'ArrowDown' }); var domNode = ReactDOM.findDOMNode(instance); expect(domNode, 'queried for', '.Select-option.is-focused', 'to have items satisfying', 'to have text', 'One'); }); it('should focus last option after up arrow pressed', () => { var selectControl = getSelectControl(instance); TestUtils.Simulate.keyDown(selectControl, { keyCode: 38, key: 'ArrowUp' }); var domNode = ReactDOM.findDOMNode(instance); expect(domNode, 'queried for', '.Select-option.is-focused', 'to have items satisfying', 'to have text', 'Three'); }); }); }); describe('with values as numbers', () => { beforeEach(() => { options = [ { value: 0, label: 'Zero' }, { value: 1, label: 'One' }, { value: 2, label: 'Two' }, { value: 3, label: 'Three' } ]; wrapper = createControlWithWrapper({ value: 2, name: 'field', options: options, simpleValue: true, }); }); it('selects the initial value', () => { expect(ReactDOM.findDOMNode(instance), 'queried for first', DISPLAYED_SELECTION_SELECTOR, 'to have text', 'Two'); }); it('set the initial value of the hidden input control', () => { return; // TODO; broken test? expect(ReactDOM.findDOMNode(wrapper).querySelector(FORM_VALUE_SELECTOR).value, 'to equal', '2' ); }); it('updates the value when the value prop is set', () => { wrapper.setPropsForChild({ value: 3 }); expect(ReactDOM.findDOMNode(instance), 'queried for first', DISPLAYED_SELECTION_SELECTOR, 'to have text', 'Three'); }); it('updates the value of the hidden input control after new value prop', () => { return; // TODO; broken test? wrapper.setPropsForChild({ value: 3 }); expect(ReactDOM.findDOMNode(wrapper).querySelector(FORM_VALUE_SELECTOR).value, 'to equal', '3' ); }); it('calls onChange with the new value as a number', () => { clickArrowToOpen(); pressDown(); pressEnterToAccept(); expect(onChange, 'was called with', 3); }); it('supports setting the value to 0 via prop', () => { wrapper.setPropsForChild({ value: 0 }); expect(ReactDOM.findDOMNode(instance), 'queried for first', DISPLAYED_SELECTION_SELECTOR, 'to have text', 'Zero'); }); it('supports selecting the zero value', () => { clickArrowToOpen(); pressUp(); pressUp(); pressEnterToAccept(); expect(onChange, 'was called with', 0); }); describe('with multi=true', () => { beforeEach(() => { options = [ { value: 0, label: 'Zero' }, { value: 1, label: 'One' }, { value: 2, label: 'Two' }, { value: 3, label: 'Three' }, { value: 4, label: 'Four' } ]; wrapper = createControlWithWrapper({ value: '2,1', options: options, multi: true, searchable: true }); }); it('selects the initial value', () => { expect(ReactDOM.findDOMNode(instance), 'queried for', '.Select-value .Select-value-label', 'to satisfy', [ expect.it('to have text', 'Two'), expect.it('to have text', 'One') ]); }); it('calls onChange with the correct value when 1 option is selected', () => { var removeIcons = ReactDOM.findDOMNode(instance).querySelectorAll('.Select-value .Select-value-icon'); TestUtils.Simulate.click(removeIcons[0]); // For multi-select, the "value" (first arg) to onChange is always a string expect(onChange, 'was called with', '1', [{ value: 1, label: 'One' }]); }); it('supports updating the values via props', () => { wrapper.setPropsForChild({ value: '3,4' }); expect(ReactDOM.findDOMNode(instance), 'queried for', '.Select-value .Select-value-label', 'to satisfy', [ expect.it('to have text', 'Three'), expect.it('to have text', 'Four') ]); }); it('supports updating the value to 0', () => { // This test is specifically in case there's a "if (value) {... " somewhere wrapper.setPropsForChild({ value: 0 }); expect(ReactDOM.findDOMNode(instance), 'queried for', '.Select-value .Select-value-label', 'to satisfy', [ expect.it('to have text', 'Zero') ]); }); it('calls onChange with the correct values when multiple options are selected', () => { typeSearchText('fo'); pressEnterToAccept(); // Select 'Four' expect(onChange, 'was called with', '2,1,4', [ { value: 2, label: 'Two' }, { value: 1, label: 'One' }, { value: 4, label: 'Four' } ]); }); }); describe('searching', () => { let searchOptions = [ { value: 1, label: 'One' }, { value: 2, label: 'Two' }, { value: 10, label: 'Ten' }, { value: 20, label: 'Twenty' }, { value: 21, label: 'Twenty-one' }, { value: 34, label: 'Thirty-four' }, { value: 54, label: 'Fifty-four' } ]; describe('with matchPos=any and matchProp=any', () => { beforeEach(() => { instance = createControl({ matchPos: 'any', matchProp: 'any', options: searchOptions }); }); it('finds text anywhere in value', () => { typeSearchText('1'); expect(ReactDOM.findDOMNode(instance), 'queried for', '.Select-option', 'to satisfy', [ expect.it('to have text', 'One'), expect.it('to have text', 'Ten'), expect.it('to have text', 'Twenty-one') ]); }); it('finds text at end', () => { typeSearchText('4'); expect(ReactDOM.findDOMNode(instance), 'queried for', '.Select-option', 'to satisfy', [ expect.it('to have text', 'Thirty-four'), expect.it('to have text', 'Fifty-four') ]); }); }); describe('with matchPos=start and matchProp=any', () => { beforeEach(() => { instance = createControl({ matchPos: 'start', matchProp: 'any', options: searchOptions }); }); it('finds text at the start of the value', () => { typeSearchText('1'); expect(ReactDOM.findDOMNode(instance), 'queried for', '.Select-option', 'to satisfy', [ expect.it('to have text', 'One'), expect.it('to have text', 'Ten') ]); }); it('does not match text at end', () => { typeSearchText('4'); expect(ReactDOM.findDOMNode(instance), 'to contain elements matching', '.Select-noresults'); expect(ReactDOM.findDOMNode(instance), 'to contain no elements matching', '.Select-option'); }); }); describe('with matchPos=any and matchProp=value', () => { beforeEach(() => { instance = createControl({ matchPos: 'any', matchProp: 'value', options: searchOptions }); }); it('finds text anywhere in value', () => { typeSearchText('1'); expect(ReactDOM.findDOMNode(instance), 'queried for', '.Select-option', 'to satisfy', [ expect.it('to have text', 'One'), expect.it('to have text', 'Ten'), expect.it('to have text', 'Twenty-one') ]); }); it('finds text at end', () => { typeSearchText('4'); expect(ReactDOM.findDOMNode(instance), 'queried for', '.Select-option', 'to satisfy', [ expect.it('to have text', 'Thirty-four'), expect.it('to have text', 'Fifty-four') ]); }); }); describe('with matchPos=start and matchProp=value', () => { beforeEach(() => { instance = createControl({ matchPos: 'start', matchProp: 'value', options: searchOptions }); }); it('finds text at the start of the value', () => { typeSearchText('1'); expect(ReactDOM.findDOMNode(instance), 'queried for', '.Select-option', 'to satisfy', [ expect.it('to have text', 'One'), expect.it('to have text', 'Ten') ]); }); it('does not match text at end', () => { typeSearchText('4'); expect(ReactDOM.findDOMNode(instance), 'to contain elements matching', '.Select-noresults'); expect(ReactDOM.findDOMNode(instance), 'to contain no elements matching', '.Select-option'); }); }); }); }); describe('with options and value', () => { beforeEach(() => { options = [ { value: 'one', label: 'One' }, { value: 'two', label: 'Two' }, { value: 'three', label: 'Three' } ]; // Render an instance of the component wrapper = createControlWithWrapper({ value: 'one', options: options, searchable: true }); }); it('starts with the given value', () => { var node = ReactDOM.findDOMNode(instance); expect(node, 'queried for', DISPLAYED_SELECTION_SELECTOR, 'to have items satisfying', 'to have text', 'One'); }); it('supports setting the value via prop', () => { wrapper.setPropsForChild({ value: 'three' }); expect(ReactDOM.findDOMNode(instance), 'queried for', DISPLAYED_SELECTION_SELECTOR, 'to have items satisfying', 'to have text', 'Three'); }); it('sets the value of the hidden form node', () => { wrapper.setPropsForChild({ value: 'three' }); expect(ReactDOM.findDOMNode(wrapper).querySelector(FORM_VALUE_SELECTOR).value, 'to equal', 'three' ); }); it('display the raw value if the option is not available', () => { wrapper.setPropsForChild({ value: 'something new' }); expect(ReactDOM.findDOMNode(instance), 'queried for', DISPLAYED_SELECTION_SELECTOR, 'to have items satisfying', 'to have text', 'something new'); }); it('updates the display text if the option appears later', () => { wrapper.setPropsForChild({ value: 'new' }); wrapper.setPropsForChild({ options: [ { value: 'one', label: 'One' }, { value: 'two', labal: 'Two' }, { value: 'new', label: 'New item in the options' }, { value: 'three', label: 'Three' } ] }); expect(ReactDOM.findDOMNode(instance), 'queried for', DISPLAYED_SELECTION_SELECTOR, 'to have items satisfying', 'to have text', 'New item in the options'); }); }); describe('with a disabled option', () => { beforeEach(() => { options = [ { value: 'one', label: 'One' }, { value: 'two', label: 'Two', disabled: true }, { value: 'three', label: 'Three' } ]; wrapper = createControlWithWrapper({ options: options, searchable: true }); }); it('adds the is-disabled class to the disabled option', () => { clickArrowToOpen(); expect(ReactDOM.findDOMNode(instance).querySelectorAll('.Select-option')[1], 'to have attributes', { class: 'is-disabled' }); }); it('is not selectable by clicking', () => { clickArrowToOpen(); TestUtils.Simulate.mouseDown(ReactDOM.findDOMNode(instance).querySelectorAll('.Select-option')[1]); expect(onChange, 'was not called'); expect(ReactDOM.findDOMNode(instance), 'queried for first', DISPLAYED_SELECTION_SELECTOR, 'to have text', 'Select...'); }); it('is not selectable by keyboard', () => { clickArrowToOpen(); // Press down to get to the second option TestUtils.Simulate.keyDown(getSelectControl(instance), { keyCode: 40, key: 'ArrowDown' }); // Check the disable option is not focused expect(ReactDOM.findDOMNode(instance), 'to contain no elements matching', '.Select-option.is-disabled.is-focused'); }); it('jumps over the disabled option', () => { clickArrowToOpen(); // Press down to get to the second option TestUtils.Simulate.keyDown(getSelectControl(instance), { keyCode: 40, key: 'ArrowDown' }); // Check the focused option is the one after the disabled option expect(ReactDOM.findDOMNode(instance), 'queried for first', '.Select-option.is-focused', 'to have text', 'Three'); }); it('jumps back to beginning when disabled option is last option', () => { wrapper = createControlWithWrapper({ options: [ { value: 'one', label: 'One' }, { value: 'two', label: 'Two' }, { value: 'three', label: 'Three', disabled: true } ] }); clickArrowToOpen(); // Down twice TestUtils.Simulate.keyDown(getSelectControl(instance), { keyCode: 40, key: 'ArrowDown' }); TestUtils.Simulate.keyDown(getSelectControl(instance), { keyCode: 40, key: 'ArrowDown' }); // Selected option should be back to 'One' expect(ReactDOM.findDOMNode(instance), 'queried for first', '.Select-option.is-focused', 'to have text', 'One'); }); it('skips over last option when looping round when last option is disabled', () => { wrapper = createControlWithWrapper({ options: [ { value: 'one', label: 'One' }, { value: 'two', label: 'Two' }, { value: 'three', label: 'Three', disabled: true } ] }); clickArrowToOpen(); // Press up, should skip the bottom entry 'Three'... TestUtils.Simulate.keyDown(getSelectControl(instance), { keyCode: 38, key: 'ArrowUp' }); // ... and land on 'Two' expect(ReactDOM.findDOMNode(instance), 'queried for first', '.Select-option.is-focused', 'to have text', 'Two'); }); it('focuses initially on the second option when the first is disabled', () => { wrapper = createControlWithWrapper({ options: [ { value: 'one', label: 'One', disabled: true }, { value: 'two', label: 'Two' }, { value: 'three', label: 'Three' } ] }); clickArrowToOpen(); expect(ReactDOM.findDOMNode(instance), 'queried for first', '.Select-option.is-focused', 'to have text', 'Two'); }); it('doesn\'t focus anything when all options are disabled', () => { wrapper = createControlWithWrapper({ options: [ { value: 'one', label: 'One', disabled: true }, { value: 'two', label: 'Two', disabled: true }, { value: 'three', label: 'Three', disabled: true } ] }); clickArrowToOpen(); TestUtils.Simulate.keyDown(getSelectControl(instance), { keyCode: 40, key: 'ArrowDown' }); expect(ReactDOM.findDOMNode(instance), 'to contain no elements matching', '.Select-option.is-focused'); }); it('doesn\'t select anything when all options are disabled and enter is pressed', () => { wrapper = createControlWithWrapper({ options: [ { value: 'one', label: 'One', disabled: true }, { value: 'two', label: 'Two', disabled: true }, { value: 'three', label: 'Three', disabled: true } ] }); clickArrowToOpen(); TestUtils.Simulate.keyDown(getSelectControl(instance), { keyCode: 13, key: 'Enter' }); expect(onChange, 'was not called'); expect(ReactDOM.findDOMNode(instance), 'queried for first', DISPLAYED_SELECTION_SELECTOR, 'to have text', 'Select...'); }); it("doesn't select anything when a disabled option is the only item in the list after a search", () => { typeSearchText('tw'); // Only 'two' in the list pressEnterToAccept(); expect(onChange, 'was not called'); // And the menu is still open expect(ReactDOM.findDOMNode(instance), 'to contain no elements matching', DISPLAYED_SELECTION_SELECTOR); expect(ReactDOM.findDOMNode(instance), 'queried for' , '.Select-option', 'to satisfy', [ expect.it('to have text', 'Two') ]); }); it("doesn't select anything when a disabled option value matches the entered text", () => { typeSearchText('two'); // Matches value pressEnterToAccept(); expect(onChange, 'was not called'); // And the menu is still open expect(ReactDOM.findDOMNode(instance), 'to contain no elements matching', DISPLAYED_SELECTION_SELECTOR); expect(ReactDOM.findDOMNode(instance), 'queried for' , '.Select-option', 'to satisfy', [ expect.it('to have text', 'Two') ]); }); it("doesn't select anything when a disabled option label matches the entered text", () => { typeSearchText('Two'); // Matches label pressEnterToAccept(); expect(onChange, 'was not called'); // And the menu is still open expect(ReactDOM.findDOMNode(instance), 'to contain no elements matching', DISPLAYED_SELECTION_SELECTOR); expect(ReactDOM.findDOMNode(instance), 'queried for' , '.Select-option', 'to satisfy', [ expect.it('to have text', 'Two') ]); }); it('shows disabled results in a search', () => { typeSearchText('t'); var options = ReactDOM.findDOMNode(instance).querySelectorAll('.Select-option'); expect(options[0], 'to have text', 'Two'); expect(options[0], 'to have attributes', { class: 'is-disabled' }); expect(options[1], 'to have text', 'Three'); }); it('is does not close menu when disabled option is clicked', () => { clickArrowToOpen(); TestUtils.Simulate.mouseDown(ReactDOM.findDOMNode(instance).querySelectorAll('.Select-option')[1]); var options = ReactDOM.findDOMNode(instance).querySelectorAll('.Select-option'); expect(options.length, 'to equal', 3); }); }); describe('with styled options', () => { beforeEach(() => { options = [ { value: 'one', label: 'One', className: 'extra-one', title: 'Eins' }, { value: 'two', label: 'Two', className: 'extra-two', title: 'Zwei' }, { value: 'three', label: 'Three', style: { fontSize: 25 } } ]; wrapper = createControlWithWrapper({ options: options }); }); it('uses the given className for an option', () => { clickArrowToOpen(); expect(ReactDOM.findDOMNode(instance).querySelectorAll('.Select-option')[0], 'to have attributes', { class: 'extra-one' }); }); it('uses the given style for an option', () => { clickArrowToOpen(); expect(ReactDOM.findDOMNode(instance).querySelectorAll('.Select-option')[2], 'to have attributes', { style: { 'font-size': '25px' } }); }); it('uses the given title for an option', () => { clickArrowToOpen(); expect(ReactDOM.findDOMNode(instance).querySelectorAll('.Select-option')[1], 'to have attributes', { title: 'Zwei' }); }); it('uses the given className for a single selection', () => { typeSearchText('tw'); pressEnterToAccept(); expect(ReactDOM.findDOMNode(instance), 'queried for first', DISPLAYED_SELECTION_SELECTOR, 'to have attributes', { class: 'extra-two' }); }); it('uses the given style for a single selection', () => { typeSearchText('th'); pressEnterToAccept(); expect(ReactDOM.findDOMNode(instance), 'queried for first', DISPLAYED_SELECTION_SELECTOR, 'to have attributes', { style: { 'font-size': '25px' } }); }); it('uses the given title for a single selection', () => { typeSearchText('tw'); pressEnterToAccept(); expect(ReactDOM.findDOMNode(instance), 'queried for first', DISPLAYED_SELECTION_SELECTOR, 'to have attributes', { title: 'Zwei' }); }); describe('with multi', () => { beforeEach(() => { wrapper.setPropsForChild({ multi: true }); }); it('uses the given className for a selected value', () => { typeSearchText('tw'); pressEnterToAccept(); expect(ReactDOM.findDOMNode(instance), 'queried for first', '.Select-value', 'to have attributes', { class: 'extra-two' }); }); it('uses the given style for a selected value', () => { typeSearchText('th'); pressEnterToAccept(); expect(ReactDOM.findDOMNode(instance), 'queried for first', '.Select-value', 'to have attributes', { style: { 'font-size': '25px' } }); }); it('uses the given title for a selected value', () => { typeSearchText('tw'); pressEnterToAccept(); expect(ReactDOM.findDOMNode(instance), 'queried for first', '.Select-value', 'to have attributes', { title: 'Zwei' }); }); }); }); describe('with allowCreate=true', () => { // TODO: allowCreate hasn't been implemented yet in 1.x return; beforeEach(() => { options = [ { value: 'one', label: 'One' }, { value: 'two', label: 'Two' }, { value: 'got spaces', label: 'Label for spaces' }, { value: 'gotnospaces', label: 'Label for gotnospaces' }, { value: 'abc 123', label: 'Label for abc 123' }, { value: 'three', label: 'Three' }, { value: 'zzzzz', label: 'test value' } ]; // Render an instance of the component wrapper = createControlWithWrapper({ value: 'one', options: options, allowCreate: true, searchable: true, addLabelText: 'Add {label} to values?' }); }); it('has an "Add xyz" option when entering xyz', () => { typeSearchText('xyz'); expect(ReactDOM.findDOMNode(instance), 'queried for', '.Select-menu .Select-option', 'to have items satisfying', 'to have text', 'Add xyz to values?'); }); it('fires an onChange with the new value when selecting the Add option', () => { typeSearchText('xyz'); TestUtils.Simulate.click(ReactDOM.findDOMNode(instance).querySelector('.Select-menu .Select-option')); expect(onChange, 'was called with', 'xyz'); }); it('allows updating the options with a new label, following the onChange', () => { typeSearchText('xyz'); TestUtils.Simulate.click(ReactDOM.findDOMNode(instance).querySelector('.Select-menu .Select-option')); expect(onChange, 'was called with', 'xyz'); // Now the client adds the option, with a new label wrapper.setPropsForChild({ options: [ { value: 'one', label: 'One' }, { value: 'xyz', label: 'XYZ Label' } ], value: 'xyz' }); expect(ReactDOM.findDOMNode(instance).querySelector(DISPLAYED_SELECTION_SELECTOR), 'to have text', 'XYZ Label'); }); it('displays an add option when a value with spaces is entered', () => { typeSearchText('got'); expect(ReactDOM.findDOMNode(instance).querySelectorAll('.Select-menu .Select-option')[0], 'to have text', 'Add got to values?'); }); it('displays an add option when a value with spaces is entered', () => { typeSearchText('got'); expect(ReactDOM.findDOMNode(instance).querySelectorAll('.Select-menu .Select-option')[0], 'to have text', 'Add got to values?'); }); it('displays an add option when a label with spaces is entered', () => { typeSearchText('test'); expect(ReactDOM.findDOMNode(instance).querySelectorAll('.Select-menu .Select-option')[0], 'to have text', 'Add test to values?'); }); it('does not display the option label when an existing value is entered', () => { typeSearchText('zzzzz'); expect(ReactDOM.findDOMNode(instance).querySelectorAll('.Select-menu .Select-option'), 'to have length', 1); expect(ReactDOM.findDOMNode(instance), 'queried for first', '.Select-menu .Select-option', 'to have text', 'Add zzzzz to values?'); }); it('renders the existing option and an add option when an existing display label is entered', () => { typeSearchText('test value'); // First item should be the add option (as the "value" is not in the collection) expect(ReactDOM.findDOMNode(instance).querySelectorAll('.Select-menu .Select-option')[0], 'to have text', 'Add test value to values?'); // Second item should be the existing option with the matching label expect(ReactDOM.findDOMNode(instance).querySelectorAll('.Select-menu .Select-option')[1], 'to have text', 'test value'); expect(ReactDOM.findDOMNode(instance).querySelectorAll('.Select-menu .Select-option'), 'to have length', 2); }); }); describe('with async options', () => { // TODO: Need to use the new Select.Async control for this return; var asyncOptions; beforeEach(() => { asyncOptions = sinon.stub(); asyncOptions.withArgs('te').callsArgWith(1, null, { options: [ { value: 'test', label: 'TEST one' }, { value: 'test2', label: 'TEST two' }, { value: 'tell', label: 'TELL three' } ] }); asyncOptions.withArgs('tes').callsArgWith(1, null, { options: [ { value: 'test', label: 'TEST one' }, { value: 'test2', label: 'TEST two' } ] }); }); describe('with autoload=true', () => { beforeEach(() => { // Render an instance of the component wrapper = createControlWithWrapper({ value: '', asyncOptions: asyncOptions, autoload: true }); }); it('calls the asyncOptions initially with autoload=true', () => { expect(asyncOptions, 'was called with', ''); }); it('calls the asyncOptions again when the input changes', () => { typeSearchText('ab'); expect(asyncOptions, 'was called twice'); expect(asyncOptions, 'was called with', 'ab'); }); it('shows the returned options after asyncOptions calls back', () => { typeSearchText('te'); var optionList = ReactDOM.findDOMNode(instance).querySelectorAll('.Select-menu .Select-option'); expect(optionList, 'to have length', 3); expect(optionList[0], 'to have text', 'TEST one'); expect(optionList[1], 'to have text', 'TEST two'); expect(optionList[2], 'to have text', 'TELL three'); }); it('uses the options cache when the same text is entered again', () => { typeSearchText('te'); typeSearchText('tes'); expect(asyncOptions, 'was called times', 3); typeSearchText('te'); expect(asyncOptions, 'was called times', 3); }); it('displays the correct options from the cache after the input is changed back to a previous value', () => { typeSearchText('te'); typeSearchText('tes'); typeSearchText('te'); // Double check the options list is still correct var optionList = ReactDOM.findDOMNode(instance).querySelectorAll('.Select-menu .Select-option'); expect(optionList, 'to have length', 3); expect(optionList[0], 'to have text', 'TEST one'); expect(optionList[1], 'to have text', 'TEST two'); expect(optionList[2], 'to have text', 'TELL three'); }); it('re-filters an existing options list if complete:true is provided', () => { asyncOptions.withArgs('te').callsArgWith(1, null, { options: [ { value: 'test', label: 'TEST one' }, { value: 'test2', label: 'TEST two' }, { value: 'tell', label: 'TELL three' } ], complete: true }); typeSearchText('te'); expect(asyncOptions, 'was called times', 2); typeSearchText('tel'); expect(asyncOptions, 'was called times', 2); var optionList = ReactDOM.findDOMNode(instance).querySelectorAll('.Select-menu .Select-option'); expect(optionList, 'to have length', 1); expect(optionList[0], 'to have text', 'TELL three'); }); it('rethrows the error if err is set in the callback', () => { asyncOptions.withArgs('tes').callsArgWith(1, new Error('Something\'s wrong jim'), { options: [ { value: 'test', label: 'TEST one' }, { value: 'test2', label: 'TEST two' } ] }); expect(() => { typeSearchText('tes'); }, 'to throw exception', new Error('Something\'s wrong jim')); }); it('calls the asyncOptions function when the value prop changes', () => { expect(asyncOptions, 'was called once'); wrapper.setPropsForChild({ value: 'test2' }); expect(asyncOptions, 'was called twice'); }); }); describe('with autoload=false', () => { beforeEach(() => { // Render an instance of the component instance = createControl({ value: '', asyncOptions: asyncOptions, autoload: false }); }); it('does not initially call asyncOptions', () => { expect(asyncOptions, 'was not called'); }); it('calls the asyncOptions on first key entry', () => { typeSearchText('a'); expect(asyncOptions, 'was called with', 'a'); }); }); describe('with cacheAsyncResults=false', () => { beforeEach(() => { // Render an instance of the component wrapper = createControlWithWrapper({ value: '', asyncOptions: asyncOptions, cacheAsyncResults: false }); // Focus on the input, such that mouse events are accepted searchInputNode = ReactDOM.findDOMNode(instance.getInputNode()).querySelector('input'); TestUtils.Simulate.focus(searchInputNode); }); it('does not use cache when the same text is entered again', () => { typeSearchText('te'); typeSearchText('tes'); expect(asyncOptions, 'was called times', 3); typeSearchText('te'); expect(asyncOptions, 'was called times', 4); }); it('updates the displayed value after changing value and refreshing from asyncOptions', () => { asyncOptions.reset(); asyncOptions.callsArgWith(1, null, { options: [ { value: 'newValue', label: 'New Value from Server' }, { value: 'test', label: 'TEST one' } ] }); wrapper.setPropsForChild({ value: 'newValue' }); expect(ReactDOM.findDOMNode(instance), 'queried for first', DISPLAYED_SELECTION_SELECTOR, 'to have text', 'New Value from Server'); }); }); }); describe('with async options (using promises)', () => { var asyncOptions, callCount, callInput; beforeEach(() => { asyncOptions = sinon.spy((input) => { const options = [ { value: 'test', label: 'TEST one' }, { value: 'test2', label: 'TEST two' }, { value: 'tell', label: 'TELL three' } ].filter((elm) => { return (elm.value.indexOf(input) !== -1 || elm.label.indexOf(input) !== -1); }); return new Promise((resolve, reject) => { input === '_FAIL'? reject('nope') : resolve({options: options}); }) }); }); describe('[mocked promise]', () => { beforeEach(() => { // Render an instance of the component wrapper = createControlWithWrapper({ value: '', asyncOptions: asyncOptions, autoload: true }); }); it('should fulfill asyncOptions promise', () => { return expect(instance.props.asyncOptions(''), 'to be fulfilled'); }); it('should fulfill with 3 options when asyncOptions promise with input = "te"', () => { return expect(instance.props.asyncOptions('te'), 'to be fulfilled with', { options: [ { value: 'test', label: 'TEST one' }, { value: 'test2', label: 'TEST two' }, { value: 'tell', label: 'TELL three' } ] }); }); it('should fulfill with 2 options when asyncOptions promise with input = "tes"', () => { return expect(instance.props.asyncOptions('tes'), 'to be fulfilled with', { options: [ { value: 'test', label: 'TEST one' }, { value: 'test2', label: 'TEST two' } ] }); }); it('should reject when asyncOptions promise with input = "_FAIL"', () => { return expect(instance.props.asyncOptions('_FAIL'), 'to be rejected'); }); }); describe('with autoload=true', () => { beforeEach(() => { // Render an instance of the component wrapper = createControlWithWrapper({ value: '', asyncOptions: asyncOptions, autoload: true }); }); it('should be called once at the beginning', () => { expect(asyncOptions, 'was called'); }); it('calls the asyncOptions again when the input changes', () => { typeSearchText('ab'); expect(asyncOptions, 'was called twice'); expect(asyncOptions, 'was called with', 'ab'); }); it('shows the returned options after asyncOptions promise is resolved', (done) => { typeSearchText('te'); return asyncOptions.secondCall.returnValue.then(() => { setTimeout(() => { expect(ReactDOM.findDOMNode(instance), 'queried for', '.Select-option', 'to satisfy', [ expect.it('to have text', 'TEST one'), expect.it('to have text', 'TEST two'), expect.it('to have text', 'TELL three') ]); done(); }); }); }); it('doesn\'t update the returned options when asyncOptions is rejected', (done) => { typeSearchText('te'); expect(asyncOptions, 'was called with', 'te'); asyncOptions.secondCall.returnValue.then(() => { setTimeout(() => { expect(ReactDOM.findDOMNode(instance), 'queried for', '.Select-option', 'to satisfy', [ expect.it('to have text', 'TEST one'), expect.it('to have text', 'TEST two'), expect.it('to have text', 'TELL three') ]); // asyncOptions mock is set to reject the promise when invoked with '_FAIL' typeSearchText('_FAIL'); expect(asyncOptions, 'was called with', '_FAIL'); asyncOptions.thirdCall.returnValue.then(null, () => { setTimeout(() => { expect(ReactDOM.findDOMNode(instance), 'queried for', '.Select-option', 'to satisfy', [ expect.it('to have text', 'TEST one'), expect.it('to have text', 'TEST two'), expect.it('to have text', 'TELL three') ]); done(); }); }); }); }); }); }); describe('with autoload=false', () => { beforeEach(() => { // Render an instance of the component instance = createControl({ value: '', asyncOptions: asyncOptions, autoload: false }); }); it('does not initially call asyncOptions', () => { expect(asyncOptions, 'was not called'); }); it('calls the asyncOptions on first key entry', () => { typeSearchText('a'); expect(asyncOptions, 'was called once'); expect(asyncOptions, 'was called with', 'a'); }); }); }); describe('with multi-select', () => { beforeEach(() => { options = [ { value: 'one', label: 'One' }, { value: 'two', label: 'Two' }, { value: 'three', label: 'Three' }, { value: 'four', label: 'Four' } ]; // Render an instance of the component wrapper = createControlWithWrapper({ value: '', options: options, searchable: true, allowCreate: true, multi: true }); }); it('selects a single option on enter', () => { typeSearchText('fo'); pressEnterToAccept(); expect(onChange, 'was called with', 'four', [{ label: 'Four', value: 'four' }]); }); it('selects a second option', () => { typeSearchText('fo'); pressEnterToAccept(); typeSearchText('th'); onChange.reset(); // Ignore previous onChange calls pressEnterToAccept(); expect(onChange, 'was called with', 'four,three', [{ label: 'Four', value: 'four' }, { label: 'Three', value: 'three' }]); }); it('displays both selected options', () => { typeSearchText('fo'); pressEnterToAccept(); typeSearchText('th'); pressEnterToAccept(); expect(ReactDOM.findDOMNode(instance).querySelectorAll('.Select-value-label')[0], 'to have text', 'Four'); expect(ReactDOM.findDOMNode(instance).querySelectorAll('.Select-value-label')[1], 'to have text', 'Three'); }); it('filters the existing selections from the options', () => { wrapper.setPropsForChild({ value: 'four,three' }); typeSearchText('o'); var options = ReactDOM.findDOMNode(instance).querySelectorAll('.Select-option'); expect(options[0], 'to have text', 'Add "o"?'); expect(options[1], 'to have text', 'One'); expect(options[2], 'to have text', 'Two'); expect(options, 'to have length', 3); // No "Four", as already selected }); it('removes the last selected option with backspace', () => { typeSearchText('fo'); pressEnterToAccept(); typeSearchText('th'); pressEnterToAccept(); onChange.reset(); // Ignore previous onChange calls pressBackspace(); expect(onChange, 'was called with', 'four', [{ label: 'Four', value: 'four' }]); }); it('does not remove the last selected option with backspace when backspaceRemoves=false', () => { // Disable backspace wrapper.setPropsForChild({ backspaceRemoves: false }); typeSearchText('fo'); pressEnterToAccept(); typeSearchText('th'); pressEnterToAccept(); onChange.reset(); // Ignore previous onChange calls pressBackspace(); expect(onChange, 'was not called'); var items = ReactDOM.findDOMNode(instance).querySelectorAll('.Select-value-label'); expect(items[0], 'to have text', 'Four'); expect(items[1], 'to have text', 'Three'); }); it('removes an item when clicking on the X', () => { typeSearchText('fo'); pressEnterToAccept(); typeSearchText('th'); pressEnterToAccept(); typeSearchText('tw'); pressEnterToAccept(); onChange.reset(); // Ignore previous onChange calls var threeDeleteButton = ReactDOM.findDOMNode(instance).querySelectorAll('.Select-value-icon')[1]; TestUtils.Simulate.click(threeDeleteButton); expect(onChange, 'was called with', 'four,two', [ { label: 'Four', value: 'four' }, { label: 'Two', value: 'two' } ]); }); it('uses the selected text as an item when comma is pressed', () => { typeSearchText('fo'); pressEnterToAccept(); typeSearchText('new item'); onChange.reset(); TestUtils.Simulate.keyDown(searchInputNode, { keyCode: 188, key: ',' }); expect(onChange, 'was called with', 'four,new item', [ { value: 'four', label: 'Four' }, { value: 'new item', label: 'new item' } ]); }); describe('with late options', () => { beforeEach(() => { wrapper = createControlWithWrapper({ multi: true, options: options, value: 'one,two' }); }); it('updates the label when the options are updated', () => { wrapper.setPropsForChild({ options: [ { value: 'one', label: 'new label for One' }, { value: 'two', label: 'new label for Two' }, { value: 'three', label: 'new label for Three' } ] }); var items = ReactDOM.findDOMNode(instance).querySelectorAll('.Select-value'); expect(items[0], 'queried for', '.Select-value-label', 'to have items satisfying', 'to have text', 'new label for One'); expect(items[1], 'queried for', '.Select-value-label', 'to have items satisfying', 'to have text', 'new label for Two'); }); }); }); describe('with multi=true and searchable=false', () => { beforeEach(() => { options = [ { value: 'one', label: 'One' }, { value: 'two', label: 'Two' }, { value: 'three', label: 'Three' }, { value: 'four', label: 'Four' } ]; // Render an instance of the component wrapper = createControlWithWrapper({ value: '', options: options, searchable: false, multi: true }); // We need a hack here. // JSDOM (at least v3.x) doesn't appear to support div's with tabindex // This just hacks that we are focused // This is (obviously) implementation dependent, and may need to change instance.setState({ isFocused: true }); }); it('selects multiple options', () => { clickArrowToOpen(); var items = ReactDOM.findDOMNode(instance).querySelectorAll('.Select-option'); TestUtils.Simulate.mouseDown(items[1]); // The menu is now closed, click the arrow to open it again clickArrowToOpen(); items = ReactDOM.findDOMNode(instance).querySelectorAll('.Select-option'); TestUtils.Simulate.mouseDown(items[0]); var selectedItems = ReactDOM.findDOMNode(instance).querySelectorAll('.Select-value-label'); expect(selectedItems[0], 'to have text', 'Two'); expect(selectedItems[1], 'to have text', 'One'); expect(selectedItems, 'to have length', 2); }); it('calls onChange when each option is selected', () => { clickArrowToOpen(); // First item var items = ReactDOM.findDOMNode(instance).querySelectorAll('.Select-option'); TestUtils.Simulate.mouseDown(items[1]); expect(onChange, 'was called once'); expect(onChange, 'was called with', 'two', [{ value: 'two', label: 'Two' }]); // Second item // The menu is now closed, click the arrow to open it again clickArrowToOpen(); items = ReactDOM.findDOMNode(instance).querySelectorAll('.Select-option'); TestUtils.Simulate.mouseDown(items[0]); expect(onChange, 'was called twice'); }); it('removes the selected options from the menu', () => { clickArrowToOpen(); var items = ReactDOM.findDOMNode(instance).querySelectorAll('.Select-option'); // Click the option "Two" to select it expect(items[1], 'to have text', 'Two'); TestUtils.Simulate.mouseDown(items[1]); expect(onChange, 'was called times', 1); // Now get the list again, // The menu is now closed, click the arrow to open it again clickArrowToOpen(); items = ReactDOM.findDOMNode(instance).querySelectorAll('.Select-option'); expect(items[0], 'to have text', 'One'); expect(items[1], 'to have text', 'Three'); expect(items[2], 'to have text', 'Four'); expect(items, 'to have length', 3); // Click first item, 'One' TestUtils.Simulate.mouseDown(items[0]); expect(onChange, 'was called times', 2); // The menu is now closed, click the arrow to open it again clickArrowToOpen(); items = ReactDOM.findDOMNode(instance).querySelectorAll('.Select-option'); expect(items[0], 'to have text', 'Three'); expect(items[1], 'to have text', 'Four'); expect(items, 'to have length', 2); // Click second item, 'Four' TestUtils.Simulate.mouseDown(items[1]); expect(onChange, 'was called times', 3); // The menu is now closed, click the arrow to open it again clickArrowToOpen(); items = ReactDOM.findDOMNode(instance).querySelectorAll('.Select-option'); expect(items[0], 'to have text', 'Three'); expect(items, 'to have length', 1); }); }); describe('with props', () => { describe('className', () => { it('assigns the className to the outer-most element', () => { var instance = createControl({ className: 'test-class' }); expect(ReactDOM.findDOMNode(instance), 'to have attributes', { class: 'test-class' }); }); }); describe('clearable=true', () => { beforeEach(() => { var instance = createControl({ clearable: true, options: defaultOptions, value: 'three' }); expect(ReactDOM.findDOMNode(instance), 'queried for', DISPLAYED_SELECTION_SELECTOR, 'to have items satisfying', 'to have text', 'Three'); }); describe('on pressing escape', () => { beforeEach(() => { pressEscape(); }); it('calls onChange with empty', () => { expect(onChange, 'was called with', ''); }); it('resets the display value', () => { expect(ReactDOM.findDOMNode(instance), 'queried for', DISPLAYED_SELECTION_SELECTOR, 'to have items satisfying', 'to have text', 'Select...'); }); it('resets the control value', () => { expect(ReactDOM.findDOMNode(instance).querySelector('input').value, 'to equal', ''); }); }); describe('on clicking `clear`', () => { beforeEach(() => { TestUtils.Simulate.click(ReactDOM.findDOMNode(instance).querySelector('.Select-clear')); }); it('calls onChange with empty', () => { expect(onChange, 'was called with', ''); }); it('resets the display value', () => { expect(ReactDOM.findDOMNode(instance), 'queried for', DISPLAYED_SELECTION_SELECTOR, 'to have items satisfying', 'to have text', 'Select...'); }); it('resets the control value', () => { expect(ReactDOM.findDOMNode(instance).querySelector('input').value, 'to equal', ''); }); }); }); describe('clearable=false', () => { beforeEach(() => { var instance = createControl({ clearable: false, options: defaultOptions, value: 'three' }); expect(ReactDOM.findDOMNode(instance), 'queried for', DISPLAYED_SELECTION_SELECTOR, 'to have items satisfying', 'to have text', 'Three'); }); it('does not render a clear button', () => { expect(ReactDOM.findDOMNode(instance), 'to contain no elements matching', '.Select-clear'); }); describe('on escape', () => { beforeEach(() => { pressEscape(); }); it('does not call onChange', () => { expect(onChange, 'was not called'); }); it('does not reset the display value', () => { expect(ReactDOM.findDOMNode(instance), 'queried for', DISPLAYED_SELECTION_SELECTOR, 'to have items satisfying', 'to have text', 'Three'); }); it('does not reset the control value', () => { expect(ReactDOM.findDOMNode(instance).querySelector('input').value, 'to equal', 'three'); }); }); describe('when open', () => { beforeEach(() => { typeSearchText('abc'); }); describe('on escape', () => { beforeEach(() => { pressEscape(); }); it('closes the menu', () => { expect(ReactDOM.findDOMNode(instance), 'to contain no elements matching', '.Select-menu'); }); it('resets the control value to the original', () => { expect(ReactDOM.findDOMNode(instance).querySelector('input').value, 'to equal', 'three'); }); it('renders the original display label', () => { expect(ReactDOM.findDOMNode(instance), 'queried for', DISPLAYED_SELECTION_SELECTOR, 'to have items satisfying', 'to have text', 'Three'); }); }); }); }); describe('clearAllText', () => { beforeEach(() => { instance = createControl({ multi: true, clearable: true, value: 'three', clearAllText: 'Remove All Items Test Title', clearValueText: 'Remove Value Test Title', // Should be ignored, multi=true options: defaultOptions }); }); it('uses the prop as the title for clear', () => { expect(ReactDOM.findDOMNode(instance).querySelector('.Select-clear-zone'), 'to have attributes', { title: 'Remove All Items Test Title' }); }); }); describe('clearValueText', () => { beforeEach(() => { instance = createControl({ multi: false, clearable: true, value: 'three', clearAllText: 'Remove All Items Test Title', // Should be ignored, multi=false clearValueText: 'Remove Value Test Title', options: defaultOptions }); }); it('uses the prop as the title for clear', () => { expect(ReactDOM.findDOMNode(instance).querySelector('.Select-clear-zone'), 'to have attributes', { title: 'Remove Value Test Title' }); }); }); describe('delimiter', () => { describe('is ;', () => { beforeEach(() => { instance = createControl({ multi: true, value: 'four;three', delimiter: ';', options: defaultOptions }); }); it('interprets the initial options correctly', () => { var values = ReactDOM.findDOMNode(instance).querySelectorAll('.Select-value'); expect(values[0], 'queried for', '.Select-value-label', 'to have items satisfying', 'to have text', 'AbcDef'); expect(values[1], 'queried for', '.Select-value-label', 'to have items satisfying', 'to have text', 'Three'); expect(values, 'to have length', 2); }); it('adds an additional option with the correct delimiter', () => { typeSearchText('one'); pressEnterToAccept(); expect(onChange, 'was called with', 'four;three;one', [ { value: 'four', label: 'AbcDef' }, { value: 'three', label: 'Three' }, { value: 'one', label: 'One' } ]); }); }); describe('is a multi-character string (`==XXX==`)', () => { beforeEach(() => { instance = createControl({ multi: true, value: 'four==XXX==three', delimiter: '==XXX==', options: defaultOptions }); }); it('interprets the initial options correctly', () => { var values = ReactDOM.findDOMNode(instance).querySelectorAll('.Select-value'); expect(values[0], 'queried for', '.Select-value-label', 'to have items satisfying', 'to have text', 'AbcDef'); expect(values[1], 'queried for', '.Select-value-label', 'to have items satisfying', 'to have text', 'Three'); expect(values, 'to have length', 2); }); it('adds an additional option with the correct delimiter', () => { typeSearchText('one'); pressEnterToAccept(); expect(onChange, 'was called with', 'four==XXX==three==XXX==one', [ { value: 'four', label: 'AbcDef' }, { value: 'three', label: 'Three' }, { value: 'one', label: 'One' } ]); }); }); }); describe('disabled=true', () => { beforeEach(() => { instance = createControl({ options: defaultOptions, value: 'three', disabled: true, searchable: true }); }); it('does not render an input search control', () => { expect(searchInputNode, 'to be null'); }); it('does not react to keyDown', () => { TestUtils.Simulate.keyDown(getSelectControl(instance), { keyCode: 40, key: 'ArrowDown' }); expect(ReactDOM.findDOMNode(instance), 'to contain no elements matching', '.Select-option'); }); it('does not respond to mouseDown', () => { TestUtils.Simulate.mouseDown(getSelectControl(instance)); expect(ReactDOM.findDOMNode(instance), 'to contain no elements matching', '.Select-option'); }); it('does not respond to mouseDown on the arrow', () => { TestUtils.Simulate.mouseDown(getSelectControl(instance).querySelector('.Select-arrow')); expect(ReactDOM.findDOMNode(instance), 'to contain no elements matching', '.Select-option'); }); it('renders the given value', () => { expect(ReactDOM.findDOMNode(instance).querySelector(DISPLAYED_SELECTION_SELECTOR), 'to have text', 'Three'); }); }); describe('custom filterOption function', () => { // Custom function returns true only for value "four" var filterOption = (option) => { if (option.value === 'four') { return true; } return false; }; var spyFilterOption; beforeEach(() => { spyFilterOption = sinon.spy(filterOption); instance = createControl({ options: defaultOptions, filterOption: spyFilterOption }); }); it('calls the filter with each option', () => { expect(spyFilterOption, 'was called times', 4); expect(spyFilterOption, 'was called with', defaultOptions[0], ''); expect(spyFilterOption, 'was called with', defaultOptions[1], ''); expect(spyFilterOption, 'was called with', defaultOptions[2], ''); expect(spyFilterOption, 'was called with', defaultOptions[3], ''); }); describe('when entering text', () => { beforeEach(() => { spyFilterOption.reset(); typeSearchText('xyz'); }); it('calls the filterOption function for each option', () => { expect(spyFilterOption, 'was called times', 4); expect(spyFilterOption, 'was called with', defaultOptions[0], 'xyz'); expect(spyFilterOption, 'was called with', defaultOptions[1], 'xyz'); expect(spyFilterOption, 'was called with', defaultOptions[2], 'xyz'); expect(spyFilterOption, 'was called with', defaultOptions[3], 'xyz'); }); it('only shows the filtered option', () => { expect(ReactDOM.findDOMNode(instance).querySelectorAll('.Select-option'), 'to have length', 1); expect(ReactDOM.findDOMNode(instance).querySelectorAll('.Select-option'), 'to have items satisfying', 'to have text', 'AbcDef'); }); }); }); describe('custom filterOptions function', () => { var spyFilterOptions; beforeEach(() => { spyFilterOptions = sinon.stub(); spyFilterOptions.returns([ { label: 'Return One', value: 'one' }, { label: 'Return Two', value: 'two' } ]); instance = createControl({ options: defaultOptions, filterOptions: spyFilterOptions, searchable: true }); }); it('calls the filterOptions function initially', () => { expect(spyFilterOptions, 'was called'); }); it('calls the filterOptions function initially with the initial options', () => { expect(spyFilterOptions, 'was called with', defaultOptions, ''); }); it('uses the returned options', () => { TestUtils.Simulate.mouseDown(ReactDOM.findDOMNode(instance).querySelector('.Select-arrow')); var options = ReactDOM.findDOMNode(instance).querySelectorAll('.Select-option'); expect(options[0], 'to have text', 'Return One'); expect(options[1], 'to have text', 'Return Two'); expect(options, 'to have length', 2); }); it('calls the filterOptions function on text change', () => { typeSearchText('xyz'); expect(spyFilterOptions, 'was called with', defaultOptions, 'xyz'); }); it('uses new options after text change', () => { spyFilterOptions.returns([ { value: 'abc', label: 'AAbbcc' }, { value: 'def', label: 'DDeeff' } ]); typeSearchText('xyz'); var options = ReactDOM.findDOMNode(instance).querySelectorAll('.Select-option'); expect(options[0], 'to have text', 'AAbbcc'); expect(options[1], 'to have text', 'DDeeff'); expect(options, 'to have length', 2); }); }); describe('ignoreCase=false', () => { beforeEach(() => { instance = createControl({ searchable: true, ignoreCase: false, options: defaultOptions }); }); it('does not find options in a different case', () => { typeSearchText('def'); expect(ReactDOM.findDOMNode(instance), 'to contain no elements matching', '.Select-option'); }); it('finds options in the same case', () => { typeSearchText('Def'); var options = ReactDOM.findDOMNode(instance).querySelectorAll('.Select-option'); expect(options[0], 'to have text', 'AbcDef'); expect(options, 'to have length', 1); }); }); describe('inputProps', () => { beforeEach(() => { instance = createControl({ searchable: true, inputProps: { inputClassName: 'extra-input-class', className: 'extra-class-name', id: 'search-input-id' }, options: defaultOptions }); }); it('passes id through to the search input box', () => { expect(searchInputNode, 'to have attributes', { id: 'search-input-id' }); }); it('passes the inputClassName to the search input box', () => { expect(searchInputNode, 'to have attributes', { class: 'extra-input-class' }); }); it('adds the className on to the auto-size input', () => { expect(ReactDOM.findDOMNode(instance.getInputNode()), 'to have attributes', { class: ['extra-class-name', 'Select-input'] }); }); describe('and not searchable', () => { beforeEach(() => { instance = createControl({ searchable: false, inputProps: { inputClassName: 'extra-input-class', className: 'extra-class-name', id: 'search-input-id' }, options: defaultOptions }); }); it('sets the className and id on the placeholder for the input', () => { expect(ReactDOM.findDOMNode(instance).querySelector('.extra-class-name'), 'to have attributes', { id: 'search-input-id' }); }); }); describe('and disabled', () => { beforeEach(() => { instance = createControl({ searchable: true, disabled: true, inputProps: { inputClassName: 'extra-input-class', className: 'extra-class-name', id: 'search-input-id' }, options: defaultOptions }); }); it('doesn\'t pass the inputProps through', () => { expect(ReactDOM.findDOMNode(instance), 'to contain no elements matching', '.extra-class-name'); expect(ReactDOM.findDOMNode(instance), 'to contain no elements matching', '#search-input-id'); }); }); }); describe('matchPos=start', () => { beforeEach(() => { instance = createControl({ searchable: true, matchPos: 'start', options: defaultOptions }); }); it('searches only at the start', () => { typeSearchText('o'); var options = ReactDOM.findDOMNode(instance).querySelectorAll('.Select-option'); expect(options[0], 'to have text', 'One'); expect(options, 'to have length', 1); }); }); describe('matchProp=value', () => { beforeEach(() => { instance = createControl({ searchable: true, matchProp: 'value', options: [ { value: 'aaa', label: '111' }, { value: 'bbb', label: '222' }, { value: 'ccc', label: 'Three' }, { value: 'four', label: 'Abcaaa' } ] }); }); it('searches only the value', () => { typeSearchText('aa'); // Matches value "three", and label "AbcDef" var options = ReactDOM.findDOMNode(instance).querySelectorAll('.Select-option'); expect(options, 'to have length', 1); expect(options[0], 'to have text', '111'); }); }); describe('matchProp=label', () => { beforeEach(() => { instance = createControl({ searchable: true, matchProp: 'label', options: [ { value: 'aaa', label: 'bbb' }, { value: 'bbb', label: '222' }, { value: 'ccc', label: 'Three' }, { value: 'four', label: 'Abcaaa' } ] }); }); it('searches only the value', () => { typeSearchText('bb'); // Matches value "three", and label "AbcDef" var options = ReactDOM.findDOMNode(instance).querySelectorAll('.Select-option'); expect(options, 'to have length', 1); expect(options[0], 'to have text', 'bbb'); }); }); describe('matchPos=start and matchProp=value', () => { beforeEach(() => { instance = createControl({ searchable: true, matchProp: 'value', matchPos: 'start', options: [ { value: 'aaa', label: '111' }, { value: 'bbb', label: '222' }, { value: 'cccaa', label: 'Three' }, { value: 'four', label: 'aaAbca' } ] }); }); it('searches only the value', () => { typeSearchText('aa'); // Matches value "three", and label "AbcDef" var options = ReactDOM.findDOMNode(instance).querySelectorAll('.Select-option'); expect(options, 'to have length', 1); expect(options[0], 'to have text', '111'); }); }); describe('matchPos=start and matchProp=label', () => { beforeEach(() => { instance = createControl({ searchable: true, matchProp: 'label', matchPos: 'start', options: [ { value: 'aaa', label: 'bbb' }, { value: 'bbb', label: '222' }, { value: 'cccbbb', label: 'Three' }, { value: 'four', label: 'Abcbbb' } ] }); }); it('searches only the label', () => { typeSearchText('bb'); // Matches value "three", and label "AbcDef" var options = ReactDOM.findDOMNode(instance).querySelectorAll('.Select-option'); expect(options, 'to have length', 1); expect(options[0], 'to have text', 'bbb'); }); }); describe('noResultsText', () => { beforeEach(() => { wrapper = createControlWithWrapper({ searchable: true, options: defaultOptions, noResultsText: 'No results unit test' }); }); it('displays the text when no results are found', () => { typeSearchText('DOES NOT EXIST'); expect(ReactDOM.findDOMNode(instance).querySelector('.Select-menu'), 'to have text', 'No results unit test'); }); it('supports updating the text', () => { wrapper.setPropsForChild({ noResultsText: 'Updated no results text' }); typeSearchText('DOES NOT EXIST'); expect(ReactDOM.findDOMNode(instance).querySelector('.Select-menu'), 'to have text', 'Updated no results text'); }); }); describe('onBlur', () => { var onBlur; it('calls the onBlur prop when blurring the input', () => { onBlur = sinon.spy(); instance = createControl({ options: defaultOptions, onBlur: onBlur }); TestUtils.Simulate.blur(searchInputNode); expect(onBlur, 'was called once'); }); }); describe('onFocus', () => { var onFocus; beforeEach(() => { onFocus = sinon.spy(); instance = createControl({ options: defaultOptions, onFocus: onFocus }); }); it('calls the onFocus prop when focusing the control', () => { expect(onFocus, 'was called once'); }); }); describe('onValueClick', () => { var onValueClick; beforeEach(() => { onValueClick = sinon.spy(); instance = createControl({ options: defaultOptions, multi: true, value: 'two,one', onValueClick: onValueClick }); }); it('calls the function when clicking on a label', () => { TestUtils.Simulate.click(ReactDOM.findDOMNode(instance).querySelector('.Select-value-label a')); expect(onValueClick, 'was called once'); }); it('calls the function with the value', () => { TestUtils.Simulate.click(ReactDOM.findDOMNode(instance).querySelectorAll('.Select-value-label a')[0]); expect(onValueClick, 'was called with', { value: 'two', label: '222' }); }); }); describe('optionRenderer', () => { var optionRenderer; beforeEach(() => { optionRenderer = (option) => { return ( <span id={'TESTOPTION_' + option.value}>{option.label.toUpperCase()}</span> ); }; optionRenderer = sinon.spy(optionRenderer); instance = createControl({ options: defaultOptions, optionRenderer: optionRenderer }); }); it('renders the options using the optionRenderer', () => { var selectArrow = ReactDOM.findDOMNode(instance).querySelector('.Select-arrow'); TestUtils.Simulate.mouseDown(selectArrow); var options = ReactDOM.findDOMNode(instance).querySelectorAll('.Select-option'); expect(options[0].querySelector('span'), 'to have attributes', { id: 'TESTOPTION_one' }); expect(options[0].querySelector('span'), 'to have text', 'ONE'); expect(options[1].querySelector('span'), 'to have attributes', { id: 'TESTOPTION_two' }); expect(options[1].querySelector('span'), 'to have text', '222'); }); it('calls the renderer exactly once for each option', () => { var selectArrow = ReactDOM.findDOMNode(instance).querySelector('.Select-arrow'); TestUtils.Simulate.mouseDown(selectArrow); expect(optionRenderer, 'was called times', 4); }); }); describe('optionRendererDisabled', () => { var optionRenderer; var renderLink = (props) => { return <a {...props} >Upgrade here!</a>; }; var links = [ { href: '/link' }, { href: '/link2', target: '_blank' } ]; var ops = [ { label: 'Disabled', value: 'disabled', disabled: true, link: renderLink(links[0]) }, { label: 'Disabled 2', value: 'disabled_2', disabled: true, link: renderLink(links[1]) }, { label: 'Enabled', value: 'enabled' } ]; /** * Since we don't have access to an actual Location object, * this method will test a string (path) by the end of global.window.location.href * @param {string} path Ending href path to check * @return {Boolean} Whether the location is at the path */ var isNavigated = (path) => { var window_location = global.window.location.href; return window_location.indexOf(path, window_location.length - path.length) !== -1; }; var startUrl = 'http://dummy/startLink'; beforeEach(() => { window.location.href = startUrl; optionRenderer = (option) => { return ( <span>{option.label} {option.link} </span> ); }; optionRenderer = sinon.spy(optionRenderer); instance = createControl({ options: ops, optionRenderer: optionRenderer }); }); it('disabled option link is still clickable', () => { var selectArrow = ReactDOM.findDOMNode(instance).querySelector('.Select-arrow'); var selectArrow = ReactDOM.findDOMNode(instance).querySelector('.Select-arrow'); TestUtils.Simulate.mouseDown(selectArrow); var options = ReactDOM.findDOMNode(instance).querySelectorAll('.Select-option'); var link = options[0].querySelector('a'); expect(link, 'to have attributes', { href: links[0].href }); expect(isNavigated(links[0].href), 'to be false'); TestUtils.Simulate.click(link); expect(isNavigated(links[0].href), 'to be true'); }); it('disabled option link with target doesn\'t navigate the current window', () => { var selectArrow = ReactDOM.findDOMNode(instance).querySelector('.Select-arrow'); TestUtils.Simulate.mouseDown(selectArrow); var options = ReactDOM.findDOMNode(instance).querySelectorAll('.Select-option'); var link = options[1].querySelector('a'); expect(link, 'to have attributes', { href: links[1].href, target: '_blank' }); expect(isNavigated(startUrl), 'to be true'); TestUtils.Simulate.click(link); expect(isNavigated(links[1].href), 'to be false'); }); }); describe('placeholder', () => { beforeEach(() => { wrapper = createControlWithWrapper({ value: null, options: defaultOptions, placeholder: 'Choose Option Placeholder test' }); }); it('uses the placeholder initially', () => { expect(ReactDOM.findDOMNode(instance), 'queried for', '.Select-placeholder', 'to have items satisfying', 'to have text', 'Choose Option Placeholder test'); }); it('displays a selected value', () => { wrapper.setPropsForChild({ value: 'three' }); expect(ReactDOM.findDOMNode(instance), 'queried for', '.Select-placeholder', 'to have items satisfying', 'to have text', 'Three'); }); it('returns to the default placeholder when value is cleared', () => { wrapper.setPropsForChild({ value: 'three' }); wrapper.setPropsForChild({ value: null }); expect(ReactDOM.findDOMNode(instance), 'queried for', '.Select-placeholder', 'to have items satisfying', 'to have text', 'Choose Option Placeholder test'); }); it('allows changing the placeholder via props', () => { wrapper.setPropsForChild({ placeholder: 'New placeholder from props' }); expect(ReactDOM.findDOMNode(instance), 'queried for', '.Select-placeholder', 'to have items satisfying', 'to have text', 'New placeholder from props'); }); it('allows setting the placeholder to the selected value', () => { /* This is an unlikely scenario, but given that the current * implementation uses the placeholder to display the selected value, * it seems prudent to check that this obscure case still works * * We set the value via props, then change the placeholder to the * same as the display label for the chosen option, then reset * the value (to null). * * The expected result is that the display does NOT change, as the * placeholder is now the same as label. */ wrapper.setPropsForChild({ value: 'three' }); wrapper.setPropsForChild({ placeholder: 'Three' // Label for value 'three' }); wrapper.setPropsForChild({ value: null }); expect(ReactDOM.findDOMNode(instance), 'queried for', '.Select-placeholder', 'to have items satisfying', 'to have text', 'Three'); }); }); describe('searchingText', () => { // TODO: Need to use the new Select.Async control for this return; var asyncOptions; var asyncOptionsCallback; beforeEach(() => { asyncOptions = sinon.spy(); instance = createControl({ asyncOptions: asyncOptions, autoload: false, searchingText: 'Testing async loading...', noResultsText: 'Testing No results found', searchPromptText: 'Testing enter search query' }); }); it('uses the searchingText whilst the asyncOptions are loading', () => { clickArrowToOpen(); expect(asyncOptions, 'was not called'); typeSearchText('abc'); expect(asyncOptions, 'was called'); expect(ReactDOM.findDOMNode(instance), 'to contain elements matching', '.Select-loading'); expect(ReactDOM.findDOMNode(instance), 'queried for first', '.Select-searching', 'to have text', 'Testing async loading...'); }); it('clears the searchingText when results arrive', () => { clickArrowToOpen(); typeSearchText('abc'); expect(ReactDOM.findDOMNode(instance), 'queried for first', '.Select-searching', 'to have text', 'Testing async loading...'); asyncOptions.args[0][1](null, { options: [{ value: 'abc', label: 'Abc' }] }); expect(ReactDOM.findDOMNode(instance), 'to contain no elements matching', '.Select-noresults'); }); it('switches the searchingText to noResultsText when options arrive, but empty', () => { clickArrowToOpen(); typeSearchText('abc'); expect(ReactDOM.findDOMNode(instance), 'queried for first', '.Select-searching', 'to have text', 'Testing async loading...'); expect(ReactDOM.findDOMNode(instance), 'to contain no elements matching', '.Select-noresults'); asyncOptions.args[0][1](null, { options: [] }); expect(ReactDOM.findDOMNode(instance), 'queried for first', '.Select-noresults', 'to have text', 'Testing No results found'); expect(ReactDOM.findDOMNode(instance), 'to contain no elements matching', '.Select-searching'); }); }); describe('searchPromptText', () => { // TODO: Need to use the new Select.Async control for this return; var asyncOptions; beforeEach(() => { asyncOptions = sinon.stub(); instance = createControl({ asyncOptions: asyncOptions, autoload: false, searchPromptText: 'Unit test prompt text' }); }); it('uses the searchPromptText before text is entered', () => { var selectArrow = ReactDOM.findDOMNode(instance).querySelector('.Select-arrow'); TestUtils.Simulate.mouseDown(selectArrow); expect(ReactDOM.findDOMNode(instance), 'queried for', '.Select-search-prompt', 'to have items satisfying', 'to have text', 'Unit test prompt text'); }); it('clears the searchPromptText when results arrive', () => { asyncOptions.callsArgWith(1, null, { options: [{ value: 'abcd', label: 'ABCD' }] }); var selectArrow = ReactDOM.findDOMNode(instance).querySelector('.Select-arrow'); TestUtils.Simulate.mouseDown(selectArrow); typeSearchText('abc'); expect(asyncOptions, 'was called once'); expect(ReactDOM.findDOMNode(instance), 'to contain no elements matching', '.Select-prompt'); expect(ReactDOM.findDOMNode(instance), 'to contain no elements matching', '.Select-noresults'); }); }); describe('valueRenderer', () => { var valueRenderer; beforeEach(() => { valueRenderer = (option) => { return ( <span id={'TESTOPTION_' + option.value}>{option.label.toUpperCase()}</span> ); }; valueRenderer = sinon.spy(valueRenderer); instance = createControl({ options: defaultOptions, value: 'three', valueRenderer: valueRenderer }); }); it('renders the value using the provided renderer', () => { var labelNode = ReactDOM.findDOMNode(instance).querySelector('.Select-value span'); expect(labelNode, 'to have text', 'THREE'); expect(labelNode, 'to have attributes', { id: 'TESTOPTION_three' }); }); }); describe('valueRenderer and multi=true', () => { var valueRenderer; beforeEach(() => { valueRenderer = (option) => { return ( <span id={'TESTOPTION_' + option.value}>{option.label.toUpperCase()}</span> ); }; valueRenderer = sinon.spy(valueRenderer); instance = createControl({ options: defaultOptions, value: 'three,two', multi: true, valueRenderer: valueRenderer }); }); it('renders the values using the provided renderer', () => { var labelNode = ReactDOM.findDOMNode(instance).querySelectorAll('.Select-value-label span'); expect(labelNode[0], 'to have text', 'THREE'); expect(labelNode[0], 'to have attributes', { id: 'TESTOPTION_three' }); expect(labelNode[1], 'to have text', '222'); expect(labelNode[1], 'to have attributes', { id: 'TESTOPTION_two' }); }); }); }); describe('clicking outside', () => { beforeEach(() => { instance = createControl({ options: defaultOptions }); }); it('closes the menu', () => { TestUtils.Simulate.mouseDown(getSelectControl(instance)); expect(ReactDOM.findDOMNode(instance), 'queried for', '.Select-option', 'to have length', 4); clickDocument(); expect(ReactDOM.findDOMNode(instance), 'to contain no elements matching', '.Select-option'); }); }); });
MattMcFarland/react-select
test/Select-test.js
JavaScript
mit
84,972
import markdownIt from 'markdown-it'; import _ from 'lodash'; import footnotes from 'markdown-it-footnote'; export default function (opts) { const mergedOpts = _.assign({}, opts, { html: true, linkify: true }); const md = markdownIt(mergedOpts).use(footnotes); if (mergedOpts.openLinksExternally) { // Remember old renderer, if overriden, or proxy to default renderer const defaultRender = md.renderer.rules.link_open || function (tokens, idx, options, env, self) { return self.renderToken(tokens, idx, options); }; md.renderer.rules.link_open = function (tokens, idx, options, env, self) { const aIndex = tokens[idx].attrIndex('target'); if (aIndex < 0) { tokens[idx].attrPush(['target', '_blank']); // add new attribute } else { tokens[idx].attrs[aIndex][1] = '_blank'; // replace value of existing attr } // pass token to default renderer. return defaultRender(tokens, idx, options, env, self); }; } return md; }
alpha721/WikiEduDashboard
app/assets/javascripts/utils/markdown_it.js
JavaScript
mit
1,010
angular.module('app', []) .controller('Controller', function($scope) { $scope.hi = 'world'; });
russmatney/slush-angular-playground
templates/scripts/controller.js
JavaScript
mit
104
'use strict'; var setPrototypeOf = require('es5-ext/object/set-prototype-of') , mixin = require('es5-ext/object/mixin-prototypes') , iterator = require('es6-iterator/valid-iterable') , forOf = require('es6-iterator/for-of') , toArray = require('es5-ext/array/to-array') , Set = require('es6-set') , d = require('d') , validObservableSet = require('observable-set/valid-observable-set') , defineProperty = Object.defineProperty, getPrototypeOf = Object.getPrototypeOf , add = Set.prototype.add, clear = Set.prototype.clear, del = Set.prototype.delete , SetsSet; module.exports = SetsSet = function (multiSet, iterable) { var sets, set; if (!(this instanceof SetsSet)) throw new TypeError('Constructor requires \'new\''); if (iterable != null) { iterator(iterable); sets = []; forOf(iterable, function (value) { sets.push(validObservableSet(value)); }); } set = new Set(sets); if (setPrototypeOf) setPrototypeOf(set, getPrototypeOf(this)); else mixin(set, getPrototypeOf(this)); defineProperty(set, '__master__', d('', multiSet)); return set; }; if (setPrototypeOf) setPrototypeOf(SetsSet, Set); SetsSet.prototype = Object.create(Set.prototype, { constructor: d(SetsSet), add: d(function (set) { if (this.has(validObservableSet(set))) return this; add.call(this, set); this.__master__._onSetAdd(set); return this; }), clear: d(function () { var sets; if (!this.size) return; sets = toArray(this); clear.call(this); this.__master__._onSetsClear(sets); }), delete: d(function (set) { if (!this.has(set)) return false; del.call(this, set); this.__master__._onSetDelete(set); return true; }) });
egovernment/eregistrations-demo
node_modules/observable-multi-set/_sets-set.js
JavaScript
mit
1,750
var gulp = require('gulp'); var argv = require('yargs').argv; var config = require('../config.js'); var dist = config.release = !!argv.dist; console.log('_________________________________________'); console.log(''); console.log(' Building for distribution: ' + dist); console.log(''); gulp.task('default', ['images', 'lib', 'sass', 'watch', 'code', 'html']);
vonWolfehaus/von-wiki
build/tasks/default.js
JavaScript
mit
364
var routes = { "index" : { title : "", url : "/", controller : main }, "404" : { title : "404", url : "/404", controller : fourohfour } };
AyphixEntertainmentLLC/espada
es1.5/app/routes.js
JavaScript
mit
154
;(function(Form) { /** * List editor * * An array editor. Creates a list of other editor items. * * Special options: * @param {String} [options.schema.itemType] The editor type for each item in the list. Default: 'Text' * @param {String} [options.schema.confirmDelete] Text to display in a delete confirmation dialog. If falsey, will not ask for confirmation. */ Form.editors.List = Form.editors.Base.extend({ events: { 'click [data-action="add"]': function(event) { event.preventDefault(); this.addItem(null, true); } }, initialize: function(options) { options = options || {}; var editors = Form.editors; editors.Base.prototype.initialize.call(this, options); var schema = this.schema; if (!schema) throw new Error("Missing required option 'schema'"); this.template = options.template || this.constructor.template; //Determine the editor to use this.Editor = (function() { var type = schema.itemType; //Default to Text if (!type) return editors.Text; //Use List-specific version if available if (editors.List[type]) return editors.List[type]; //Or whichever was passed return editors[type]; })(); this.items = []; }, render: function() { var self = this, value = this.value || [], $ = Backbone.$; //Create main element var $el = $($.trim(this.template())); //Store a reference to the list (item container) this.$list = $el.is('[data-items]') ? $el : $el.find('[data-items]'); //Add existing items if (value.length) { _.each(value, function(itemValue) { self.addItem(itemValue); }); } //If no existing items create an empty one, unless the editor specifies otherwise else { if (!this.Editor.isAsync) this.addItem(); } this.setElement($el); this.$el.attr('id', this.id); this.$el.attr('name', this.key); if (this.hasFocus) this.trigger('blur', this); return this; }, /** * Add a new item to the list * @param {Mixed} [value] Value for the new item editor * @param {Boolean} [userInitiated] If the item was added by the user clicking 'add' */ addItem: function(value, userInitiated) { var self = this, editors = Form.editors; //Create the item var item = new this.constructor.Item({ list: this, form: this.form, schema: this.schema, value: value, Editor: this.Editor, key: this.key }).render(); var _addItem = function() { self.items.push(item); self.$list.append(item.el); item.editor.on('all', function(event) { if (event === 'change') return; // args = ["key:change", itemEditor, fieldEditor] var args = _.toArray(arguments); args[0] = 'item:' + event; args.splice(1, 0, self); // args = ["item:key:change", this=listEditor, itemEditor, fieldEditor] editors.List.prototype.trigger.apply(this, args); }, self); item.editor.on('change', function() { if (!item.addEventTriggered) { item.addEventTriggered = true; this.trigger('add', this, item.editor); } this.trigger('item:change', this, item.editor); this.trigger('change', this); }, self); item.editor.on('focus', function() { if (this.hasFocus) return; this.trigger('focus', this); }, self); item.editor.on('blur', function() { if (!this.hasFocus) return; var self = this; setTimeout(function() { if (_.find(self.items, function(item) { return item.editor.hasFocus; })) return; self.trigger('blur', self); }, 0); }, self); if (userInitiated || value) { item.addEventTriggered = true; } if (userInitiated) { self.trigger('add', self, item.editor); self.trigger('change', self); } }; //Check if we need to wait for the item to complete before adding to the list if (this.Editor.isAsync) { item.editor.on('readyToAdd', _addItem, this); } //Most editors can be added automatically else { _addItem(); item.editor.focus(); } return item; }, /** * Remove an item from the list * @param {List.Item} item */ removeItem: function(item) { //Confirm delete var confirmMsg = this.schema.confirmDelete; if (confirmMsg && !confirm(confirmMsg)) return; var index = _.indexOf(this.items, item); this.items[index].remove(); this.items.splice(index, 1); if (item.addEventTriggered) { this.trigger('remove', this, item.editor); this.trigger('change', this); } if (!this.items.length && !this.Editor.isAsync) this.addItem(); }, getValue: function() { var values = _.map(this.items, function(item) { return item.getValue(); }); //Filter empty items return _.without(values, undefined, ''); }, setValue: function(value) { this.value = value; this.render(); }, focus: function() { if (this.hasFocus) return; if (this.items[0]) this.items[0].editor.focus(); }, blur: function() { if (!this.hasFocus) return; var focusedItem = _.find(this.items, function(item) { return item.editor.hasFocus; }); if (focusedItem) focusedItem.editor.blur(); }, /** * Override default remove function in order to remove item views */ remove: function() { _.invoke(this.items, 'remove'); Form.editors.Base.prototype.remove.call(this); }, /** * Run validation * * @return {Object|Null} */ validate: function() { if (!this.validators) return null; //Collect errors var errors = _.map(this.items, function(item) { return item.validate(); }); //Check if any item has errors var hasErrors = _.compact(errors).length ? true : false; if (!hasErrors) return null; //If so create a shared error var fieldError = { type: 'list', message: 'Some of the items in the list failed validation', errors: errors }; return fieldError; } }, { //STATICS template: _.template('\ <div>\ <div data-items></div>\ <button type="button" data-action="add">Add</button>\ </div>\ ', null, Form.templateSettings) }); /** * A single item in the list * * @param {editors.List} options.list The List editor instance this item belongs to * @param {Function} options.Editor Editor constructor function * @param {String} options.key Model key * @param {Mixed} options.value Value * @param {Object} options.schema Field schema */ Form.editors.List.Item = Form.editors.Base.extend({ events: { 'click [data-action="remove"]': function(event) { event.preventDefault(); this.list.removeItem(this); }, 'keydown input[type=text]': function(event) { if(event.keyCode !== 13) return; event.preventDefault(); this.list.addItem(); this.list.$list.find("> li:last input").focus(); } }, initialize: function(options) { this.list = options.list; this.schema = options.schema || this.list.schema; this.value = options.value; this.Editor = options.Editor || Form.editors.Text; this.key = options.key; this.template = options.template || this.schema.itemTemplate || this.constructor.template; this.errorClassName = options.errorClassName || this.constructor.errorClassName; this.form = options.form; }, render: function() { var $ = Backbone.$; //Create editor this.editor = new this.Editor({ key: this.key, schema: this.schema, value: this.value, list: this.list, item: this, form: this.form }).render(); //Create main element var $el = $($.trim(this.template())); $el.find('[data-editor]').append(this.editor.el); //Replace the entire element so there isn't a wrapper tag this.setElement($el); return this; }, getValue: function() { return this.editor.getValue(); }, setValue: function(value) { this.editor.setValue(value); }, focus: function() { this.editor.focus(); }, blur: function() { this.editor.blur(); }, remove: function() { this.editor.remove(); Backbone.View.prototype.remove.call(this); }, validate: function() { var value = this.getValue(), formValues = this.list.form ? this.list.form.getValue() : {}, validators = this.schema.validators, getValidator = this.getValidator; if (!validators) return null; //Run through validators until an error is found var error = null; _.every(validators, function(validator) { error = getValidator(validator)(value, formValues); return error ? false : true; }); //Show/hide error if (error){ this.setError(error); } else { this.clearError(); } //Return error to be aggregated by list return error ? error : null; }, /** * Show a validation error */ setError: function(err) { this.$el.addClass(this.errorClassName); this.$el.attr('title', err.message); }, /** * Hide validation errors */ clearError: function() { this.$el.removeClass(this.errorClassName); this.$el.attr('title', null); } }, { //STATICS template: _.template('\ <div>\ <span data-editor></span>\ <button type="button" data-action="remove">&times;</button>\ </div>\ ', null, Form.templateSettings), errorClassName: 'error' }); /** * Base modal object editor for use with the List editor; used by Object * and NestedModal list types */ Form.editors.List.Modal = Form.editors.Base.extend({ events: { 'click': 'openEditor' }, /** * @param {Object} options * @param {Form} options.form The main form * @param {Function} [options.schema.itemToString] Function to transform the value for display in the list. * @param {String} [options.schema.itemType] Editor type e.g. 'Text', 'Object'. * @param {Object} [options.schema.subSchema] Schema for nested form,. Required when itemType is 'Object' * @param {Function} [options.schema.model] Model constructor function. Required when itemType is 'NestedModel' */ initialize: function(options) { options = options || {}; Form.editors.Base.prototype.initialize.call(this, options); //Dependencies if (!Form.editors.List.Modal.ModalAdapter) throw new Error('A ModalAdapter is required'); this.form = options.form; if (!options.form) throw new Error('Missing required option: "form"'); //Template this.template = options.template || this.constructor.template; }, /** * Render the list item representation */ render: function() { var self = this; //New items in the list are only rendered when the editor has been OK'd if (_.isEmpty(this.value)) { this.openEditor(); } //But items with values are added automatically else { this.renderSummary(); setTimeout(function() { self.trigger('readyToAdd'); }, 0); } if (this.hasFocus) this.trigger('blur', this); return this; }, /** * Renders the list item representation */ renderSummary: function() { this.$el.html($.trim(this.template({ summary: this.getStringValue() }))); }, /** * Function which returns a generic string representation of an object * * @param {Object} value * * @return {String} */ itemToString: function(value) { var createTitle = function(key) { var context = { key: key }; return Form.Field.prototype.createTitle.call(context); }; value = value || {}; //Pretty print the object keys and values var parts = []; _.each(this.nestedSchema, function(schema, key) { var desc = schema.title ? schema.title : createTitle(key), val = value[key]; if (_.isUndefined(val) || _.isNull(val)) val = ''; parts.push(desc + ': ' + val); }); return parts.join('<br />'); }, /** * Returns the string representation of the object value */ getStringValue: function() { var schema = this.schema, value = this.getValue(); if (_.isEmpty(value)) return '[Empty]'; //If there's a specified toString use that if (schema.itemToString) return schema.itemToString(value); //Otherwise use the generic method or custom overridden method return this.itemToString(value); }, openEditor: function() { var self = this, ModalForm = this.form.constructor; var form = this.modalForm = new ModalForm({ schema: this.nestedSchema, data: this.value }); var modal = this.modal = new Form.editors.List.Modal.ModalAdapter({ content: form, animate: true }); modal.open(); this.trigger('open', this); this.trigger('focus', this); modal.on('cancel', this.onModalClosed, this); modal.on('ok', _.bind(this.onModalSubmitted, this)); }, /** * Called when the user clicks 'OK'. * Runs validation and tells the list when ready to add the item */ onModalSubmitted: function() { var modal = this.modal, form = this.modalForm, isNew = !this.value; //Stop if there are validation errors var error = form.validate(); if (error) return modal.preventClose(); //Store form value this.value = form.getValue(); //Render item this.renderSummary(); if (isNew) this.trigger('readyToAdd'); this.trigger('change', this); this.onModalClosed(); }, /** * Cleans up references, triggers events. To be called whenever the modal closes */ onModalClosed: function() { this.modal = null; this.modalForm = null; this.trigger('close', this); this.trigger('blur', this); }, getValue: function() { return this.value; }, setValue: function(value) { this.value = value; }, focus: function() { if (this.hasFocus) return; this.openEditor(); }, blur: function() { if (!this.hasFocus) return; if (this.modal) { this.modal.trigger('cancel'); } } }, { //STATICS template: _.template('\ <div><%= summary %></div>\ ', null, Form.templateSettings), //The modal adapter that creates and manages the modal dialog. //Defaults to BootstrapModal (http://github.com/powmedia/backbone.bootstrap-modal) //Can be replaced with another adapter that implements the same interface. ModalAdapter: Backbone.BootstrapModal, //Make the wait list for the 'ready' event before adding the item to the list isAsync: true }); Form.editors.List.Object = Form.editors.List.Modal.extend({ initialize: function () { Form.editors.List.Modal.prototype.initialize.apply(this, arguments); var schema = this.schema; if (!schema.subSchema) throw new Error('Missing required option "schema.subSchema"'); this.nestedSchema = schema.subSchema; } }); Form.editors.List.NestedModel = Form.editors.List.Modal.extend({ initialize: function() { Form.editors.List.Modal.prototype.initialize.apply(this, arguments); var schema = this.schema; if (!schema.model) throw new Error('Missing required option "schema.model"'); var nestedSchema = schema.model.prototype.schema; this.nestedSchema = (_.isFunction(nestedSchema)) ? nestedSchema() : nestedSchema; }, /** * Returns the string representation of the object value */ getStringValue: function() { var schema = this.schema, value = this.getValue(); if (_.isEmpty(value)) return null; //If there's a specified toString use that if (schema.itemToString) return schema.itemToString(value); //Otherwise use the model return new (schema.model)(value).toString(); } }); })(Backbone.Form);
fonji/backbone-forms
src/editors/extra/list.js
JavaScript
mit
17,112
var searchData= [ ['rgb',['Rgb',['../structarctic_1_1_rgb.html',1,'arctic']]], ['rgba',['Rgba',['../structarctic_1_1easy_1_1_rgba.html',1,'arctic::easy']]] ];
t800danya/desert-engine
doc/html/search/classes_5.js
JavaScript
mit
163
define(function(require, exports, module) { require('vendor/zepto/zepto'); var $ = window.Zepto; // Zepto.js // (c) 2010-2014 Thomas Fuchs // Zepto.js may be freely distributed under the MIT license. var touch = {}, touchTimeout, tapTimeout, swipeTimeout, longTapTimeout, longTapDelay = 750, gesture; function swipeDirection(x1, x2, y1, y2) { return Math.abs(x1 - x2) >= Math.abs(y1 - y2) ? (x1 - x2 > 0 ? 'Left' : 'Right') : (y1 - y2 > 0 ? 'Up' : 'Down') } function longTap() { longTapTimeout = null; if (touch.last) { touch.el.trigger('longTap'); touch = {} } } function cancelLongTap() { if (longTapTimeout) clearTimeout(longTapTimeout); longTapTimeout = null; } function cancelAll() { if (touchTimeout) clearTimeout(touchTimeout); if (tapTimeout) clearTimeout(tapTimeout); if (swipeTimeout) clearTimeout(swipeTimeout); if (longTapTimeout) clearTimeout(longTapTimeout); touchTimeout = tapTimeout = swipeTimeout = longTapTimeout = null; touch = {} } function isPrimaryTouch(event) { return (event.pointerType == 'touch' || event.pointerType == event.MSPOINTER_TYPE_TOUCH) && event.isPrimary; } function isPointerEventType(e, type) { return (e.type == 'pointer' + type || e.type.toLowerCase() == 'mspointer' + type); } $(document).ready(function() { var now, delta, deltaX = 0, deltaY = 0, firstTouch, _isPointerType; if ('MSGesture' in window) { gesture = new MSGesture(); gesture.target = document.body; } $(document) .on('MSGestureEnd', function(e) { var swipeDirectionFromVelocity = e.velocityX > 1 ? 'Right' : e.velocityX < -1 ? 'Left' : e.velocityY > 1 ? 'Down' : e.velocityY < -1 ? 'Up' : null; if (swipeDirectionFromVelocity) { touch.el.trigger('swipe'); touch.el.trigger('swipe' + swipeDirectionFromVelocity); } }) .on('touchstart MSPointerDown pointerdown', function(e) { if ((_isPointerType = isPointerEventType(e, 'down')) && !isPrimaryTouch(e)) return; firstTouch = _isPointerType ? e : e.touches[0]; if (e.touches && e.touches.length === 1 && touch.x2) { // Clear out touch movement data if we have it sticking around // This can occur if touchcancel doesn't fire due to preventDefault, etc. touch.x2 = undefined; touch.y2 = undefined; } now = Date.now(); delta = now - (touch.last || now); touch.el = $('tagName' in firstTouch.target ? firstTouch.target : firstTouch.target.parentNode); touchTimeout && clearTimeout(touchTimeout); touch.x1 = firstTouch.pageX; touch.y1 = firstTouch.pageY; if (delta > 0 && delta <= 250) touch.isDoubleTap = true; touch.last = now; longTapTimeout = setTimeout(longTap, longTapDelay); // adds the current touch contact for IE gesture recognition if (gesture && _isPointerType) gesture.addPointer(e.pointerId); }) .on('touchmove MSPointerMove pointermove', function(e) { if ((_isPointerType = isPointerEventType(e, 'move')) && !isPrimaryTouch(e)) return firstTouch = _isPointerType ? e : e.touches[0]; cancelLongTap(); touch.x2 = firstTouch.pageX; touch.y2 = firstTouch.pageY; deltaX += Math.abs(touch.x1 - touch.x2); deltaY += Math.abs(touch.y1 - touch.y2); }) .on('touchend MSPointerUp pointerup', function(e) { if ((_isPointerType = isPointerEventType(e, 'up')) && !isPrimaryTouch(e)) return; cancelLongTap(); // swipe if ((touch.x2 && Math.abs(touch.x1 - touch.x2) > 30) || (touch.y2 && Math.abs(touch.y1 - touch.y2) > 30)) swipeTimeout = setTimeout(function() { touch.el.trigger('swipe'); touch.el.trigger('swipe' + (swipeDirection(touch.x1, touch.x2, touch.y1, touch.y2))) touch = {} }, 0); // normal tap else if ('last' in touch) // don't fire tap when delta position changed by more than 30 pixels, // for instance when moving to a point and back to origin if (deltaX < 30 && deltaY < 30) { // delay by one tick so we can cancel the 'tap' event if 'scroll' fires // ('tap' fires before 'scroll') tapTimeout = setTimeout(function() { // trigger universal 'tap' with the option to cancelTouch() // (cancelTouch cancels processing of single vs double taps for faster 'tap' response) var event = $.Event('tap'); event.cancelTouch = cancelAll; touch.el.trigger(event); // trigger double tap immediately if (touch.isDoubleTap) { if (touch.el) touch.el.trigger('doubleTap'); touch = {} } // trigger single tap after 250ms of inactivity else { touchTimeout = setTimeout(function() { touchTimeout = null; if (touch.el) touch.el.trigger('singleTap'); touch = {} }, 250) } }, 0) } else { touch = {} } deltaX = deltaY = 0; }) // when the browser window loses focus, // for example when a modal dialog is shown, // cancel all ongoing events .on('touchcancel MSPointerCancel pointercancel', cancelAll); // scrolling the window indicates intention of the user // to scroll, not tap or swipe, so cancel all ongoing events $(window).on('scroll', cancelAll); }); ['swipe', 'swipeLeft', 'swipeRight', 'swipeUp', 'swipeDown', 'doubleTap', 'tap', 'singleTap', 'longTap'].forEach(function(eventName) { $.fn[eventName] = function(callback) { return this.on(eventName, callback) } }); });
MDM-Team/MDMUI
src/1.0.0/js/ui/zepto.touch.js
JavaScript
mit
7,098
/* FusionCharts JavaScript Library - Tree Map Chart Copyright FusionCharts Technologies LLP License Information at <http://www.fusioncharts.com/license> @version 3.11.0 */ FusionCharts.register("module",["private","modules.renderer.js-treemap",function(){function U(c){return c?c.replace(/^#*/,"#"):"#E5E5E5"}function z(c,b,d){this.label=c;this.value=parseFloat(b,10);this.colorValue=parseFloat(d,10);this.prev=this.next=void 0;this.meta={}}function M(){this._b=[];this._css=void 0;this.rangeOurEffectApplyFn=function(){};this.statePointerLow={value:void 0,index:void 0};this.statePointerHigh={value:void 0,index:void 0}}var ca,da,$,ea,K=this.hcLib,V=K.chartAPI,N=Math,R=N.max, fa=N.round,la=N.tan,ga=N.min,ma=N.PI,ha=K.extend2,Q=this.window,N=K.Raphael,ia=K.graphics,W=ia.convertColor,ja=ia.getLightColor,I=this.raiseEvent,C=K.pluckNumber,F=K.pluck,na=K.each,aa=K.BLANKSTRING,oa="rgba(192,192,192,"+(/msie/i.test(Q.navigator.userAgent)&&!Q.opera?.002:1E-6)+")",Q=!/fusioncharts\.com$/i.test(Q.location.hostname);N.addSymbol({backIcon:function(c,b,d){--d;var a=b+d,g=a-d/2,s=c+d,q=g-d;return["M",c,b-d,"L",c-d,b,c,a,c,g,s,g,s,q,s-d,q,"Z"]},homeIcon:function(c,b,d){--d;var a=2*d, g=c-d,s=g+a/6,q=b+d,D=s+a/4,l=q-d/2,v=D+a/6,t=l+d/2,u=v+a/4,f=t-d;return["M",c,b-d,"L",g,b,s,b,s,q,D,q,D,l,v,l,v,t,u,t,u,f,u+a/6,f,"Z"]}});z.prototype.constructor=z;z.prototype.getCSSconf=function(){return this.cssConf};z.prototype.getPath=function(){return this.path};z.prototype.setPath=function(){var c=this.getParent();this.path=(c?c.getPath():[]).concat(this)};z.prototype.addChild=function(c){c instanceof z&&(this.next=this.next||[],[].push.call(this.next,c),c.setParent(this));return this.next}; z.prototype.getChildren=function(){return this.next};z.prototype.addChildren=function(c,b){var d=this.getChildren()||(this.next=[]),a=d.length;b||(b=a-1);d.splice(b>a-1?a-1:0>b?0:b,0,c);c.setParent(this)};z.prototype.getDepth=function(){return this.meta.depth};z.prototype.isLeaf=function(c){return(c?this.getDepth()<c:!0)&&this.next};z.prototype.setParent=function(c){c instanceof z&&(this.prev=c);return this};z.prototype.getSiblingCount=function(c){var b,d=0,a=this;if(this instanceof z){b=this.getParent(); if(c){for(;a;)(a=a.getSibling(c))&&(d+=1);return d}if(b)return b.getChildren().length}};z.prototype.getParent=function(){return this.prev};z.prototype.getLabel=function(){return this.label};z.prototype.getValue=function(){return this.value};z.prototype.setValue=function(c,b){this.value=b?this.value+c:c};z.prototype.getColorValue=function(){return this.colorValue};z.prototype.getSibling=function(c){c=c.toLowerCase();var b=this.getParent(),d=this.getLabel(),a,g;if(b)for(b=b.getChildren(),a=0;a<b.length;a++)if(g= b[a],g=g.getLabel(),g===d)switch(c){case "left":return b[a-1];case "right":return b[a+1]}};z.prototype.setMeta=function(c,b){this.meta[c]=b};z.prototype.setDepth=function(c){this.meta.depth=c};z.prototype.getMeta=function(c){return c?this.meta[c]:this.meta};M.prototype.constructor=M;M.prototype.resetPointers=function(){this.statePointerLow={value:void 0,index:void 0};this.statePointerHigh={value:void 0,index:void 0}};M.prototype.setRangeOutEffect=function(c,b){this._css=c;this.rangeOurEffectApplyFn= b};M.prototype.addInBucket=function(c){var b=this._b,d=c.getColorValue(),a=0,g=b.length-1;if(d){a:{for(var s,q;a<=g;)if(s=(a+g)/2|0,q=b[s],q=q.getColorValue(),q<d)a=s+1;else if(q>d)g=s-1;else{d=s;break a}d=~g}b.splice(Math.abs(d),0,c)}};M.prototype.moveLowerShadePointer=function(c){var b=this._b,d,a,g,s=this.statePointerLow;d=s.index;a=s.value;var q=!1;d=void 0!==d?d:0;a=void 0!==a?a:Number.NEGATIVE_INFINITY;if(c!==a){if(a<=c){for(;;){g=(a=b[d++])?a.getColorValue():0;if(c<g||!a)break;q=!0;a.rangeOutEffect= this._css;this.rangeOurEffectApplyFn.call(a,this._css)}d=q?d-2:d-1}else{for(;;){g=(a=b[d--])?a.getColorValue():0;if(c>=g||!a)break;a.cssConf=a.cssConf||{};q=!0;delete a.rangeOutEffect;a.cssConf.opacity=1;this.rangeOurEffectApplyFn.call(a,a.cssConf)}d=q?d+2:d+1}s.index=d;s.value=c}};M.prototype.moveHigherShadePointer=function(c){var b=this._b,d=b.length,a,g,s=this.statePointerHigh;g=s.index;a=s.value;var q=!1,d=void 0!==g?g:d-1;a=void 0!==a?a:Number.POSITIVE_INFINITY;if(c!==a){if(a>c){for(;;){g=(a= b[d--])?a.getColorValue():0;if(c>=g||!a)break;q=!0;a.rangeOutEffect=this._css;this.rangeOurEffectApplyFn.call(a,this._css)}d=q?d+2:d+1}else{for(;;){g=(a=b[d++])?a.getColorValue():0;if(c<g||!a)break;a.cssConf=a.cssConf||{};q=!0;delete a.rangeOutEffect;a.cssConf.opacity=1;this.rangeOurEffectApplyFn.call(a,a.cssConf)}d=q?d-2:d-1}s.index=d;s.value=c}};V("treemap",{friendlyName:"TreeMap",standaloneInit:!0,hasGradientLegend:!0,creditLabel:Q,defaultDatasetType:"treemap",applicableDSList:{treemap:!0},addData:function(){var c= this._ref.algorithmFactory,b=Array.prototype.slice.call(arguments,0);b.unshift("addData");b.unshift(this._getCleanValue());c.realTimeUpdate.apply(this,b)},removeData:function(){var c=this._ref.algorithmFactory,b=Array.prototype.slice.call(arguments,0);b.unshift("deleteData");b.unshift(this._getCleanValue());c.realTimeUpdate.apply(this,b)},_createToolBox:function(){var c,b,d,a,g=this.components;c=g.chartMenuBar;c&&c.drawn||(V.mscartesian._createToolBox.call(this),c=g.tb,b=c.getAPIInstances(c.ALIGNMENT_HORIZONTAL), d=b.Symbol,b=g.chartMenuBar.componentGroups[0],a=new d("backIcon",!1,(c.idCount=c.idCount||0,c.idCount++),c.pId),c=new d("homeIcon",!1,c.idCount++,c.pId),b.addSymbol(c,!0),b.addSymbol(a,!0),g.toolbarBtns={back:a,home:c})},_getCleanValue:function(){var c=this.components.numberFormatter;return function(b){return c.getCleanValue(b)}},_createDatasets:function(){var c=this.components,b=this.jsonData,d=b.dataset,d=b.data||d&&d[0].data,a=this.defaultDatasetType,g=[];d&&d.length||this.setChartMessage();na(d, function(a){a.vline||g.push(a)});b={data:g};this.config.categories=g;c=c.dataset||(c.dataset=[]);d?a&&(d=FusionCharts.get("component",["dataset",a]))&&(c[0]?(c[0].JSONData=g[0],c[0].configure()):(this._dsInstance=d=new d,c.push(d),d.chart=this,d.init(b))):this.setChartMessage()},init:function(){var c={},b={},d={};this._ref={afAPI:ca(c,b,d),algorithmFactory:da(c,b,d),containerManager:ea(c,b,d),treeOpt:$};V.guageBase.init.apply(this,arguments)}},V.guageBase);FusionCharts.register("component",["dataset", "TreeMap",{type:"treemap",pIndex:2,customConfigFn:"_createDatasets",init:function(c){this.JSONData=c.data[0];this.components={};this.conf={};this.graphics={elemStore:{rect:[],label:[],highlight:[],hot:[],polypath:[]}};this.configure()},configure:function(){var c,b=this.chart,d=b.components,a=this.conf,b=b.jsonData.chart;a.metaTreeInf={};a.algorithm=(b.algorithm||"squarified").toLowerCase();a.horizontalPadding=C(b.horizontalpadding,5);a.horizontalPadding=0>a.horizontalPadding?0:a.horizontalPadding; a.verticalPadding=C(b.verticalpadding,5);a.verticalPadding=0>a.verticalPadding?0:a.verticalPadding;a.showParent=C(b.showparent,1);a.showChildLabels=C(b.showchildlabels,0);a.highlightParentsOnHover=C(b.highlightparentsonhover,0);a.defaultParentBGColor=F(b.defaultparentbgcolor,void 0);a.defaultNavigationBarBGColor=F(b.defaultnavigationbarbgcolor,a.defaultParentBGColor);a.showTooltip=C(b.showtooltip,1);a.baseFontSize=C(b.basefontsize,10);a.baseFontSize=1>a.baseFontSize?1:a.baseFontSize;a.labelFontSize= C(b.labelfontsize,void 0);a.labelFontSize=1>a.labelFontSize?1:a.labelFontSize;a.baseFont=F(b.basefont,"Verdana, Sans");a.labelFont=F(b.labelfont,void 0);a.baseFontColor=F(b.basefontcolor,"#000000").replace(/^#?([a-f0-9]+)/ig,"#$1");a.labelFontColor=F(b.labelfontcolor,void 0);a.labelFontColor&&(a.labelFontColor=a.labelFontColor.replace(/^#?([a-f0-9]+)/ig,"#$1"));a.labelFontBold=C(b.labelfontbold,0);a.labelFontItalic=C(b.labelfontitalic,0);a.plotBorderThickness=C(b.plotborderthickness,1);a.plotBorderThickness= 0>a.plotBorderThickness?0:5<a.plotBorderThickness?5:a.plotBorderThickness;a.plotBorderColor=F(b.plotbordercolor,"#000000").replace(/^#?([a-f0-9]+)/ig,"#$1");a.tooltipSeparationCharacter=F(b.tooltipsepchar,",");a.plotToolText=F(b.plottooltext,"");a.parentLabelLineHeight=C(b.parentlabellineheight,12);a.parentLabelLineHeight=0>a.parentLabelLineHeight?0:a.parentLabelLineHeight;a.labelGlow=C(b.labelglow,1);a.labelGlowIntensity=C(b.labelglowintensity,100)/100;a.labelGlowIntensity=0>a.labelGlowIntensity? 0:1<a.labelGlowIntensity?1:a.labelGlowIntensity;a.labelGlowColor=F(b.labelglowcolor,"#ffffff").replace(/^#?([a-f0-9]+)/ig,"#$1");a.labelGlowRadius=C(b.labelglowradius,2);a.labelGlowRadius=0>a.labelGlowRadius?0:10<a.labelGlowRadius?10:a.labelGlowRadius;a.btnResetChartTooltext=F(b.btnresetcharttooltext,"Back to Top");a.btnBackChartTooltext=F(b.btnbackcharttooltext,"Back to Parent");a.rangeOutBgColor=F(b.rangeoutbgcolor,"#808080").replace(/^#?([a-f0-9]+)/ig,"#$1");a.rangeOutBgAlpha=C(b.rangeoutbgalpha, 100);a.rangeOutBgAlpha=1>a.rangeOutBgAlpha||100<a.rangeOutBgAlpha?100:a.rangeOutBgAlpha;c=C(b.maxdepth);a.maxDepth=void 0!==c?R(c,1):void 0;c=a.showNavigationBar=C(b.shownavigationbar,1);a.slicingMode=F(b.slicingmode,"alternate");a.navigationBarHeight=C(b.navigationbarheight);a.navigationBarHeightRatio=C(b.navigationbarheightratio);a.navigationBarBorderColor=F(b.navigationbarbordercolor,a.plotBorderColor).replace(/^#?([a-f0-9]+)/ig,"#$1");a.navigationBarBorderThickness=c?C(b.navigationbarborderthickness, a.plotBorderThickness):0;a.seperatorAngle=C(b.seperatorangle)*(ma/180);d.postLegendInitFn({min:0,max:100});a.isConfigured=!0},draw:function(){var c=this.conf,b=this.chart,d=b.config,a=b.components,g=d.canvasLeft,s=d.canvasRight,q=d.canvasBottom,D=d.canvasTop,l=a.paper,v=b.graphics,t=v.trackerGroup,u,f,B,h,n,d=c.metaTreeInf,m=this.graphics.elemStore,x={},p,e,k,a=a.gradientLegend,w,y=b._ref,X=y.afAPI.visibilityController,r=b.get("config","animationObj"),A=r.duration||0,Y=r.dummyObj,O=r.animObj,S=r.animType, Z,ba,E,z,r=y.containerManager,y=y.algorithmFactory;for(f in m){Z=m[f];E=0;for(z=Z.length;E<z;E++)(ba=Z[E])&&ba.remove&&ba.remove();Z.length=0}r.remove();u=v.datasetGroup=v.datasetGroup||l.group("dataset");f=v.datalabelsGroup=v.datalabelsGroup||l.group("datalabels").insertAfter(u);B=v.lineHot=v.lineHot||l.group("line-hot",t);h=v.labelHighlight=v.labelHighlight||l.group("labelhighlight",f);n=v.floatLabel=v.floatLabel||l.group("labelfloat",f).insertAfter(h);c.colorRange=a.colorRange;d.effectiveWidth= s-g;d.effectiveHeight=q-D;d.startX=g;d.startY=D;p=d.effectiveWidth/2;e=d.effectiveHeight/2;p=d.effectiveWidth/2;e=d.effectiveHeight/2;x.drawPolyPath=function(a,e){var c,b;c=(x.graphicPool(!1,"polyPathItem")||(b=l.path(u))).attr({path:a._path}).animateWith(Y,O,{path:a.path},A,S);c.css(e);b&&m.polypath.push(b);return c};x.drawRect=function(a,c,b,d){var n,h,w={},f={},t;for(n in a)h=a[n],0>h&&(a[n]=0,f.visibility="hidden");ha(w,a);w.x=p;w.y=e;w.height=0;w.width=0;k=x.graphicPool(!1,"plotItem")||(t=l.rect(u)); k.attr(b&&(b.x||b.y)&&b||w);k.attr(d);k.animateWith(Y,O,a,A,S,X.controlPostAnimVisibility);k.css(c).toFront();k.css(f);t&&m.rect.push(t);return k};x.drawText=function(a,b,k,d,w){var f={},t,v,r=x.graphicPool(!1,"labelItem")||(t=l.text(n)),y=x.graphicPool(!1,"highlightItem")||(v=l.text(h)),ka=k.textAttrs;k=k.highlightAttrs;ha(f,ka);delete f.fill;f["stroke-linejoin"]="round";r.attr({x:d.x||p,y:d.y||e,fill:"#000000"}).css(ka);r.attr(w);a=0>b.x||0>b.y?aa:a;r.animateWith(Y,O,{text:a,x:b.x,y:b.y},A,S);y.attr({text:a, x:d.x||p,y:d.y||e,stroke:c.labelGlow?"#ffffff":oa}).css(f).css(k);y.attr(w);y.animateWith(Y,O,{x:b.x,y:b.y},A,S);m.label.push(t);m.highlight.push(v);return{label:r,highlightMask:y}};x.drawHot=function(a,c){var e;e=a.plotItem||{};var b=a.rect,k,d,n;for(d in b)n=b[d],0>n&&(b[d]=0);e=e.tracker=l.rect(B).attr(b).attr({cursor:"pointer",fill:"rgba(255, 255, 255, 0)",stroke:"none"});for(k in c)b=c[k],e[k].apply(e,b);m.hot.push(e);return e};x.disposeItems=function(a,e){var c,b,m,k=e||"plotItem labelItem hotItem highlightItem polyPathItem pathlabelItem pathhighlightItem stackedpolyPathItem stackedpathlabelItem stackedpathhighlightItem".split(" "); for(c=0;c<k.length;c+=1)m=k[c],(b=a[m])&&x.graphicPool(!0,m,b,a.rect),b&&b.hide(),a[m]=void 0};x.disposeChild=function(){var a,e=function(){return a.disposeItems},c=function(a,b){var m,k;e(a);for(m=0;m<(a.getChildren()||[]).length;m++)k=a.getChildren(),m=c(k[m],m);return b};return function(b){var m=b.getParent();a||(a=this,e=e());m?a.disposeChild(m):c(b,0)}}();x.graphicPool=function(){var a={};return function(e,c,b){var m=a[c];m||(m=a[c]=[]);"hotItem"!==c&&"pathhotItem"!==c||b.remove();if(e)m.push(b); else if(e=m.splice(0,1)[0])return e.show(),e}}();x.disposeComplimentary=function(a){var e,c;e=a.getParent();var b=a.getSiblingCount("left");e&&(c=e.getChildren(),e=c.splice(b,1)[0],this.disposeChild(a),c.splice(b,0,e));this.removeLayers()};x.removeLayers=function(){var a,e,c,b;c=m.hot;b=c.length;for(a=0;a<b;a++)(e=c[a])&&e.remove();c.length=0};y.init(c.algorithm,!0,c.maxDepth);b=y.plotOnCanvas(this.JSONData,void 0,b._getCleanValue());r.init(this,d,x,void 0,b);r.draw();w=y.applyShadeFiltering({fill:c.rangeOutBgColor, opacity:.01*c.rangeOutBgAlpha},function(a){this.plotItem&&this.plotItem.css(a)});a&&a.enabled&&(a.resetLegend(),a.clearListeners());a.notifyWhenUpdate(function(a,e){w.call(this,{start:a,end:e})},this);c.isConfigured=!1}}]);ca=function(c,b,d){function a(a,c,b){this.node=a;this.bucket=c?new M:void 0;this.cleansingFn=b}var g,s,q,D;a.prototype.get=function(){var a=this.order,c=this.bucket,b=this.cleansingFn;return function f(d,h){var n,m,x,p;m=["label","value","data","svalue"];if(d)for(p in n=new z(d.label, b(d.value),b(d.svalue)),x=d.data||[],0===x.length&&c&&c.addInBucket(n),n.setDepth(h),d)-1===m.indexOf(p)&&n.setMeta(p,d[p]);a&&(x=a(x));for(m=0;m<x.length;m++)p=x[m],p=f(p,h+1),n.addChild(p);return n}(this.node,0)};a.prototype.getBucket=function(){return this.bucket};a.prototype.getMaxDepth=function(){return s};g=function(a,c){function b(a){this.iterAPI=a}var d=c&&c.exception,f,g;b.prototype.constructor=b;b.prototype.initWith=function(a){return this.iterAPI(a)};f=(new b(function(a){var c=a,b=[],x= !1;b.push(c);return{next:function(a){var c,k;if(!x){c=b.shift();if(d&&c===d&&(c=b.shift(),!c)){x=!0;return}(k=(a=void 0!==a?c.getDepth()>=a?[]:c.getChildren():c.getChildren())&&a.length||0)&&[].unshift.apply(b,a);0===b.length&&(x=!0);return c}},reset:function(){x=!1;c=a;b.length=0;b.push(c)}}})).initWith(a);g=(new b(function(a){var c=a,b=[],d=[],f=!1;b.push(c);d.push(c);return{next:function(){var a,c,d;if(!f)return c=b.shift(),(d=(a=c.getChildren())&&a.length||0)&&[].push.apply(b,a),0===b.length&& (f=!0),c},nextBatch:function(){var a,c;if(!f)return a=d.shift(),(c=(a=a.getChildren())&&a.length||0)&&[].push.apply(d,a),0===b.length&&(f=!0),a},reset:function(){f=!1;c=a;b.length=0;b.push(c)}}})).initWith(a);return{df:f,bf:g}};D=function(){function a(){this.con={}}var c={},b;a.prototype.constructor=a;a.prototype.get=function(a){return this.con[a]};a.prototype.set=function(a,c){this.con[a]=c};a.prototype["delete"]=function(a){return delete this.con[a]};return{getInstance:function(d){var f;return(f= c[d])?b=f:b=c[d]=new a}}}();b=function(){var a=[],c,b=!1,d={visibility:"visible"};return{controlPreAnimVisibility:function(d,B){var h,n,m;if(d){for(n=d;;){n=n.getParent();if(!n)break;h=n}h=g(h,{exception:d});for(h=h.df;;){n=h.next();if(!n)break;m=n.overAttr||(n.overAttr={});m.visibility="hidden";a.push(n)}c=B||d.getParent();b=!1;return a}},displayAll:function(d){var B;if(d){d=g(d.getParent()||d);for(d=d.df;;){B=d.next();if(!B)break;B=B.overAttr||(B.overAttr={});B.visibility="visible"}c=void 0;a.length= 0;b=!1}},controlPostAnimVisibility:function(){var f,B;if(!b&&(b=!0,c)){B=g(c);for(B=B.df;;){f=B.next(s);if(!f)break;if(f=f.dirtyNode)f&&f.plotItem.attr(d),(f=f&&f.textItem)&&f.label&&f.label.attr(d),f&&f.label&&f.highlightMask.attr(d)}c=void 0;a.length=0}}}}();c.AbstractTreeMaker=a;c.iterator=g;c.initConfigurationForlabel=function(a,c,b){var d=a.x,f=a.y,g=c/2,h=b.showParent?0:1,n=b.showChildLabels;return function(a,x,p,e){p=!1;var k={x:void 0,y:void 0,width:void 0,height:void 0},w={},y=0,l={},r={}, A,l=a.meta;if(a)return a.isLeaf(s)||(p=!0),w.label=a.getLabel(),k.width=x.width-2*d,k.x=x.x+x.width/2,a=x.height-2*f,!p&&a<c&&(k.height=-1),!e&&p?(k.height=n?k.height?k.height:x.height-2*f:-1,k.y=x.y+x.height/2):h?(k.y=-1,c=f=0,A="hidden"):(k.height=k.height?k.height:c,k.y=x.y+f+g),y+=2*f,y+=c,w.rectShiftY=y,w.textRect=k,b.labelGlow?(r["stroke-width"]=b.labelGlowRadius,r.opacity=b.labelGlowIntensity,r.stroke=b.labelGlowColor,r.visibility="hidden"===A?"hidden":"visible"):r.visibility="hidden",l={fontSize:b.labelFontSize|| b.baseFontSize,fontFamily:b.labelFont||b.baseFont,fill:l&&l.fontcolor&&U(l.fontcolor)||b.labelFontColor||b.baseFontColor,fontWeight:b.labelFontBold&&"bold",fontStyle:b.labelFontItalic&&"italic",visibility:A},{conf:w,attr:l,highlight:r}}};c.context=D;c.mapColorManager=function(a,c,b){var d=U(b?a.defaultNavigationBarBGColor:a.defaultParentBGColor);return function(b,g,h){g={};var n=b.cssConf,m=b.meta,m=m.fillcolor?U(m.fillcolor):void 0,x=b.getParent(),p;p=b.getColorValue();a.isLegendEnabled=!0;p=a.isLegendEnabled&& p===p?c.getColorByValue(p)&&"#"+c.getColorByValue(p)||U(c.rangeOutsideColor):void 0;b.isLeaf(s)?g.fill=m||p||d:(b=(b=(x?x:b).cssConf)&&b.fill,g.fill=m||(p?p:b));g.stroke=h?a.navigationBarBorderColor:a.plotBorderColor;g.strokeWidth=h?a.navigationBarBorderThickness:a.plotBorderThickness;g["stroke-dasharray"]="none";!h&&n&&"--"===n["stroke-dasharray"]&&(g["stroke-dasharray"]=n["stroke-dasharray"],g.strokeWidth=n.strokeWidth);return g}};c.abstractEventRegisterer=function(a,b,g,u){function f(a){var c= {},b,e;for(b in A)e=A[b],c[e]=a[b];return c}var s=b.chart,h=s.components,n=h.toolbarBtns,m=s.chartInstance,x=b.conf,p=h.gradientLegend,e=a.drawTree,k=u.disposeChild,w,y=arguments,X,r,A={colorValue:"svalue",label:"name",value:"value",rect:"metrics"};X=c.context.getInstance("ClickedState");s._intSR={};s._intSR.backToParent=w=function(a){var b=this,d=b,n=d&&b.getParent(),h=c.context.getInstance("ClickedState").get("VisibileRoot")||{};a?I("beforedrillup",{node:b,withoutHead:!x.showParent},m,void 0,function(){n&& (h.state="drillup",h.node=[{virginNode:c.getVisibleRoot()},n],k(d),e.apply(n,y));I("drillup",{node:b,withoutHead:!x.showParent,drillUp:w,drillUpToTop:r},m);b=b&&b.getParent()},function(){I("drillupcancelled",{node:b,withoutHead:!x.showParent},m)}):(n&&(h.state="drillup",h.node=[{virginNode:c.getVisibleRoot()},n],k(d),e.apply(n,y)),b=b&&b.getParent())};s._intSR.resetTree=r=function(a){for(var b=this,d=b&&b.getParent(),n,h=c.context.getInstance("ClickedState").get("VisibileRoot")||{};d;)n=d,d=d.getParent(); a?I("beforedrillup",{node:b,withoutHead:!x.showParent},m,void 0,function(){n&&(h.state="drillup",h.node=[{virginNode:c.getVisibleRoot()},n],k(n),e.apply(n,y),I("drillup",{node:b,sender:s.fusionCharts,withoutHead:!x.showParent,drillUp:w,drillUpToTop:r},m))},function(){I("drillupcancelled",{node:b,withoutHead:!x.showParent},m)}):n&&(h.state="drillup",h.node=[{virginNode:c.getVisibleRoot()},n],k(n),e.apply(n,y))};return{click:function(b,c){var e=b.virginNode,h,y,g;I("dataplotclick",f(b.virginNode),m); if(y=e.getParent()){if(e===c)g=y,h="drillup";else{if(e.next)g=e;else if(g=y,c===g){h=void 0;return}h="drilldown"}p&&p.enabled&&p.resetLegend();a.applyShadeFiltering.reset();h&&I("before"+h,{node:g,withoutHead:!x.showParent},m,void 0,function(){X.set("VisibileRoot",{node:b,state:h});k.call(u,g);q=g;d.draw();I(h,{node:g,withoutHead:!x.showParent,drillUp:w,drillUpToTop:r},m)},function(){I(h+"cancelled",{node:g,withoutHead:!x.showParent},m)});n.back&&n.back.attachEventHandlers({click:w.bind(g)});n.home&& n.home.attachEventHandlers({click:r.bind(g)})}},mouseover:function(a){var b=f(a.virginNode);I("dataplotrollover",b,m,void 0,void 0,function(){I("dataplotrollovercancelled",b,m)})},mouseout:function(a){var b=f(a.virginNode);I("dataplotrollout",f(a.virginNode),m,void 0,void 0,function(){I("dataplotrolloutcancelled",b,m)})}}};c.setMaxDepth=function(a){return s=a};c.getVisibleRoot=function(){return q};c.setVisibleRoot=function(a){q=a};c.visibilityController=b;return c};da=function(c,b){function d(){D.apply(this, arguments)}function a(a,b,m){v=new d(a,u,b);a=v.get();!1!==m&&(t=a);c.setVisibleRoot(a);return a}function g(){var a=q[l],d;b.realTimeUpdate=s.apply(this,arguments);d=Array.prototype.slice.call(arguments,0);d.unshift(a);a.drawTree.apply(c.getVisibleRoot(),d)}function s(){var a,b,c=q[l];b=Array.prototype.slice.call(arguments,0);b.unshift(c);a=b.slice(-1)[0];return function(){var d=Array.prototype.slice.call(arguments,0),p=d.shift(),e=d.shift();$(t,function(a){c.drawTree.apply(a||t,b)},a,p)[e].apply(this, d)}}var q,D=c.AbstractTreeMaker,l,v,t,u,f,B;q={sliceanddice:{areaBaseCalculator:function(a,b){return function(c,d,p){var e,k,w={},y,g,r,f=e=0;if(c){p&&(e=p.textMargin||e);f=e;p=c.getParent();e=c.getSibling("left");if(p){k=p.getValue();r=p.rect;y=r.height-2*b-f;g=r.width-2*a;w.effectiveRect={height:y,width:g,x:r.x+a,y:r.y+b+f};w.effectiveArea=y*g;w.ratio=c.getValue()/k;if(e)return d.call(c,w,e,p);w.lastIsParent=!0;return d.call(c,w,p)}return null}}},applyShadeFiltering:function(a,b,c){a.setRangeOutEffect(b, c);this.applyShadeFiltering.reset=function(){a.resetPointers()};return function(b){a.moveLowerShadePointer(b.start);a.moveHigherShadePointer(b.end)}},alternateModeManager:function(){return function(a,b){var c,d,g,e,k,w=a.effectiveArea*a.ratio;d=a.effectiveRect;var y=b.rect;a.lastIsParent?(e=d.x,k=d.y,c=d.height,d=d.width,g=this.isDirectionVertical=!0):(c=d.height+d.y-(y.height+y.y),d=d.width+d.x-(y.width+y.x),g=this.isDirectionVertical=!b.isDirectionVertical);g?(d=w/c,e=void 0!==e?e:y.x,k=void 0!== k?k:y.y+y.height):(c=w/d,e=void 0!==e?e:y.x+y.width,k=void 0!==k?k:y.y);return{height:c,width:d,x:e,y:k}}},horizontalVerticalManager:function(a){var b=Boolean("vertical"===a?!0:!1);return function(a,c,d){var e,k,w,g=a.effectiveArea*a.ratio,h=a.effectiveRect,f=c.rect;a.lastIsParent?(k=h.x,w=h.y,a=h.height,e=h.width,c=this.isDirectionVertical=!c.isDirectionVertical):(a=h.height+h.y-(f.height+f.y),e=h.width+h.x-(f.width+f.x),c=this.isDirectionVertical=!d.isDirectionVertical);(c=b?c:!c)?(0===a&&(a=h.height, k=void 0!==k?k:f.x+f.width,w=void 0!==w?w:f.y),e=g/a,k=void 0!==k?k:f.x,w=void 0!==w?w:f.y+f.height):(0===e&&(e=h.width,k=void 0!==k?k:f.x,w=void 0!==w?w:f.y+f.height),a=g/e,k=void 0!==k?k:f.x+f.width,w=void 0!==w?w:f.y);return{height:a,width:e,x:k,y:w}}},drawTree:function(a,b,d,g){var p=b.chart,e=p.components,k=e.numberFormatter,e=e.toolbarBtns,w=g.drawRect,y=g.drawText,v=g.drawHot,r=d.horizontalPadding,A=d.verticalPadding,t=b.chart.linkedItems.smartLabel,l=c.iterator,s=l(this).df,q,u=a.areaBaseCalculator(r, A),E=b.conf,D=E.highlightParentsOnHover,z,C=c.context,r=c.visibilityController,L=c.mapColorManager(E,b.conf.colorRange),A=c.abstractEventRegisterer.apply(c,arguments),F=A.click,I=A.mouseover,G=A.mouseout,A=E.slicingMode,J=a["alternate"===A?"alternateModeManager":"horizontalVerticalManager"](A),A=p._intSR,H,l=C.getInstance("ClickedState").get("VisibileRoot")||{};(H=l.node)&&l.state&&("drillup"===l.state.toLowerCase()?H instanceof Array?r.controlPreAnimVisibility(H[0].virginNode,H[1]):r.controlPreAnimVisibility(H.virginNode): r.displayAll(l.node.virginNode));z=c.initConfigurationForlabel({x:5,y:5},E.parentLabelLineHeight,E);for(r=q=s.next(B=c.setMaxDepth(this.getDepth()+f));r.getParent();)r=r.getParent();E.showNavigationBar?(e.home.hide(),e.back.hide()):r!=q?(e.home.show(),e.back.show()):(e.home.hide(),e.back.hide());t.useEllipsesOnOverflow(p.config.useEllipsesWhenOverflow);t.setStyle(E._setStyle={fontSize:(E.labelFontSize||E.baseFontSize)+"px",fontFamily:E.labelFont||E.baseFont,lineHeight:1.2*(E.labelFontSize||E.baseFontSize)+ "px"});p=A.backToParent;r=A.resetTree;e.back&&e.back.attachEventHandlers({click:p.bind(q)});e.home&&e.home.attachEventHandlers({click:r.bind(q)});(function P(a,b){var c,d,e,n,m,f,h,p;f={};var r,l,A={},O={};h={};var H="",M,N;a&&(M=k.yAxis(a.getValue()),N=k.sYAxis(a.getColorValue()),a.setPath(),c=a.rect||{},d=a.textRect||{},e=a.rect={},h=a.textRect={},e.width=b.width,e.height=b.height,e.x=b.x,e.y=b.y,h=L(a),(l=a.plotItem)&&g.graphicPool(!0,"plotItem",l,c),l=a.plotItem=w(e,h,c,a.overAttr),a.cssConf= h,p=z(a,e),n=p.conf,f.textMargin=n.rectShiftY,h=a.textRect=n.textRect,r=t.getSmartText(n.label,h.width,h.height).text,a.plotItem=l,(n=a.labelItem)?(m=a.highlightItem,g.graphicPool(!0,"labelItem",n,c),g.graphicPool(!0,"highlightItem",m,c)):d=d||{},d=y(r,h,{textAttrs:p.attr,highlightAttrs:p.highlight},d,a.overAttr),a.labelItem=d.label,a.highlightItem=d.highlightMask,A.virginNode=a,A.plotItem=l,A.textItem=d,A.virginNode.dirtyNode=A,a.getColorValue()&&(H=E.tooltipSeparationCharacter+N),A.toolText=K.parseTooltext(E.plotToolText, [1,2,3,119,122],{label:a.getLabel(),formattedValue:M,formattedsValue:N},{value:a.getValue(),svalue:a.getColorValue()})||a.getLabel()+E.tooltipSeparationCharacter+M+H,A.rect=e,O.hover=[function(){var a,b,c;c=C.getInstance("hover");b=this.virginNode;a=D&&!b.next?(a=b.getParent())?a:b:this.virginNode;c.set("element",a);c=W(ja(a.cssConf.fill,80),60);a.plotItem.tracker.attr({fill:c});I(this)}.bind(A),function(){var a,b;a=C.getInstance("hover").get("element");b=W(a.cssConf.fill||"#fff",0);a.plotItem.tracker.attr({fill:b}); G(this)}.bind(A)],O.tooltip=[A.toolText],O.click=[function(){F(this,q)}.bind(A)],(e=a.hotItem)&&g.graphicPool(!0,"hotItem",e,c),e=a.hotItem=v(A,O),c=s.next(B),f=u(c,J,f),P(c,f))})(q,d)}},squarified:{orderNodes:function(){return this.sort(function(a,b){return parseFloat(a.value,10)<parseFloat(b.value,10)?1:-1})},areaBaseCalculator:function(a,b){return function(c,d,f){var e={},k,w=k=0,g,l;if(c&&0!==c.length)return f&&(k=f.textMargin||k),w=k,g=c[0],(c=g.getParent())?(l=c.rect,f=l.height-2*b-w,k=l.width- 2*a,e.effectiveRect={height:f,width:k,x:l.x+a,y:l.y+b+w},e.effectiveArea=f*k,d.call(g,e,c)):null}},layoutManager:function(){function a(b,c){this.totalValue=c;this._rHeight=b.height;this._rWidth=b.width;this._rx=b.x;this._ry=b.y;this._rTotalArea=b.height*b.width;this.nodes=[];this._prevAR=void 0;this._rHeight<this._rWidth&&(this._hSegmented=!0)}a.prototype.constructor=a;a.prototype.addNode=function(a){var b=this._rTotalArea,c,d,e,k,f,g,h,r=this._hSegmented,l=this._rx,v=this._ry,t,s,q,u,E=0;this.nodes.push(a); e=0;for(d=this.nodes.length;e<d;e++)E+=parseFloat(this.nodes[e].getValue(),10);c=E/this.totalValue*b;r?(b=this._rHeight,d=c/b,t=l+d,s=v,q=this._rHeight,u=this._rWidth-d):(d=this._rWidth,b=c/d,t=l,s=v+b,q=this._rHeight-b,u=this._rWidth);e=0;for(k=this.nodes.length;e<k;e++)a=this.nodes[e],f=a.getValue(),g=f/E*c,a.hRect=a.rect||{},a._hRect=a._rect||{},f=a.rect={},r?(f.width=h=d,f.height=h=g/h,f.x=l,f.y=v,v+=h):(f.height=h=b,f.width=h=g/h,f.x=l,f.y=v,l+=h),g=R(f.height,f.width),f=ga(f.height,f.width), a.aspectRatio=g/f;if(1<this.nodes.length){if(this.prevAR<a.aspectRatio){this.nodes.pop().rect={};e=0;for(d=this.nodes.length;e<d;e++)this.nodes[e].rect=1===d&&this.nodes[e].firstPassed?this.nodes[e]._hRect:this.nodes[e].hRect,r=this.nodes[e]._rect={},l=this.nodes[e].rect,r.width=l.width,r.height=l.height,r.x=l.x,r.y=l.y;return!1}}else a&&(r=a._rect={},l=a.rect,r.width=l.width,r.height=l.height,r.x=l.x,r.y=l.y,a.firstPassed=!0);this.prevAR=a.aspectRatio;this.height=b;this.width=d;this.getNextLogicalDivision= function(){return{height:q,width:u,x:t,y:s}};return a};return{RowLayout:a}}(),applyShadeFiltering:function(a,b,c){a.setRangeOutEffect(b,c);this.applyShadeFiltering.reset=function(){a.resetPointers()};return function(b){a.moveLowerShadePointer(b.start);a.moveHigherShadePointer(b.end)}},drawTree:function(a,b,d,g){var l=b.chart,e=l.components,k=e.numberFormatter,e=e.toolbarBtns,w=a.areaBaseCalculator(d.horizontalPadding,d.verticalPadding),y=a.layoutManager.RowLayout,v=b.chart.linkedItems.smartLabel, r=g.drawRect,t=g.drawText,s=g.drawHot,q=c.iterator,u=q(this).bf,z,D=b.conf,E=D.highlightParentsOnHover,C,F=c.context,I=c.mapColorManager(D,b.conf.colorRange),q=c.abstractEventRegisterer.apply(c,arguments),L=q.click,M=q.mouseover,N=q.mouseout,q=l._intSR,G=c.visibilityController,J,H;J=F.getInstance("ClickedState").get("VisibileRoot")||{};(H=J.node)&&J.state&&("drillup"===J.state.toLowerCase()?H instanceof Array?G.controlPreAnimVisibility(H[0].virginNode,H[1]):G.controlPreAnimVisibility(H.virginNode): G.displayAll(J.node.virginNode));C=c.initConfigurationForlabel({x:5,y:5},D.parentLabelLineHeight,D);for(u=z=u.next(B=c.setMaxDepth(this.getDepth()+f));u.getParent();)u=u.getParent();D.showNavigationBar?(e.home.hide(),e.back.hide()):u!=z?(e.home.show(),e.back.show()):(e.home.hide(),e.back.hide());v.useEllipsesOnOverflow(l.config.useEllipsesWhenOverflow);v.setStyle(D._setStyle={fontSize:(D.labelFontSize||D.baseFontSize)+"px",fontFamily:D.labelFont||D.baseFont,lineHeight:1.2*(D.labelFontSize||D.baseFontSize)+ "px"});l=q.backToParent;q=q.resetTree;e.back&&e.back.attachEventHandlers({click:l.bind(z)});e.home&&e.home.attachEventHandlers({click:q.bind(z)});(function P(a,b){var c,d={},e,f,h,l,m,n,q=0,p,u,G,H;n={};var J;p={};u={};l={};var O="",S,R;if(a){S=k.yAxis(a.getValue());R=k.sYAxis(a.getColorValue());a.setPath();if(c=a.__initRect)d.x=c.x,d.y=c.y,d.width=c.width,d.height=c.height;h=a.textRect||{};c=a.rect=a.__initRect={};l=a.textRect={};c.width=b.width;c.height=b.height;c.x=b.x;c.y=b.y;l=I(a);(G=a.plotItem)&& g.graphicPool(!0,"plotItem",G,d);G=a.plotItem=r(c,l,d,a.overAttr);a.cssConf=l;J=C(a,c);e=J.conf;n.textMargin=e.rectShiftY;l=a.textRect=e.textRect;H=v.getSmartText(e.label,l.width,l.height).text;(f=a.labelItem)?(e=a.highlightItem,g.graphicPool(!0,"labelItem",f,d),g.graphicPool(!0,"highlightItem",e,d)):h=h||{};h=t(H,l,{textAttrs:J.attr,highlightAttrs:J.highlight},h,a.overAttr);a.labelItem=h.label;a.highlightItem=h.highlightMask;a.plotItem=G;p.virginNode=a;p.plotItem=G;p.textItem=h;p.virginNode.dirtyNode= p;a.getColorValue()&&(O=D.tooltipSeparationCharacter+R);p.toolText=D.showTooltip?K.parseTooltext(D.plotToolText,[1,2,3,119,122],{label:a.getLabel(),formattedValue:S,formattedsValue:R},{value:a.getValue(),svalue:a.getColorValue()})||a.getLabel()+D.tooltipSeparationCharacter+S+O:aa;p.rect=c;u.hover=[function(){var a,b,c;c=F.getInstance("hover");b=this.virginNode;a=E&&!b.next?(a=b.getParent())?a:b:this.virginNode;c.set("element",a);c=a.cssConf;c=W(c.fill&&ja(c.fill,80),60);a.plotItem.tracker.attr({fill:c}); M(this)}.bind(p),function(){var a,b;a=F.getInstance("hover").get("element");b=W(a.cssConf.fill||"#fff",0);a.plotItem.tracker.attr({fill:b});N(this)}.bind(p)];u.tooltip=[p.toolText];u.click=[function(){L(this,z)}.bind(p)];(c=a.hotItem)&&g.graphicPool(!0,"hotItem",c,d);c=a.hotItem=s(p,u);if(m=void 0!==B?a.getDepth()>=B?void 0:a.getChildren():a.getChildren())for(p=w(m,function(a,b){var c,d,e=0,k,f,g=[];c=new y({width:a.effectiveRect.width,height:a.effectiveRect.height,x:a.effectiveRect.x,y:a.effectiveRect.y}, b.getValue());for(d=m.length;e++!==d;)k=m[e-1],f=c.addNode(k),!1===f?(c=c.getNextLogicalDivision(),c=new y(c,b.getValue()-q),e--):(q+=parseFloat(k.getValue(),10),g.push(k));return g},n),d=0,n=p.length;d<n;d++)u=p[d],P(u,u.rect)}})(z,d)}}};d.prototype=Object.create(D.prototype);d.prototype.constructor=D;d.prototype.order=function(a){var b=q[l],c=b.orderNodes;return c?c.apply(a,[b]):a};b.init=function(a,b,d){l=a;u=b;f=c.setMaxDepth(d);return q[l]};b.plotOnCanvas=function(b,c,d){t=a(b,d);return g};b.applyShadeFiltering= function(a,b){var c,d;d=q[l].applyShadeFiltering(v.getBucket(),a,b);return function(a){c=Array.prototype.slice.call(arguments,0);c.unshift(a);d.apply(v.getBucket(),c)}};b.setTreeBase=function(a){return a&&(t=a)};b.realTimeUpdate=s;b.makeTree=a;return b};$=function(c,b,d,a){function g(a){var b,d=0;b=c;if(!a.length)return c;for(;b;){b=s.call(b,a[d]);if(d===a.length-1&&b)return q=b.getValue(),b;d+=1}}function s(a){var b,c,d,g=this.getChildren()||[],f=g.length;for(b=0;b<f;b+=1)if(d=g[b],d.label.toLowerCase().trim()=== a.toLowerCase().trim()){c=d;break}return c}var q;return{deleteData:function(a,c){var v=g(a),t=(void 0).iterator(v).df,u=v&&v.getParent(),f=v&&v.getSiblingCount("left"),s=u&&u.getChildren(),h=(void 0).getVisibleRoot();if(v&&u){s.splice(f,1);for(v===h&&(h=v.getParent()||h);v;)d.disposeItems(v),v=t.next();for(;u;)u.setValue(-q,!0),u=u.getParent();c&&b(h)}},addData:function(c,d,q,t){for(var u,f,s,h=0,n=!0,m=(void 0).getVisibleRoot();c.length;)if(u=c.pop(),u=(void 0).makeTree(u,a,!1),h=u.getValue(),f= g(d||[]))for(f.getChildren()||(s=f.getValue(),n=!1),f.addChildren(u,t);f;)f.setValue(h,n),s&&(h-=s,s=void 0,n=!0),f=f.getParent();q&&b(m)}}};ea=function(c,b,d){function a(){}function g(a){var b=t.plotBorderThickness;l.apply(c.getVisibleRoot(),[z,{width:a.effectiveWidth,height:a.effectiveHeight,x:a.startX,y:a.startY,horizontalPadding:t.horizontalPadding,verticalPadding:t.verticalPadding},u]);t.plotBorderThickness=b}function s(a,b,c){var d=a.width,f=a.height,g=t.seperatorAngle/2;a=["M",a.x,a.y];var h= C(g?f/2*(1-la(g)):c,15);c=function(a){return{both:["h",d,"v",a,"h",-d,"v",-a],right:["h",d,"v",a,"h",-d,"l",h,-a/2,"l",-h,-a/2],no:["h",d,"l",h,a/2,"l",-h,a/2,"h",-d,"l",h,-a/2,"l",-h,-a/2],left:["h",d,"l",h,a/2,"l",-h,a/2,"h",-d,"v",-a]}};return{path:a.concat(c(f)[b]),_path:a.concat(c(0)[b]),offset:h}}function q(){var a=Array.prototype.splice.call(arguments,0);a.push(!0);h("navigationBar").apply(this,a)}var z,l,v,t,u,f,B=function(a,b){var f,g,h=c.mapColorManager(t,t.colorRange,!0),l=function(){var a; return{get:function(b,c,d){var e={y:b.startY,height:b.effectiveHeight};c=f[c];var k=c.getParent();e.x=a||(a=b.startX);a=d?a+(e.width=b.effectiveWidth*(c.getValue()/k.getValue())):a+(e.width=b.effectiveWidth/g);return e},resetAllocation:function(){a=void 0}}}(),m=c.initConfigurationForlabel({x:5,y:5},t.parentLabelLineHeight,t),p=u.drawPolyPath,q=u.drawText,C=u.drawHot,B={navigationHistory:{path:"polyPathItem",label:"pathlabelItem",highlightItem:"pathhighlightItem",hotItem:"pathhotItem"}},F=z.chart, E=F.components.gradientLegend,F=F.linkedItems.smartLabel,I=function(a){return function(){var b=c.context.getInstance("ClickedState").get("VisibileRoot")||{};b.state="drillup";b.node=[{virginNode:c.getVisibleRoot()},a];E&&E.enabled&&E.resetLegend();d.draw([a,a,a])}},M=function(){return function(){}},N=function(){return function(){}},L,K,T,G,J,H,Q=t._setStyle,P;L=n.get().navigationBar;G=2*x("navigationBar");Q=ga(L*v.effectiveHeight-(G+6),Q.fontSize.replace(/\D+/g,""));L=Q+"px";B.stacked={path:"stacked"+ B.navigationHistory.path,label:"stacked"+B.navigationHistory.label,highlightItem:"stacked"+B.navigationHistory.highlightItem,hotItem:"stacked"+B.navigationHistory.hotItem};l.resetAllocation();(function(a){var b=c.getVisibleRoot();f=a?b.getChildren():b.getPath()||[].concat(b);f.pop();g=f.length})(b);F.setStyle({fontSize:L,lineHeight:L});for(L=0;L<g;L+=1)G=f[L],J=l.get(a,L,b),K=(T=s(J,b?"both":1===g?"both":0===L?"left":L<g-1?"no":"right")).offset,G[B[b?"stacked":"navigationHistory"].path]=p(T,h(G,!0, !0),L),T=m(G,J,!1,!0),H=T.conf,P=H.textRect,P.width-=2*K,P.y=J.y+J.height/2,K=F.getSmartText(H.label,P.width,R(Q,P.height)).text,K=q(K,P,{textAttrs:T.attr,highlightAttrs:T.highlight},{y:J.height/10,"font-size":t._setStyle.fontSize,"font-family":t._setStyle.fontFamily},(b?"stacked":"")+"path"),G[B[b?"stacked":"navigationHistory"].label]=K.label,G[B[b?"stacked":"navigationHistory"].highlightItem]=K.highlightMask,G[B[b?"stacked":"navigationHistory"].hotItem]=C({rect:J},{click:[I(G,b)],hover:[M(G),N()], tooltip:[t.showTooltip?G.getLabel():aa]})},h=function(a){return{treeMap:g,navigationBar:B,stackedNavigation:q}[a]},n=function(){var a={treeMap:1,navigationBar:0,stackedNavigation:0};return{set:function(b){var c=C(t.navigationBarHeightRatio,t.navigationBarHeight/v.effectiveHeight,.15),d=t.labelFontSize?R(t.labelFontSize,t.baseFontSize):t.baseFontSize,f=2*x("navigationBar"),c=R((6+d+f)/v.effectiveHeight,c);.1>c?c=.1:.15<c&&(c=.15);t.navigationBarHeightRatio=c;a=b?{treeMap:1-c,navigationBar:c,stackedNavigation:0}: {treeMap:1,navigationBar:0,stackedNavigation:0}},get:function(){return a}}}(),m=0,x=function(a){var b=t.plotBorderThickness,c=t.navigationBarBorderThickness;return t.verticalPadding+("navigationBar"===a?c:b)},p=function(a){var b=v.effectiveWidth,c=v.effectiveHeight,d=x(a);a=n.get()[a];1<=m&&(m=0);m+=a;return{effectiveHeight:fa(a*c*100)/100-d,effectiveWidth:b,startX:v.startX,startY:v.startY+d+fa((m-a)*c*100)/100}};a.prototype.constructor=a;a.prototype.init=function(a,b){(this.conf||(this.conf={})).name= a.name;this.setDrawingArea(a.drawingAreaMeasurement);this.draw=this.draw(b)};a.prototype.setDrawingArea=function(a){this.conf.drawingAreaMeasurement=a};a.prototype.draw=function(a){return function(){var b=this.conf;0<b.drawingAreaMeasurement.effectiveHeight&&a(b.drawingAreaMeasurement)}};a.prototype.eventCallback=function(){};f=function(){var b=[];return{get:function(){return b},set:function(c){var d;c?(d=new a,d.init({name:c.type,drawingAreaMeasurement:c.drawingArea},c.drawFn),b.push(d)):b.length= 0;return b}}}();d.init=function(){var a,b=["navigationBar","treeMap","stackedNavigation"];a=Array.prototype.slice.call(arguments,0);z=a[0];v=a[1];t=z.conf;u=a[2];l=a[4];for(f.get().length>=b.length&&f.set();b.length;)a=b.shift(),f.set({type:a,drawFn:h(a),drawingArea:p(a)})};d.draw=function(a){var b,g,h;b=c.getVisibleRoot();u.disposeChild(b);a&&(b=a[1]);b.getParent()?t.showNavigationBar&&d.heightProportion.set(!0):d.heightProportion.set(!1);g=f.get();for(b=0;b<g.length;b+=1)h=g[b],h.setDrawingArea(p(h.conf.name)), a&&c.setVisibleRoot(a[b]),h.draw()};d.heightProportion=n;d.remove=function(){var a=c.getVisibleRoot();a&&u.disposeChild(a)};return d}}]);
whadever/ezpz_2
js/fusioncharts.treemap.js
JavaScript
mit
37,676
var lightstep = require("../../../.."); var FileTransport = require("../../../util/file_transport"); var path = require('path'); var reportFilename = path.join(__dirname, "../../../results/on_exit_child.json"); Tracer = new lightstep.Tracer({ access_token : "{your_access_token}", component_name : "lightstep-tracer/unit-test/on_exit", override_transport : new FileTransport(reportFilename), }); for (var i = 0; i < 10; i++) { var span = Tracer.startSpan("test_span_" + i); span.log({"log_index" : i}); span.finish(); }
lightstephq/lightstep-tracer-javascript
test/suites/node/on_exit/child.js
JavaScript
mit
557
/* RequireJS Module Dependency Definitions */ define([ 'app', 'jquery', 'marionette', 'handlebars', 'collections/TopBarMessagesCollection', 'text!templates/main_topbar.html', 'foundation-reveal', 'foundation-topbar' ], function (App, $, Marionette, Handlebars, TopBarMessagesCollection, template){ "use strict"; return Marionette.ItemView.extend({ //Template HTML string template: Handlebars.compile(template), collection: new TopBarMessagesCollection(), initialize: function(options){ this.options = options; }, events: { "click #logoutButton": "logout", "click #topbar_settingsButton": "settingsShow", "click #topbar_profileButton": "myprofileShow", "click #topbar_message-seeall": "messageSeeall", "click #topbar_forumsButton": "forumsShow", "click #topbar_leaderboardsButton": "leaderboardsShow", "click #topbar_announcementsButton": "announcementsShow", "click #topbar_adminButton": "adminShow", "mouseenter #topbar_messageButton,#topbar_messageContainer": "messagesShow", "mouseleave #topbar_messageButton,#topbar_messageContainer": "messagesHide", "click li.name": "getMessages" }, onRender: function(){ this.getMessages(); }, onBeforeDestroy: function() { this.unbind(); }, getMessages: function(event){ if(event){ event.stopPropagation(); event.preventDefault(); } var self = this; $.ajax({ url: '/api/messages/chat/?username='+App.session.user.get('username'), type: 'GET', contentType: 'application/json', dataType: 'json', crossDomain: true, xhrFields: { withCredentials: true }, success: function(data){ self.collection.reset(); self.collection.add(data, {merge: true}); var html = self.template(self.collection.toJSON()); html += self.template({messageCount:self.collection.length}); html += self.template($.extend({messageCount:self.collection.length},App.session.user.toJSON())); self.$el.html(html); $(document).foundation('reflow'); }, error: function(data){ console.log(data); } }); }, messagesShow: function() { this.$("#topbar_messageContainer").show(); }, messagesHide: function() { this.$("#topbar_messageContainer").hide(); }, messageSeeall: function(){ this.triggerMethod("click:messages:show"); }, detectUserAgent: function() { var userAgent; var fileType; if(navigator.userAgent.match(/Android/g)) { userAgent = "You are using an Android"; fileType = ".apk"; } else if(navigator.userAgent.match(/iPhone/g)){ userAgent = "iPhone"; fileType = ".ipa"; } else if(navigator.userAgent.match(/Windows/g)){ userAgent = "Windows"; fileType = ".exe"; } else if(navigator.userAgent.match(/Mac/g)){ userAgent = "Mac"; fileType = ".dmg"; } else if(navigator.userAgent.match(/Linux/g)){ userAgent = "Linux"; fileType = ".deb"; } this.$el.find("#modalPlatform").html("You have the following OS: "+userAgent); this.$el.find("#modalDownload").html("Download the "+fileType+" on the right to begin playing the game! -->"); this.$el.find("#myModal").foundation('reveal','open'); }, settingsShow: function(){ this.triggerMethod("click:settings:show"); }, myprofileShow: function(){ this.triggerMethod("click:myprofile:show"); }, forumsShow: function(){ this.triggerMethod("click:forums:show"); }, leaderboardsShow: function(){ this.triggerMethod("click:leaderboards:show"); }, announcementsShow: function(){ this.triggerMethod("click:announcements:show"); }, adminShow: function() { this.triggerMethod("click:admin:show"); }, logout: function(event) { if(event){ event.stopPropagation(); event.preventDefault(); } App.session.logout({ },{ success: function(){ console.log("Logged out"); Backbone.history.navigate('home', {trigger: true}); }, error: function() { console.log("Logged out failed"); } }); } }); });
evanyc15/Fort-Nitta
backend/static/js/app/views/Main_TopBarView.js
JavaScript
mit
4,082
module.exports = function(grunt) { "use strict"; var fs = require('fs'), pkginfo = grunt.file.readJSON("package.json"); grunt.initConfig({ pkg: pkginfo, meta: { banner: "/*! <%= pkg.title %> <%= pkg.version %> | <%= pkg.homepage %> | (c) 2014 YOOtheme | MIT License */" }, jshint: { src: { options: { jshintrc: "src/.jshintrc" }, src: ["src/js/*.js"] } }, less: (function(){ var lessconf = { "docsmin": { options: { paths: ["docs/less"], cleancss: true }, files: { "docs/css/uikit.docs.min.css": ["docs/less/uikit.less"] } } }, themes = []; //themes ["default", "custom"].forEach(function(f){ if(grunt.option('quick') && f=="custom") return; if(fs.existsSync('themes/'+f)) { fs.readdirSync('themes/'+f).forEach(function(t){ var themepath = 'themes/'+f+'/'+t, distpath = f=="default" ? "dist/css" : themepath+"/dist"; // Is it a directory? if (fs.lstatSync(themepath).isDirectory() && t!=="blank" && t!=='.git') { var files = {}; if(t=="default") { files[distpath+"/uikit.css"] = [themepath+"/uikit.less"]; } else { files[distpath+"/uikit."+t+".css"] = [themepath+"/uikit.less"]; } lessconf[t] = { "options": { paths: [themepath] }, "files": files }; var filesmin = {}; if(t=="default") { filesmin[distpath+"/uikit.min.css"] = [themepath+"/uikit.less"]; } else { filesmin[distpath+"/uikit."+t+".min.css"] = [themepath+"/uikit.less"]; } lessconf[t+"min"] = { "options": { paths: [themepath], cleancss: true}, "files": filesmin }; themes.push({ "path":themepath, "name":t, "dir":f }); } }); } }); //addons themes.forEach(function(theme){ if(fs.existsSync(theme.path+'/uikit-addons.less')) { var name = (theme.dir == 'default' && theme.name == 'default') ? 'uikit.addons' : 'uikit.'+theme.name+'.addons', dest = (theme.dir == 'default') ? 'dist/css/addons' : theme.path+'/dist/addons'; lessconf["addons-"+theme.name] = {options: { paths: ['src/less/addons'] }, files: {} }; lessconf["addons-"+theme.name].files[dest+"/"+name+".css"] = [theme.path+'/uikit-addons.less']; lessconf["addons-min-"+theme.name] = {options: { paths: ['src/less/addons'], cleancss: true }, files: {} }; lessconf["addons-min-"+theme.name].files[dest+"/"+name+".min.css"] = [theme.path+'/uikit-addons.less']; } }); return lessconf; })(), copy: { fonts: { files: [{ expand: true, cwd: "src/fonts", src: ["*"], dest: "dist/fonts/" }] } }, concat: { dist: { options: { separator: "\n\n" }, src: [ "src/js/core.js", "src/js/utility.js", "src/js/touch.js", "src/js/alert.js", "src/js/button.js", "src/js/dropdown.js", "src/js/grid.js", "src/js/modal.js", "src/js/offcanvas.js", "src/js/nav.js", "src/js/tooltip.js", "src/js/switcher.js", "src/js/tab.js", "src/js/scrollspy.js", "src/js/smooth-scroll.js", "src/js/toggle.js", ], dest: "dist/js/uikit.js" } }, usebanner: { dist: { options: { position: 'top', banner: "<%= meta.banner %>\n" }, files: { src: [ 'dist/css/**/*.css', 'dist/js/**/*.js' ] } } }, uglify: { distmin: { options: { //banner: "<%= meta.banner %>\n" }, files: { "dist/js/uikit.min.js": ["dist/js/uikit.js"] } }, addonsmin: { files: (function(){ var files = {}; fs.readdirSync('src/js/addons').forEach(function(f){ if(f.match(/\.js/)) { var addon = f.replace(".js", ""); grunt.file.copy('src/js/addons/'+f, 'dist/js/addons/'+addon+'.js'); files['dist/js/addons/'+addon+'.min.js'] = ['src/js/addons/'+f]; } }); return files; })() } }, compress: { dist: { options: { archive: ("dist/uikit-"+pkginfo.version+".zip") }, files: [ { expand: true, cwd: "dist/", src: ["css/*", "js/*", "fonts/*", "addons/**/*"], dest: "" } ] } }, watch: { src: { files: ["src/**/*.less", "themes/**/*.less","src/js/*.js"], tasks: ["build"] } } }); grunt.registerTask('indexthemes', 'Rebuilding theme index.', function() { var themes = []; ["default", "custom"].forEach(function(f){ if(fs.existsSync('themes/'+f)) { fs.readdirSync('themes/'+f).forEach(function(t){ var themepath = 'themes/'+f+'/'+t; // Is it a directory? if (fs.lstatSync(themepath).isDirectory() && t!=="blank" && t!=='.git') { var theme = { "name" : t.split("-").join(" ").replace(/^([a-z\u00E0-\u00FC])|\s+([a-z\u00E0-\u00FC])/g, function ($1) { return $1.toUpperCase(); }), "url" : "../"+themepath+"/uikit.less", "config": (fs.existsSync(themepath+"/customizer.json") ? "../"+themepath+"/customizer.json" : "../themes/default/uikit/customizer.json"), "styles": {} }; if(fs.existsSync(themepath+'/styles')) { var styles = {}; fs.readdirSync(themepath+'/styles').forEach(function(sf){ var stylepath = [themepath, 'styles', sf, 'style.less'].join('/'); if(fs.existsSync(stylepath)) { styles[sf] = "../"+themepath+"/styles/"+sf+"/style.less"; } }); theme.styles = styles; } themes.push(theme); } }); } }); grunt.log.writeln(themes.length+' themes found: ' + themes.map(function(theme){ return theme.name;}).join(", ")); fs.writeFileSync("themes/themes.json", JSON.stringify(themes, " ", 4)); }); grunt.registerTask('sublime', 'Building Sublime Text Package', function() { // generates a python list (returns string representation) var pythonList = function(classes) { var result = []; classes.forEach(function(cls) { // wrap class name in double quotes, add comma (except for last element) result.push(['"', cls, '"', (i !== classes.length-1 ? ", " : "")].join('')); // break lines every n elements if ((i !== 0) && (i%20 === 0)) { result.push("\n "); } }); return "[" + result.join("") + "]"; }; // css core var filepath = 'dist/css/uikit.css', cssFiles = [filepath]; if (!fs.existsSync(filepath)) { grunt.log.error("Not found: " + filepath); return; } // css addons fs.readdirSync('dist/css/addons').forEach(function(f){ if (f.match(/\.css$/)) { cssFiles.push('dist/css/addons/'+f); } }); var cssContent = ""; for (var i in cssFiles) { cssContent += grunt.file.read(cssFiles[i])+' '; } var classesList = cssContent.match(/\.(uk-[a-z\d\-]+)/g), classesSet = {}, pystring = '# copy & paste into sublime plugin code:\n'; // use object as set (no duplicates) classesList.forEach(function(c) { c = c.substr(1); // remove leading dot classesSet[c] = true; }); // convert set back to list classesList = Object.keys(classesSet); pystring += 'uikit_classes = ' + pythonList(classesList) + '\n'; // JS core filepath = 'dist/js/uikit.js'; if (!fs.existsSync(filepath)) { grunt.log.error("Not found: " + filepath); return; } var jsFiles = [filepath]; // JS addons fs.readdirSync('dist/js/addons').forEach(function(f){ if (f.match(/\.js$/)) { jsFiles.push('dist/js/addons/'+f); } }); var jsContent = ""; for (var i in jsFiles) { jsContent += grunt.file.read(jsFiles[i]) + ' '; } var dataList = jsContent.match(/data-uk-[a-z\d\-]+/g), dataSet = {}; dataList.forEach(function(s) { dataSet[s] = true; }); dataList = Object.keys(dataSet); pystring += 'uikit_data = ' + pythonList(dataList) + '\n'; grunt.file.write('dist/uikit_completions.py', pystring); grunt.log.writeln('Written: dist/uikit_completions.py'); }); // Load grunt tasks from NPM packages grunt.loadNpmTasks("grunt-contrib-less"); grunt.loadNpmTasks("grunt-contrib-copy"); grunt.loadNpmTasks("grunt-contrib-concat"); grunt.loadNpmTasks("grunt-contrib-jshint"); grunt.loadNpmTasks("grunt-contrib-uglify"); grunt.loadNpmTasks("grunt-contrib-compress"); grunt.loadNpmTasks("grunt-contrib-watch"); grunt.loadNpmTasks("grunt-banner"); // Register grunt tasks grunt.registerTask("build", ["jshint", "indexthemes", "less", "concat", "copy", "uglify", "usebanner"]); grunt.registerTask("default", ["build", "compress"]); };
risatya/smartlogicpro
vendor/uikit/uikit/Gruntfile.js
JavaScript
mit
11,518
/* * Misc Javascript variables and functions. * * This could all likely use some cleanup. Some of this stuff could be: * * - turned into event-based unobtrusive javascript * - simply named / namespaced a bit better * - the html generated from javascript strings could * likely be improved or moved to the server-side * */ // DEPRECATED var image_attribution_panel_open = false; function toggle_image_attribution() { EOL.log("obsolete method called: toggle_image_attribution"); } function hide_image_attribution() { EOL.log("obsolete method called: hide_image_attribution"); } function show_image_attribution() { EOL.log("obsolete method called: show_image_attribution"); } function create_attribution_table_header() { EOL.log("obsolete method called: create_attribution_table_header"); } function create_attribution_table_row() { EOL.log("obsolete method called: create_attribution_table_row"); } function create_attribution_table_footer() { EOL.log("obsolete method called: create_attribution_table_footer"); } function textCounter(field,cntfield,maxlimit) { if (field.value.length > maxlimit) // if too long...trim it! field.value = field.value.substring(0, maxlimit); // otherwise, update 'characters left' counter else cntfield.innerHTML = maxlimit - field.value.length + ' remaining'; } // update the content area function eol_update_content_area(taxon_concept_id, category_id, allow_user_text) { if($('insert_text_popup')) { EOL.popup_links['new_text_toc_text'].popup.toggle(); } // i feel like this could be a lot simpler ... new Ajax.Request('/taxa/content/', { parameters: { id: taxon_concept_id, category_id: category_id }, onComplete:function(request){hideAjaxIndicator(true);updateReferences();}, onSuccess:function(request){hideAjaxIndicator(true);updateReferences();}, onError: function(request){hideAjaxIndicator(true);}, onLoading:function(request){showAjaxIndicator(true);}, asynchronous:true, evalScripts:true}); $A(document.getElementsByClassName('active', $('toc'))).each(function(e) { e.className = 'toc_item'; }); } // show the pop-up in the div function eol_show_pop_up(div_name, partial_name, taxon_name) { if (partial_name==null) partial_name=div_name; if (taxon_name==null) taxon_name=''; new Ajax.Updater( div_name, '/taxa/show_popup', { asynchronous:true, evalScripts:true, method:'post', onComplete:function(request){hideAjaxIndicator();EOL.Effect.toggle_with_effect(div_name);}, onLoading:function(request){showAjaxIndicator();}, parameters:{name: partial_name, taxon_name: taxon_name} } ); } // Updates the main image and calls eol_update_credit() function eol_update_image(large_image_url, params) { $('main-image').src = large_image_url; $('main-image').alt=params.nameString; $('main-image').title=params.nameString; // update the hrefs for the comment, curation, etc popups if($$('div#large-image-trust-button a')[0]) { if (!params.curated) { $$('div#large-image-trust-button a')[0].href="/data_objects/"+params.data_object_id+"/curate?_method=put&curator_activity_id=3"; $$('div#large-image-untrust-button a')[0].href="/data_objects/"+params.data_object_id+"/curate?_method=put&curator_activity_id=7"; $$('div#large-image-untrust-button a')[0].writeAttribute('data-data_object_id', params.data_object_id); $$('div#large-image-trust-button a')[0].writeAttribute('data-data_object_id', params.data_object_id); $('large-image-trust-button').appear(); $('large-image-untrust-button').appear(); } else { $('large-image-trust-button').disappear(); $('large-image-untrust-button').disappear(); } } if ($('large-image-comment-button-popup-link')) $('large-image-comment-button-popup-link').href = "/data_objects/" + params.data_object_id + "/comments"; if ($('large-image-attribution-button-popup-link')) $('large-image-attribution-button-popup-link').href = "/data_objects/" + params.data_object_id + "/attribution"; if ($('large-image-tagging-button-popup-link')) $('large-image-tagging-button-popup-link').href = "/data_objects/" + params.data_object_id + "/tags"; if ($('large-image-curator-button-popup-link')) $('large-image-curator-button-popup-link').href = "/data_objects/" + params.data_object_id + "/curation"; //update star rating links if($$('div.image-rating ul.user-rating a.one-star')[0]) { $$('div.image-rating ul.user-rating a.one-star')[0].href = '/data_objects/rate/' + params.data_object_id +'?stars=1'; $$('div.image-rating ul.user-rating a.one-star')[0].writeAttribute('data-data_object_id', params.data_object_id); } if($$('div.image-rating ul.user-rating a.two-stars')[0]) { $$('div.image-rating ul.user-rating a.two-stars')[0].href = '/data_objects/rate/' + params.data_object_id +'?stars=2'; $$('div.image-rating ul.user-rating a.two-stars')[0].writeAttribute('data-data_object_id', params.data_object_id); } if($$('div.image-rating ul.user-rating a.three-stars')[0]) { $$('div.image-rating ul.user-rating a.three-stars')[0].href = '/data_objects/rate/' + params.data_object_id +'?stars=3'; $$('div.image-rating ul.user-rating a.three-stars')[0].writeAttribute('data-data_object_id', params.data_object_id); } if($$('div.image-rating ul.user-rating a.four-stars')[0]) { $$('div.image-rating ul.user-rating a.four-stars')[0].href = '/data_objects/rate/' + params.data_object_id +'?stars=4'; $$('div.image-rating ul.user-rating a.four-stars')[0].writeAttribute('data-data_object_id', params.data_object_id); } if($$('div.image-rating ul.user-rating a.five-stars')[0]) { $$('div.image-rating ul.user-rating a.five-stars')[0].href = '/data_objects/rate/' + params.data_object_id +'?stars=5'; $$('div.image-rating ul.user-rating a.five-stars')[0].writeAttribute('data-data_object_id', params.data_object_id); } EOL.Rating.update_average_image_rating(params.data_object_id, params.average_rating); EOL.Rating.update_user_image_rating(params.data_object_id, params.user_rating); eol_update_credit(params); // make a logging call to let the server know that we've viewed this image eol_log_data_objects_for_taxon_concept( params.taxonID, params.data_object_id ); return false; } // Updates the image credit box // // TODO - this should be fetched from the server-side ... way too much HTML generation in the javascript // // ... this updates abunchof stuff and is pretty disorganized :( // function eol_update_credit(params){ // ! FIELD NOTES ! <start> NOTE: this should really be moved into a partial on the server side! field_notes_area = ''; if (params.taxaIDs.length > 0 ) { var current_page_name_or_id = window.location.toString().sub(/.*\//,'').sub(/\?.*/,''); var taxa_thats_not_the_current_page = 0; // loop thru and find a taxa that's NOT the current page's taxa while (params.taxaIDs[taxa_thats_not_the_current_page] != null && current_page_name_or_id == params.taxaIDs[taxa_thats_not_the_current_page].toString() ) { taxa_thats_not_the_current_page++; } // if it exists, show it ... if ( params.taxaIDs[taxa_thats_not_the_current_page] != null ) { field_notes_area += 'Image of <a href="/pages/' + params.taxaIDs[taxa_thats_not_the_current_page] + '">' + params.taxaNames[taxa_thats_not_the_current_page] + '</a><br />'; } } license_info='COPYRIGHT: '; if (params.license_text != '') { license_info += params.license_text; } if (params.license_logo != '') { license_info += '&nbsp;&nbsp;<a href="' + params.license_link + '" class="external_link"><img src="' + params.license_logo + '" border="0"></a>'; } field_notes_area += license_info+'<br />' if (params.data_supplier != '') { if (params.data_supplier_url != '') { field_notes_area += 'SUPPLIER: <a href="'+params.data_supplier_url+'" class="external_link">' + params.data_supplier + ' <img alt="external link" src="/images/external_link.png"></a> ' + params.data_supplier_icon + '<br />'; } else { field_notes_area += 'SUPPLIER: ' + params.data_supplier + '<br />'; } } if (params.authors_linked != '') { field_notes_area += 'AUTHOR: ' + params.authors_linked + '<br />'; } if (params.sources != '' && params.info_url != '' && params.info_url != null) { field_notes_area += 'SOURCE: <a href="'+params.info_url+'" class="external_link">' + params.sources + ' <img alt="external link" src="/images/external_link.png"></a><br />'; } else if (params.sources_linked != '') { field_notes_area += 'SOURCE:' + params.sources_linked + '<br />'; } if (params.sources_icons_linked != '') { field_notes_area += params.sources_icons_linked + '<br />'; } field_notes_area += '<br /><br />'; field_notes_area += params.field_notes ? params.field_notes : ""; $$('#large-image-button-group .published_icon')[0].hide(); $$('#large-image-button-group .unpublished_icon')[0].hide(); $$('#large-image-button-group .inappropriate_icon')[0].hide(); $$('#large-image-button-group .invisible_icon')[0].hide(); if (params.published_by_agent){ $$('#large-image-button-group .published_icon')[0].show(); } else if(!params.published) { $$('#large-image-button-group .unpublished_icon')[0].show(); } if (params.visibility_id == EOL.Curation.INVISIBLE_ID) { $$('#large-image-button-group .invisible_icon')[0].show(); } else if (params.visibility_id == EOL.Curation.INAPPROPRIATE_ID) { $$('#large-image-button-group .inappropriate_icon')[0].show(); } $('large-image-attribution-button').removeClassName('unknown'); $('large-image-attribution-button').removeClassName('untrusted'); $('mc-notes').removeClassName('unknown-background-text'); $('mc-notes').removeClassName('untrusted-background-text'); $('main-image-bg').removeClassName('unknown-background-image'); $('main-image-bg').removeClassName('untrusted-background-image'); if (params.vetted_id == EOL.Curation.UNKNOWN_ID) { $('mc-notes').addClassName('unknown-background-text'); $('main-image-bg').addClassName('unknown-background-image'); $('large-image-attribution-button').addClassName('unknown'); field_notes_area += '<br /><br /><strong>Note:</strong> The image from this source has not been reviewed.'; } else if (params.vetted_id == EOL.Curation.UNTRUSTED_ID) { $('mc-notes').addClassName('untrusted-background-text'); $('main-image-bg').addClassName('untrusted-background-image'); $('large-image-attribution-button').addClassName('untrusted'); field_notes_area += '<br /><br /><strong>Note:</strong> The image from this source is not trusted.'; } $('field-notes').innerHTML = field_notes_area; // this is the 'gray box' // ! FIELD NOTES ! </end> EOL.reload_behaviors(); } // Updates the main image and calls eol_update_credit() function eol_update_video(params) { $$('div#media-videos div.attribution_link')[0].show(); for(var i in EOL.popups) { EOL.popups[i].destroy(); } $('video_attributions').href = "/data_objects/" + params.data_object_id + "/attribution"; new Ajax.Request('/taxa/show_video/', { parameters: { video_type: params.video_type, video_url: params.video_url }, onComplete:function(request){hideAjaxIndicator();}, onLoading:function(request){showAjaxIndicator();}, asynchronous:true, evalScripts:true}); $('video-notes').removeClassName('untrusted-background-text'); $('video-player').removeClassName('untrusted-background-color'); $('video_attributions').removeClassName('untrusted'); $('video-notes').removeClassName('unknown-background-text'); $('video-player').removeClassName('unknown-background-color'); $('video_attributions').removeClassName('unknown'); if (params.video_trusted == EOL.Curation.UNTRUSTED_ID){ $('video-notes').addClassName('untrusted-background-text'); $('video-player').addClassName('untrusted-background-color'); $('video_attributions').addClassName('untrusted'); } else if (params.video_trusted == EOL.Curation.UNKNOWN_ID){ $('video-notes').addClassName('unknown-background-text'); $('video-player').addClassName('unknown-background-color'); $('video_attributions').addClassName('unknown'); } license_info='COPYRIGHT: '; if (params.license_text != '') { license_info += params.license_text; } if (params.license_logo != '') { license_info += '&nbsp;&nbsp;<a href="' + params.license_link + '" class="external_link"><img src="' + params.license_logo + '" border="0"></a>'; } video_notes_area = ''; video_notes_area += params.title +'<br /><br />'; if (license_info != '') {video_notes_area += license_info + '<br />';} data_supplier = params.video_data_supplier; data_supplier_name = params.video_supplier_name; data_supplier_url = params.video_supplier_url; if (data_supplier != '') { if (data_supplier_url != '') { video_notes_area += 'SUPPLIER: <a href="'+data_supplier_url+'" class="external_link">' + data_supplier + ' <img alt="external link" src="/images/external_link.png"></a> ' + params.video_supplier_icon + '<br />'; } else { video_notes_area += 'SUPPLIER: ' + data_supplier + '<br />'; } } if (params.author != '') {video_notes_area += 'AUTHOR: ' + params.author + '<br />';} if (params.collection != '') {video_notes_area += 'SOURCE: ' + params.collection + '<br />';} video_notes_area += params.field_notes ? '<br />' + params.field_notes : ''; $('video-notes').innerHTML = video_notes_area; // make a logging call to let the server know that we've viewed this video eol_log_data_objects_for_taxon_concept( params.taxon_concept_id, params.data_object_id ); return false; } function displayNode(id) { displayNode(id, false) } // call remote function to show the selected node in the text-based navigational tree view function displayNode(id, for_selection) { url = '/navigation/show_tree_view' if(for_selection) { url = '/navigation/show_tree_view_for_selection' } new Ajax.Updater( 'browser-text', url, { asynchronous:true, evalScripts:true, method:'post', onComplete:function(request){hideAjaxIndicator();}, onLoading:function(request){showAjaxIndicator();}, parameters:'id='+id } ); } function eol_change_to_flash_browser() { if ($('classification-attribution-button_popup') != null) {EOL.Effect.disappear('classification-attribution-button_popup');} EOL.Effect.disappear('browser-text'); EOL.Effect.appear('browser-flash'); update_default_taxonomic_browser('flash'); } function eol_change_to_text_browser() { if ($('classification-attribution-button_popup') != null) {EOL.Effect.disappear('classification-attribution-button_popup');} EOL.Effect.disappear('browser-flash'); EOL.Effect.appear('browser-text'); update_default_taxonomic_browser('text'); } function update_default_taxonomic_browser(default_browser) { new Ajax.Request( '/navigation/set_default_taxonomic_browser', { asynchronous:true, evalScripts:true, method:'get', parameters:'browser='+default_browser } ); } function toggle_children() { Element.toggle('taxonomic-children'); if ($('toggle_children_link').innerHTML=='-') { $('toggle_children_link').innerHTML='+' } else { $('toggle_children_link').innerHTML='-' } } // DEPRECATED! let's use EOL.Ajax.start() / .finish() function showAjaxIndicator(on_content_area) { on_content_area = on_content_area || false if (on_content_area) { Element.show('center-page-content-loading'); } Element.show('ajax-indicator'); } function hideAjaxIndicator(on_content_area) { on_content_area = on_content_area || false if (on_content_area) { Element.hide('center-page-content-loading'); } Element.hide('ajax-indicator'); } function eol_log_data_objects_for_taxon_concept( taxon_concept_id, data_object_ids ) { // make a logging call to let the server know we have seen an object new Ajax.Request('/taxa/view_object/', { method: 'post', parameters: { id: data_object_ids, taxon_concept_id: taxon_concept_id }, asynchronous: true }); } function taxon_comments_permalink(comment_id) { window.onload = function() { EOL.load_taxon_comments_tab({page_to_comment_id: comment_id}); $('media-images').hide(); if($('image').childNodes[0].className='active'){ $('image').childNodes[0].removeClassName('active'); } $('taxa-comments').childNodes[0].addClassName('active'); } var id_arrays = $$('#tab_media_center li').pluck('id'); function hide_taxa_comment(element){ $(element).childNodes[0].observe('click', function() { $('media-taxa-comments').hide(); }) } id_arrays.forEach(hide_taxa_comment); } function text_comments_permalink(data_object_id, text_comment_id, comment_page) { document.observe("dom:loaded", function(e) { textComments = "text-comments-" + data_object_id; textCommentsWrapper = "text-comments-wrapper-" + data_object_id; if ($(textCommentsWrapper).style.display == 'none') { new Ajax.Updater(textComments, '/data_objects/'+data_object_id+'/comments', {asynchronous:true, evalScripts:true, method:'get', parameters: { body_div_name: textComments, comment_id: text_comment_id, page: comment_page}, onLoading: Effect.BlindDown(textCommentsWrapper), onComplete: function() { $('comment_'+text_comment_id).scrollTo(); } }); } else { Effect.DropOut(textCommentsWrapper); } e.stop(); }); }
agrimm/eol
public/javascripts/misc.js
JavaScript
mit
18,745
/*jshint node: true*/ 'use strict'; // Defaults derived from: https://github.com/dequelabs/axe-core const defaults = { rules: { 'area-alt': { 'enabled': true }, 'audio-caption': { 'enabled': true }, 'button-name': { 'enabled': true }, 'document-title': { 'enabled': true }, 'empty-heading': { 'enabled': true }, 'frame-title': { 'enabled': true }, 'frame-title-unique': { 'enabled': true }, 'image-alt': { 'enabled': true }, 'image-redundant-alt': { 'enabled': true }, 'input-image-alt': { 'enabled': true }, 'link-name': { 'enabled': true }, 'object-alt': { 'enabled': true }, 'server-side-image-map': { 'enabled': true }, 'video-caption': { 'enabled': true }, 'video-description': { 'enabled': true }, 'definition-list': { 'enabled': true }, 'dlitem': { 'enabled': true }, 'heading-order': { 'enabled': true }, 'href-no-hash': { 'enabled': true }, 'layout-table': { 'enabled': true }, 'list': { 'enabled': true }, 'listitem': { 'enabled': true }, 'p-as-heading': { 'enabled': true }, 'scope-attr-valid': { 'enabled': true }, 'table-duplicate-name': { 'enabled': true }, 'table-fake-caption': { 'enabled': true }, 'td-has-header': { 'enabled': true }, 'td-headers-attr': { 'enabled': true }, 'th-has-data-cells': { 'enabled': true }, 'duplicate-id': { 'enabled': true }, 'html-has-lang': { 'enabled': true }, 'html-lang-valid': { 'enabled': true }, 'meta-refresh': { 'enabled': true }, 'valid-lang': { 'enabled': true }, 'checkboxgroup': { 'enabled': true }, 'label': { 'enabled': true }, 'radiogroup': { 'enabled': true }, 'accesskeys': { 'enabled': true }, 'bypass': { 'enabled': true }, 'tabindex': { 'enabled': true }, // TODO: this should be re-enabled when we upgrade to axe-core ^3.1.1 (https://github.com/dequelabs/axe-core/issues/961) 'aria-allowed-attr': { 'enabled': false }, 'aria-required-attr': { 'enabled': true }, 'aria-required-children': { 'enabled': true }, 'aria-required-parent': { 'enabled': true }, 'aria-roles': { 'enabled': true }, 'aria-valid-attr': { 'enabled': true }, 'aria-valid-attr-value': { 'enabled': true }, 'blink': { 'enabled': true }, 'color-contrast': { 'enabled': true }, 'link-in-text-block': { 'enabled': true }, 'marquee': { 'enabled': true }, 'meta-viewport': { 'enabled': true }, 'meta-viewport-large': { 'enabled': true } } }; module.exports = { getConfig: () => { const skyPagesConfigUtil = require('../sky-pages/sky-pages.config'); const skyPagesConfig = skyPagesConfigUtil.getSkyPagesConfig(); let config = {}; // Merge rules from skyux config. if (skyPagesConfig.skyux.a11y && skyPagesConfig.skyux.a11y.rules) { config.rules = Object.assign({}, defaults.rules, skyPagesConfig.skyux.a11y.rules); } // The consuming SPA wishes to disable all rules. if (skyPagesConfig.skyux.a11y === false) { config.rules = Object.assign({}, defaults.rules); Object.keys(config.rules).forEach((key) => { config.rules[key].enabled = false; }); } if (!config.rules) { return defaults; } return config; } };
blackbaud/skyux-builder
config/axe/axe.config.js
JavaScript
mit
3,261
angular.module('app.controllers') .controller('detailsEventCtrl', ['$stateParams', '$window', '$http','eventService','personService','commentService','participantService', '$state', '$filter', '$ionicPopup', 'reviewService',// The following is the constructor function for this page's controller. See https://docs.angularjs.org/guide/controller // You can include any angular dependencies as parameters for this function // TIP: Access Route Parameters for your page via $stateParams.parameterName function ($stateParams, $window, $http, eventService,personService,commentService,participantService, $state, $filter, $ionicPopup, reviewService) { var vm = this; vm.data = {}; vm.event; vm.isRegister; vm.dateOfDay; vm.connectedUser; vm.isLogged; vm.ListCommentResponse = []; vm.registerUserToEvent = registerUserToEvent; vm.unregisterUserToEvent = unregisterUserToEvent; vm.getCommentMargin = getCommentMargin; vm.cancelEvent = cancelEvent; vm.detailsParticipant = detailsParticipant; vm.swipeOnImage = swipeOnImage; vm.formatDate = formatDate; vm.displayRateForm = displayRateForm; vm.hideRateForm = hideRateForm; vm.noteEvent = noteEvent; vm.openPopup = openPopup; vm.registerComment = registerComment; vm.showResponse = showResponse; vm.imageToDisplay = ""; vm.getGoogleImage = getGoogleImage; vm.images = {}; activate(); function activate(){ vm.dateOfDay = $filter('date')(new Date(), 'yyyy-MM-dd HH:mm'); if (personService.getConnectedUser() == null){ vm.connectedUser = -1; vm.isLogged = "false" } else { vm.connectedUser = personService.getConnectedUser().PersonId; vm.isLogged = "true" } vm.event = eventService.getEvent(); var rng = Math.random(); if(rng < 0.4){ vm.imageToDisplay = "grosChat.jpg"; } else if(rng < 0.8) { vm.imageToDisplay = "chaton.jpg"; } else if (rng < 0.98){ vm.imageToDisplay = "defaultUser2.jpg"; } else { vm.imageToDisplay = "d74c8cec9490f925a191d4f677fb37ae.jpg" } commentService.getCommentByEvent(vm.event.EventId) .then(function successCallback(response) { vm.ListComment = response.reverse(); console.log(response); }, function erroCallabck(response) { console.log("Il y a eu des erreurs!") console.log(response); }); participantService.getAllParticipantById(vm.event.EventId) .then(function successCallback(response) { console.log(response); vm.ListParticipant = response; vm.nbParticipants = vm.ListParticipant.length; if (personService.getConnectedUser() == null){ vm.isRegister = "null"; }else { var isRegister = "false"; for(i=0;i<vm.ListParticipant.length;i++){ if(vm.ListParticipant[i].PersonId == personService.getConnectedUser().PersonId){ isRegister = "true"; } } if (isRegister == "true"){ vm.isRegister = "true"; }else{ vm.isRegister = "false"; } } console.log("isRegister"); console.log(vm.isRegister); }, function erroCallabck(response) { console.log("Participant: Il y a eu des erreurs!") console.log(response); }); } function registerUserToEvent () { participantService.saveParticipant(personService.getResponseGoogle().idToken, personService.getConnectedUser().PersonId, eventService.getEvent().EventId) .then(function(response){ vm.isRegister = "true"; }) } function unregisterUserToEvent() { participantService.cancelParticipation(personService.getResponseGoogle().idToken, personService.getConnectedUser().PersonId, eventService.getEvent().EventId) .then(function(response){ vm.isRegister = "false"; }) } function getCommentMargin(owner){ if (owner == null){ return "0%"; }else { return "5%"; } } function cancelEvent() { var responseGoogle = personService.getResponseGoogle(); var eventToSend = { "EventId" : vm.event.EventId, "Name" : vm.event.Name, "DateStart" : vm.event.DateStart, "DateEnd" : vm.event.DateEnd, "PlaceId" : vm.event.PlaceId, "Description": vm.event.Description, "Image" : vm.event.Image, "IsCanceled" : 1, "Owner" : vm.event.Owner, "EventType" : vm.event.EventType }; eventService.registerEvent(responseGoogle.idToken,eventToSend); alert('Votre évènement à bien été annulé'); } function detailsParticipant(){ var div = document.getElementById("participantDiv"); if (div.style.display == 'none'){ div.style.display = 'block'; }else{ div.style.display = 'none'; } } function displayRateForm() { document.getElementById("ratingForm").style.display = "block"; document.getElementById("beforeRate").style.display = "none"; } function hideRateForm() { document.getElementById("ratingForm").style.display = "none"; document.getElementById("beforeRate").style.display = "block"; } function noteEvent() { var note = document.getElementById("note").value; var comment = document.getElementById("comment").value; console.log(note); console.log(comment); var reviewToSend = { "person" : personService.getConnectedUser().PersonId, "event" : vm.event.EventId, "rate" : note, "text" : comment }; reviewService.updateReview(personService.getResponseGoogle().idToken, reviewToSend ) .then(function(result){ vm.hideRateForm(); }) } function registerComment(responseTo) { if (responseTo == 'NULL'){ responseTo = null; } var commentToSend = { "ResponseTo" : responseTo, "Text" : document.getElementById("commentText").value, "DatePost" : $filter('date')(new Date(), 'yyyy-MM-dd HH:mm'), "EventId" : vm.event.EventId, "PersonId" : personService.getConnectedUser().PersonId, "Person" : personService.getConnectedUser() }; commentService.registerComment(personService.getResponseGoogle().idToken, commentToSend ) .then(function(result){ commentService.getCommentByEvent(vm.event.EventId) .then(function successCallback(response) { vm.ListComment = response.reverse(); console.log(response); }, function erroCallabck(response) { console.log("Il y a eu des erreurs!") console.log(response); }); }) } function swipeOnImage() { /*var audio = new Audio('img/986.mp3'); audio.play();*/ } function formatDate(date){ var dateOut = new Date(date); return dateOut; } function getGoogleImage(email){ var res = personService.getGooglePicture(email) .then(function(result){ if (!(email in vm.images)){ vm.images[email]=result; } return result; }) .catch(function(error){console.log(error)}); return res; } function openPopup(responseTo, $event) { var myPopup = $ionicPopup.show({ template: '<textarea id="commentText" rows="6" cols="150" maxlength="300" ng-model="data.model" ng-model="vm.data.comment" ></textarea>', title: 'Commentaire', subTitle: 'Les commentaires que vous rentrez doivent être assumés, ils ne pourront pas être effacés!', buttons: [ { text: 'Annuler' }, { text: '<b>Commenter</b>', type: 'button-positive', onTap: function(e) { if (!document.getElementById("commentText").value.trim()) { e.preventDefault(); } else { return document.getElementById("commentText").value; } } } ] }); myPopup.then(function(res) { if (res){ registerComment(responseTo); } }); $event.stopPropagation(); } function showResponse(eventId, commentId, $event) { if (vm.ListCommentResponse[commentId] == undefined || vm.ListCommentResponse[commentId].length == 0){ commentService.getResponseList(eventId, commentId) .then(function(result){ vm.ListCommentResponse[commentId] = result.reverse(); }) $event.stopPropagation(); } else { vm.ListCommentResponse[commentId] = []; } } }])
TraineeSIIp/FrontPepSII
www/js/controllers/detailsEventCtrl.js
JavaScript
mit
7,865